repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
amanchamola/color-detection | [
"e87a02009fa34e831a1a757483918458fda5fe16"
]
| [
"Color detection/color_detection.py"
]
| [
"import cv2\r\nimport pandas as pd\r\n\r\n\r\nimg_path = 'pic2.jpg'\r\n\r\ncsv_path = 'colors.csv'\r\n\r\n\r\nindex = ['color', 'color_name', 'hex', 'R', 'G', 'B']\r\n\r\ndf = pd.read_csv(csv_path, names=index, header=None)\r\n\r\n\r\nimg = cv2.imread(img_path)\r\n\r\nimg = cv2.resize(img,(800,600))\r\n\r\n\r\nclicked = False\r\n\r\nr = g = b = xpos = ypos = 0\r\n\r\n\r\ndef get_color_name(R,G,B):\r\n \r\n\tminimum = 1000\r\n\t\r\n\tfor i in range(len(df)):\r\n \r\n\t\td = abs(R - int(df.loc[i,'R'])) + abs(G - int(df.loc[i,'G'])) + abs(B - int(df.loc[i,'B']))\r\n\t\t\r\n\t\tif d <= minimum:\r\n \r\n\t\t\tminimum = d\r\n\t\t\t\r\n\t\t\tcname = df.loc[i, 'color_name']\r\n\r\n\treturn cname\r\n\r\n\r\ndef draw_function(event, x, y, flags, params):\r\n \r\n\tif event == cv2.EVENT_LBUTTONDBLCLK:\r\n \r\n\t\tglobal b, g, r, xpos, ypos, clicked\r\n\t\t\r\n\t\tclicked = True\r\n\t\t\r\n\t\txpos = x\r\n\t\t\r\n\t\typos = y\r\n\t\t\r\n\t\tb,g,r = img[y,x]\r\n\t\t\r\n\t\tb = int(b)\r\n\t\t\r\n\t\tg = int(g)\r\n\t\t\r\n\t\tr = int(r)\r\n\r\n\r\ncv2.namedWindow('image')\r\n\r\ncv2.setMouseCallback('image', draw_function)\r\n\r\nwhile True:\r\n \r\n\tcv2.imshow('image', img)\r\n\t\r\n\tif clicked:\r\n\t\t\r\n\t\tcv2.rectangle(img, (20,20), (600,60), (b,g,r), -1)\r\n\r\n\t\t\r\n\t\ttext = get_color_name(r,g,b) + ' R=' + str(r) + ' G=' + str(g) + ' B=' + str(b)\r\n\t\t\r\n\t\tcv2.putText(img, text, (50,50), 2,0.8, (255,255,255),2,cv2.LINE_AA)\r\n\t\t\r\n\t\tif r+g+b >=600:\r\n \r\n\t\t\tcv2.putText(img, text, (50,50), 2,0.8, (0,0,0),2,cv2.LINE_AA)\r\n\r\n\tif cv2.waitKey(20) & 0xFF == 27:\r\n \r\n\t\tbreak\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ncv2.destroyAllWindows()\r\n"
]
| [
[
"pandas.read_csv"
]
]
|
Hymwgk/REGNet_for_3D_Grasping | [
"90d2aabeba32c6899b7b8bb8c1ce4ff73c227859"
]
| [
"test.py"
]
| [
"import argparse\r\nimport os\r\nimport pickle, copy\r\n\r\nimport torch\r\nimport torch.utils.data\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nimport numpy as np\r\nimport open3d\r\nfrom tensorboardX import SummaryWriter\r\nfrom torch.optim.lr_scheduler import StepLR, MultiStepLR\r\nimport time\r\n\r\nfrom dataset_utils.get_regiondataset import get_grasp_allobj\r\nfrom dataset_utils.eval_score.eval import eval_test, eval_validate\r\nimport utils\r\nimport glob\r\n\r\nparser = argparse.ArgumentParser(description='GripperRegionNetwork')\r\nparser.add_argument('--tag', type=str, default='default')\r\nparser.add_argument('--debug', type=bool, default=False)\r\nparser.add_argument('--epoch', type=int, default=101)\r\n \r\nparser.add_argument('--cuda', action='store_true')\r\nparser.add_argument('--gpu-num', type=int, default=2)\r\nparser.add_argument('--gpu', type=int, default=0)\r\nparser.add_argument('--gpus', type=str, default='0,2,3')\r\nparser.add_argument('--lr-score' , type=float, default=0.001)\r\nparser.add_argument('--lr-region', type=float, default=0.001)\r\n\r\nparser.add_argument('--load-score-path', type=str, default='/data1/cxg6/REGNet_for_3D_Grasping/assets/models/final/score_20.model')\r\nparser.add_argument('--load-region-path', type=str, default='/data1/cxg6/REGNet_for_3D_Grasping/assets/models/final/region_20.model')\r\n# parser.add_argument('--load-score-path', type=str, default='/data1/cxg6/REGNet_for_3D_Grasping/assets/models/0.12/score_38.model')\r\n# parser.add_argument('--load-region-path', type=str, default='/data1/cxg6/REGNet_for_3D_Grasping/assets/models/0.12/region_38.model')\r\n# #parser.add_argument('--load-score-path', type=str, default='')\r\n# parser.add_argument('--load-region-path', type=str, default='')\r\nparser.add_argument('--load-score-flag', type=bool, default=True)\r\nparser.add_argument('--load-region-flag', type=bool, default=True)\r\n\r\nparser.add_argument('--data-path', type=str, default='/data1/cxg6/eval_data', help='data path')\r\n\r\nparser.add_argument('--model-path', type=str, default='/data1/cxg6/REGNet_for_3D_Grasping/assets/models/', help='to saved model path')\r\nparser.add_argument('--log-path', type=str, default='/data1/cxg6/REGNet_for_3D_Grasping/assets/log/', help='to saved log path')\r\nparser.add_argument('--folder-name', type=str, default='/data1/cxg6/REGNet_for_3D_Grasping/test_file/virtual_data')\r\nparser.add_argument('--file-name', type=str, default='')\r\nparser.add_argument('--log-interval', type=int, default=1)\r\nparser.add_argument('--save-interval', type=int, default=1)\r\n\r\n\r\nargs = parser.parse_args()\r\n\r\nargs.cuda = args.cuda if torch.cuda.is_available else False\r\n\r\nnp.random.seed(int(time.time()))\r\nif args.cuda:\r\n torch.cuda.manual_seed(1)\r\ntorch.cuda.set_device(args.gpu)\r\n\r\nall_points_num = 25600\r\nobj_class_num = 43\r\n\r\n# width, height, depth = 0.060, 0.010, 0.060\r\nwidth, height, depth = 0.06, 0.010, 0.06\r\ntable_height = 0.75\r\ngrasp_score_threshold = 0.5 # 0.3\r\ncenter_num = 4000#64#128\r\nscore_thre = 0.5\r\ngroup_num=256\r\ngroup_num_more=2048\r\nr_time_group = 0.1\r\nr_time_group_more = 0.8\r\ngripper_num = 64\r\nuse_theta = True\r\nreg_channel = 8 \r\n \r\ngripper_params = [width, height, depth]\r\nmodel_params = [obj_class_num, group_num, gripper_num, grasp_score_threshold, depth, reg_channel]\r\nparams = [center_num, score_thre, group_num, r_time_group, \\\r\n group_num_more, r_time_group_more, width, height, depth]\r\n\r\nscore_model, region_model, resume_epoch = utils.construct_net(model_params, 'test_one_file', gpu_num=args.gpu, \r\n load_score_flag=args.load_score_flag, score_path=args.load_score_path,\r\n load_rnet_flag=args.load_region_flag, rnet_path=args.load_region_path)\r\nscore_model, region_model = utils.map_model(score_model, region_model, args.gpu_num, args.gpu, args.gpus)\r\n\r\nclass RefineModule():\r\n def __init__(self):\r\n self.eval_params = [depth, width, table_height, args.gpu, center_num]\r\n self.params = params\r\n self.gripper_params = gripper_params\r\n\r\n def test_one_file(self, epoch, pc_path, real_data=True):\r\n print(\"---------------ONE FILE: test_score epoch\", epoch, \"------------------\")\r\n # np.random.seed(1)\r\n score_model.eval()\r\n region_model.eval()\r\n torch.set_grad_enabled(False)\r\n\r\n if real_data:\r\n data = open3d.io.read_point_cloud(pc_path)\r\n center_camera = np.array([0, 0, 1.658])\r\n data.transform(utils.local_to_global_transformation_quat(center_camera))\r\n pc = np.array(data.points)\r\n pc_color = np.array(data.colors)\r\n else:\r\n data = np.load(pc_path, allow_pickle=True)\r\n pc = data['view_cloud'].astype(np.float32)\r\n pc_color = data['view_cloud_color'].astype(np.float32)\r\n \r\n pc = np.c_[pc, pc_color]\r\n if real_data: \r\n pc = pc[pc[:,0] < 0.26]\r\n pc = pc[pc[:,0] > -0.4]\r\n pc = pc[pc[:,2] < 1]\r\n pc = pc[pc[:,1] < 0.65]\r\n pc = pc[pc[:,1] > 0.2]\r\n pc_back, color_back = copy.deepcopy(pc[:,:3]), copy.deepcopy(pc[:,3:6])\r\n pc = utils.noise_color(pc)\r\n\r\n select_point_index = None\r\n if len(pc) >= all_points_num:\r\n select_point_index = np.random.choice(len(pc), all_points_num, replace=False)\r\n elif len(pc) < all_points_num:\r\n select_point_index = np.random.choice(len(pc), all_points_num, replace=True)\r\n pc = pc[select_point_index]\r\n\r\n pc_torch = torch.Tensor(pc).view(1, -1, 6)\r\n if args.gpu != -1:\r\n pc_torch = pc_torch.cuda()\r\n \r\n # all_feature: [B, N, C], output_score: [B, N]\r\n all_feature, output_score, _ = score_model(pc_torch)\r\n center_pc, center_pc_index, pc_group_index, pc_group, pc_group_more_index, \\\r\n pc_group_more, _ = get_grasp_allobj(pc_torch, output_score, self.params, [], use_theta)\r\n\r\n grasp_stage2, keep_grasp_num_stage2, stage2_mask, _, _, _, select_grasp_class, select_grasp_score, \\\r\n select_grasp_class_stage2, keep_grasp_num_stage3, keep_grasp_num_stage3_score, \\\r\n stage3_mask, stage3_score_mask, _, _, _ = region_model(pc_group, pc_group_more, pc_group_index, \\\r\n pc_group_more_index, center_pc, center_pc_index, pc_torch, all_feature, self.gripper_params, None, [])\r\n \r\n grasp_save_path = pc_path.replace('_data', '_data_predict')\r\n if real_data:\r\n grasp_save_path = grasp_save_path.replace('.pcd', '.p')\r\n \r\n record_stage2 = utils.eval_notruth(pc_back, color_back, grasp_stage2, select_grasp_class, select_grasp_score, \\\r\n select_grasp_class_stage2, output_score, self.eval_params, grasp_save_path)\r\n\r\ndef main():\r\n refineModule = RefineModule()\r\n real_data = True if 'real_data' in args.folder_name else False\r\n\r\n if not args.file_name:\r\n if real_data:\r\n pc_paths = glob.glob(args.folder_name+\"/*.pcd\",recursive=True)\r\n else:\r\n pc_paths = glob.glob(args.folder_name+\"/*.p\",recursive=True)\r\n\r\n for pc_path in pc_paths:\r\n refineModule.test_one_file(resume_epoch-1, pc_path, real_data)\r\n else:\r\n pc_path = os.path.join(args.folder_name, args.file_name)\r\n refineModule.test_one_file(resume_epoch-1, pc_path, real_data)\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n"
]
| [
[
"numpy.array",
"torch.cuda.manual_seed",
"numpy.load",
"torch.cuda.set_device",
"torch.Tensor",
"torch.set_grad_enabled"
]
]
|
rplom/turicreate | [
"eb6711aa74a4f6edd7e6107ca818f1054bff8c04"
]
| [
"src/python/turicreate/toolkits/object_detector/object_detector.py"
]
| [
"# -*- coding: utf-8 -*-\n# Copyright © 2017 Apple Inc. All rights reserved.\n#\n# Use of this source code is governed by a BSD-3-clause license that can\n# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause\n\"\"\"\nClass definition and utilities for the object detection toolkit.\n\"\"\"\nfrom __future__ import print_function as _\nfrom __future__ import division as _\nfrom __future__ import absolute_import as _\nimport time as _time\nimport itertools as _itertools\nfrom datetime import datetime as _datetime\n\nimport six as _six\nimport turicreate as _tc\nimport numpy as _np\nfrom threading import Thread as _Thread\nfrom six.moves.queue import Queue as _Queue\n\nfrom turicreate.toolkits._model import CustomModel as _CustomModel\nimport turicreate.toolkits._internal_utils as _tkutl\nfrom turicreate.toolkits import _coreml_utils\nfrom turicreate.toolkits._model import PythonProxy as _PythonProxy\nfrom turicreate.toolkits._internal_utils import (_raise_error_if_not_sframe,\n _numeric_param_check_range)\nfrom turicreate import config as _tc_config\nfrom turicreate.toolkits._main import ToolkitError as _ToolkitError\nfrom .. import _pre_trained_models\nfrom ._evaluation import average_precision as _average_precision\nfrom .._mps_utils import (use_mps as _use_mps,\n mps_device_memory_limit as _mps_device_memory_limit,\n MpsGraphAPI as _MpsGraphAPI,\n MpsGraphNetworkType as _MpsGraphNetworkType,\n MpsGraphMode as _MpsGraphMode,\n mps_to_mxnet as _mps_to_mxnet,\n mxnet_to_mps as _mxnet_to_mps)\n\n\n_MXNET_MODEL_FILENAME = \"mxnet_model.params\"\n\ndef _get_mps_od_net(input_image_shape, batch_size, output_size, anchors,\n config, weights={}):\n \"\"\"\n Initializes an MpsGraphAPI for object detection.\n \"\"\"\n network = _MpsGraphAPI(network_id=_MpsGraphNetworkType.kODGraphNet)\n\n c_in, h_in, w_in = input_image_shape\n c_out = output_size\n h_out = h_in // 32\n w_out = w_in // 32\n\n c_view = c_in\n h_view = h_in\n w_view = w_in\n\n network.init(batch_size, c_in, h_in, w_in, c_out, h_out, w_out,\n weights=weights, config=config)\n return network\n\n\n# Standard lib functions would be great here, but the formatting options of\n# timedelta are not great\ndef _seconds_as_string(seconds):\n \"\"\"\n Returns seconds as a human-friendly string, e.g. '1d 4h 47m 41s'\n \"\"\"\n TIME_UNITS = [('s', 60), ('m', 60), ('h', 24), ('d', None)]\n unit_strings = []\n cur = max(int(seconds), 1)\n for suffix, size in TIME_UNITS:\n if size is not None:\n cur, rest = divmod(cur, size)\n else:\n rest = cur\n if rest > 0:\n unit_strings.insert(0, '%d%s' % (rest, suffix))\n return ' '.join(unit_strings)\n\n\ndef _raise_error_if_not_detection_sframe(dataset, feature, annotations, require_annotations):\n _raise_error_if_not_sframe(dataset, 'datset')\n if feature not in dataset.column_names():\n raise _ToolkitError(\"Feature column '%s' does not exist\" % feature)\n if dataset[feature].dtype != _tc.Image:\n raise _ToolkitError(\"Feature column must contain images\")\n\n if require_annotations:\n if annotations not in dataset.column_names():\n raise _ToolkitError(\"Annotations column '%s' does not exist\" % annotations)\n if dataset[annotations].dtype not in [list, dict]:\n raise _ToolkitError(\"Annotations column must be of type dict or list\")\n\n\ndef create(dataset, annotations=None, feature=None, model='darknet-yolo',\n classes=None, batch_size=0, max_iterations=0,\n verbose=True, grid_shape=[13, 13], **kwargs):\n \"\"\"\n Create a :class:`ObjectDetector` model.\n\n Parameters\n ----------\n dataset : SFrame\n Input data. The columns named by the ``feature`` and ``annotations``\n parameters will be extracted for training the detector.\n\n annotations : string\n Name of the column containing the object detection annotations. This\n column should be a list of dictionaries (or a single dictionary), with\n each dictionary representing a bounding box of an object instance. Here\n is an example of the annotations for a single image with two object\n instances::\n\n [{'label': 'dog',\n 'type': 'rectangle',\n 'coordinates': {'x': 223, 'y': 198,\n 'width': 130, 'height': 230}},\n {'label': 'cat',\n 'type': 'rectangle',\n 'coordinates': {'x': 40, 'y': 73,\n 'width': 80, 'height': 123}}]\n\n The value for `x` is the horizontal center of the box paired with\n `width` and `y` is the vertical center of the box paired with `height`.\n 'None' (the default) indicates the only list column in `dataset` should\n be used for the annotations.\n\n feature : string\n Name of the column containing the input images. 'None' (the default)\n indicates the only image column in `dataset` should be used as the\n feature.\n\n model : string optional\n Object detection model to use:\n\n - \"darknet-yolo\" : Fast and medium-sized model\n\n grid_shape : array optional\n Shape of the grid used for object detection. Higher values increase precision for small objects, but at a higher computational cost\n\n - [13, 13] : Default grid value for a Fast and medium-sized model\n\n classes : list optional\n List of strings containing the names of the classes of objects.\n Inferred from the data if not provided.\n\n batch_size: int\n The number of images per training iteration. If 0, then it will be\n automatically determined based on resource availability.\n\n max_iterations : int\n The number of training iterations. If 0, then it will be automatically\n be determined based on the amount of data you provide.\n\n verbose : bool, optional\n If True, print progress updates and model details.\n\n Returns\n -------\n out : ObjectDetector\n A trained :class:`ObjectDetector` model.\n\n See Also\n --------\n ObjectDetector\n\n Examples\n --------\n .. sourcecode:: python\n\n # Train an object detector model\n >>> model = turicreate.object_detector.create(data)\n\n # Make predictions on the training set and as column to the SFrame\n >>> data['predictions'] = model.predict(data)\n\n # Visualize predictions by generating a new column of marked up images\n >>> data['image_pred'] = turicreate.object_detector.util.draw_bounding_boxes(data['image'], data['predictions'])\n \"\"\"\n _raise_error_if_not_sframe(dataset, \"dataset\")\n from ._mx_detector import YOLOLoss as _YOLOLoss\n from ._model import tiny_darknet as _tiny_darknet\n from ._sframe_loader import SFrameDetectionIter as _SFrameDetectionIter\n from ._manual_scheduler import ManualScheduler as _ManualScheduler\n import mxnet as _mx\n from .._mxnet import _mxnet_utils\n\n if len(dataset) == 0:\n raise _ToolkitError('Unable to train on empty dataset')\n\n _numeric_param_check_range('max_iterations', max_iterations, 0, _six.MAXSIZE)\n start_time = _time.time()\n\n supported_detectors = ['darknet-yolo']\n\n if feature is None:\n feature = _tkutl._find_only_image_column(dataset)\n if verbose:\n print(\"Using '%s' as feature column\" % feature)\n if annotations is None:\n annotations = _tkutl._find_only_column_of_type(dataset,\n target_type=[list, dict],\n type_name='list',\n col_name='annotations')\n if verbose:\n print(\"Using '%s' as annotations column\" % annotations)\n\n _raise_error_if_not_detection_sframe(dataset, feature, annotations,\n require_annotations=True)\n _tkutl._handle_missing_values(dataset, feature, 'dataset')\n is_annotations_list = dataset[annotations].dtype == list\n\n _tkutl._check_categorical_option_type('model', model,\n supported_detectors)\n\n base_model = model.split('-', 1)[0]\n ref_model = _pre_trained_models.OBJECT_DETECTION_BASE_MODELS[base_model]()\n\n params = {\n 'anchors': [\n (1.0, 2.0), (1.0, 1.0), (2.0, 1.0),\n (2.0, 4.0), (2.0, 2.0), (4.0, 2.0),\n (4.0, 8.0), (4.0, 4.0), (8.0, 4.0),\n (8.0, 16.0), (8.0, 8.0), (16.0, 8.0),\n (16.0, 32.0), (16.0, 16.0), (32.0, 16.0),\n ],\n 'grid_shape': grid_shape,\n 'aug_resize': 0,\n 'aug_rand_crop': 0.9,\n 'aug_rand_pad': 0.9,\n 'aug_rand_gray': 0.0,\n 'aug_aspect_ratio': 1.25,\n 'aug_hue': 0.05,\n 'aug_brightness': 0.05,\n 'aug_saturation': 0.05,\n 'aug_contrast': 0.05,\n 'aug_horizontal_flip': True,\n 'aug_min_object_covered': 0,\n 'aug_min_eject_coverage': 0.5,\n 'aug_area_range': (.15, 2),\n 'aug_pca_noise': 0.0,\n 'aug_max_attempts': 20,\n 'aug_inter_method': 2,\n 'lmb_coord_xy': 10.0,\n 'lmb_coord_wh': 10.0,\n 'lmb_obj': 100.0,\n 'lmb_noobj': 5.0,\n 'lmb_class': 2.0,\n 'non_maximum_suppression_threshold': 0.45,\n 'rescore': True,\n 'clip_gradients': 0.025,\n 'weight_decay': 0.0005,\n 'sgd_momentum': 0.9,\n 'learning_rate': 1.0e-3,\n 'shuffle': True,\n 'mps_loss_mult': 8,\n # This large buffer size (8 batches) is an attempt to mitigate against\n # the SFrame shuffle operation that can occur after each epoch.\n 'io_thread_buffer_size': 8,\n 'use_tensorflow': False\n }\n\n if '_advanced_parameters' in kwargs:\n # Make sure no additional parameters are provided\n new_keys = set(kwargs['_advanced_parameters'].keys())\n set_keys = set(params.keys())\n unsupported = new_keys - set_keys\n if unsupported:\n raise _ToolkitError('Unknown advanced parameters: {}'.format(unsupported))\n\n params.update(kwargs['_advanced_parameters'])\n\n anchors = params['anchors']\n num_anchors = len(anchors)\n\n if batch_size < 1:\n batch_size = 32 # Default if not user-specified\n cuda_gpus = _mxnet_utils.get_gpus_in_use(max_devices=batch_size)\n num_mxnet_gpus = len(cuda_gpus)\n use_mps = _use_mps() and num_mxnet_gpus == 0\n batch_size_each = batch_size // max(num_mxnet_gpus, 1)\n if use_mps and _mps_device_memory_limit() < 4 * 1024 * 1024 * 1024:\n # Reduce batch size for GPUs with less than 4GB RAM\n if batch_size_each > 16:\n batch_size_each = 16\n # Note, this may slightly alter the batch size to fit evenly on the GPUs\n batch_size = max(num_mxnet_gpus, 1) * batch_size_each\n if verbose:\n print(\"Setting 'batch_size' to {}\".format(batch_size))\n\n\n # The IO thread also handles MXNet-powered data augmentation. This seems\n # to be problematic to run independently of a MXNet-powered neural network\n # in a separate thread. For this reason, we restrict IO threads to when\n # the neural network backend is MPS.\n io_thread_buffer_size = params['io_thread_buffer_size'] if use_mps else 0\n\n if verbose:\n # Estimate memory usage (based on experiments)\n cuda_mem_req = 550 + batch_size_each * 85\n\n _tkutl._print_neural_compute_device(cuda_gpus=cuda_gpus, use_mps=use_mps,\n cuda_mem_req=cuda_mem_req)\n\n input_image_shape = (3,\n grid_shape[0] * ref_model.spatial_reduction,\n grid_shape[1] * ref_model.spatial_reduction)\n\n try:\n if is_annotations_list:\n instances = (dataset.stack(annotations, new_column_name='_bbox', drop_na=True)\n .unpack('_bbox', limit=['label']))\n else:\n instances = dataset.rename({annotations: '_bbox'}).dropna('_bbox')\n instances = instances.unpack('_bbox', limit=['label'])\n\n except (TypeError, RuntimeError):\n # If this fails, the annotation format isinvalid at the coarsest level\n raise _ToolkitError(\"Annotations format is invalid. Must be a list of \"\n \"dictionaries or single dictionary containing 'label' and 'coordinates'.\")\n\n num_images = len(dataset)\n num_instances = len(instances)\n if classes is None:\n classes = instances['_bbox.label'].unique()\n classes = sorted(classes)\n\n # Make a class-to-index look-up table\n class_to_index = {name: index for index, name in enumerate(classes)}\n num_classes = len(classes)\n\n if max_iterations == 0:\n # Set number of iterations through a heuristic\n num_iterations_raw = 5000 * _np.sqrt(num_instances) / batch_size\n num_iterations = 1000 * max(1, int(round(num_iterations_raw / 1000)))\n if verbose:\n print(\"Setting 'max_iterations' to {}\".format(num_iterations))\n else:\n num_iterations = max_iterations\n\n # Create data loader\n loader = _SFrameDetectionIter(dataset,\n batch_size=batch_size,\n input_shape=input_image_shape[1:],\n output_shape=grid_shape,\n anchors=anchors,\n class_to_index=class_to_index,\n aug_params=params,\n shuffle=params['shuffle'],\n loader_type='augmented',\n feature_column=feature,\n annotations_column=annotations,\n io_thread_buffer_size=io_thread_buffer_size,\n iterations=num_iterations)\n\n # Predictions per anchor box: x/y + w/h + object confidence + class probs\n preds_per_box = 5 + num_classes\n output_size = preds_per_box * num_anchors\n ymap_shape = (batch_size_each,) + tuple(grid_shape) + (num_anchors, preds_per_box)\n\n net = _tiny_darknet(output_size=output_size)\n\n loss = _YOLOLoss(input_shape=input_image_shape[1:],\n output_shape=grid_shape,\n batch_size=batch_size_each,\n num_classes=num_classes,\n anchors=anchors,\n parameters=params)\n\n base_lr = params['learning_rate']\n steps = [num_iterations // 2, 3 * num_iterations // 4, num_iterations]\n steps_and_factors = [(step, 10**(-i)) for i, step in enumerate(steps)]\n\n steps, factors = zip(*steps_and_factors)\n lr_scheduler = _ManualScheduler(step=steps, factor=factors)\n\n ctx = _mxnet_utils.get_mxnet_context(max_devices=batch_size)\n\n net_params = net.collect_params()\n net_params.initialize(_mx.init.Xavier(), ctx=ctx)\n net_params['conv7_weight'].initialize(_mx.init.Xavier(factor_type='avg'), ctx=ctx, force_reinit=True)\n net_params['conv8_weight'].initialize(_mx.init.Uniform(0.00005), ctx=ctx, force_reinit=True)\n # Initialize object confidence low, preventing an unnecessary adjustment\n # period toward conservative estimates\n bias = _np.zeros(output_size, dtype=_np.float32)\n bias[4::preds_per_box] -= 6\n from ._mx_detector import ConstantArray\n net_params['conv8_bias'].initialize(ConstantArray(bias), ctx, force_reinit=True)\n\n # Take a subset and then load the rest of the parameters. It is possible to\n # do allow_missing=True directly on net_params. However, this will more\n # easily hide bugs caused by names getting out of sync.\n ref_model.available_parameters_subset(net_params).load(ref_model.model_path, ctx)\n\n column_names = ['Iteration', 'Loss', 'Elapsed Time']\n num_columns = len(column_names)\n column_width = max(map(lambda x: len(x), column_names)) + 2\n hr = '+' + '+'.join(['-' * column_width] * num_columns) + '+'\n\n progress = {'smoothed_loss': None, 'last_time': 0}\n iteration = 0\n\n def update_progress(cur_loss, iteration):\n iteration_base1 = iteration + 1\n if progress['smoothed_loss'] is None:\n progress['smoothed_loss'] = cur_loss\n else:\n progress['smoothed_loss'] = 0.9 * progress['smoothed_loss'] + 0.1 * cur_loss\n cur_time = _time.time()\n\n # Printing of table header is deferred, so that start-of-training\n # warnings appear above the table\n if verbose and iteration == 0:\n # Print progress table header\n print(hr)\n print(('| {:<{width}}' * num_columns + '|').format(*column_names, width=column_width-1))\n print(hr)\n\n if verbose and (cur_time > progress['last_time'] + 10 or\n iteration_base1 == max_iterations):\n # Print progress table row\n elapsed_time = cur_time - start_time\n print(\"| {cur_iter:<{width}}| {loss:<{width}.3f}| {time:<{width}.1f}|\".format(\n cur_iter=iteration_base1, loss=progress['smoothed_loss'],\n time=elapsed_time , width=column_width-1))\n progress['last_time'] = cur_time\n\n if params['use_tensorflow']:\n from ._tf_model_architecture import ODTensorFlowModel\n\n if verbose:\n print(\"Using TensorFlow\")\n\n # Force initialization of net_params\n # TODO: Do not rely on MXNet to initialize MPS-based network\n net.forward(_mx.nd.uniform(0, 1, (batch_size_each,) + input_image_shape))\n tf_net_params = {}\n # Store weights from MXNet into a dict for TF\n keys = list(net_params)\n for k in keys:\n tf_net_params[k] = net_params[k].data().asnumpy()\n\n tf_config = {\n 'mode': 'train',\n 'learning_rate': base_lr,\n 'gradient_clipping': params.get('clip_gradients'),\n 'weight_decay': params['weight_decay'],\n 'od_include_network': True,\n 'od_include_loss': True,\n 'num_classes': num_classes,\n 'grid_shape': grid_shape,\n 'anchors':anchors,\n 'output_size': output_size,\n 'batch_size': batch_size,\n 'box_per_cell': 15,\n 'lmb_coord_xy': params['lmb_coord_xy'],\n 'lmb_coord_wh': params['lmb_coord_wh'],\n 'lmb_obj': params['lmb_obj'],\n 'lmb_noobj': params['lmb_noobj'],\n 'lmb_class': params['lmb_class'],\n 'rescore': params['rescore'],\n 'od_max_iou_for_no_object': 0.3,\n 'od_min_iou_for_object': 0.7,\n 'num_iterations': num_iterations\n }\n\n od_model_train = ODTensorFlowModel(input_image_shape=input_image_shape,\n batch_size=batch_size,\n output_size=output_size,\n init_weights=tf_net_params,\n config=tf_config,\n is_train=True)\n\n # Use worker threads to isolate different points of synchronization\n # and/or waiting for non-Python tasks to finish. The\n # sframe_worker_thread will spend most of its time waiting for SFrame\n # operations, largely image I/O and decoding, along with scheduling\n # MXNet data augmentation. The numpy_worker_thread will spend most of\n # its time waiting for MXNet data augmentation to complete, along with\n # copying the results into NumPy arrays. Finally, the main thread will\n # spend most of its time copying NumPy data into MPS and waiting for the\n # results. Note that using three threads here only makes sense because\n # each thread spends time waiting for non-Python code to finish (so that\n # no thread hogs the global interpreter lock).\n mxnet_batch_queue = _Queue(1)\n numpy_batch_queue = _Queue(1)\n\n def sframe_worker():\n # Once a batch is loaded into NumPy, pass it immediately to the\n # numpy_worker so that we can start I/O and decoding for the next\n # batch.\n for batch in loader:\n mxnet_batch_queue.put(batch)\n mxnet_batch_queue.put(None)\n\n def numpy_worker():\n while True:\n batch = mxnet_batch_queue.get()\n if batch is None:\n break\n\n for x, y in zip(batch.data, batch.label):\n # Convert to NumPy arrays with required shapes. Note that\n # asnumpy waits for any pending MXNet operations to finish.\n # We use the same mxnet_to_mps function for mxnet to tensorflow\n input_data = _mxnet_to_mps(x.asnumpy()) # NCHW to NHWC\n label_data = y.asnumpy()\n\n # Convert to packed 32-bit arrays.\n input_data = input_data.astype(_np.float32)\n if not input_data.flags.c_contiguous:\n input_data = input_data.copy()\n label_data = label_data.astype(_np.float32)\n if not label_data.flags.c_contiguous:\n label_data = label_data.copy()\n\n # Push this batch to the main thread.\n numpy_batch_queue.put({'input': input_data,\n 'label': label_data,\n 'iteration': batch.iteration})\n # Tell the main thread there's no more data.\n numpy_batch_queue.put(None)\n\n sframe_worker_thread = _Thread(target=sframe_worker)\n sframe_worker_thread.start()\n numpy_worker_thread = _Thread(target=numpy_worker)\n numpy_worker_thread.start()\n\n batch_queue = []\n\n def wait_for_batch():\n pending_loss = batch_queue.pop(0)\n batch_loss = pending_loss # Waits for the batch to finish\n return batch_loss.sum()\n while True:\n batch = numpy_batch_queue.get()\n if batch is None:\n break\n\n # TODO: Adjust learning rate according to our schedule and send to set_learning_rate()\n # if batch['iteration'] in steps:\n # ii = steps.index(batch['iteration']) + 1\n # new_lr = factors[ii] * base_lr\n # od_model_train.set_learning_rate(new_lr)\n\n # Submit this match to TensorFlow\n feed_dict = {'input': batch['input'],\n 'label': batch['label'],\n 'iteration': batch['iteration']}\n\n batch_queue.append(od_model_train.train(feed_dict=feed_dict))\n\n # If we have two batches in flight, wait for the first one.\n if len(batch_queue) > 1:\n cur_loss = wait_for_batch()\n\n # If we just submitted the first batch of an iteration, update\n # progress for the iteration completed by the last batch we just\n # waited for.\n if batch['iteration'] > iteration:\n update_progress(cur_loss, iteration)\n iteration = batch['iteration']\n\n # Wait for any pending batches and finalize our progress updates.\n while len(batch_queue) > 0:\n cur_loss = wait_for_batch()\n update_progress(cur_loss, iteration)\n\n sframe_worker_thread.join()\n numpy_worker_thread.join()\n\n # Load weights back into mxnet\n tf_export_params = od_model_train.export_weights()\n\n keys = tf_export_params.keys()\n for k in keys:\n if k in net_params:\n net_params[k].set_data(_np.copy(tf_export_params[k]))\n\n elif use_mps:\n # Force initialization of net_params\n # TODO: Do not rely on MXNet to initialize MPS-based network\n net.forward(_mx.nd.uniform(0, 1, (batch_size_each,) + input_image_shape))\n mps_net_params = {}\n keys = list(net_params)\n for k in keys:\n mps_net_params[k] = net_params[k].data().asnumpy()\n\n # Multiplies the loss to move the fp16 gradients away from subnormals\n # and gradual underflow. The learning rate is correspondingly divided\n # by the same multiple to make training mathematically equivalent. The\n # update is done in fp32, which is why this trick works. Does not\n # affect how loss is presented to the user.\n mps_loss_mult = params['mps_loss_mult']\n\n mps_config = {\n 'mode': _MpsGraphMode.Train,\n 'use_sgd': True,\n 'learning_rate': base_lr / params['mps_loss_mult'],\n 'gradient_clipping': params.get('clip_gradients', 0.0) * mps_loss_mult,\n 'weight_decay': params['weight_decay'],\n 'od_include_network': True,\n 'od_include_loss': True,\n 'od_scale_xy': params['lmb_coord_xy'] * mps_loss_mult,\n 'od_scale_wh': params['lmb_coord_wh'] * mps_loss_mult,\n 'od_scale_no_object': params['lmb_noobj'] * mps_loss_mult,\n 'od_scale_object': params['lmb_obj'] * mps_loss_mult,\n 'od_scale_class': params['lmb_class'] * mps_loss_mult,\n 'od_max_iou_for_no_object': 0.3,\n 'od_min_iou_for_object': 0.7,\n 'od_rescore': params['rescore'],\n }\n\n mps_net = _get_mps_od_net(input_image_shape=input_image_shape,\n batch_size=batch_size,\n output_size=output_size,\n anchors=anchors,\n config=mps_config,\n weights=mps_net_params)\n\n # Use worker threads to isolate different points of synchronization\n # and/or waiting for non-Python tasks to finish. The\n # sframe_worker_thread will spend most of its time waiting for SFrame\n # operations, largely image I/O and decoding, along with scheduling\n # MXNet data augmentation. The numpy_worker_thread will spend most of\n # its time waiting for MXNet data augmentation to complete, along with\n # copying the results into NumPy arrays. Finally, the main thread will\n # spend most of its time copying NumPy data into MPS and waiting for the\n # results. Note that using three threads here only makes sense because\n # each thread spends time waiting for non-Python code to finish (so that\n # no thread hogs the global interpreter lock).\n mxnet_batch_queue = _Queue(1)\n numpy_batch_queue = _Queue(1)\n\n def sframe_worker():\n # Once a batch is loaded into NumPy, pass it immediately to the\n # numpy_worker so that we can start I/O and decoding for the next\n # batch.\n for batch in loader:\n mxnet_batch_queue.put(batch)\n mxnet_batch_queue.put(None)\n\n def numpy_worker():\n while True:\n batch = mxnet_batch_queue.get()\n if batch is None:\n break\n\n for x, y in zip(batch.data, batch.label):\n # Convert to NumPy arrays with required shapes. Note that\n # asnumpy waits for any pending MXNet operations to finish.\n input_data = _mxnet_to_mps(x.asnumpy())\n label_data = y.asnumpy().reshape(y.shape[:-2] + (-1,))\n\n # Convert to packed 32-bit arrays.\n input_data = input_data.astype(_np.float32)\n if not input_data.flags.c_contiguous:\n input_data = input_data.copy()\n label_data = label_data.astype(_np.float32)\n if not label_data.flags.c_contiguous:\n label_data = label_data.copy()\n\n # Push this batch to the main thread.\n numpy_batch_queue.put({'input' : input_data,\n 'label' : label_data,\n 'iteration' : batch.iteration})\n # Tell the main thread there's no more data.\n numpy_batch_queue.put(None)\n sframe_worker_thread = _Thread(target=sframe_worker)\n sframe_worker_thread.start()\n numpy_worker_thread = _Thread(target=numpy_worker)\n numpy_worker_thread.start()\n\n batch_queue = []\n\n def wait_for_batch():\n pending_loss = batch_queue.pop(0)\n batch_loss = pending_loss.asnumpy() # Waits for the batch to finish\n return batch_loss.sum() / mps_loss_mult\n\n while True:\n batch = numpy_batch_queue.get()\n if batch is None:\n break\n\n # Adjust learning rate according to our schedule.\n if batch['iteration'] in steps:\n ii = steps.index(batch['iteration']) + 1\n new_lr = factors[ii] * base_lr\n mps_net.set_learning_rate(new_lr / mps_loss_mult)\n\n # Submit this match to MPS.\n batch_queue.append(mps_net.train(batch['input'], batch['label']))\n\n # If we have two batches in flight, wait for the first one.\n if len(batch_queue) > 1:\n cur_loss = wait_for_batch()\n\n # If we just submitted the first batch of an iteration, update\n # progress for the iteration completed by the last batch we just\n # waited for.\n if batch['iteration'] > iteration:\n update_progress(cur_loss, iteration)\n iteration = batch['iteration']\n\n # Wait for any pending batches and finalize our progress updates.\n while len(batch_queue) > 0:\n cur_loss = wait_for_batch()\n update_progress(cur_loss, iteration)\n\n sframe_worker_thread.join()\n numpy_worker_thread.join()\n\n # Load back into mxnet\n mps_net_params = mps_net.export()\n keys = mps_net_params.keys()\n for k in keys:\n if k in net_params:\n net_params[k].set_data(mps_net_params[k])\n\n else: # Use MxNet\n\n net.hybridize()\n\n options = {'learning_rate': base_lr, 'lr_scheduler': lr_scheduler,\n 'momentum': params['sgd_momentum'], 'wd': params['weight_decay'], 'rescale_grad': 1.0}\n clip_grad = params.get('clip_gradients')\n if clip_grad:\n options['clip_gradient'] = clip_grad\n trainer = _mx.gluon.Trainer(net.collect_params(), 'sgd', options)\n\n for batch in loader:\n data = _mx.gluon.utils.split_and_load(batch.data[0], ctx_list=ctx, batch_axis=0, even_split=False)\n label = _mx.gluon.utils.split_and_load(batch.label[0], ctx_list=ctx, batch_axis=0, even_split=False)\n\n Ls = []\n Zs = []\n\n with _mx.autograd.record():\n for x, y in zip(data, label):\n z = net(x)\n z0 = _mx.nd.transpose(z, [0, 2, 3, 1]).reshape(ymap_shape)\n L = loss(z0, y)\n Ls.append(L)\n for L in Ls:\n L.backward()\n\n trainer.step(1, ignore_stale_grad=True)\n cur_loss = _np.mean([L.asnumpy()[0] for L in Ls])\n\n update_progress(cur_loss, batch.iteration)\n iteration = batch.iteration\n\n training_time = _time.time() - start_time\n if verbose:\n print(hr) # progress table footer\n\n # Save the model\n training_iterations = iteration + 1\n state = {\n '_model': net,\n '_class_to_index': class_to_index,\n '_training_time_as_string': _seconds_as_string(training_time),\n '_grid_shape': grid_shape,\n 'anchors': anchors,\n 'model': model,\n 'classes': classes,\n 'batch_size': batch_size,\n 'input_image_shape': input_image_shape,\n 'feature': feature,\n 'non_maximum_suppression_threshold': params['non_maximum_suppression_threshold'],\n 'annotations': annotations,\n 'num_classes': num_classes,\n 'num_examples': num_images,\n 'num_bounding_boxes': num_instances,\n 'training_time': training_time,\n 'training_epochs': training_iterations * batch_size // num_images,\n 'training_iterations': training_iterations,\n 'max_iterations': max_iterations,\n 'training_loss': progress['smoothed_loss'],\n }\n return ObjectDetector(state)\n\n\nclass ObjectDetector(_CustomModel):\n \"\"\"\n An trained model that is ready to use for classification, exported to\n Core ML, or for feature extraction.\n\n This model should not be constructed directly.\n \"\"\"\n\n _PYTHON_OBJECT_DETECTOR_VERSION = 1\n\n def __init__(self, state):\n self.__proxy__ = _PythonProxy(state)\n\n @classmethod\n def _native_name(cls):\n return \"object_detector\"\n\n def _get_native_state(self):\n from .._mxnet import _mxnet_utils\n state = self.__proxy__.get_state()\n mxnet_params = state['_model'].collect_params()\n state['_model'] = _mxnet_utils.get_gluon_net_params_state(mxnet_params)\n return state\n\n def _get_version(self):\n return self._PYTHON_OBJECT_DETECTOR_VERSION\n\n @classmethod\n def _load_version(cls, state, version):\n _tkutl._model_version_check(version, cls._PYTHON_OBJECT_DETECTOR_VERSION)\n from ._model import tiny_darknet as _tiny_darknet\n from .._mxnet import _mxnet_utils\n\n num_anchors = len(state['anchors'])\n num_classes = state['num_classes']\n output_size = (num_classes + 5) * num_anchors\n\n net = _tiny_darknet(output_size=output_size)\n ctx = _mxnet_utils.get_mxnet_context(max_devices=state['batch_size'])\n\n net_params = net.collect_params()\n _mxnet_utils.load_net_params_from_state(net_params, state['_model'], ctx=ctx)\n state['_model'] = net\n state['input_image_shape'] = tuple([int(i) for i in state['input_image_shape']])\n state['_grid_shape'] = tuple([int(i) for i in state['_grid_shape']])\n return ObjectDetector(state)\n\n def __str__(self):\n \"\"\"\n Return a string description of the model to the ``print`` method.\n\n Returns\n -------\n out : string\n A description of the ObjectDetector.\n \"\"\"\n return self.__repr__()\n\n def __repr__(self):\n \"\"\"\n Print a string description of the model when the model name is entered\n in the terminal.\n \"\"\"\n\n width = 40\n sections, section_titles = self._get_summary_struct()\n out = _tkutl._toolkit_repr_print(self, sections, section_titles,\n width=width)\n return out\n\n def _get_summary_struct(self):\n \"\"\"\n Returns a structured description of the model, including (where\n relevant) the schema of the training data, description of the training\n data, training statistics, and model hyperparameters.\n\n Returns\n -------\n sections : list (of list of tuples)\n A list of summary sections.\n Each section is a list.\n Each item in a section list is a tuple of the form:\n ('<label>','<field>')\n section_titles: list\n A list of section titles.\n The order matches that of the 'sections' object.\n \"\"\"\n model_fields = [\n ('Model', 'model'),\n ('Number of classes', 'num_classes'),\n ('Non-maximum suppression threshold', 'non_maximum_suppression_threshold'),\n ('Input image shape', 'input_image_shape'),\n ]\n training_fields = [\n ('Training time', '_training_time_as_string'),\n ('Training epochs', 'training_epochs'),\n ('Training iterations', 'training_iterations'),\n ('Number of examples (images)', 'num_examples'),\n ('Number of bounding boxes (instances)', 'num_bounding_boxes'),\n ('Final loss (specific to model)', 'training_loss'),\n ]\n\n section_titles = ['Schema', 'Training summary']\n return([model_fields, training_fields], section_titles)\n\n def _predict_with_options(self, dataset, with_ground_truth,\n postprocess=True, confidence_threshold=0.001,\n iou_threshold=None,\n verbose=True):\n \"\"\"\n Predict with options for what kind of SFrame should be returned.\n\n If postprocess is False, a single numpy array with raw unprocessed\n results will be returned.\n \"\"\"\n if iou_threshold is None: iou_threshold = self.non_maximum_suppression_threshold\n _raise_error_if_not_detection_sframe(dataset, self.feature, self.annotations,\n require_annotations=with_ground_truth)\n from ._sframe_loader import SFrameDetectionIter as _SFrameDetectionIter\n from ._detection import (yolo_map_to_bounding_boxes as _yolo_map_to_bounding_boxes,\n non_maximum_suppression as _non_maximum_suppression,\n bbox_to_ybox as _bbox_to_ybox)\n\n from .._mxnet import _mxnet_utils\n import mxnet as _mx\n loader = _SFrameDetectionIter(dataset,\n batch_size=self.batch_size,\n input_shape=self.input_image_shape[1:],\n output_shape=self._grid_shape,\n anchors=self.anchors,\n class_to_index=self._class_to_index,\n loader_type='stretched',\n load_labels=with_ground_truth,\n shuffle=False,\n epochs=1,\n feature_column=self.feature,\n annotations_column=self.annotations)\n\n num_anchors = len(self.anchors)\n preds_per_box = 5 + len(self.classes)\n output_size = preds_per_box * num_anchors\n\n # If prediction is done with ground truth, two sframes of the same\n # structure are returned, the second one containing ground truth labels\n num_returns = 2 if with_ground_truth else 1\n\n sf_builders = [\n _tc.SFrameBuilder([int, str, float, float, float, float, float],\n column_names=['row_id', 'label', 'confidence',\n 'x', 'y', 'width', 'height'])\n for _ in range(num_returns)\n ]\n\n num_mxnet_gpus = _mxnet_utils.get_num_gpus_in_use(max_devices=self.batch_size)\n use_mps = _use_mps() and num_mxnet_gpus == 0\n if use_mps:\n if not hasattr(self, '_mps_inference_net') or self._mps_inference_net is None:\n mxnet_params = self._model.collect_params()\n mps_net_params = { k : mxnet_params[k].data().asnumpy()\n for k in mxnet_params }\n mps_config = {\n 'mode': _MpsGraphMode.Inference,\n 'od_include_network': True,\n 'od_include_loss': False,\n }\n mps_net = _get_mps_od_net(input_image_shape=self.input_image_shape,\n batch_size=self.batch_size,\n output_size=output_size,\n anchors=self.anchors,\n config=mps_config,\n weights=mps_net_params)\n self._mps_inference_net = mps_net\n\n dataset_size = len(dataset)\n ctx = _mxnet_utils.get_mxnet_context()\n done = False\n last_time = 0\n raw_results = []\n for batch in loader:\n if batch.pad is not None:\n size = self.batch_size - batch.pad\n b_data = _mx.nd.slice_axis(batch.data[0], axis=0, begin=0, end=size)\n b_indices = _mx.nd.slice_axis(batch.label[1], axis=0, begin=0, end=size)\n b_oshapes = _mx.nd.slice_axis(batch.label[2], axis=0, begin=0, end=size)\n else:\n b_data = batch.data[0]\n b_indices = batch.label[1]\n b_oshapes = batch.label[2]\n size = self.batch_size\n\n if b_data.shape[0] < len(ctx):\n ctx0 = ctx[:b_data.shape[0]]\n else:\n ctx0 = ctx\n\n split_data = _mx.gluon.utils.split_and_load(b_data, ctx_list=ctx0, even_split=False)\n split_indices = _mx.gluon.utils.split_data(b_indices, num_slice=len(ctx0), even_split=False)\n split_oshapes = _mx.gluon.utils.split_data(b_oshapes, num_slice=len(ctx0), even_split=False)\n\n for data, indices, oshapes in zip(split_data, split_indices, split_oshapes):\n if use_mps:\n mps_data = _mxnet_to_mps(data.asnumpy())\n n_samples = mps_data.shape[0]\n if mps_data.shape[0] != self.batch_size:\n mps_data_padded = _np.zeros((self.batch_size,) + mps_data.shape[1:],\n dtype=mps_data.dtype)\n mps_data_padded[:mps_data.shape[0]] = mps_data\n mps_data = mps_data_padded\n mps_float_array = self._mps_inference_net.predict(mps_data)\n mps_z = mps_float_array.asnumpy()[:n_samples]\n z = _mps_to_mxnet(mps_z)\n else:\n z = self._model(data).asnumpy()\n if not postprocess:\n raw_results.append(z)\n continue\n\n ypred = z.transpose(0, 2, 3, 1)\n ypred = ypred.reshape(ypred.shape[:-1] + (num_anchors, -1))\n\n zipped = zip(indices.asnumpy(), ypred, oshapes.asnumpy())\n for index0, output0, oshape0 in zipped:\n index0 = int(index0)\n x_boxes, x_classes, x_scores = _yolo_map_to_bounding_boxes(\n output0[_np.newaxis], anchors=self.anchors,\n confidence_threshold=confidence_threshold,\n nms_thresh=None)\n\n x_boxes0 = _np.array(x_boxes).reshape(-1, 4)\n\n # Normalize\n x_boxes0[:, 0::2] /= self.input_image_shape[1]\n x_boxes0[:, 1::2] /= self.input_image_shape[2]\n\n # Re-shape to original input size\n x_boxes0[:, 0::2] *= oshape0[0]\n x_boxes0[:, 1::2] *= oshape0[1]\n\n # Clip the boxes to the original sizes\n x_boxes0[:, 0::2] = _np.clip(x_boxes0[:, 0::2], 0, oshape0[0])\n x_boxes0[:, 1::2] = _np.clip(x_boxes0[:, 1::2], 0, oshape0[1])\n\n # Non-maximum suppression (also limit to 100 detection per\n # image, inspired by the evaluation in COCO)\n x_boxes0, x_classes, x_scores = _non_maximum_suppression(\n x_boxes0, x_classes, x_scores,\n num_classes=self.num_classes, threshold=iou_threshold,\n limit=100)\n\n for bbox, cls, s in zip(x_boxes0, x_classes, x_scores):\n cls = int(cls)\n values = [index0, self.classes[cls], s] + list(_bbox_to_ybox(bbox))\n sf_builders[0].append(values)\n\n if index0 == len(dataset) - 1:\n done = True\n\n cur_time = _time.time()\n # Do not print process if only a few samples are predicted\n if verbose and (dataset_size >= 5 and cur_time > last_time + 10 or done):\n print('Predicting {cur_n:{width}d}/{max_n:{width}d}'.format(\n cur_n=index0 + 1, max_n=dataset_size, width=len(str(dataset_size))))\n last_time = cur_time\n\n if done:\n break\n\n # Ground truth\n if with_ground_truth:\n zipped = _itertools.islice(zip(batch.label[1].asnumpy(), batch.raw_bboxes, batch.raw_classes), size)\n for index0, bbox0, cls0 in zipped:\n index0 = int(index0)\n for bbox, cls in zip(bbox0, cls0):\n cls = int(cls)\n if cls == -1:\n break\n values = [index0, self.classes[cls], 1.0] + list(bbox)\n sf_builders[1].append(values)\n\n if index0 == len(dataset) - 1:\n break\n\n if postprocess:\n ret = tuple([sb.close() for sb in sf_builders])\n if len(ret) == 1:\n return ret[0]\n else:\n return ret\n else:\n return _np.concatenate(raw_results, axis=0)\n\n def _raw_predict(self, dataset):\n return self._predict_with_options(dataset, with_ground_truth=False,\n postprocess=False)\n\n def _canonize_input(self, dataset):\n \"\"\"\n Takes input and returns tuple of the input in canonical form (SFrame)\n along with an unpack callback function that can be applied to\n prediction results to \"undo\" the canonization.\n \"\"\"\n unpack = lambda x: x\n if isinstance(dataset, _tc.SArray):\n dataset = _tc.SFrame({self.feature: dataset})\n elif isinstance(dataset, _tc.Image):\n dataset = _tc.SFrame({self.feature: [dataset]})\n unpack = lambda x: x[0]\n return dataset, unpack\n\n def predict(self, dataset, confidence_threshold=0.25, iou_threshold=None, verbose=True):\n \"\"\"\n Predict object instances in an SFrame of images.\n\n Parameters\n ----------\n dataset : SFrame | SArray | turicreate.Image\n The images on which to perform object detection.\n If dataset is an SFrame, it must have a column with the same name\n as the feature column during training. Additional columns are\n ignored.\n\n confidence_threshold : float\n Only return predictions above this level of confidence. The\n threshold can range from 0 to 1.\n\n iou_threshold : float\n Threshold value for non-maximum suppression. Non-maximum suppression\n prevents multiple bounding boxes appearing over a single object.\n This threshold, set between 0 and 1, controls how aggressive this\n suppression is. A value of 1 means no maximum suppression will\n occur, while a value of 0 will maximally suppress neighboring\n boxes around a prediction.\n\n verbose : bool\n If True, prints prediction progress.\n\n Returns\n -------\n out : SArray\n An SArray with model predictions. Each element corresponds to\n an image and contains a list of dictionaries. Each dictionary\n describes an object instances that was found in the image. If\n `dataset` is a single image, the return value will be a single\n prediction.\n\n See Also\n --------\n evaluate\n\n Examples\n --------\n .. sourcecode:: python\n\n # Make predictions\n >>> pred = model.predict(data)\n\n # Stack predictions, for a better overview\n >>> turicreate.object_detector.util.stack_annotations(pred)\n Data:\n +--------+------------+-------+-------+-------+-------+--------+\n | row_id | confidence | label | x | y | width | height |\n +--------+------------+-------+-------+-------+-------+--------+\n | 0 | 0.98 | dog | 123.0 | 128.0 | 80.0 | 182.0 |\n | 0 | 0.67 | cat | 150.0 | 183.0 | 129.0 | 101.0 |\n | 1 | 0.8 | dog | 50.0 | 432.0 | 65.0 | 98.0 |\n +--------+------------+-------+-------+-------+-------+--------+\n [3 rows x 7 columns]\n\n # Visualize predictions by generating a new column of marked up images\n >>> data['image_pred'] = turicreate.object_detector.util.draw_bounding_boxes(data['image'], data['predictions'])\n \"\"\"\n _numeric_param_check_range('confidence_threshold', confidence_threshold, 0.0, 1.0)\n dataset, unpack = self._canonize_input(dataset)\n stacked_pred = self._predict_with_options(dataset, with_ground_truth=False,\n confidence_threshold=confidence_threshold,\n iou_threshold=iou_threshold,\n verbose=verbose)\n\n from . import util\n return unpack(util.unstack_annotations(stacked_pred, num_rows=len(dataset)))\n\n def evaluate(self, dataset, metric='auto',\n output_type='dict', iou_threshold=None,\n confidence_threshold=None, verbose=True):\n \"\"\"\n Evaluate the model by making predictions and comparing these to ground\n truth bounding box annotations.\n\n Parameters\n ----------\n dataset : SFrame\n Dataset of new observations. Must include columns with the same\n names as the annotations and feature used for model training.\n Additional columns are ignored.\n\n metric : str or list, optional\n Name of the evaluation metric or list of several names. The primary\n metric is average precision, which is the area under the\n precision/recall curve and reported as a value between 0 and 1 (1\n being perfect). Possible values are:\n\n - 'auto' : Returns all primary metrics.\n - 'all' : Returns all available metrics.\n - 'average_precision_50' : Average precision per class with\n intersection-over-union threshold at\n 50% (PASCAL VOC metric).\n - 'average_precision' : Average precision per class calculated over multiple\n intersection-over-union thresholds\n (at 50%, 55%, ..., 95%) and averaged.\n - 'mean_average_precision_50' : Mean over all classes (for ``'average_precision_50'``).\n This is the primary single-value metric.\n - 'mean_average_precision' : Mean over all classes (for ``'average_precision'``)\n\n output_type : str\n Type of output:\n\n - 'dict' : You are given a dictionary where each key is a metric name and the\n value is another dictionary containing class-to-metric entries.\n - 'sframe' : All metrics are returned as a single `SFrame`, where each row is a\n class and each column is a metric. Metrics that are averaged over\n class cannot be returned and are ignored under this format.\n However, these are easily computed from the `SFrame` (e.g.\n ``results['average_precision'].mean()``).\n\n iou_threshold : float\n Threshold value for non-maximum suppression. Non-maximum suppression\n prevents multiple bounding boxes appearing over a single object.\n This threshold, set between 0 and 1, controls how aggressive this\n suppression is. A value of 1 means no maximum suppression will\n occur, while a value of 0 will maximally suppress neighboring\n boxes around a prediction.\n\n confidence_threshold : float\n Only return predictions above this level of confidence. The\n threshold can range from 0 to 1.\n\n verbose : bool\n If True, prints evaluation progress.\n\n Returns\n -------\n out : dict / SFrame\n Output type depends on the option `output_type`.\n\n See Also\n --------\n create, predict\n\n Examples\n --------\n >>> results = model.evaluate(data)\n >>> print('mAP: {:.1%}'.format(results['mean_average_precision']))\n mAP: 43.2%\n \"\"\"\n if iou_threshold is None: iou_threshold = self.non_maximum_suppression_threshold\n if confidence_threshold is None: confidence_threshold = 0.001\n\n AP = 'average_precision'\n MAP = 'mean_average_precision'\n AP50 = 'average_precision_50'\n MAP50 = 'mean_average_precision_50'\n ALL_METRICS = {AP, MAP, AP50, MAP50}\n if isinstance(metric, (list, tuple, set)):\n metrics = metric\n elif metric == 'all':\n metrics = ALL_METRICS\n elif metric == 'auto':\n metrics = {AP50, MAP50}\n elif metric in ALL_METRICS:\n metrics = {metric}\n else:\n raise _ToolkitError(\"Metric '{}' not supported\".format(metric))\n\n pred, gt = self._predict_with_options(dataset, with_ground_truth=True,\n confidence_threshold=confidence_threshold,\n iou_threshold=iou_threshold,\n verbose=verbose)\n\n pred_df = pred.to_dataframe()\n gt_df = gt.to_dataframe()\n\n thresholds = _np.arange(0.5, 1.0, 0.05)\n all_th_aps = _average_precision(pred_df, gt_df,\n class_to_index=self._class_to_index,\n iou_thresholds=thresholds)\n\n def class_dict(aps):\n return {classname: aps[index]\n for classname, index in self._class_to_index.items()}\n\n if output_type == 'dict':\n ret = {}\n if AP50 in metrics:\n ret[AP50] = class_dict(all_th_aps[0])\n if AP in metrics:\n ret[AP] = class_dict(all_th_aps.mean(0))\n if MAP50 in metrics:\n ret[MAP50] = all_th_aps[0].mean()\n if MAP in metrics:\n ret[MAP] = all_th_aps.mean()\n elif output_type == 'sframe':\n ret = _tc.SFrame({'label': self.classes})\n if AP50 in metrics:\n ret[AP50] = all_th_aps[0]\n if AP in metrics:\n ret[AP] = all_th_aps.mean(0)\n else:\n raise _ToolkitError(\"Output type '{}' not supported\".format(output_type))\n\n return ret\n\n def _create_coreml_model(self, include_non_maximum_suppression,\n iou_threshold, confidence_threshold):\n import mxnet as _mx\n from .._mxnet._mxnet_to_coreml import _mxnet_converter\n import coremltools\n from coremltools.models import datatypes, neural_network\n\n if iou_threshold is None: iou_threshold = self.non_maximum_suppression_threshold\n if confidence_threshold is None: confidence_threshold = 0.25\n\n preds_per_box = 5 + self.num_classes\n num_anchors = len(self.anchors)\n num_classes = self.num_classes\n batch_size = 1\n image_shape = (batch_size,) + tuple(self.input_image_shape)\n s_image_uint8 = _mx.sym.Variable(self.feature, shape=image_shape, dtype=_np.float32)\n s_image = s_image_uint8 / 255\n\n # Swap a maxpool+slice in mxnet to a coreml natively supported layer\n from copy import copy\n net = copy(self._model)\n net._children = copy(self._model._children)\n from ._model import _SpecialDarknetMaxpoolBlock\n op = _SpecialDarknetMaxpoolBlock(name='pool5')\n # Make sure we are removing the right layers\n assert (self._model[23].name == 'pool5' and\n self._model[24].name == 'specialcrop5')\n\n try:\n del net._children[24]\n net._children[23] = op\n except KeyError:\n # Newer versions of MXNet use string keys\n del net._children['24']\n net._children['23'] = op\n\n s_ymap = net(s_image)\n mod = _mx.mod.Module(symbol=s_ymap, label_names=None, data_names=[self.feature])\n mod.bind(for_training=False, data_shapes=[(self.feature, image_shape)])\n\n # Copy over params from net\n mod.init_params()\n arg_params, aux_params = mod.get_params()\n net_params = net.collect_params()\n new_arg_params = {}\n for k, param in arg_params.items():\n new_arg_params[k] = net_params[k].data(net_params[k].list_ctx()[0])\n new_aux_params = {}\n for k, param in aux_params.items():\n new_aux_params[k] = net_params[k].data(net_params[k].list_ctx()[0])\n mod.set_params(new_arg_params, new_aux_params)\n\n input_names = [self.feature]\n input_dims = [list(self.input_image_shape)]\n input_types = [datatypes.Array(*dim) for dim in input_dims]\n input_features = list(zip(input_names, input_types))\n\n num_spatial = self._grid_shape[0] * self._grid_shape[1]\n num_bounding_boxes = num_anchors * num_spatial\n CONFIDENCE_STR = (\"raw_confidence\" if include_non_maximum_suppression\n else \"confidence\")\n COORDINATES_STR = (\"raw_coordinates\" if include_non_maximum_suppression\n else \"coordinates\")\n output_names = [\n CONFIDENCE_STR,\n COORDINATES_STR\n ]\n output_dims = [\n (num_bounding_boxes, num_classes),\n (num_bounding_boxes, 4),\n ]\n output_types = [datatypes.Array(*dim) for dim in output_dims]\n output_features = list(zip(output_names, output_types))\n mode = None\n builder = neural_network.NeuralNetworkBuilder(input_features, output_features, mode)\n _mxnet_converter.convert(mod, mode=None,\n input_shape=[(self.feature, image_shape)],\n builder=builder, verbose=False)\n\n prefix = '__tc__internal__'\n\n # (1, B, C+5, S*S)\n builder.add_reshape(name=prefix + 'ymap_sp_pre',\n target_shape=[batch_size, num_anchors, preds_per_box, num_spatial],\n mode=0,\n input_name='conv8_fwd_output',\n output_name=prefix + 'ymap_sp_pre')\n\n # (1, C+5, B, S*S)\n builder.add_permute(name=prefix + 'ymap_sp',\n dim=[0, 2, 1, 3],\n input_name=prefix + 'ymap_sp_pre',\n output_name=prefix + 'ymap_sp')\n\n # POSITION: X/Y\n\n # (1, 2, B, S*S)\n builder.add_slice(name=prefix + 'raw_rel_xy_sp',\n axis='channel',\n start_index=0,\n end_index=2,\n stride=1,\n input_name=prefix + 'ymap_sp',\n output_name=prefix + 'raw_rel_xy_sp')\n # (1, 2, B, S*S)\n builder.add_activation(name=prefix + 'rel_xy_sp',\n non_linearity='SIGMOID',\n input_name=prefix + 'raw_rel_xy_sp',\n output_name=prefix + 'rel_xy_sp')\n\n # (1, 2, B*H*W, 1)\n builder.add_reshape(name=prefix + 'rel_xy',\n target_shape=[batch_size, 2, num_bounding_boxes, 1],\n mode=0,\n input_name=prefix + 'rel_xy_sp',\n output_name=prefix + 'rel_xy')\n\n c_xy = _np.array(_np.meshgrid(_np.arange(self._grid_shape[1]),\n _np.arange(self._grid_shape[0])), dtype=_np.float32)\n\n c_xy_reshaped = (_np.tile(c_xy[:, _np.newaxis], (num_anchors, 1, 1))\n .reshape(2, -1))[_np.newaxis, ..., _np.newaxis]\n\n # (1, 2, B*H*W, 1)\n builder.add_load_constant(prefix + 'constant_xy',\n constant_value=c_xy_reshaped,\n shape=c_xy_reshaped.shape[1:],\n output_name=prefix + 'constant_xy')\n\n # (1, 2, B*H*W, 1)\n builder.add_elementwise(name=prefix + 'xy',\n mode='ADD',\n input_names=[prefix + 'constant_xy', prefix + 'rel_xy'],\n output_name=prefix + 'xy')\n\n # SHAPE: WIDTH/HEIGHT\n\n # (1, 2, B, S*S)\n builder.add_slice(name=prefix + 'raw_rel_wh_sp',\n axis='channel',\n start_index=2,\n end_index=4,\n stride=1,\n input_name=prefix + 'ymap_sp',\n output_name=prefix + 'raw_rel_wh_sp')\n\n # (1, 2, B, S*S)\n builder.add_unary(name=prefix + 'rel_wh_sp',\n mode='exp',\n input_name=prefix + 'raw_rel_wh_sp',\n output_name=prefix + 'rel_wh_sp')\n\n # (1, 2*B, S, S)\n builder.add_reshape(name=prefix + 'rel_wh',\n target_shape=[batch_size, 2 * num_anchors] + list(self._grid_shape),\n mode=0,\n input_name=prefix + 'rel_wh_sp',\n output_name=prefix + 'rel_wh')\n\n np_anchors = _np.asarray(self.anchors, dtype=_np.float32).T\n anchors_0 = _np.tile(np_anchors.reshape([2 * num_anchors, 1, 1]), self._grid_shape)\n\n # (1, 2*B, S, S)\n builder.add_load_constant(name=prefix + 'c_anchors',\n constant_value=anchors_0,\n shape=anchors_0.shape,\n output_name=prefix + 'c_anchors')\n\n # (1, 2*B, S, S)\n builder.add_elementwise(name=prefix + 'wh_pre',\n mode='MULTIPLY',\n input_names=[prefix + 'c_anchors', prefix + 'rel_wh'],\n output_name=prefix + 'wh_pre')\n\n # (1, 2, B*H*W, 1)\n builder.add_reshape(name=prefix + 'wh',\n target_shape=[1, 2, num_bounding_boxes, 1],\n mode=0,\n input_name=prefix + 'wh_pre',\n output_name=prefix + 'wh')\n\n # (1, 4, B*H*W, 1)\n builder.add_elementwise(name=prefix + 'boxes_out_transposed',\n mode='CONCAT',\n input_names=[prefix + 'xy', prefix + 'wh'],\n output_name=prefix + 'boxes_out_transposed')\n\n # (1, B*H*W, 4, 1)\n builder.add_permute(name=prefix + 'boxes_out',\n dim=[0, 2, 1, 3],\n input_name=prefix + 'boxes_out_transposed',\n output_name=prefix + 'boxes_out')\n\n scale = _np.zeros((num_bounding_boxes, 4, 1))\n scale[:, 0::2] = 1.0 / self._grid_shape[1]\n scale[:, 1::2] = 1.0 / self._grid_shape[0]\n\n # (1, B*H*W, 4, 1)\n builder.add_scale(name=COORDINATES_STR,\n W=scale,\n b=0,\n has_bias=False,\n shape_scale=(num_bounding_boxes, 4, 1),\n input_name=prefix + 'boxes_out',\n output_name=COORDINATES_STR)\n\n # CLASS PROBABILITIES AND OBJECT CONFIDENCE\n\n # (1, C, B, H*W)\n builder.add_slice(name=prefix + 'scores_sp',\n axis='channel',\n start_index=5,\n end_index=preds_per_box,\n stride=1,\n input_name=prefix + 'ymap_sp',\n output_name=prefix + 'scores_sp')\n\n # (1, C, B, H*W)\n builder.add_softmax(name=prefix + 'probs_sp',\n input_name=prefix + 'scores_sp',\n output_name=prefix + 'probs_sp')\n\n # (1, 1, B, H*W)\n builder.add_slice(name=prefix + 'logit_conf_sp',\n axis='channel',\n start_index=4,\n end_index=5,\n stride=1,\n input_name=prefix + 'ymap_sp',\n output_name=prefix + 'logit_conf_sp')\n\n # (1, 1, B, H*W)\n builder.add_activation(name=prefix + 'conf_sp',\n non_linearity='SIGMOID',\n input_name=prefix + 'logit_conf_sp',\n output_name=prefix + 'conf_sp')\n\n # (1, C, B, H*W)\n if num_classes > 1:\n conf = prefix + 'conf_tiled_sp'\n builder.add_elementwise(name=prefix + 'conf_tiled_sp',\n mode='CONCAT',\n input_names=[prefix+'conf_sp']*num_classes,\n output_name=conf)\n else:\n conf = prefix + 'conf_sp'\n\n # (1, C, B, H*W)\n builder.add_elementwise(name=prefix + 'confprobs_sp',\n mode='MULTIPLY',\n input_names=[conf, prefix + 'probs_sp'],\n output_name=prefix + 'confprobs_sp')\n\n # (1, C, B*H*W, 1)\n builder.add_reshape(name=prefix + 'confprobs_transposed',\n target_shape=[1, num_classes, num_bounding_boxes, 1],\n mode=0,\n input_name=prefix + 'confprobs_sp',\n output_name=prefix + 'confprobs_transposed')\n\n # (1, B*H*W, C, 1)\n builder.add_permute(name=CONFIDENCE_STR,\n dim=[0, 2, 1, 3],\n input_name=prefix + 'confprobs_transposed',\n output_name=CONFIDENCE_STR)\n\n _mxnet_converter._set_input_output_layers(\n builder, input_names, output_names)\n builder.set_input(input_names, input_dims)\n builder.set_output(output_names, output_dims)\n builder.set_pre_processing_parameters(image_input_names=self.feature)\n model = builder.spec\n\n if include_non_maximum_suppression:\n # Non-Maximum Suppression is a post-processing algorithm\n # responsible for merging all detections that belong to the\n # same object.\n # Core ML schematic\n # +------------------------------------+\n # | Pipeline |\n # | |\n # | +------------+ +-------------+ |\n # | | Neural | | Non-maximum | |\n # | | network +---> suppression +-----> confidences\n # Image +----> | | | |\n # | | +---> +-----> coordinates\n # | | | | | |\n # Optional inputs: | +------------+ +-^---^-------+ |\n # | | | |\n # IOU threshold +-----------------------+ | |\n # | | |\n # Confidence threshold +---------------------------+ |\n # +------------------------------------+\n\n model_neural_network = model.neuralNetwork\n model.specificationVersion = 3\n model.pipeline.ParseFromString(b'')\n model.pipeline.models.add()\n model.pipeline.models[0].neuralNetwork.ParseFromString(b'')\n model.pipeline.models.add()\n model.pipeline.models[1].nonMaximumSuppression.ParseFromString(b'')\n # begin: Neural network model\n nn_model = model.pipeline.models[0]\n\n nn_model.description.ParseFromString(b'')\n input_image = model.description.input[0]\n input_image.type.imageType.width = self.input_image_shape[1]\n input_image.type.imageType.height = self.input_image_shape[2]\n nn_model.description.input.add()\n nn_model.description.input[0].ParseFromString(\n input_image.SerializeToString())\n\n for i in range(2):\n del model.description.output[i].type.multiArrayType.shape[:]\n names = [\"raw_confidence\", \"raw_coordinates\"]\n bounds = [self.num_classes, 4]\n for i in range(2):\n output_i = model.description.output[i]\n output_i.name = names[i]\n for j in range(2):\n ma_type = output_i.type.multiArrayType\n ma_type.shapeRange.sizeRanges.add()\n ma_type.shapeRange.sizeRanges[j].lowerBound = (\n bounds[i] if j == 1 else 0)\n ma_type.shapeRange.sizeRanges[j].upperBound = (\n bounds[i] if j == 1 else -1)\n nn_model.description.output.add()\n nn_model.description.output[i].ParseFromString(\n output_i.SerializeToString())\n\n ma_type = nn_model.description.output[i].type.multiArrayType\n ma_type.shape.append(num_bounding_boxes)\n ma_type.shape.append(bounds[i])\n\n # Think more about this line\n nn_model.neuralNetwork.ParseFromString(\n model_neural_network.SerializeToString())\n nn_model.specificationVersion = model.specificationVersion\n # end: Neural network model\n\n # begin: Non maximum suppression model\n nms_model = model.pipeline.models[1]\n nms_model_nonMaxSup = nms_model.nonMaximumSuppression\n\n for i in range(2):\n output_i = model.description.output[i]\n nms_model.description.input.add()\n nms_model.description.input[i].ParseFromString(\n output_i.SerializeToString())\n\n nms_model.description.output.add()\n nms_model.description.output[i].ParseFromString(\n output_i.SerializeToString())\n nms_model.description.output[i].name = (\n 'confidence' if i==0 else 'coordinates')\n\n nms_model_nonMaxSup.iouThreshold = iou_threshold\n nms_model_nonMaxSup.confidenceThreshold = confidence_threshold\n nms_model_nonMaxSup.confidenceInputFeatureName = 'raw_confidence'\n nms_model_nonMaxSup.coordinatesInputFeatureName = 'raw_coordinates'\n nms_model_nonMaxSup.confidenceOutputFeatureName = 'confidence'\n nms_model_nonMaxSup.coordinatesOutputFeatureName = 'coordinates'\n nms_model.specificationVersion = model.specificationVersion\n nms_model_nonMaxSup.stringClassLabels.vector.extend(self.classes)\n\n for i in range(2):\n nms_model.description.input[i].ParseFromString(\n nn_model.description.output[i].SerializeToString()\n )\n\n if include_non_maximum_suppression:\n # Iou Threshold\n IOU_THRESHOLD_STRING = 'iouThreshold'\n model.description.input.add()\n model.description.input[1].type.doubleType.ParseFromString(b'')\n model.description.input[1].name = IOU_THRESHOLD_STRING\n nms_model.description.input.add()\n nms_model.description.input[2].ParseFromString(\n model.description.input[1].SerializeToString()\n )\n nms_model_nonMaxSup.iouThresholdInputFeatureName = IOU_THRESHOLD_STRING\n\n # Confidence Threshold\n CONFIDENCE_THRESHOLD_STRING = 'confidenceThreshold'\n model.description.input.add()\n model.description.input[2].type.doubleType.ParseFromString(b'')\n model.description.input[2].name = CONFIDENCE_THRESHOLD_STRING\n\n nms_model.description.input.add()\n nms_model.description.input[3].ParseFromString(\n model.description.input[2].SerializeToString())\n\n nms_model_nonMaxSup.confidenceThresholdInputFeatureName = \\\n CONFIDENCE_THRESHOLD_STRING\n\n # end: Non maximum suppression model\n model.description.output[0].name = 'confidence'\n model.description.output[1].name = 'coordinates'\n\n iouThresholdString = '(optional) IOU Threshold override (default: {})'\n confidenceThresholdString = ('(optional)' +\n ' Confidence Threshold override (default: {})')\n model_type = 'object detector (%s)' % self.model\n if include_non_maximum_suppression:\n model_type += ' with non-maximum suppression'\n model.description.metadata.shortDescription = \\\n _coreml_utils._mlmodel_short_description(model_type)\n model.description.input[0].shortDescription = 'Input image'\n if include_non_maximum_suppression:\n iouThresholdString = '(optional) IOU Threshold override (default: {})'\n model.description.input[1].shortDescription = \\\n iouThresholdString.format(iou_threshold)\n confidenceThresholdString = ('(optional)' +\n ' Confidence Threshold override (default: {})')\n model.description.input[2].shortDescription = \\\n confidenceThresholdString.format(confidence_threshold)\n model.description.output[0].shortDescription = \\\n u'Boxes \\xd7 Class confidence (see user-defined metadata \"classes\")'\n model.description.output[1].shortDescription = \\\n u'Boxes \\xd7 [x, y, width, height] (relative to image size)'\n version = ObjectDetector._PYTHON_OBJECT_DETECTOR_VERSION\n partial_user_defined_metadata = {\n 'model': self.model,\n 'max_iterations': str(self.max_iterations),\n 'training_iterations': str(self.training_iterations),\n 'include_non_maximum_suppression': str(\n include_non_maximum_suppression),\n 'non_maximum_suppression_threshold': str(\n iou_threshold),\n 'confidence_threshold': str(confidence_threshold),\n 'iou_threshold': str(iou_threshold),\n 'feature': self.feature,\n 'annotations': self.annotations,\n 'classes': ','.join(self.classes)\n }\n user_defined_metadata = _coreml_utils._get_model_metadata(\n self.__class__.__name__,\n partial_user_defined_metadata,\n version)\n model.description.metadata.userDefined.update(user_defined_metadata)\n return model\n\n def export_coreml(self, filename,\n include_non_maximum_suppression = True,\n iou_threshold = None,\n confidence_threshold = None):\n \"\"\"\n Save the model in Core ML format. The Core ML model takes an image of\n fixed size as input and produces two output arrays: `confidence` and\n `coordinates`.\n\n The first one, `confidence` is an `N`-by-`C` array, where `N` is the\n number of instances predicted and `C` is the number of classes. The\n number `N` is fixed and will include many low-confidence predictions.\n The instances are not sorted by confidence, so the first one will\n generally not have the highest confidence (unlike in `predict`). Also\n unlike the `predict` function, the instances have not undergone\n what is called `non-maximum suppression`, which means there could be\n several instances close in location and size that have all discovered\n the same object instance. Confidences do not need to sum to 1 over the\n classes; any remaining probability is implied as confidence there is no\n object instance present at all at the given coordinates. The classes\n appear in the array alphabetically sorted.\n\n The second array `coordinates` is of size `N`-by-4, where the first\n dimension `N` again represents instances and corresponds to the\n `confidence` array. The second dimension represents `x`, `y`, `width`,\n `height`, in that order. The values are represented in relative\n coordinates, so (0.5, 0.5) represents the center of the image and (1,\n 1) the bottom right corner. You will need to multiply the relative\n values with the original image size before you resized it to the fixed\n input size to get pixel-value coordinates similar to `predict`.\n\n See Also\n --------\n save\n\n Parameters\n ----------\n filename : string\n The path of the file where we want to save the Core ML model.\n\n include_non_maximum_suppression : bool\n Non-maximum suppression is only available in iOS 12+.\n A boolean parameter to indicate whether the Core ML model should be\n saved with built-in non-maximum suppression or not.\n This parameter is set to True by default.\n\n iou_threshold : float\n Threshold value for non-maximum suppression. Non-maximum suppression\n prevents multiple bounding boxes appearing over a single object.\n This threshold, set between 0 and 1, controls how aggressive this\n suppression is. A value of 1 means no maximum suppression will\n occur, while a value of 0 will maximally suppress neighboring\n boxes around a prediction.\n\n confidence_threshold : float\n Only return predictions above this level of confidence. The\n threshold can range from 0 to 1.\n\n Examples\n --------\n >>> model.export_coreml('detector.mlmodel')\n \"\"\"\n from coremltools.models.utils import save_spec as _save_spec\n model = self._create_coreml_model(include_non_maximum_suppression=include_non_maximum_suppression,\n iou_threshold=iou_threshold, confidence_threshold=confidence_threshold)\n _save_spec(model, filename)"
]
| [
[
"numpy.concatenate",
"numpy.array",
"numpy.asarray",
"numpy.zeros",
"numpy.copy",
"numpy.tile",
"numpy.arange",
"numpy.sqrt",
"numpy.clip"
]
]
|
SaraLatif99/car-classification | [
"27b017e9cba66935c0f715d5584cfd7fe7bd4653",
"27b017e9cba66935c0f715d5584cfd7fe7bd4653"
]
| [
"car_classifier/copy_images_for_prefilter.py",
"car_classifier/quiz.py"
]
| [
"\"\"\"\nOnly for model case, else top 300 makes no sense for classes\n\"\"\"\n\nimport os\nfrom shutil import copy2\nimport pandas as pd\n\nIMAGE_DIR = 'data/car-classifier-raw/' # Directory images are stored in\nSTORAGE_DIR = 'data/' # Directory to store split images\n\n# Load prediction file created using notebook \"prefilter.ipynb\" in notebooks\ndf = pd.read_csv('data/filenames_with_car_flags_bw_added.csv', header=None, index_col=0, squeeze=True)\n\n# List to store filenames of car images\ncar_images = []\n\n# List to store filenames of non-car images\nnon_car_images = []\n\nfor file, car_flag in df.items():\n if car_flag:\n car_images.append(file)\n else:\n non_car_images.append(file)\n\n\nprint(len(car_images), len(non_car_images))\n\n\n# Filter out classes with too few representatives (only for model)\ndef get_class_counts(files):\n \"\"\"\n Get class label count from file paths\n \"\"\"\n return pd.Series(['_'.join([file.split('_')[0], file.split('_')[1]]) for file in files]).value_counts()\n\n\nto_filter = get_class_counts(car_images)[300:].keys()\n\nfiles_filtered = [file for file in car_images if '_'.join([file.split('_')[0], file.split('_')[1]]) not in to_filter]\n\nassert(len(car_images) - get_class_counts(car_images)[300:].sum() == len(files_filtered))\n\ncar_images = files_filtered\n\nprint(len(car_images))\n\nstorage_dir_ext = STORAGE_DIR\n\nos.mkdir(storage_dir_ext + 'cars')\n# os.mkdir(storage_dir_ext + 'non_cars')\n\nfor filename in car_images:\n copy2(IMAGE_DIR + filename, storage_dir_ext + 'cars')\n\n# for filename in non_car_images:\n# copy2(IMAGE_DIR + filename, storage_dir_ext + 'non_cars')\n",
"import inquirer\nimport os\nimport pickle\nimport numpy as np\n\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.keras.preprocessing import image\nfrom random import sample\n\n\n# Global settings\nINPUT_DATA_DIR = 'data/raw_filtered/'\nINPUT_SHAPE = (224, 224, 3)\nTARGET = 'make'\n\n# All available training images\nfiles = [file for file in os.listdir(INPUT_DATA_DIR) if file.endswith(\".jpg\")]\nfile_paths = [INPUT_DATA_DIR + file for file in files]\n\n# Create a list of all possible outcomes\nif TARGET == 'make':\n classes = list(set([file.split('_')[0] for file in files]))\nif TARGET == 'model':\n classes = list(set([file.split('_')[0] + '_' + file.split('_')[1] for file in files]))\n\nfile = open('models/classes_all_filtered.pkl', 'rb')\nclasses = pickle.load(file)\n\n# Load trained model\nmodel = tf.keras.models.load_model('models/resnet_unfreeze_all_filtered.tf')\n\n\ndef quiz():\n \"\"\"\n Interactive challenge of human (manual input) vs. model\n\n Returns:\n No return\n \"\"\"\n\n while True:\n\n # Get file\n path = sample(file_paths, 1)[0]\n\n # Get label\n parts = path.split('/')[-1]\n label = parts.split('_')[0]\n\n # Prepare image\n img = image.load_img(path, target_size=(224, 224))\n img = image.img_to_array(img)\n img /= 255.0\n\n # Show image\n plt.figure()\n plt.imshow(img)\n plt.axis('off')\n plt.show()\n\n # Get user input\n questions = [\n inquirer.List('make',\n message=\"What car make is it?\",\n choices=classes,\n ),\n ]\n answer = inquirer.prompt(questions)\n\n # Model prediction\n img = img.reshape(-1, *img.shape)\n p = model.predict(img)\n y_hat_idx = np.argmax(p)\n y_hat = classes[y_hat_idx]\n\n # Outputs\n print(f'Your choice: {answer}')\n print(f'Model prediction: {y_hat} (with {round(np.max(p)*100, 1)}%)')\n print(f'Correct label: {label}')\n\n\nif __name__ == '__main__':\n quiz()\n"
]
| [
[
"pandas.read_csv"
],
[
"numpy.max",
"tensorflow.keras.preprocessing.image.load_img",
"matplotlib.pyplot.figure",
"tensorflow.keras.models.load_model",
"tensorflow.keras.preprocessing.image.img_to_array",
"numpy.argmax",
"matplotlib.pyplot.show",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.imshow"
]
]
|
vsokhatskyi/catalyst | [
"8516b9d44546600ad597a1fffdf03b7eb23c5e98"
]
| [
"catalyst/contrib/models/sequential.py"
]
| [
"from typing import Dict, List, Union # isort:skip\nfrom collections import OrderedDict\nfrom copy import deepcopy\n\nimport torch\nimport torch.nn as nn\n\nfrom catalyst import utils\nfrom catalyst.contrib.registry import MODULES\n\n\ndef _process_additional_params(params, layers):\n if isinstance(params, List):\n assert len(params) == len(layers)\n else:\n params = [params] * len(layers)\n return params\n\n\nclass ResidualWrapper(nn.Module):\n def __init__(self, net):\n super().__init__()\n self.net = net\n\n def forward(self, x):\n return x + self.net(x)\n\n\nclass SequentialNet(nn.Module):\n def __init__(\n self,\n hiddens,\n layer_fn: Union[str, Dict, List],\n norm_fn: Union[str, Dict, List] = None,\n dropout_fn: Union[str, Dict, List] = None,\n activation_fn: Union[str, Dict, List] = None,\n residual: Union[bool, str] = False,\n layer_order: List = None,\n ):\n\n super().__init__()\n assert len(hiddens) > 1, \"No sequence found\"\n\n # layer params\n layer_fn = _process_additional_params(layer_fn, hiddens[1:])\n # normalization params\n norm_fn = _process_additional_params(norm_fn, hiddens[1:])\n # dropout params\n dropout_fn = _process_additional_params(dropout_fn, hiddens[1:])\n # activation params\n activation_fn = _process_additional_params(activation_fn, hiddens[1:])\n\n if isinstance(residual, bool) and residual:\n residual = \"hard\"\n residual = _process_additional_params(residual, hiddens[1:])\n\n layer_order = layer_order or [\"layer\", \"norm\", \"drop\", \"act\"]\n\n def _layer_fn(layer_fn, f_in, f_out, **kwargs):\n layer_fn = MODULES.get_if_str(layer_fn)\n layer_fn = layer_fn(f_in, f_out, **kwargs)\n return layer_fn\n\n def _normalization_fn(normalization_fn, f_in, f_out, **kwargs):\n normalization_fn = MODULES.get_if_str(normalization_fn)\n normalization_fn = \\\n normalization_fn(f_out, **kwargs) \\\n if normalization_fn is not None \\\n else None\n return normalization_fn\n\n def _dropout_fn(dropout_fn, f_in, f_out, **kwargs):\n dropout_fn = MODULES.get_if_str(dropout_fn)\n dropout_fn = dropout_fn(**kwargs) \\\n if dropout_fn is not None \\\n else None\n return dropout_fn\n\n def _activation_fn(activation_fn, f_in, f_out, **kwargs):\n activation_fn = MODULES.get_if_str(activation_fn)\n activation_fn = activation_fn(**kwargs) \\\n if activation_fn is not None \\\n else None\n return activation_fn\n\n name2fn = {\n \"layer\": _layer_fn,\n \"norm\": _normalization_fn,\n \"drop\": _dropout_fn,\n \"act\": _activation_fn,\n }\n name2params = {\n \"layer\": layer_fn,\n \"norm\": norm_fn,\n \"drop\": dropout_fn,\n \"act\": activation_fn,\n }\n\n net = []\n for i, (f_in, f_out) in enumerate(utils.pairwise(hiddens)):\n block = []\n for key in layer_order:\n sub_fn = name2fn[key]\n sub_params = deepcopy(name2params[key][i])\n\n if isinstance(sub_params, Dict):\n sub_module = sub_params.pop(\"module\")\n else:\n sub_module = sub_params\n sub_params = {}\n\n sub_block = sub_fn(sub_module, f_in, f_out, **sub_params)\n if sub_block is not None:\n block.append((f\"{key}\", sub_block))\n\n block_ = OrderedDict(block)\n block = torch.nn.Sequential(block_)\n\n if block_.get(\"act\", None) is not None:\n activation = block_[\"act\"]\n activation_init = \\\n utils.get_optimal_inner_init(nonlinearity=activation)\n block.apply(activation_init)\n\n if residual == \"hard\" or (residual == \"soft\" and f_in == f_out):\n block = ResidualWrapper(net=block)\n net.append((f\"block_{i}\", block))\n\n self.net = torch.nn.Sequential(OrderedDict(net))\n\n def forward(self, x):\n x = self.net.forward(x)\n return x\n\n\n__all__ = [\"ResidualWrapper\", \"SequentialNet\"]\n"
]
| [
[
"torch.nn.Sequential"
]
]
|
caishenghang/oneflow | [
"db239cc9f98e551823bf6ce2d4395bd5c339b1c5"
]
| [
"oneflow/python/test/ops/test_non_distribute_optimizer.py"
]
| [
"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport unittest\nimport numpy as np\nimport oneflow as flow\nimport oneflow.typing as oft\n\n\ndef _test_two_job_non_distribute_optimizer(test_case):\n flow.config.gpu_device_num(2)\n flow.config.enable_debug_mode(True)\n eval_config = flow.FunctionConfig()\n eval_config.default_logical_view(flow.scope.consistent_view())\n\n @flow.global_function(eval_config)\n def Bar():\n w = flow.get_variable(\"w\", (10,), initializer=flow.constant_initializer(100))\n return w\n\n func_config = flow.FunctionConfig()\n func_config.default_logical_view(flow.scope.consistent_view())\n func_config.enable_non_distributed_optimizer(True)\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def Foo(x: oft.Numpy.Placeholder((2, 10))):\n w = flow.get_variable(\"w\", (10,), initializer=flow.constant_initializer(100))\n flow.optimizer.SGD(\n flow.optimizer.PiecewiseConstantScheduler([], [5]), momentum=0\n ).minimize(x + w)\n\n Foo(np.ones((2, 10), dtype=np.float32))\n\n\ndef _test_non_distribute_optimizer_var_as_loss(test_case):\n flow.config.gpu_device_num(2)\n flow.config.enable_debug_mode(True)\n func_config = flow.FunctionConfig()\n func_config.default_logical_view(flow.scope.consistent_view())\n func_config.enable_non_distributed_optimizer(True)\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def Foo():\n w = flow.get_variable(\"w\", (10,), initializer=flow.constant_initializer(100))\n flow.optimizer.SGD(\n flow.optimizer.PiecewiseConstantScheduler([], [5]), momentum=0\n ).minimize(w)\n\n Foo()\n\n\[email protected]_unless_1n2d()\nclass TestNonDistributeOptimizer(flow.unittest.TestCase):\n def test_non_distribute_optimizer(test_case):\n flow.config.gpu_device_num(2)\n flow.config.enable_debug_mode(True)\n func_config = flow.FunctionConfig()\n func_config.default_logical_view(flow.scope.consistent_view())\n func_config.enable_non_distributed_optimizer(True)\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def Foo(x: oft.Numpy.Placeholder((2, 10))):\n w = flow.get_variable(\n \"w\", (10,), initializer=flow.constant_initializer(100)\n )\n flow.optimizer.SGD(\n flow.optimizer.PiecewiseConstantScheduler([], [5]), momentum=0\n ).minimize(x + w)\n\n Foo(np.ones((2, 10), dtype=np.float32))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
]
| [
[
"numpy.ones"
]
]
|
Taiji-pipeline/Taiji-utils | [
"f5e009cf7a9a683f7e43bf97fb33c758ba13d97b"
]
| [
"python/taiji-utils/taiji_utils/Normalization.py"
]
| [
"import numpy as np\nfrom statsmodels.nonparametric.kernel_regression import KernelReg\n\nfrom .Utils import readMatrix\n\ndef fitSmooth(X, Y, newX, output=None):\n X = X[..., np.newaxis]\n if output is not None:\n import matplotlib.pyplot as plt\n plt.figure()\n X_plot = np.linspace(np.min(X), np.max(X), 10000)[:, None]\n y_, _ = KernelReg(Y, X, 'c').fit(X_plot)\n plt.scatter(X, Y, c='k', label='data', zorder=1,\n edgecolors=(0, 0, 0))\n plt.plot(X_plot, y_, c='r', label='fit')\n plt.xlabel('log(gene mean)')\n plt.ylabel('parameter')\n plt.legend()\n plt.savefig(output)\n plt.close()\n return KernelReg(Y, X, 'c').fit(newX)[0]\n\n'''\nY: numpy array, rows are samples, columns are genes \nX: numpy array, columns are covariates, rows are samples.\n'''\ndef fitNB2(X, Y):\n from rpy2.robjects.packages import importr\n import rpy2.robjects as robjects\n from rpy2.robjects import numpy2ri\n numpy2ri.activate()\n\n glmGamPoi = importr('glmGamPoi')\n robjects.r('''\n fit_glmGamPoi <- function(X, Y) {\n fit <- glmGamPoi::glm_gp(data = t(Y),\n design = ~ .,\n col_data = as.data.frame(X),\n size_factors = FALSE)\n fit$theta <- pmin(1 / fit$overdispersions, rowMeans(fit$Mu) / 1e-4)\n colnames(fit$Beta)[match(x = 'Intercept', colnames(fit$Beta))] <- \"(Intercept)\"\n return(cbind(fit$Beta, fit$theta))\n }\n ''')\n\n rfit = robjects.r['fit_glmGamPoi']\n res = np.array(rfit(X, Y))\n numpy2ri.deactivate()\n return(res)\n\ndef sctransform(cellxgene, cell_reads, log_gene_mean, new_data, dir):\n params = fitNB2(cell_reads, cellxgene.todense())\n beta0 = fitSmooth(log_gene_mean, params[:, 0], new_data[:, None], output=dir + \"/beta0.png\")\n beta1 = fitSmooth(log_gene_mean, params[:, 1], new_data[:, None], output=dir + \"/beta1.png\") \n\n theta_proxy = np.log10(1 + 10**log_gene_mean / params[:, 2])\n \n # variance of NB is mu * (1 + mu / theta)\n # (1 + mu / theta) is what we call overdispersion factor here\n od_factor = fitSmooth(log_gene_mean, theta_proxy, new_data[:, None], output=dir + \"/theta.png\")\n theta = 10**new_data / (10**od_factor - 1)\n\n return(np.array([beta0, beta1, 1 / theta]))\n\ndef normalize(args):\n np.random.seed(0) \n inputMat = readMatrix(args.input)\n\n with open(args.genemean, 'r') as fl:\n geneMean = np.array([float(l.strip()) for l in fl])\n with open(args.cellreads, 'r') as fl:\n cellReads = np.array([float(l.strip()) for l in fl])\n with open(args.data, 'r') as fl:\n data = np.array([float(l.strip()) for l in fl])\n np.savetxt(args.output, sctransform(inputMat, cellReads, geneMean, data, args.plot_dir))"
]
| [
[
"numpy.max",
"numpy.array",
"numpy.random.seed",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.close",
"numpy.min",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.scatter",
"numpy.log10"
]
]
|
shiningliang/Multi-level-Causality-Detection-Network | [
"126a11735781224aaa31af37728e6dd0b2e511c2"
]
| [
"utils/figure_analyze.py"
]
| [
"import seaborn as sns\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nsns.set_context(context=\"talk\")\nplt.switch_backend('agg')\n\nresults = pd.read_csv(\"analysis.csv\")\n\nplt.rcParams[\"font.family\"] = \"Times New Roman\"\nfig, axes = plt.subplots(nrows=2, ncols=2, figsize=(20, 10))\nsns.set(style=\"whitegrid\", font=\"Times New Roman\")\nplt.subplots_adjust(wspace=0.25, hspace=0.25)\nc0 = sns.barplot(x=results[\"train_freq\"][:10].tolist(), y=results[\"train_word\"][:10].tolist(), ax=axes[0, 0])\nc0.set_xlabel(\"(a) Train\")\nc1 = sns.barplot(x=results[\"test_freq\"][:10].tolist(), y=results[\"test_word\"][:10].tolist(), ax=axes[0, 1])\nc1.set_xlabel(\"(b) Test\")\nc2 = sns.barplot(x=results[\"fn_freq\"][:10].tolist(), y=results[\"fn_word\"][:10].tolist(), ax=axes[1, 0])\nc2.set_xlabel(\"(c) FN\")\nc2.set(xlim=(0, 12))\nc3 = sns.barplot(x=results[\"fp_freq\"][:10].tolist(), y=results[\"fp_word\"][:10].tolist(), ax=axes[1, 1])\nc3.set_xlabel(\"(d) FP\")\nc3.set(xlim=(0, 12))\nc0.figure.savefig(\"word_freq.eps\", dpi=400)\n"
]
| [
[
"matplotlib.pyplot.switch_backend",
"pandas.read_csv",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.subplots"
]
]
|
ethinallen/campus_simulation | [
"414ec93bcf6d671971f33be97aa6b53d36b808cb"
]
| [
"scripts/campus.py"
]
| [
"import numpy as np\nfrom building import building\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport time\nimport dateutil.parser\nfrom dateutil.parser import parse\nimport os\n\nimport meerschaum as mrsm\n\nclass campus:\n\n # initialize the sensor based on type and set age to 0\n def __init__(self, numRows, *attrs):\n\n self.df = pd.DataFrame()\n self.buildings = { }\n\n self.entries = { }\n self.metrics = {\n 'power' : [],\n 'temperature' : []\n }\n\n if attrs:\n for buildingID in attrs[0]['buildings']:\n building_attributes = {'id': buildingID, 'info' : attrs[0]['buildings'][buildingID]}\n self.buildings[buildingID] = building(np.int64(buildingID), numRows, building_attributes)\n self.entries[buildingID] = []\n\n else:\n # num_buildings = np.random.poisson(10, 1)[0]\n num_buildings = 5\n\n self.makeBuildings(num_buildings, numRows)\n\n def introduce(self):\n for buildingID in self.buildings:\n building = self.buildings[buildingID]\n print('BUILDING ID:\\t{}'.format(building.id))\n for roomID in building.rooms:\n room = building.rooms[roomID]\n print('ROOM ID:\\t{}'.format(room.id))\n for sensorID in room.sensors:\n sensor = room.sensors[sensorID]\n print('ROOM ID:\\t{}'.format(sensor.id))\n\n # instantiate buildings\n def makeBuildings(self, num_buildings, numRows):\n for i in range(num_buildings):\n self.buildings[i] = building(i, numRows)\n self.entries[i] = []\n\n # age every building 1 unit of time\n def getOlder(self, row, index):\n for building in self.buildings:\n building_object = self.buildings[building]\n\n reading = building_object.generate_power_consumption(row['AEP_MW'], index)\n\n epoch_time = time.mktime(datetime.datetime.strptime(row['datetime'], \"%Y-%m-%d %H:%M:%S\").timetuple())\n entry = [np.int64(epoch_time), np.int64(building_object.id), np.int64(reading)]\n\n self.metrics['power'].append(entry)\n\n for room in building_object.rooms:\n room_object = building_object.rooms[room]\n for i, sensor in enumerate(room_object.sensors):\n sensor_object = room_object.sensors[sensor]\n deviation = sensor_object.getOlder(index)\n entry = [np.int64(epoch_time), np.int64(building_object.id), np.int64(room_object.id), int(sensor_object.id), np.int64(deviation)]\n self.metrics['temperature'].append(entry)\n\n for corridor in building_object.corridors:\n corridor_object = building_object.corridors[corridor]\n for i, sensor in enumerate(corridor_object.sensors):\n sensor_object = corridor_object.sensors[sensor]\n\n deviation = sensor_object.getOlder(index)\n entry = [np.int64(epoch_time), np.int64(building_object.id), np.int64(corridor_object.id), np.int64(sensor_object.id), np.int64(deviation)]\n self.metrics['temperature'].append(entry)\n\n def makePipe(self):\n pipe = mrsm.Pipe('sim', 'power', str(building))\n pipe.parameters = {\n 'columns' : {\n 'datetime' : 'epochTime',\n 'id' : 'sensorid'\n }\n }\n\n pipe.register(debug=True)\n return pipe\n\n '''\n def writeDB(self):\n - write power from building\n - write every sensor output\n '''\n\nif __name__ == '__main__':\n c = campus()\n c.makePipe()\n"
]
| [
[
"pandas.DataFrame",
"numpy.int64"
]
]
|
ksk0014/tensorflow | [
"6732ac1789d1b4b29de5f83ee58e6e69e26cf095"
]
| [
"tensorflow/python/eager/function.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# pylint: disable=unidiomatic-typecheck\n\"\"\"Defun decorator for defining graph-mode functions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport functools\nimport itertools\nimport threading\nimport types as types_lib\nimport weakref\n\nimport numpy as np\nimport six\nfrom six.moves import map\n\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.core.framework import function_pb2\nfrom tensorflow.python import pywrap_tensorflow\nfrom tensorflow.python import _pywrap_utils\nfrom tensorflow.python.compat import compat as fwd_compat\nfrom tensorflow.python.eager import backprop\nfrom tensorflow.python.eager import backprop_util\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import execute\nfrom tensorflow.python.eager import forwardprop_util\nfrom tensorflow.python.eager import tape\nfrom tensorflow.python.eager.graph_only_ops import graph_placeholder\nfrom tensorflow.python.framework import c_api_util\nfrom tensorflow.python.framework import composite_tensor\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import device as pydev\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import error_interpolation\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import func_graph as func_graph_module\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import custom_gradient\nfrom tensorflow.python.ops import default_gradient\nfrom tensorflow.python.ops import functional_ops\nfrom tensorflow.python.ops import gradients_util\nfrom tensorflow.python.ops import resource_variable_ops\n\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util import compat\nfrom tensorflow.python.util import function_utils\nfrom tensorflow.python.util import lazy_loader\nfrom tensorflow.python.util import memory\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util import object_identity\nfrom tensorflow.python.util import tf_decorator\nfrom tensorflow.python.util import tf_inspect\n\n# Loaded lazily due to a circular dependency (roughly\n# tf.function->autograph->->dataset->tf.function).\n# TODO(b/133251390): Use a regular import.\nag_ctx = lazy_loader.LazyLoader(\n \"ag_ctx\", globals(),\n \"tensorflow.python.autograph.core.ag_ctx\")\n\n\nFORWARD_FUNCTION_ATTRIBUTE_NAME = \"forward_function_name\"\nBACKWARD_FUNCTION_ATTRIBUTE_NAME = \"backward_function_name\"\nIMPLEMENTS_ATTRIBUTE_NAME = \"_implements\"\n\n\ndef _make_input_signature_hashable(elem, variable_map=None):\n \"\"\"Rewrite input signature to be hashable.\n\n We replace nested variables in the input signature with TensorSpec in order to\n be hashable.\n\n Args:\n elem: Input signature element\n variable_map: Internal argument used for tracking variable aliases\n\n Returns:\n A hashable object for the requested input signature\n \"\"\"\n if variable_map is None:\n variable_map = {}\n\n # TODO(slebedev): consider using nest.\n if isinstance(elem, tuple):\n return tuple(map(lambda e: _make_input_signature_hashable(e, variable_map),\n elem))\n\n # If the element is not hashable, assume it is a weakref to a variable\n # and return the dtype & shape. Else, simply return the element\n try:\n hash(elem)\n except TypeError:\n assert isinstance(elem, weakref.ReferenceType)\n v = elem()\n idx = variable_map.get(id(v))\n if idx is None:\n idx = len(variable_map)\n variable_map[id(v)] = idx\n\n # We include the class name to avoid having different types of variables\n # having the same hash. We Also include the variable index which allows\n # us to return a different hash if variables have been aliased in a call.\n return v.__class__, tensor_spec.TensorSpec(v.shape, v.dtype), idx\n\n return elem\n\n\nCacheKey = collections.namedtuple(\"CacheKey\", [\n \"input_signature\",\n \"parent_graph\",\n \"device_functions\",\n \"colocation_stack\",\n \"in_cross_replica_context\",\n \"xla_context_id\",\n])\n\n\ndef _flat_shape_list(*params):\n \"\"\"Return a flat list of TensorShapes, one for each tensor[spec] in `*params`.\n\n If `params` contains `CompositeTensors`, then they are expanded to their\n components `Tensors`.\n\n Args:\n *params: Set of nested entries containing Tensors, TensorSpec, and\n non-tensors.\n\n Returns:\n A list of entries containing either `None` or `TensorShape`.\n \"\"\"\n return [\n tensor_shape.TensorShape(x.shape)\n if isinstance(x, (ops.Tensor, tensor_spec.DenseSpec)) else None\n for x in nest.flatten(params, expand_composites=True)\n ]\n\n\ndef _shape_less_specific_than(relaxed, to_check):\n \"\"\"Checks if `relaxed` is less specific than `to_check`.\n\n This is an asymmetric check, unlike `TensorShape.is_compatible_with`. If\n `to_check` has a dimension with an undefined shape, `relaxed` must also have\n an undefined shape for that dimension.\n\n Args:\n relaxed: A `TensorShape` to check against.\n to_check: A second `TensorShape`.\n\n Returns:\n True if `to_check` represents a set of shapes which is a subset of\n `relaxed`'s shapes and False otherwise.\n \"\"\"\n if to_check.dims is not None and relaxed.dims is not None:\n if to_check.rank != relaxed.rank:\n return False\n for check_dim, relaxed_dim in zip(to_check.dims, relaxed.dims):\n if check_dim.value is None and relaxed_dim.value is not None:\n return False\n if not relaxed_dim.is_compatible_with(check_dim):\n return False\n return True\n\n\ndef _compatible_shapes(flat_relaxed, flat_to_check):\n \"\"\"Check if lists of TensorShapes contain compatible shapes.\n\n Checks that each `flat_relaxed` shape covers a superset of the shapes of the\n corresponding `flat_to_check` shape.\n\n Args:\n flat_relaxed: List of TensorShape or None.\n flat_to_check: List of TensorShape or None.\n\n Returns:\n A python bool.\n\n Raises:\n RuntimeError:\n if `len(flat_relaxed) != len(flat_to_check)`.\n RuntimeError:\n if `flat_relaxed[i] is None != flat_to_check[i] is None` for any `i`.\n \"\"\"\n\n if len(flat_relaxed) != len(flat_to_check):\n raise RuntimeError(\"Expected shape lists of identical lengths, but saw: \"\n \"%s and %s\" % (flat_relaxed, flat_to_check))\n def is_compatible(relaxed, to_check):\n \"\"\"Internal help function.\n\n Args:\n relaxed: TensorShape or None.\n to_check: TensorShape or None.\n\n Returns:\n Python bool.\n\n Raises:\n RuntimeError: If `relaxed is None != to_check is None`.\n \"\"\"\n # If both x and y are None, there is no shape to compare. Otherwise check\n # if they are compatible with each other. Either way, both input signatures\n # must have have Tensors in the same entries. If not, raise an assertion\n # error.\n if relaxed is None != to_check is None:\n raise RuntimeError(\n \"Expected signature type matches between flattened input shapes \"\n \"%s and %s; but saw that (%s is None) != (%s is None)\"\n % (flat_relaxed, flat_to_check, relaxed, to_check))\n return relaxed is None or _shape_less_specific_than(relaxed, to_check)\n return all(is_compatible(relaxed, to_check)\n for relaxed, to_check in zip(flat_relaxed, flat_to_check))\n\n\ndef common_shape(x, y):\n \"\"\"Find a `TensorShape` that is compatible with both `x` and `y`.\"\"\"\n if x is None != y is None:\n raise RuntimeError(\n \"Cannot find a common shape when LHS shape is None but RHS shape \"\n \"is not (or vice versa): %s vs. %s\" % (x, y))\n if x is None:\n return None # The associated input was not a Tensor, no shape generated.\n if not isinstance(x, tensor_shape.TensorShape):\n raise TypeError(\"Expected x to be a TensorShape but saw %s\" % (x,))\n if not isinstance(y, tensor_shape.TensorShape):\n raise TypeError(\"Expected y to be a TensorShape but saw %s\" % (y,))\n if x.rank != y.rank or x.rank is None:\n return tensor_shape.TensorShape(None)\n dims = []\n for dim_x, dim_y in zip(x.dims, y.dims):\n if (dim_x != dim_y\n or tensor_shape.dimension_value(dim_x) is None\n or tensor_shape.dimension_value(dim_y) is None):\n dims.append(None)\n else:\n dims.append(tensor_shape.dimension_value(dim_x))\n return tensor_shape.TensorShape(dims)\n\n\ndef is_same_structure(structure1,\n structure2,\n check_values=False):\n \"\"\"Check two structures for equality, optionally of types and of values.\"\"\"\n try:\n nest.assert_same_structure(structure1, structure2, expand_composites=True)\n except (ValueError, TypeError):\n return False\n if check_values:\n flattened1 = nest.flatten(structure1, expand_composites=True)\n flattened2 = nest.flatten(structure2, expand_composites=True)\n # First check the types to avoid AttributeErrors.\n if any(type(f1) != type(f2) for f1, f2 in zip(flattened1, flattened2)):\n return False\n return flattened1 == flattened2\n return True\n\n\ndef _parse_func_attrs(attributes):\n \"\"\"Convert the keyword arguments into function_def attributes.\n\n Currently only support primitive types: bool, int, float and string.\n\n Args:\n attributes: the dictionary of attributes.\n Returns:\n A dict of attributes where the key is the name of attribute and the value\n is the AttrValue proto.\n Raises:\n ValueError: If the kwargs contains unwhitelisted name or unsupported value\n types.\n \"\"\"\n attrs = {}\n for key, value in attributes.items():\n if isinstance(value, attr_value_pb2.AttrValue):\n attrs[key] = value\n # bool type check has to happen before int since bool is a subclass of int.\n elif isinstance(value, bool):\n attrs[key] = attr_value_pb2.AttrValue(b=value)\n elif isinstance(value, int):\n attrs[key] = attr_value_pb2.AttrValue(i=value)\n elif isinstance(value, float):\n attrs[key] = attr_value_pb2.AttrValue(f=value)\n elif isinstance(value, (str, bytes, six.text_type)):\n attrs[key] = attr_value_pb2.AttrValue(s=compat.as_bytes(value))\n else:\n raise ValueError(\"Unsupported attribute type for %s with type %s\" %\n (key, type(value)))\n return attrs\n\n\nclass _InterpolateFunctionError(object):\n \"\"\"Context Manager that interpolates the exception from 'top_level_func'.\"\"\"\n\n def __init__(self, top_level_func):\n self._func = top_level_func\n\n def __enter__(self):\n pass\n\n def __exit__(self, typ, exc, tb):\n if not exc or not isinstance(exc, errors.OpError):\n return False\n message = compat.as_text(exc.message)\n _, tags = error_interpolation.parse_message(message)\n g = None\n func_stack = []\n for t in tags:\n if t.type == \"function_node\":\n # TODO(mdan): Tests should cover this.\n if t.name == compat.as_str(self._func.name):\n g = self._func.graph\n elif g:\n next_func = g._get_function(t.name)\n if next_func is not None and isinstance(next_func,\n _EagerDefinedFunction):\n g = next_func.graph\n if g:\n func_stack.append(g.name)\n else:\n func_stack.append(\"<unknown>\")\n if g:\n message = error_interpolation.interpolate(message, g)\n message += \"\\n\\nFunction call stack:\\n\"\n message += \" -> \".join(func_stack)\n message += \"\\n\"\n exc._message = message # pylint: disable=protected-access\n return False\n\n\ndef _forward_name(n):\n \"\"\"The name of a generated forward defun named n.\"\"\"\n return \"__forward_%s_%s\" % (n, ops.uid())\n\n\ndef _backward_name(n):\n \"\"\"The name of a generated backward defun named n.\"\"\"\n return \"__backward_%s_%s\" % (n, ops.uid())\n\n\ndef _inference_name(n):\n \"\"\"The name of a forward-but-no-gradient defun named n.\"\"\"\n return \"__inference_%s_%s\" % (n, ops.uid())\n\n\ndef _enclosing_xla_context():\n \"\"\"Returns the XLAControlFlowContext, which exists inside a tpu.rewrite().\"\"\"\n graph = ops.get_default_graph()\n while graph is not None:\n # pylint: disable=protected-access\n context_ = graph._get_control_flow_context()\n # pylint: enable=protected-access\n while context_ is not None:\n if isinstance(context_, control_flow_ops.XLAControlFlowContext):\n return context_\n context_ = context_.outer_context\n # This may be a FuncGraph due to defuns or v2 control flow. We need to\n # find the original graph with the XLAControlFlowContext.\n graph = getattr(graph, \"outer_graph\", None)\n return None\n\n\nclass _EagerDefinedFunctionDeleter(object):\n \"\"\"Unregister function from eager context.\"\"\"\n\n def __init__(self, name):\n self.name = name\n\n def __del__(self):\n try:\n context.remove_function(self.name)\n except TypeError:\n # Suppress some exceptions, mainly for the case when we're running on\n # module deletion. Things that can go wrong include the context module\n # already being unloaded, self._handle._handle_data no longer being\n # valid, and so on. Printing warnings in these cases is silly\n # (exceptions raised from __del__ are printed as warnings to stderr).\n pass # 'NoneType' object is not callable when the handle has been\n # partially unloaded.\n except AttributeError:\n pass # 'NoneType' object has no attribute 'eager_mode' when context has\n # been unloaded. Will catch other module unloads as well.\n\n\n# TODO(apassos) get rid of this by splitting framework.function._DefinedFunction\n# so it doesn't have the definition-generating logic and is just a container for\n# an already-defined function.\nclass _EagerDefinedFunction(object):\n \"\"\"Callable with the interface of `framework.function._DefinedFunction`.\n\n `_EagerDefinedFunction` encapsulates a function definition and its properties,\n and it provides a method for calling the encapsulated function. Some Ops\n take functions as attributes, which have type `func`; an instance of this\n class may be provided as the value of these `func` attributes.\n \"\"\"\n\n def __init__(self, name, graph, inputs, outputs, attrs):\n \"\"\"Initializes an eager defined function.\n\n Args:\n name: str, the name for the created function.\n graph: Graph, the graph containing the operations in the function\n inputs: the tensors in the graph to be used as inputs to the function\n outputs: the tensors in the graph which will be outputs to the function\n attrs: dict mapping names of attributes to their AttrValue values\n \"\"\"\n input_ops = set(arg.op for arg in inputs)\n operations = [op for op in graph.get_operations() if op not in input_ops]\n\n graph_output_names = graph._output_names # pylint: disable=protected-access\n if (graph_output_names is not None and\n all(ops.tensor_id(t) in graph_output_names for t in outputs)):\n output_names = [\n compat.as_bytes(graph_output_names[ops.tensor_id(t)]) for t in outputs\n ]\n if len(set(output_names)) != len(output_names):\n # There are duplicate names for some reason, probably an invalid\n # signature. Revert to auto-naming.\n output_names = []\n else:\n output_names = []\n fn = pywrap_tensorflow.TF_GraphToFunction_wrapper(\n graph._c_graph, # pylint: disable=protected-access\n compat.as_str(name),\n False,\n [o._c_op for o in operations], # pylint: disable=protected-access\n [t._as_tf_output() for t in inputs], # pylint: disable=protected-access\n [t._as_tf_output() for t in outputs], # pylint: disable=protected-access\n output_names,\n [o._c_op for o in graph.control_outputs], # pylint: disable=protected-access\n [], # control_output_names\n None,\n compat.as_str(\"\"))\n\n for name, attr_value in attrs.items():\n serialized = attr_value.SerializeToString()\n # TODO(iga): this creates and deletes a new TF_Status for every attr.\n # It might be worth creating a convenient way to re-use status.\n pywrap_tensorflow.TF_FunctionSetAttrValueProto(\n fn, compat.as_str(name), serialized)\n\n # TODO(apassos) avoid creating a FunctionDef (specially to grab the\n # signature, but also in general it's nice not to depend on it.\n with c_api_util.tf_buffer() as buffer_:\n pywrap_tensorflow.TF_FunctionToFunctionDef(fn, buffer_)\n proto_data = pywrap_tensorflow.TF_GetBuffer(buffer_)\n function_def = function_pb2.FunctionDef()\n function_def.ParseFromString(compat.as_bytes(proto_data))\n self.name = compat.as_bytes(function_def.signature.name)\n with ops.init_scope():\n if context.executing_eagerly():\n context.ensure_initialized()\n context.add_function(fn)\n self._function_deleter = _EagerDefinedFunctionDeleter(self.name)\n self._registered_on_context = True\n self.definition = function_def\n self.signature = function_def.signature\n self._num_outputs = len(self.signature.output_arg)\n self._output_types = [o.type for o in self.signature.output_arg]\n self._output_shapes = [o.shape for o in outputs]\n self._control_captures = graph.control_captures\n # Shallow copy outputs since ConcreteFunction may mutate it.\n self._func_graph_outputs = list(outputs)\n self.grad_func_name = None\n self.python_grad_func = None\n self._c_func = c_api_util.ScopedTFFunction(fn)\n self._grad_func = None\n self.graph = graph\n self._stateful_ops = tuple(op for op in operations if op._is_stateful) # pylint: disable=protected-access\n\n def add_to_graph(self, g=None):\n # pylint: disable=protected-access\n if not g and context.executing_eagerly():\n context.context().add_function_def(self.definition)\n else:\n if self.name not in g._functions:\n g._add_function(self)\n for f in self.graph._functions.values():\n if f.name not in g._functions:\n g._add_function(f)\n # pylint: enable=protected-access\n\n @property\n def stateful_ops(self):\n return self._stateful_ops\n\n def call(self, ctx, args, cancellation_manager=None):\n \"\"\"Calls this function with `args` as inputs.\n\n `ConcreteFunction` execution respects device annotations only if the\n function won't be compiled with xla.\n\n Args:\n ctx: a Context object\n args: a list of arguments to supply this function with.\n cancellation_manager: a `CancellationManager` object that can be used to\n cancel function execution.\n\n Returns:\n The outputs of the function call.\n\n Raises:\n ValueError: if the number of arguments is incorrect.\n \"\"\"\n if len(args) != len(self.signature.input_arg):\n raise ValueError(\n \"Arguments and signature arguments do not match. \"\n \"got: %s, expected: %s \" %\n (len(args), len(list(self.signature.input_arg))))\n\n function_call_options = ctx.function_call_options\n if function_call_options.config_proto_serialized is None:\n config = function_utils.get_disabled_rewriter_config()\n else:\n config = function_call_options.config_proto_serialized\n executor_type = function_call_options.executor_type or \"\"\n\n executing_eagerly = ctx.executing_eagerly()\n if executing_eagerly:\n with _InterpolateFunctionError(self):\n if cancellation_manager is None:\n outputs = execute.execute(\n str(self.signature.name),\n num_outputs=self._num_outputs,\n inputs=args,\n attrs=(\"executor_type\", executor_type, \"config_proto\", config),\n ctx=ctx)\n else:\n outputs = execute.execute_with_cancellation(\n str(self.signature.name),\n num_outputs=self._num_outputs,\n inputs=args,\n attrs=(\"executor_type\", executor_type, \"config_proto\", config),\n ctx=ctx,\n cancellation_manager=cancellation_manager)\n # Replace empty list with None\n outputs = outputs or None\n else:\n # TODO(akshayka): Either remove this if the FunctionLibraryRuntime\n # creates `PartitionedCallOp` kernels by default, or remove the previous\n # branch if a TPU kernel is registered for `PartitionedCall`.\n with _InterpolateFunctionError(self):\n with ops.control_dependencies(self._control_captures):\n # The caller must use record_operation to record this operation in the\n # eager case, so we enforce the same requirement for the non-eager\n # case by explicitly pausing recording. We don't have a gradient\n # registered for PartitionedCall, so recording this operation confuses\n # forwardprop code (GradientTape manages to ignore it).\n with tape.stop_recording():\n outputs = functional_ops.partitioned_call(\n args=args,\n f=self,\n tout=self._output_types,\n executing_eagerly=executing_eagerly,\n config=config,\n executor_type=executor_type)\n\n if executing_eagerly:\n return outputs\n else:\n # TODO(b/128924522): This additional set_shape should not be\n # necessary. ShapeRefiner likely needs to inspect handle_data. Remove this\n # once that's done.\n for i, shape in enumerate(self._output_shapes):\n outputs[i].set_shape(shape)\n for i, func_graph_output in enumerate(self._func_graph_outputs):\n custom_gradient.copy_handle_data(func_graph_output, outputs[i])\n return outputs\n\n\nclass _DelayedRewriteGradientFunctions(object):\n \"\"\"Caches forward/backward functions with a delayed forward rewrite.\"\"\"\n\n def __init__(self, func_graph, attrs, func_graph_deleter):\n \"\"\"Construct an inference function and initialize caches.\"\"\"\n # A map from the number of forward function outputs with accepted gradients\n # to forward and backward functions, used to cache non-tape backward\n # function generation.\n self._cached_function_pairs = {}\n self._func_graph = func_graph\n self._inference_function = _EagerDefinedFunction(\n _inference_name(self._func_graph.name), self._func_graph,\n self._func_graph.inputs, self._func_graph.outputs, attrs)\n self._attrs = attrs\n self._gradient_name = None\n # Note that the FuncGraph is mutated later, so we need to inspect it now to\n # figure out the user-specified outputs of the inference function.\n self._num_inference_outputs = len(self._func_graph.outputs)\n self._func_graph_deleter = func_graph_deleter\n\n def forward_backward(self, num_doutputs=None):\n \"\"\"A possibly-cached pair of forward and backward functions.\"\"\"\n if num_doutputs is None:\n num_doutputs = self._num_inference_outputs\n forward_backward = self._cached_function_pairs.get(num_doutputs)\n if forward_backward is not None:\n return forward_backward\n forward, backward = self._construct_forward_backward(num_doutputs)\n self._cached_function_pairs[num_doutputs] = (forward, backward)\n return forward, backward\n\n def _construct_forward_backward(self, num_doutputs):\n \"\"\"Constructs a pair of forward and backward functions.\n\n Args:\n num_doutputs: The constructed backprop function will take output gradients\n for the first `num_doutputs` outputs of the forward function. Defaults\n to the number of outputs for the inference function, but when\n higher-order gradients are computed this will increase to include side\n outputs.\n\n Returns:\n A pair of (forward_function, backward_function):\n forward_function: A re-generated inference function (an\n _EagerDefinedFunction) to account for new side outputs, if any extra\n were required when building the backward pass.\n backward_function: A ConcreteFunction that Takes `num_doutputs`\n arguments and returns gradients with respect to inputs of the forward\n function.\n \"\"\"\n trainable_outputs = [\n output for output in self._func_graph.outputs[:num_doutputs]\n if backprop_util.IsTrainable(output)]\n\n signature = []\n for t in trainable_outputs:\n signature.append(\n tensor_spec.TensorSpec(*default_gradient.shape_and_dtype(t)))\n\n def _backprop_function(*grad_ys):\n with ops.device(None):\n return gradients_util._GradientsHelper( # pylint: disable=protected-access\n trainable_outputs,\n self._func_graph.inputs,\n grad_ys=grad_ys,\n src_graph=self._func_graph)\n\n with self._func_graph.as_default():\n backwards_graph = func_graph_module.FuncGraph(\n _backward_name(self._func_graph.name))\n func_graph_module.func_graph_from_py_func(\n name=backwards_graph.name,\n python_func=_backprop_function,\n args=[], kwargs={},\n signature=signature,\n func_graph=backwards_graph)\n backwards_graph_captures = backwards_graph.external_captures\n captures_from_forward = [\n c for c in backwards_graph_captures if\n not isinstance(c, ops.EagerTensor) and c.graph is self._func_graph]\n\n forward_function_name = _forward_name(self._func_graph.name)\n\n # NB: forward and backward function have their \"_implements\"\n # attribute set to None if it was present. This is because we don't\n # support replacing those functions. If we do want for those functions\n # to have implements function we need to provide a mechanism that\n # would allow to identify all functions that call this one\n # and trace and update their signatures as well. At the moment\n # we disable this, until the tooling for doing this becomes available.\n # See:\n # https://github.com/tensorflow/community/blob/master/rfcs/20190610-standardizing-composite_ops.md#appendix-future-support-for-optimizing-gradient-functions\n common_attributes = dict(self._attrs)\n common_attributes.pop(IMPLEMENTS_ATTRIBUTE_NAME, None)\n\n existing_outputs = object_identity.ObjectIdentitySet(\n self._func_graph.outputs)\n for capture in captures_from_forward:\n if capture not in existing_outputs:\n existing_outputs.add(capture)\n self._func_graph.outputs.append(capture)\n backward_function_attr = _parse_func_attrs(\n {FORWARD_FUNCTION_ATTRIBUTE_NAME: forward_function_name})\n backward_function_attr.update(common_attributes)\n\n backward_function = ConcreteFunction(\n backwards_graph, attrs=backward_function_attr)\n forward_function_attr = _parse_func_attrs({\n BACKWARD_FUNCTION_ATTRIBUTE_NAME:\n backward_function.name})\n forward_function_attr.update(common_attributes)\n forward_function = _EagerDefinedFunction(\n forward_function_name, self._func_graph, self._func_graph.inputs,\n self._func_graph.outputs, forward_function_attr)\n return forward_function, backward_function\n\n def _rewrite_forward_and_call_backward(self, op, *doutputs):\n \"\"\"Add outputs to the forward call and feed them to the grad function.\"\"\"\n forward_function, backwards_function = self.forward_backward(len(doutputs))\n if not backwards_function.outputs:\n return backwards_function.structured_outputs\n forward_function.add_to_graph(op.graph)\n\n # pylint: disable=protected-access\n # Rewrite an inference call op to be a forward call op\n op._set_func_attr(\"f\", forward_function.name)\n op._set_type_list_attr(\"Tout\", forward_function._output_types)\n op._add_outputs(\n forward_function._output_types[len(op.outputs):],\n forward_function._output_shapes[len(op.outputs):])\n for i in range(len(op.outputs)):\n func_graph_output = forward_function._func_graph_outputs[i]\n custom_gradient.copy_handle_data(func_graph_output, op.outputs[i])\n # pylint: enable=protected-access\n\n capture_mapping = dict(\n zip([ops.tensor_id(t) for t in self._func_graph.outputs], op.outputs))\n remapped_captures = [\n capture_mapping.get(ops.tensor_id(capture), capture)\n for capture in backwards_function.captured_inputs\n ]\n\n # Replace Nones with zeros since we're calling a graph function which\n # expects numeric inputs.\n cleaned_doutputs = []\n for doutput, placeholder in zip(doutputs, self._func_graph.outputs):\n if backprop_util.IsTrainable(placeholder):\n if doutput is not None:\n cleaned_doutputs.append(doutput)\n else:\n cleaned_doutputs.append(default_gradient.zeros_like(placeholder))\n\n # Compute the gradients using the side outputs\n return backwards_function._call_flat( # pylint: disable=protected-access\n cleaned_doutputs, remapped_captures)\n\n def get_gradient_function(self):\n \"\"\"Returns gradient function.\n\n The gradient rewrites an inference call op to a forward call op, but does\n not modify a pre-existing forward call op. It then computes the gradient\n from the output's gradients and the side outputs of the forward op.\n \"\"\"\n return self._rewrite_forward_and_call_backward\n\n def forward(self, inference_args=None, input_tangents=None):\n \"\"\"A forward function with only user-specified outputs.\n\n The call operation for the returned inference function can be rewritten into\n a forward function. This only happens if the backward function (from the\n `backward` method) ends up being used to compute gradients.\n\n This approach avoids constructing unnecessary graphs, but it only works if\n we are calling this function when not executing eagerly.\n\n Args:\n inference_args: A flat list of Tensors, arguments to the inference\n function. Unused, but taken for compatibility with\n _TapeGradientFunctions.\n input_tangents: A flat list of Tensors, jvps associated with\n `inference_args`. Unused; if required, tape functions must be used\n instead.\n\n Returns:\n An _EagerDefinedFunction.\n \"\"\"\n del inference_args # unused\n if input_tangents:\n # This class does not support special-cased forwardprop. The arguments are\n # here for compatibility with _TapeGradientFunctions.\n raise AssertionError(\n \"Internal error: unexpectedly got forwardprop information in a class \"\n \"that does not support forwardprop.\")\n return self._inference_function\n\n def _backward(self, outputs):\n \"\"\"Fetch a backward function for `outputs` from the forward function.\"\"\"\n def _backward_function(*args):\n call_op = outputs[0].op\n return self._rewrite_forward_and_call_backward(call_op, *args)\n return _backward_function, outputs\n\n def record(self, flat_outputs, inference_args, input_tangents):\n \"\"\"Record the function call operation.\n\n _DelayedRewriteGradientFunctions supports only first-order backprop tape\n gradients (and then only when graph building). It does not work with\n higher-order tape gradients or forward autodiff, but does work with\n higher-order symbolic gradients (tf.gradients).\n\n Args:\n flat_outputs: The restult of running `forward`.\n inference_args: A flat list of Tensors with inference inputs to the\n operation.\n input_tangents: A flat list of Tensors with input tangents consumed by the\n operation.\n \"\"\"\n backward_function, to_record = self._backward(flat_outputs)\n tape.record_operation(self._inference_function.signature.name,\n to_record, inference_args + input_tangents,\n backward_function)\n\n\n# Contains information about a forward function wrapped to compute jvps.\n_ForwardWrapper = collections.namedtuple(\n \"_ForwardWrapper\", (\n # The wrapper Graph.\n \"graph\",\n # A flat list of non-tangent Tensor outputs from the wrapped forward\n # function.\n \"outputs\",\n # Indices for output tangents, same format as\n # forwardprop_util.pack_tangents.\n \"output_indices\",\n # A flat list of tangents for `outputs`.\n \"output_tangents\"))\n\n\nclass _TapeGradientFunctions(object):\n \"\"\"Caches forward and backward functions compatible with eager gradients.\n\n In contrast to the delayed-rewrite approach in\n `_DelayedRewriteGradientFunctions` which only works with delayed execution,\n the forward function generated by this class has a fixed set of outputs which\n may be preserved by a tape in order to compute gradients later.\n\n This class is abstract; its child classes differ in how many side outputs of\n the forward function their backward function accepts gradients for, which\n determines whether higher-order tape gradients are possible.\n \"\"\"\n\n def __init__(self, func_graph, attrs, func_graph_deleter,\n forwardprop_input_indices, delayed_rewrite_functions,\n need_gradients_for_jvps):\n self._func_graph = func_graph\n self._forward_graph = None\n self._attrs = attrs\n self._forward = None\n self._backward = None\n self._num_outputs = len(func_graph.outputs)\n self._func_graph_deleter = func_graph_deleter\n self._forwardprop_input_indices = forwardprop_input_indices\n self._forwardprop_output_indices = None\n self._num_forwardprop_outputs = 0\n self._num_inference_outputs = len(func_graph.outputs)\n self._num_trainable_inference_outputs = len(\n [t for t in func_graph.outputs if backprop_util.IsTrainable(t)])\n self._delayed_rewrite_functions = delayed_rewrite_functions\n self._need_gradients_for_jvps = need_gradients_for_jvps\n\n def _build_functions_for_outputs(\n self, outputs, inference_args, input_tangents):\n \"\"\"Forward+backward functions where the backward function sees `outputs`.\"\"\"\n # First figure out which of `outputs` are trainable. We'll accept gradients\n # for each of these in the backward function.\n handles_to_variables = self._func_graph.variable_captures\n trainable_outputs = []\n trainable_indices = []\n for index, output in enumerate(outputs):\n\n if backprop_util.IsTrainable(output):\n # Swap in the Variable object for resource handles if we can so\n # sparse gradients work.\n output = handles_to_variables.get(id(output), output)\n trainable_outputs.append(output)\n trainable_indices.append(index)\n\n backwards_graph = func_graph_module.FuncGraph(\n _backward_name(self._func_graph.name))\n with backwards_graph.as_default():\n gradients_wrt_outputs = []\n for output in trainable_outputs:\n gradient_shape, gradient_dtype = default_gradient.shape_and_dtype(\n output)\n gradients_wrt_outputs.append(\n graph_placeholder(gradient_dtype, gradient_shape))\n with ops.device(None):\n gradients_wrt_inputs = gradients_util._GradientsHelper( # pylint: disable=protected-access\n trainable_outputs,\n self._func_graph.inputs,\n grad_ys=gradients_wrt_outputs,\n src_graph=self._func_graph)\n\n captures_from_forward = [\n c for c in backwards_graph.external_captures\n if not isinstance(c, ops.EagerTensor) and c.graph is self._func_graph\n ]\n existing_outputs = object_identity.ObjectIdentitySet(\n self._func_graph.outputs)\n for capture in captures_from_forward:\n if capture not in existing_outputs:\n existing_outputs.add(capture)\n self._func_graph.outputs.append(capture)\n\n forward_function_name = _forward_name(self._func_graph.name)\n backward_function_attr = _parse_func_attrs(\n {FORWARD_FUNCTION_ATTRIBUTE_NAME: forward_function_name})\n backward_function_attr.update(self._attrs)\n\n # The ordering of `backwards_graph.inputs` is important: inputs of\n # `backward_function` correspond to outputs (including\n # side outputs) of `self._tape_forward_function`.\n backwards_graph.inputs = (\n gradients_wrt_outputs + backwards_graph.internal_captures)\n backwards_graph.outputs.extend(\n grad\n for grad in nest.flatten(gradients_wrt_inputs, expand_composites=True)\n if grad is not None)\n backwards_graph.structured_outputs = gradients_wrt_inputs\n backward_function = ConcreteFunction(\n backwards_graph, attrs=backward_function_attr)\n\n forward_function_attr = _parse_func_attrs({\n BACKWARD_FUNCTION_ATTRIBUTE_NAME:\n backward_function.name})\n forward_function_attr.update(self._attrs)\n\n forward_function = _EagerDefinedFunction(\n forward_function_name, self._func_graph, self._func_graph.inputs,\n self._func_graph.outputs,\n forward_function_attr)\n\n if not self._func_graph.outputs or not input_tangents:\n # There is no need to special-case forwardprop, so we can return the\n # forward+backward pair we've created without further wrapping.\n return (forward_function, self._func_graph, backward_function,\n # No forwardprop outputs.\n None, 0)\n forward_wrapper = self._wrap_forward_function_with_jvps(\n forward_function, backward_function, inference_args, input_tangents)\n (wrapped_backwards_graph,\n forward_wrapper) = self._wrap_backward_function_with_jvp_backprop(\n backward_function, gradients_wrt_outputs, forward_wrapper)\n # Now that we've added new captures, we need to make sure forward outputs\n # are in the same order the backward function expects them to be in:\n # [inference outputs] + [jvps] + [side outputs] + [captures].\n forward_wrapper = self._shuffle_forward_outputs(forward_wrapper)\n\n wrapped_forward_function = _EagerDefinedFunction(\n _forward_name(self._func_graph.name), forward_wrapper.graph,\n forward_wrapper.graph.inputs, forward_wrapper.graph.outputs,\n forward_function_attr)\n wrapped_backward_function = ConcreteFunction(\n wrapped_backwards_graph, attrs=backward_function_attr)\n\n if (len(inference_args) + len(input_tangents)\n != len(forward_wrapper.graph.inputs)):\n raise AssertionError(\n (\"Internal error: the forward graph had {} inputs, but we expected\"\n \" {} ({} inference inputs and {} input tangents)\")\n .format(len(len(forward_wrapper.graph.inputs)),\n len(inference_args) + len(input_tangents),\n len(inference_args), len(input_tangents)))\n return (wrapped_forward_function, forward_wrapper.graph,\n wrapped_backward_function, forward_wrapper.output_indices,\n len(forward_wrapper.output_tangents))\n\n def _wrap_forward_function_with_jvps(\n self, forward_function, backward_function,\n inference_args, input_tangents):\n \"\"\"Adds inline JVP computation to a forward function.\"\"\"\n forward_wrapper_graph = func_graph_module.FuncGraph(\n _forward_name(self._func_graph.name))\n with forward_wrapper_graph.as_default():\n # Tell forward accumulators to free up space for new JVP computations,\n # since one may be in the process of computing a JVP (if that computation\n # triggered this function building).\n #\n # We'll make symbolic versions of input JVPs, run the forward function\n # under forward accumulators to get symbolic output JVPs, then set those\n # as outputs of the new wrapped forward function.\n with forwardprop_util.push_forwardprop_state():\n forward_captures = {\n ops.tensor_id(internal): external\n for external, internal in self._func_graph.captures}\n for input_index, real_input in enumerate(self._func_graph.inputs):\n # This loop is more or less equivalent to running tf.identity on each\n # of self._func_graph.inputs. However, doing that also captures jvps\n # for resource handles, which confuses the jvp capturing code below\n # (since primal inputs are interwoven with jvp inputs).\n input_placeholder = array_ops.placeholder(\n dtype=real_input.dtype,\n shape=real_input.shape)\n capture = forward_captures.get(ops.tensor_id(real_input))\n if capture is not None:\n forward_wrapper_graph.add_capture(capture, input_placeholder)\n if capture.dtype == dtypes.resource:\n custom_gradient.copy_handle_data(capture, input_placeholder)\n else:\n forward_wrapper_graph.inputs.append(input_placeholder)\n for inp, arg in zip(forward_wrapper_graph.inputs, inference_args):\n tape.record_operation(\n \"captured_value\", [inp], [arg],\n backward_function=lambda x: [x],\n forward_function=lambda x: [x])\n num_inference_inputs = len(inference_args)\n for tape_indices in self._forwardprop_input_indices:\n for input_index, jvp_index in tape_indices:\n input_placeholder = forward_wrapper_graph.inputs[input_index]\n if len(forward_wrapper_graph.inputs) != jvp_index:\n raise AssertionError(\n (\"Internal error: expected {} forward graph inputs, but \"\n \"found {}.\")\n .format(jvp_index, len(forward_wrapper_graph.inputs)))\n gradient_shape, gradient_dtype = default_gradient.shape_and_dtype(\n input_placeholder)\n jvp_placeholder = graph_placeholder(gradient_dtype, gradient_shape)\n external_jvp = input_tangents[jvp_index - num_inference_inputs]\n forward_wrapper_graph.add_capture(external_jvp, jvp_placeholder)\n tensor_shape.TensorShape(\n external_jvp.shape).assert_is_compatible_with(\n jvp_placeholder.shape)\n tape.record_operation(\n \"captured_value\",\n [jvp_placeholder],\n [external_jvp],\n backward_function=lambda x: [x],\n forward_function=lambda x: [x])\n forward_inputs = forward_wrapper_graph.inputs[:num_inference_inputs]\n gradient_function = (\n self._delayed_rewrite_functions._rewrite_forward_and_call_backward) # pylint: disable=protected-access\n with ops.get_default_graph()._override_gradient_function( # pylint: disable=protected-access\n {\"PartitionedCall\": gradient_function,\n \"StatefulPartitionedCall\": gradient_function}):\n # Previously, we relyed on \"_gradient_op_type\" attribute to restore a\n # function gradient in function_deserialization.py, So add a dummy\n # value \"PartitionedCallUnused\" for the forward compatibility.\n if fwd_compat.forward_compatible(2019, 11, 16):\n forward_outputs = forward_function.call(context.context(),\n forward_inputs)\n else:\n with ops.get_default_graph().gradient_override_map(\n {\"PartitionedCall\": \"PartitionedCallUnused\",\n \"StatefulPartitionedCall\": \"PartitionedCallUnused\"}):\n forward_outputs = forward_function.call(context.context(),\n forward_inputs)\n py_backward, _ = self._wrap_backward_function(\n self._func_graph, backward_function, forward_outputs)\n # We will never request backward tape gradients for this operation\n # directly since we're wrapping the call; forwardprop will call the\n # backward function (and nested forward accumulators may build\n # higher-order gradients), but any watching GradientTapes should ignore\n # it.\n #\n # TODO(allenl): It might be better to explicitly stop backward recording\n # so we don't use the second-order tape cases unnecessarily.\n tape.record_operation_forwardprop_only(\n forward_function.signature.name,\n forward_outputs, forward_inputs, py_backward, None)\n output_indices, output_tangents = (\n pywrap_tensorflow.TFE_Py_PackJVPs(forward_outputs))\n output_tangents = [forward_wrapper_graph.capture(t)\n for t in output_tangents]\n return _ForwardWrapper(\n graph=forward_wrapper_graph, outputs=forward_outputs,\n output_indices=output_indices, output_tangents=output_tangents)\n\n def _wrap_backward_function_with_jvp_backprop(\n self, backward_function, gradients_wrt_outputs, forward_wrapper):\n \"\"\"Wraps `backward_function` to include gradients for JVPs.\"\"\"\n wrapped_backwards_graph = func_graph_module.FuncGraph(\n _backward_name(self._func_graph.name))\n with wrapped_backwards_graph.as_default():\n py_backward, recorded_outputs = self._wrap_backward_function(\n self._func_graph, backward_function, forward_wrapper.outputs)\n trainable_index = 0\n forward_doutputs = []\n doutput_args = []\n for output in recorded_outputs:\n if backprop_util.IsTrainable(output):\n doutput = gradients_wrt_outputs[trainable_index]\n doutput_placeholder = graph_placeholder(doutput.dtype, doutput.shape)\n doutput_args.append(doutput_placeholder)\n forward_doutputs.append(doutput_placeholder)\n trainable_index += 1\n else:\n doutput_args.append(None)\n\n dinputs = py_backward(*doutput_args)\n existing_outputs = object_identity.ObjectIdentitySet(\n forward_wrapper.outputs + forward_wrapper.output_tangents)\n num_processed_output_tangents = 0\n gradients_wrt_output_tangents = []\n tangent_doutputs = []\n output_tangents = forward_wrapper.output_tangents\n output_indices = forward_wrapper.output_indices\n if self._need_gradients_for_jvps:\n # TODO(allenl): Consider using a throwaway graph to avoid extra gradient\n # evaluations; gradients for jvps may have common subgraphs.\n while num_processed_output_tangents != len(output_tangents):\n for output in output_tangents[num_processed_output_tangents:]:\n gradient_shape, gradient_dtype = default_gradient.shape_and_dtype(\n output)\n placeholder = graph_placeholder(gradient_dtype, gradient_shape)\n gradients_wrt_output_tangents.append(placeholder)\n tangent_doutputs.append(placeholder)\n num_processed_output_tangents = len(output_tangents)\n with ops.device(None):\n gradients_wrt_inputs = gradients_util._GradientsHelper( # pylint: disable=protected-access\n output_tangents,\n forward_wrapper.graph.inputs,\n grad_ys=gradients_wrt_output_tangents,\n src_graph=forward_wrapper.graph)\n dinputs = [\n backprop.aggregate_indexed_slices_gradients((existing, new))\n for existing, new in zip(dinputs, gradients_wrt_inputs)\n if existing is not None or new is not None]\n dinputs.extend(gradients_wrt_inputs[len(dinputs):])\n captures_from_forward = [\n c for c in wrapped_backwards_graph.external_captures\n if (not isinstance(c, ops.EagerTensor)\n and c.graph is forward_wrapper.graph)]\n for capture in captures_from_forward:\n if capture not in existing_outputs:\n existing_outputs.add(capture)\n forward_wrapper.outputs.append(capture)\n output_indices, output_tangents = (\n forwardprop_util.pack_tangents(forward_wrapper.outputs))\n output_tangents = [forward_wrapper.graph.capture(t)\n for t in output_tangents]\n for t in output_tangents:\n existing_outputs.add(t)\n wrapped_backwards_graph.inputs = (\n forward_doutputs[:self._num_trainable_inference_outputs]\n + tangent_doutputs\n + forward_doutputs[self._num_trainable_inference_outputs:]\n + wrapped_backwards_graph.internal_captures)\n wrapped_backwards_graph.structured_outputs = dinputs\n wrapped_backwards_graph.outputs = [t for t in dinputs if t is not None]\n return (wrapped_backwards_graph,\n forward_wrapper._replace(output_indices=output_indices,\n output_tangents=output_tangents))\n\n def _shuffle_forward_outputs(self, forward_wrapper):\n \"\"\"Reorders function outputs so captures are last.\"\"\"\n def _index_map(original):\n if original < self._num_inference_outputs:\n return original\n if original >= len(forward_wrapper.outputs):\n return (original - len(forward_wrapper.outputs)\n + self._num_inference_outputs)\n return original + len(forward_wrapper.output_tangents)\n output_indices = nest.map_structure(\n _index_map, forward_wrapper.output_indices)\n forward_wrapper.graph.outputs = (\n forward_wrapper.outputs[:self._num_inference_outputs]\n + forward_wrapper.output_tangents\n + forward_wrapper.outputs[self._num_inference_outputs:])\n return forward_wrapper._replace(output_indices=output_indices)\n\n def forward(self, inference_args, input_tangents):\n \"\"\"Construct or fetch a forward function with side-outputs.\n\n When graph building without a tape active, symbolic gradients rely on\n regenerating the backward function for higher-order gradients (to account\n for new side outputs of the rewritten forward function call). Thus there is\n no fixed backward function for this case. However, when a tape is active\n (eager or graph building), we generate fixed backward and forward functions\n at forward function call time.\n\n This difference between the tape and non-tape cases is to avoid building\n unneeded backward functions while graph building (where we may or may not\n eventually need gradients).\n\n Args:\n inference_args: A flat list of Tensors, arguments to the inference\n function.\n input_tangents: A flat list of Tensors, jvps associated with\n `inference_args`.\n\n Returns:\n A forward _EagerDefinedFunction.\n \"\"\"\n if self._forward is None:\n (self._forward, self._forward_graph, self._backward,\n self._forwardprop_output_indices, self._num_forwardprop_outputs) = (\n self._forward_and_backward_functions(inference_args, input_tangents))\n return self._forward\n\n def _wrap_backward_function(self, forward_graph, backward, outputs):\n \"\"\"Create a backward function given `outputs` from the forward function.\"\"\"\n capture_mapping = dict(\n zip([ops.tensor_id(t) for t in forward_graph.outputs], outputs))\n remapped_captures = [\n capture_mapping.get(ops.tensor_id(capture), capture)\n for capture in backward.captured_inputs\n ]\n if any(t.graph is forward_graph for t in remapped_captures\n if not isinstance(t, ops.EagerTensor)):\n raise AssertionError(\n \"Internal error: failed to map all backward graph captures to the \"\n \"forward graph. Incorrectly mapped: {}\".format(\n [t for t in remapped_captures\n if (not isinstance(t, ops.EagerTensor)\n and t.graph is not forward_graph)]))\n # We may need to use zeros_like to get a zero for variant Tensors with\n # unconnected gradients. We do that in advance so we don't have to hold on\n # to the outputs themselves, which may not be needed otherwise.\n variant_zeros_like = {}\n backward_function_inputs = (\n len(backward.inputs) - len(backward.captured_inputs))\n recorded_outputs = []\n trainable_recorded_outputs = 0\n skip_positions = []\n if self._num_forwardprop_outputs and not self._need_gradients_for_jvps:\n relevant_outputs = (\n outputs[:self._num_inference_outputs]\n + outputs[self._num_inference_outputs\n + self._num_forwardprop_outputs:])\n else:\n relevant_outputs = outputs\n for output_index, output in enumerate(relevant_outputs):\n if trainable_recorded_outputs < backward_function_inputs:\n recorded_outputs.append(output)\n if backprop_util.IsTrainable(output):\n trainable_recorded_outputs += 1\n else:\n skip_positions.append(output_index)\n if output.dtype == dtypes.variant:\n variant_zeros_like[output_index] = default_gradient.zeros_like(output)\n\n def _backward_function_wrapper(*args):\n \"\"\"Process output gradients and call the backward function.\"\"\"\n if not backward.outputs:\n return backward.structured_outputs\n\n processed_args = []\n input_index = 0\n for output_index, arg in enumerate(args):\n if output_index in skip_positions:\n continue\n if arg is None:\n # We're calling a (non-polymorphic) ConcreteFunction, so we need to\n # have a Tensor value for each Tensor we thought would be trainable\n # based on its dtype, even if it ended up being unconnected.\n input_placeholder = backward.inputs[\n input_index]\n if input_placeholder.dtype == dtypes.variant:\n arg = variant_zeros_like[output_index]\n else:\n arg = array_ops.zeros(\n *default_gradient.shape_and_dtype(input_placeholder))\n processed_args.append(arg)\n input_index += 1\n if input_index >= backward_function_inputs:\n break\n return backward._call_flat( # pylint: disable=protected-access\n processed_args, remapped_captures)\n\n return _backward_function_wrapper, recorded_outputs\n\n def record(self, flat_outputs, inference_args, input_tangents):\n \"\"\"Record the function call operation.\n\n For backprop, indicates the backward function to use and which new Tensors\n must be watched. For forwardprop from eager, the function call itself will\n have produced tangents which need to be recorded.\n\n Args:\n flat_outputs: The restult of running `forward`.\n inference_args: A flat list of Tensors with inference inputs to the\n operation.\n input_tangents: A flat list of Tensors with input tangents consumed by the\n operation.\n \"\"\"\n backward_function, to_record = self._wrap_backward_function(\n self._forward_graph, self._backward, flat_outputs)\n if self._forwardprop_output_indices:\n tape.record_operation_backprop_only(\n self._forward.signature.name,\n to_record, inference_args,\n backward_function)\n tape.record_operation_forwardprop_only(\n self._forward.signature.name,\n flat_outputs, inference_args + input_tangents,\n backward_function,\n self._forwardprop_output_indices)\n else:\n tape.record_operation(self._forward.signature.name,\n to_record, inference_args + input_tangents,\n backward_function)\n\n\nclass _FirstOrderTapeGradientFunctions(_TapeGradientFunctions):\n \"\"\"Caches tape-friendly functions for first-order gradients.\"\"\"\n\n def __init__(self, func_graph, attrs, func_graph_deleter,\n forwardprop_input_indices, delayed_rewrite_functions,\n need_gradients_for_jvps):\n super(_FirstOrderTapeGradientFunctions, self).__init__(\n func_graph, attrs, func_graph_deleter, forwardprop_input_indices,\n delayed_rewrite_functions, need_gradients_for_jvps)\n self._func_graph_deleter = func_graph_deleter\n self._forwardprop_input_indices = forwardprop_input_indices\n\n def _forward_and_backward_functions(self, inference_args, input_tangents):\n \"\"\"Shortcut for when only first-order gradients are required.\n\n The returned backward function does not accept gradients with respect to\n side output of forward_function. This is fine as long as the user can't\n possibly request second order tape gradients, as when they've used a single\n non-persistent GradientTape. Since we don't need the backward function to\n take gradients with respect to side outputs, we can skip some potentially\n slow graph building.\n\n Args:\n inference_args: A flat list of Tensors, arguments to the inference\n function.\n input_tangents: A flat list of Tensors, jvps associated with\n `inference_args`.\n\n Returns:\n A tuple of (forward_function, backward_function):\n forward_function: Takes the same inputs as the inference function, but\n returns side outputs used by backward_function in addition to the\n inference function's outputs.\n backward_function: Takes side outputs from forward_function and\n gradients with respect to the \"real\" outputs of forward_function and\n returns gradients with respect to the inputs.\n \"\"\"\n outputs = self._func_graph.outputs[:self._num_inference_outputs]\n return self._build_functions_for_outputs(\n outputs, inference_args, input_tangents)\n\n\nclass _HigherOrderTapeGradientFunctions(_TapeGradientFunctions):\n \"\"\"Caches tape-friendly functions for higher-order gradients.\"\"\"\n\n # TODO(b/136189779): Cond/while under a tape may need similar logic. Consider\n # generalizing if so.\n def _forward_and_backward_functions(self, inference_args, input_tangents):\n \"\"\"Forward and backward functions suitable for higher-order gradients.\n\n Unlike in `_FirstOrderTapeGradientFunctions`, the backward function built by\n this method accepts gradients for all of the outputs of the returned forward\n function, including side outputs.\n\n Args:\n inference_args: A flat list of Tensors, arguments to the inference\n function.\n input_tangents: A flat list of Tensors, jvps associated with\n `inference_args`.\n\n Returns:\n A tuple of (forward_function, backward_function):\n forward_function: Takes the same inputs as the inference function, but\n returns side outputs used by backward_function in addition to the\n inference function's outputs.\n backward_function: Takes side outputs from forward_function and\n gradients with respect to all of its outputs, real and side. Returns\n gradients with respect to the inputs.\n \"\"\"\n outputs = []\n # First we need to figure out how many side outputs from the forward pass\n # will be required. We do this in a temporary graph to avoid actually\n # running multiple copies of the backward pass (one per _GradientsHelper\n # call).\n #\n # While computing gradients, the backward function captures Tensors from\n # the forward function. We add these as side outputs of the original\n # function. However, we then need to accept output gradients with respect\n # to these side outputs for higher order gradients to work. Thus we loop\n # until the number of outputs of the function stabilizes. Note that this\n # is only required for tape gradients, where we need to declare in advance\n # all of the forward op's outputs: symbolic gradients with tf.gradients\n # instead rely on regenerating backward functions when higher-order\n # gradients are requested.\n while len(outputs) < len(self._func_graph.outputs):\n outputs = list(self._func_graph.outputs)\n self._build_functions_for_outputs(\n outputs, inference_args, input_tangents)\n (forward_function, forward_graph,\n backward_function, output_indices, num_output_tangents) = (\n self._build_functions_for_outputs(\n outputs, inference_args, input_tangents))\n if len(self._func_graph.outputs) != len(outputs):\n raise AssertionError(\n (\"Unexpectedly added new outputs to the forward function when \"\n \"building the backward function: {}\").format(\n self._func_graph.outputs[len(outputs):]))\n return (forward_function, forward_graph, backward_function, output_indices,\n num_output_tangents)\n\n\n# Represents the output of TFE_Py_TapeSetPossibleGradientTypes. Real enums are\n# unfortunately too slow to use here.\n_POSSIBLE_GRADIENT_TYPES_NONE = 0\n_POSSIBLE_GRADIENT_TYPES_FIRST_ORDER = 1\n_POSSIBLE_GRADIENT_TYPES_HIGHER_ORDER = 2\n\n\nclass _ForwardBackwardCall(object):\n \"\"\"Holds the state of a function call between execution and recording.\"\"\"\n\n def __init__(self, functions, inference_args, input_tangents, tape_watching):\n \"\"\"Collects information about the function call.\n\n Args:\n functions: An object which produces forward and backward functions, either\n a _DelayedRewriteGradientFunctions or a _TapeGradientFunctions object.\n inference_args: A flat list of Tensors, arguments to the inference\n function.\n input_tangents: A flat list of Tensors, jvps associated with\n `inference_args`.\n tape_watching: Boolean, with True indicating that recording is necessary.\n \"\"\"\n self._functions = functions\n self._inference_args = inference_args\n self._input_tangents = input_tangents\n self._tape_watching = tape_watching\n\n def forward(self):\n \"\"\"Builds or retrieves a forward function for this call.\"\"\"\n forward_function = self._functions.forward(\n self._inference_args, self._input_tangents)\n return forward_function, self._inference_args + self._input_tangents\n\n def record(self, flat_outputs):\n \"\"\"Given outputs from the execution of `forward`, records the operation.\"\"\"\n if (self._tape_watching\n and not isinstance(flat_outputs, ops.Operation)\n and flat_outputs is not None):\n # We only record function calls which have outputs, and then only when a\n # tape is watching.\n self._functions.record(\n flat_outputs, self._inference_args, self._input_tangents)\n\n\nclass ConcreteFunction(object):\n \"\"\"Callable object encapsulating a function definition and its gradient.\n\n `ConcreteFunction` is a callable that encapsulates a function definition and\n is differentiable under `tf.GradientTape` objects.\n \"\"\"\n\n def __init__(self, func_graph, attrs=None, signature=None,\n shared_func_graph=True):\n \"\"\"Initialize a `ConcreteFunction`.\n\n Args:\n func_graph: An instance of FuncGraph: the function body to wrap.\n attrs: (optional) dict mapping names of attributes to their AttrValue\n values. Attributes in `attrs` will be included in this function's\n definition.\n signature: a nested sequence of `TensorSpec` objects specifying the input\n signature of this function.\n shared_func_graph: If False, the ConcreteFunction takes ownership of\n `func_graph` and will break reference cycles when it is deleted. This\n makes the FuncGraph inoperable.\n\n Raises:\n ValueError: If number of input_placeholders is not equal to the number\n of function inputs.\n \"\"\"\n self._arg_keywords = None\n self._num_positional_args = None\n self._func_graph = func_graph\n self._captured_inputs = self._func_graph.external_captures\n self._captured_closures = self._func_graph.deferred_external_captures\n if attrs and IMPLEMENTS_ATTRIBUTE_NAME in attrs:\n # The alternative is to silently drop \"implements\" tag\n # but it seems likely it would lead to hard to catch bugs.\n # Another alternative is to make func_body to preserve the order\n # of arguments if variables are present. Yet another option\n # is to automatically replace variables as arguments to functions\n # to v.read_value() whenever \"implements\" tag is present\n # Anytime we annotate existing function we probably want to wrap\n # it with safe read_value for backward compatibility.\n has_resource_vars = any(inp.dtype == dtypes.resource\n for inp in self.inputs)\n\n assert not any(\n (has_resource_vars, self._captured_inputs, self._captured_closures)\n ), ('Function {name} has \"{attr}={value}\" attribute and thus can not '\n \"depend on any tensors outside of its signature or modify variables. \"\n \"\\n\\nNote: variables are always captured and cause function \"\n \"re-tracing for every variable called.\\n\"\n \" inputs: {inputs}\\n captures: {captured}\\n\"\n \" closures: {closures}.\\n\\n\"\n \"To pass a variable to such function use \"\n \"use variable.read_value().\".format(\n name=func_graph.name,\n attr=IMPLEMENTS_ATTRIBUTE_NAME,\n value=attrs[IMPLEMENTS_ATTRIBUTE_NAME],\n inputs=self.inputs,\n captured=self._captured_inputs,\n closures=self._captured_closures))\n self._output_shapes = tuple(\n output.shape for output in self._func_graph.outputs)\n self._attrs = _parse_func_attrs(attrs or {})\n self._signature = signature\n\n if shared_func_graph:\n self._garbage_collector = None\n else:\n self._garbage_collector = ConcreteFunctionGarbageCollector(func_graph)\n\n # Pairs of forward and backward functions used for computing gradients.\n #\n # These each get a reference to the FuncGraph deleter since they use the\n # FuncGraph directly.\n self._delayed_rewrite_functions = _DelayedRewriteGradientFunctions(\n func_graph, self._attrs, self._garbage_collector)\n self._first_order_tape_functions = {}\n self._higher_order_tape_functions = {}\n # Cache the inference function to avoid a (Python) function call when not\n # building gradients.\n self._inference_function = self._delayed_rewrite_functions.forward()\n\n @property\n def variables(self):\n \"\"\"Sequence of variables for this function.\"\"\"\n return tuple(self._func_graph.variables)\n\n @property\n def trainable_variables(self):\n \"\"\"Sequence of trainable variables for this function.\"\"\"\n return tuple(self._func_graph.trainable_variables)\n\n def __call__(self, *args, **kwargs):\n \"\"\"Executes the wrapped function.\n\n Args:\n *args: Tensors or Variables. Positional arguments are only accepted when\n they correspond one-to-one with arguments of the traced Python function.\n **kwargs: Tensors or Variables specified by name. When\n `get_concrete_function` was called to create this `ConcreteFunction`,\n each Tensor input was given a name, defaulting to the name of the Python\n function's argument but possibly overridden by the `name=` argument to\n `tf.TensorSpec`. These names become the argument names for the concrete\n function.\n\n Returns:\n The result of applying the TF function on the given Tensors.\n\n Raises:\n AssertionError: If this `ConcreteFunction` was not created through\n `get_concrete_function`.\n ValueError: If arguments contains anything other than Tensors or\n Variables.\n TypeError: For invalid positional/keyword argument combinations.\n \"\"\"\n return self._call_impl(args, kwargs)\n\n def _call_impl(self, args, kwargs, cancellation_manager=None):\n \"\"\"See `__call__` for details.\"\"\"\n if self._arg_keywords is None or self._num_positional_args is None:\n if self._signature is not None:\n if kwargs:\n raise NotImplementedError(\n \"Keyword arguments not supported when calling a \"\n \"wrap_function-decorated function.\")\n return self._call_flat(args, self.captured_inputs)\n raise AssertionError(\n \"Tried to call a concrete function obtained from an internal API \"\n \"through the public interface. Use get_concrete_function instead.\")\n if len(args) > self._num_positional_args:\n raise TypeError(\n (\"Expected at most {} positional arguments (and the rest keywords, \"\n \"of {}), got {}. When calling a concrete function, positional \"\n \"arguments may not be bound to Tensors within nested structures.\"\n ).format(self._num_positional_args, self._arg_keywords, args))\n args = list(args)\n for keyword in self._arg_keywords[len(args):]:\n try:\n args.append(kwargs.pop(compat.as_str(keyword)))\n except KeyError:\n specified_keywords = (list(self._arg_keywords[:len(args)])\n + list(kwargs.keys()))\n raise TypeError(\n \"Expected argument names {} but got values for {}. Missing: {}.\"\n .format(\n list(self._arg_keywords),\n specified_keywords,\n list(set(self._arg_keywords) - set(specified_keywords))))\n if kwargs:\n positional_arg_keywords = set(self._arg_keywords[:len(args)])\n for unused_key in kwargs:\n if unused_key in positional_arg_keywords:\n raise TypeError(\"Got two values for keyword '{}'.\".format(unused_key))\n raise TypeError(\"Keyword arguments {} unknown. Expected {}.\".format(\n list(kwargs.keys()), list(self._arg_keywords)))\n return self._call_flat(args, self.captured_inputs, cancellation_manager)\n\n def _filtered_call(self, args, kwargs):\n \"\"\"Executes the function, filtering arguments from the Python function.\n\n Objects aside from Tensors, CompositeTensors, and Variables are ignored.\n CompositeTensors are expanded into their components.\n\n Args:\n args: Canonicalized positional arguments of the Python function.\n kwargs: Canonicalized keyword arguments of the Python function.\n\n Returns:\n The result of applying the function on the Tensors/Variables contained in\n `args` and `kwargs`.\n \"\"\"\n return self._call_flat(\n (t for t in nest.flatten((args, kwargs), expand_composites=True)\n if isinstance(t, (ops.Tensor,\n resource_variable_ops.BaseResourceVariable))),\n self.captured_inputs)\n\n def _call_flat(self, args, captured_inputs, cancellation_manager=None):\n \"\"\"Executes the wrapped function.\n\n Args:\n args: a list of Tensors or Variables. Any CompositeTensors should be\n expanded before calling this method.\n captured_inputs: the captured inputs that are also part of the input args\n to the actual execution. By default, it should be self._captured_inputs.\n cancellation_manager: (Optional.) A `CancellationManager` that can be\n used to cancel function invocation.\n\n Returns:\n The result of applying the TF function to `args`.\n\n Raises:\n ValueError: If `args` contains anything other than Tensors or Variables.\n \"\"\"\n args = list(args)\n ctx = context.context()\n executing_eagerly = ctx.executing_eagerly()\n\n # Copy saveable status of function's graph to current FuncGraph.\n default_graph = ops.get_default_graph()\n if default_graph.building_function and not self._func_graph.saveable:\n default_graph.mark_as_unsaveable(self._func_graph.saving_errors)\n\n if (tape.could_possibly_record() or\n hasattr(ops.get_default_graph(), \"watch_variable\")):\n for v in self._func_graph.variables:\n resource_variable_ops.variable_accessed(v)\n\n tensor_inputs = []\n variables_used = set([])\n for i, arg in enumerate(args):\n if isinstance(arg, resource_variable_ops.BaseResourceVariable):\n # We can pass a variable more than once, and in this case we need to\n # pass its handle only once.\n if id(arg.handle) in variables_used:\n continue\n resource_variable_ops.variable_accessed(arg)\n tensor_inputs.append(arg.handle)\n variables_used.add(id(arg.handle))\n elif isinstance(arg, ops.Tensor):\n tensor_inputs.append(arg)\n if not executing_eagerly:\n # If we're graph building, shape inference is on. We check for input\n # compatibility up front to avoid hard to debug incompatibilities\n # later.\n graph_input_shape = tensor_shape.TensorShape(\n self._func_graph.inputs[i].shape)\n if not graph_input_shape.is_compatible_with(arg.shape):\n if self._arg_keywords:\n arg_name = \"'{}'\".format(self._arg_keywords[i])\n else:\n arg_name = \"with index {}\".format(i)\n raise ValueError(\n (\"The argument {} (value {}) is not compatible with the shape \"\n \"this function was traced with. Expected shape {}, but got \"\n \"shape {}.\\n\\nIf you called get_concrete_function, you may \"\n \"need to pass a tf.TensorSpec(..., shape=...) with a less \"\n \"specific shape, having None on axes which can vary.\").format(\n arg_name, arg,\n self._func_graph.inputs[i].shape,\n arg.shape))\n elif (self._signature is not None and\n isinstance(self._signature[i], tensor_spec.DenseSpec)):\n tensor_inputs.append(\n ops.convert_to_tensor(arg, self._signature[i].dtype))\n else:\n raise ValueError(\"All inputs to `ConcreteFunction`s must be Tensors; \"\n \"on invocation of %s, the %d-th input (%s) was not a \"\n \"Tensor.\" % (self._func_graph.name, i, str(arg)))\n args = tensor_inputs + captured_inputs\n possible_gradient_type = (\n pywrap_tensorflow.TFE_Py_TapeSetPossibleGradientTypes(args))\n if (possible_gradient_type == _POSSIBLE_GRADIENT_TYPES_NONE\n and executing_eagerly):\n # No tape is watching; skip to running the function.\n return self._build_call_outputs(self._inference_function.call(\n ctx, args, cancellation_manager=cancellation_manager))\n forward_backward = self._select_forward_and_backward_functions(\n args,\n possible_gradient_type,\n executing_eagerly)\n forward_function, args_with_tangents = forward_backward.forward()\n if executing_eagerly:\n flat_outputs = forward_function.call(\n ctx, args_with_tangents,\n cancellation_manager=cancellation_manager)\n else:\n with ops.get_default_graph()._override_gradient_function( # pylint: disable=protected-access\n {\"PartitionedCall\": self._get_gradient_function(),\n \"StatefulPartitionedCall\": self._get_gradient_function()}):\n # Previously, we relyed on \"_gradient_op_type\" attribute to restore a\n # function gradient in function_deserialization.py. So add a dummy\n # value \"PartitionedCallUnused\" for the forward compatibility.\n if fwd_compat.forward_compatible(2019, 11, 16):\n flat_outputs = forward_function.call(ctx, args_with_tangents)\n else:\n with ops.get_default_graph().gradient_override_map(\n {\"PartitionedCall\": \"PartitionedCallUnused\",\n \"StatefulPartitionedCall\": \"PartitionedCallUnused\"}):\n flat_outputs = forward_function.call(ctx, args_with_tangents)\n forward_backward.record(flat_outputs)\n return self._build_call_outputs(flat_outputs)\n\n def _experimental_with_cancellation_manager(self, cancellation_manager):\n \"\"\"Returns a callable that invokes a cancelable version of this function.\n\n Args:\n cancellation_manager: A `CancellationManager` object that can be used to\n cancel function invocation.\n\n Returns:\n A callable with the same signature as this concrete function.\n \"\"\"\n\n def cancellable_call(*args, **kwargs):\n return self._call_impl(\n args, kwargs, cancellation_manager=cancellation_manager)\n\n return cancellable_call\n\n @property\n def name(self):\n \"\"\"`ConcreteFunction` name.\"\"\"\n return self._delayed_rewrite_functions.forward().name\n\n @property\n def graph(self):\n \"\"\"Returns the graph from which this function was constructed.\"\"\"\n return self._func_graph\n\n @property\n def inputs(self):\n \"\"\"Returns tensors in `self.graph` corresponding to arguments.\"\"\"\n return self._func_graph.inputs\n\n @property\n def structured_input_signature(self):\n \"\"\"Returns structured signature of the original function.\"\"\"\n return self._func_graph.structured_input_signature\n\n @property\n def outputs(self):\n \"\"\"Returns tensors in `self.graph` corresponding to returned tensors.\"\"\"\n return self._func_graph.outputs\n\n @property\n def structured_outputs(self):\n \"\"\"Returns outputs in `self.graph` as returned by the original function.\"\"\"\n return self._func_graph.structured_outputs\n\n @property\n def captured_inputs(self):\n \"\"\"Returns external Tensors captured by this function.\n\n self.__call__(*args) passes `args + self.captured_inputs` to the function.\n \"\"\"\n from_closures = nest.flatten([x() for x in self._captured_closures],\n expand_composites=True)\n return self._captured_inputs + from_closures\n\n @property\n def function_def(self):\n \"\"\"Returns a `FunctionDef` object representing this function.\"\"\"\n return self._delayed_rewrite_functions.forward().definition\n\n @property\n def output_shapes(self):\n \"\"\"The function's output shapes.\"\"\"\n return nest.map_structure(\n lambda x: getattr(x, \"shape\", tensor_shape.TensorShape(None)),\n composite_tensor.replace_composites_with_components(\n self._func_graph.structured_outputs),\n expand_composites=False)\n\n @property\n def output_dtypes(self):\n # TODO(akshayka): Consider removing this.\n return nest.map_structure(\n lambda x: x.dtype if x is not None else None,\n composite_tensor.replace_composites_with_components(\n self._func_graph.structured_outputs),\n expand_composites=False)\n\n def add_to_graph(self, g=None):\n \"\"\"Registers the function, adds it to the graph g or default graph.\n\n Args:\n g: If specified, registers the function with this graph. Defaults to the\n current context (either the default graph or the eager context).\n \"\"\"\n # If we are not executing eagerly, adds the function to default graph if no\n # graph is specified.\n # In case of eager execution, function definition gets added to context\n # during construction itself.\n\n if not context.executing_eagerly() and not g:\n g = ops.get_default_graph()\n self._delayed_rewrite_functions.forward().add_to_graph(g)\n\n def add_gradient_functions_to_graph(self, g=None):\n \"\"\"Add forward/backward functions to graph `g` or the current context.\"\"\"\n if not context.executing_eagerly() and not g:\n g = ops.get_default_graph()\n self._delayed_rewrite_functions.forward().add_to_graph(g)\n forward_function, backward_function = (\n self._delayed_rewrite_functions.forward_backward())\n forward_function.add_to_graph(g)\n backward_function.add_to_graph(g)\n\n def _get_gradient_function(self):\n \"\"\"Returns gradient function. It will be lazily created at first call.\"\"\"\n return self._delayed_rewrite_functions._rewrite_forward_and_call_backward # pylint: disable=protected-access\n\n def _select_forward_and_backward_functions(\n self, args, possible_gradient_type, executing_eagerly):\n \"\"\"Selects forward and backward functions based on the calling context.\n\n The forward function computes the \"real\" function outputs, `self._outputs`,\n and any extra values needed by the corresponding backward function.\n\n Args:\n args: A flat list of Tensors with all of the inputs to the forward\n function (including user-specified and captured inputs).\n possible_gradient_type: One of _POSSIBLE_GRADIENT_TYPES_*.\n executing_eagerly: Boolean, the value of context.executing_eagerly().\n\n Returns:\n An object with a `forward` method returning a tuple of (forward_function :\n _EagerDefinedFunction, augmented_arguments : List), and a corresponding\n `record` method which takes outputs from the forward function and records\n the operation. forward_function should be called with augmented_arguments.\n \"\"\"\n if executing_eagerly:\n input_tangents = forwardprop_util.pack_tangents(args)\n else:\n input_tangents = forwardprop_util.TangentInfo()\n need_gradients_for_jvps = tape.should_record_backprop(\n input_tangents.tangents)\n # Allows re-use of forward and backward function pairs depending on the\n # tapes and forward accumulators watching its inputs.\n cache_key = (need_gradients_for_jvps, input_tangents.indices)\n if possible_gradient_type == _POSSIBLE_GRADIENT_TYPES_FIRST_ORDER:\n if input_tangents.indices or executing_eagerly:\n # There is a single non-persistent tape active, so the user can only\n # request first-order gradients from a tape. We can spend less time\n # graph building since we know this.\n #\n # We may still end up computing higher-order gradients, but that'd be\n # through `tf.gradients`, which can re-write the forward pass and so\n # needs no preparation here.\n functions = self._first_order_tape_functions.get(cache_key, None)\n if functions is None:\n functions = _FirstOrderTapeGradientFunctions(\n self._func_graph, self._attrs, self._garbage_collector,\n forwardprop_input_indices=input_tangents.indices,\n delayed_rewrite_functions=self._delayed_rewrite_functions,\n need_gradients_for_jvps=need_gradients_for_jvps)\n self._first_order_tape_functions[cache_key] = functions\n return _ForwardBackwardCall(\n functions, args, input_tangents.tangents, tape_watching=True)\n else:\n # We can avoid computing second-order gradients in some cases by doing a\n # delayed rewrite when graph building. Since we know we'll only compute\n # first-order tape gradients, the delayed rewrite is safe: we won't need\n # to tell the tape about side outputs.\n #\n # TODO(allenl): This case is really dirty. It would be better if we\n # could temporarily pop all of the current tapes to avoid\n # accidentally taking second-order gradients.\n return _ForwardBackwardCall(\n self._delayed_rewrite_functions, args, input_tangents.tangents,\n tape_watching=True)\n elif possible_gradient_type == _POSSIBLE_GRADIENT_TYPES_HIGHER_ORDER:\n # Either there's a persistent tape watching, or there are multiple nested\n # tapes. Either way, the user may request higher-order gradients. We'll\n # spend a bit more time and make sure higher-order gradients are correct.\n functions = self._higher_order_tape_functions.get(\n cache_key, None)\n if functions is None:\n functions = _HigherOrderTapeGradientFunctions(\n self._func_graph, self._attrs, self._garbage_collector,\n forwardprop_input_indices=input_tangents.indices,\n delayed_rewrite_functions=self._delayed_rewrite_functions,\n need_gradients_for_jvps=need_gradients_for_jvps)\n self._higher_order_tape_functions[cache_key] = functions\n return _ForwardBackwardCall(functions, args, input_tangents.tangents,\n tape_watching=True)\n # else possible_gradient_type == _POSSIBLE_GRADIENT_TYPES_NONE, meaning no\n # tape is recording.\n return _ForwardBackwardCall(\n self._delayed_rewrite_functions, args, input_tangents.tangents,\n tape_watching=False)\n\n def _build_call_outputs(self, result):\n \"\"\"Maps the fdef output list to actual output structure.\n\n Args:\n result: Output lists defined by FunctionDef.\n Returns:\n The actual call output.\n \"\"\"\n if self._func_graph.structured_outputs is None:\n return result\n\n # Replace outputs with results, skipping over any 'None' values.\n outputs_list = nest.flatten(self._func_graph.structured_outputs,\n expand_composites=True)\n j = 0\n for i, o in enumerate(outputs_list):\n if o is not None:\n outputs_list[i] = result[j]\n j += 1\n ret = nest.pack_sequence_as(self._func_graph.structured_outputs,\n outputs_list, expand_composites=True)\n return ret\n\n\n_pywrap_utils.RegisterType(\"Tensor\", ops.Tensor)\n_pywrap_utils.RegisterType(\"EagerTensor\", ops.EagerTensor)\n_pywrap_utils.RegisterType(\"IndexedSlices\", ops.IndexedSlices)\n\n\ndef _deterministic_dict_values(dictionary):\n return tuple(dictionary[key] for key in sorted(dictionary))\n\n\nclass FunctionSpec(object):\n \"\"\"Specification of how to bind arguments to a function.\"\"\"\n\n @staticmethod\n def from_function_and_signature(python_function, input_signature,\n is_pure=False):\n \"\"\"Create a FunctionSpec instance given a python function and signature.\n\n Args:\n python_function: a function to inspect\n input_signature: a signature of the function (None, if variable)\n is_pure: if True all input arguments (including variables and constants)\n will be converted to tensors and no variable changes allowed.\n\n Returns:\n instance of FunctionSpec\n \"\"\"\n fullargspec = tf_inspect.getfullargspec(python_function)\n # Treat a wrapped partial function as a special case. For all arguments that\n # were overridden with keywords in the partial:\n # - remove the corresponding arguments,\n # - remove the corresponding keywords.\n _, unwrapped = tf_decorator.unwrap(python_function)\n # TODO(b/131153379): Consider Python3's fullargspec.kwonlyargs and\n # fullargspec.kwonlydefaults.\n if isinstance(unwrapped, functools.partial):\n # Also consider the Python3 case with kwonlydefaults.\n if fullargspec.defaults or fullargspec.kwonlydefaults:\n new_defaults = fullargspec.defaults\n new_args = fullargspec.args\n if fullargspec.defaults:\n # To be able to canonicalize the function properly, we want to ignore\n # default values that are overridden via a partial kwarg. For example:\n #\n # def func(a, b, c, d=5, e=7):\n # return a, b, c, d, e\n # p_func = functools.partial(tf.function(func, 10, e=9))\n #\n # Here we want to drop from the defaults the parameter `e`. If we\n # forwarded the call to the partial function with a default for `e`\n # we would get an error for passing two values for one parameter.\n #\n # Note that this has a limitation: we can only override parameters at\n # the end of the parameter list.\n #\n # In this case we want to end up with 3 arguments (b, c, d) and 1\n # default value (5). We do this by constructing a mask where 0 stands\n # for a value that was overridden by a partial kwarg. The seemingly\n # complicated logic below does just that - for arguments (b, c, d, e)\n # we would get a mask (1, 1, 1, 0).\n old_args = fullargspec.args\n old_defaults = fullargspec.defaults\n\n no_default = object()\n num_args_without_defaults = len(old_args) - len(old_defaults)\n left_padding = tuple([no_default] * num_args_without_defaults)\n\n args_with_defaults = zip(old_args, left_padding + old_defaults)\n\n # Create a mask where 0 stands for args that had a partial kwarg\n # defined.\n non_keyword_defaults_mask = [\n 0 if key in unwrapped.keywords else 1 for key in old_args\n ]\n # Keep only arguments and defaults that were not kwargs of partial.\n new_args_with_defaults = list(\n itertools.compress(args_with_defaults, non_keyword_defaults_mask))\n # Keep all args.\n new_args = [arg for arg, _ in new_args_with_defaults]\n # Keep only real default values.\n new_defaults = [\n default for _, default in new_args_with_defaults\n if default is not no_default\n ]\n fullargspec = tf_inspect.FullArgSpec(\n args=new_args,\n varargs=fullargspec.varargs,\n varkw=fullargspec.varkw,\n defaults=new_defaults,\n kwonlyargs=[],\n kwonlydefaults={},\n annotations=fullargspec.annotations)\n is_method = tf_inspect.ismethod(python_function)\n return FunctionSpec(fullargspec, is_method, [], {}, input_signature,\n is_pure=is_pure)\n\n def __init__(self, fullargspec, is_method, args_to_prepend, kwargs_to_include,\n input_signature, is_pure=False):\n self._fullargspec = fullargspec\n self._is_method = is_method\n self._is_pure = is_pure\n del args_to_prepend\n del kwargs_to_include\n self._default_values = fullargspec.defaults\n\n if self._is_method:\n # Remove `self`: default arguments shouldn't be matched to it.\n # TODO(b/127938157): Should this error out if there is no arg to\n # be removed?\n args = fullargspec.args[1:]\n else:\n args = fullargspec.args\n\n # A cache mapping from argument name to index, for canonicalizing\n # arguments that are called in a keyword-like fashion.\n self._args_to_indices = {arg: i for i, arg in enumerate(args)}\n self.arg_names = args\n self.vararg_name = fullargspec.varargs\n\n # A cache mapping from arg index to default value, for canonicalization.\n offset = len(args) - len(self._default_values or [])\n self._arg_indices_to_default_values = {\n offset + index: default\n for index, default in enumerate(self._default_values or [])\n }\n if input_signature is None:\n self._input_signature = None\n else:\n if fullargspec.kwonlyargs:\n raise ValueError(\"Cannot define a TensorFlow function from a Python \"\n \"function with keyword arguments when \"\n \"input_signature is provided.\")\n\n if not isinstance(input_signature, (tuple, list)):\n raise TypeError(\"input_signature must be either a tuple or a \"\n \"list, received \" + str(type(input_signature)))\n\n self._input_signature = tuple(input_signature)\n self._flat_input_signature = tuple(nest.flatten(input_signature,\n expand_composites=True))\n\n @property\n def fullargspec(self):\n return self._fullargspec\n\n @property\n def is_method(self):\n return self._is_method\n\n @property\n def args_to_prepend(self):\n return self._args_to_prepend\n\n @property\n def kwargs_to_include(self):\n return self._kwargs_to_include\n\n @property\n def input_signature(self):\n return self._input_signature\n\n @property\n def flat_input_signature(self):\n return self._flat_input_signature\n\n def _convert_variables_to_tensors(self, args, kwargs):\n args = [ops.convert_to_tensor(x) for x in args]\n kwargs = {kw: ops.convert_to_tensor(x) for kw, x in kwargs.items()}\n return tuple(args), kwargs\n\n def canonicalize_function_inputs(self, *args, **kwargs):\n \"\"\"Canonicalizes `args` and `kwargs`.\n\n Canonicalize the inputs to the Python function using a `FunctionSpec`\n instance. In particular, we parse the varags and kwargs that the\n original function was called with into a tuple corresponding to the\n Python function's positional (named) arguments and a dictionary\n corresponding to its kwargs.\n\n Args:\n *args: The varargs this object was called with.\n **kwargs: The keyword args this function was called with.\n\n Returns:\n A canonicalized ordering of the inputs representened by a tuple in the\n form (args, kwargs). Here: `args` is a full list of bound arguments, and\n `kwargs` contains only true keyword arguments, as opposed to named\n arguments called in a keyword-like fashion.\n\n Raises:\n ValueError: If a keyword in `kwargs` cannot be matched with a positional\n argument when an input signature is specified, or when the inputs\n do not conform to the input signature.\n \"\"\"\n if self._is_pure:\n args, kwargs = self._convert_variables_to_tensors(args, kwargs)\n if self._input_signature is not None:\n if len(args) > len(self._input_signature):\n raise TypeError(\n \"When input_signature is provided, only pass arguments \"\n \"covered by it. Received %d argument(s).\" % len(args))\n for arg in six.iterkeys(kwargs):\n index = self._args_to_indices.get(arg, None)\n if index is None:\n raise TypeError(\n \"Function got an unexpected keyword argument %s\" % arg)\n if index >= len(self._input_signature):\n raise TypeError(\n \"When input_signature is provided, only pass arguments \"\n \"covered by it. Received argument %s.\" % arg)\n\n if not kwargs:\n inputs = args\n default_keys = sorted(self._arg_indices_to_default_values.keys())\n if default_keys:\n assert min(default_keys) <= len(\n args), \"Not enough arguments (%s, %s, %s)\" % (args, default_keys,\n self.arg_names)\n for index in default_keys:\n if index >= len(args):\n inputs += (self._arg_indices_to_default_values[index],)\n else:\n # Maps from index of arg to its corresponding value, according to `args`\n # and `kwargs`; seeded with the default values for the named args that\n # aren't in `args`.\n arg_indices_to_values = {\n index: default for index, default in six.iteritems(\n self._arg_indices_to_default_values) if index >= len(args)\n }\n consumed_args = []\n for arg, value in six.iteritems(kwargs):\n index = self._args_to_indices.get(arg, None)\n if index is not None:\n arg_indices_to_values[index] = value\n consumed_args.append(arg)\n elif self._input_signature is not None:\n raise ValueError(\"Cannot define a TensorFlow function from a Python \"\n \"function with keyword arguments when \"\n \"input_signature is provided.\")\n for arg in consumed_args:\n # After this loop, `kwargs` will only contain true keyword arguments, as\n # opposed to named arguments called in a keyword-like fashion.\n kwargs.pop(arg)\n inputs = args + _deterministic_dict_values(arg_indices_to_values)\n\n if self._input_signature is None:\n inputs = _convert_numpy_inputs(inputs)\n return inputs, kwargs\n else:\n assert not kwargs\n inputs = _convert_inputs_to_signature(\n inputs,\n self._input_signature,\n self._flat_input_signature)\n return inputs, {}\n\n\ndef _convert_numpy_inputs(inputs):\n \"\"\"Convert numpy array inputs to tensors.\"\"\"\n # We assume that any CompositeTensors have already converted their components\n # from numpy arrays to Tensors, so we don't need to expand composites here.\n flat_inputs = nest.flatten(inputs, expand_composites=False)\n\n # Check for NumPy arrays in arguments and convert them to Tensors.\n # TODO(nareshmodi): Skip ndarray conversion to tensor altogether, perhaps\n # finding a way to store them directly in the cache key (currently not\n # possible since ndarrays are not hashable).\n need_packing = False\n for index, value in enumerate(flat_inputs):\n if type(value) == np.ndarray:\n flat_inputs[index] = constant_op.constant(value)\n need_packing = True\n if need_packing:\n return nest.pack_sequence_as(\n structure=inputs, flat_sequence=flat_inputs, expand_composites=False)\n else:\n return inputs\n\n\ndef _convert_inputs_to_signature(inputs, input_signature, flat_input_signature):\n \"\"\"Convert inputs to pass into a function with an explicit signature.\"\"\"\n\n def format_error_message(inputs, input_signature):\n return (\" inputs: (\\n\" + \" \" +\n \",\\n \".join([str(i) for i in inputs]) + \")\\n\" +\n \" input_signature: (\\n\" + \" \" +\n \",\\n \".join([str(i) for i in input_signature]) + \")\")\n\n try:\n # TODO(b/124370185): Use all elements as inputs to throw an error if there\n # are ignored arguments. Calling with arguments that are not part of the\n # signature should throw an error.\n flatten_inputs = nest.flatten_up_to(\n input_signature,\n inputs[:len(input_signature)],\n expand_composites=True)\n except ValueError:\n raise ValueError(\"Structure of Python function inputs does not match \"\n \"input_signature:\\n%s\" %\n format_error_message(inputs, input_signature))\n\n need_packing = False\n for index, (value, spec) in enumerate(zip(flatten_inputs,\n flat_input_signature)):\n if (isinstance(spec, tensor_spec.TensorSpec) and\n not _pywrap_utils.IsTensor(value)):\n try:\n flatten_inputs[index] = ops.convert_to_tensor(\n value, dtype_hint=spec.dtype)\n need_packing = True\n except ValueError:\n raise ValueError(\"When input_signature is provided, all inputs to \"\n \"the Python function must be convertible to \"\n \"tensors:\\n%s\" %\n format_error_message(inputs, input_signature))\n\n if any(not spec.is_compatible_with(other) for spec, other in zip(\n flat_input_signature,\n flatten_inputs)):\n raise ValueError(\"Python inputs incompatible with input_signature:\\n%s\" %\n format_error_message(inputs, input_signature))\n\n if need_packing:\n inputs = nest.pack_sequence_as(\n structure=input_signature,\n flat_sequence=flatten_inputs,\n expand_composites=True)\n\n return inputs\n\n\nclass FunctionCache(object):\n \"\"\"A lightweight container for cached functions.\n \"\"\"\n\n def __init__(self):\n # The set of functions that have been missed; entries are CacheKey with\n # input_signature `None` (e.g. a \"call context key\")\n self.missed = set()\n # The primary cache, mapping a fully shaped CacheKey to a function.\n self.primary = collections.OrderedDict()\n # A cache key lookup, mapping a CacheKey generated without shape info to a\n # flat list of relaxed shapes (one for each argument). Arguments that are\n # not Tensors contain a `None` for the corresponding relaxed shape.\n self.arg_relaxed_shapes = collections.OrderedDict()\n # The secondary cache, mapping a CacheKey generated without shape info to a\n # function.\n self.arg_relaxed = collections.OrderedDict()\n # All OrderedDicts require manual garbage collection.\n self._garbage_collectors = [\n _FunctionGarbageCollector(self.primary),\n _FunctionGarbageCollector(self.arg_relaxed),\n _FunctionGarbageCollector(self.arg_relaxed_shapes)]\n\n def all_values(self):\n \"\"\"A set of all `ConcreteFunction` instances held by this cache.\"\"\"\n return set(self.primary.values()) | set(self.arg_relaxed.values())\n\n\nclass Function(object):\n \"\"\"Wrapper class for the graph functions defined for a Python function.\n\n See the documentation for `defun` for more information on the semantics of\n defined functions.\n\n `Function` class is thread-compatible meaning that minimal usage of defuns\n (defining and calling) is thread-safe, but if users call other methods or\n invoke the base `python_function` themselves, external synchronization is\n necessary.\n In addition, Function is not reentrant, so recursive functions need to call\n the wrapped function, not the wrapper.\n \"\"\"\n\n def __init__(self,\n python_function,\n name,\n input_signature=None,\n attributes=None,\n autograph=True,\n autograph_options=None,\n experimental_relax_shapes=False,\n capture_by_value=None):\n \"\"\"Initializes a `Function`.\n\n Args:\n python_function: the function to be wrapped.\n name: the name given to it.\n input_signature: a possibly nested sequence of `TensorSpec` objects\n specifying the input signature of this function. If `None`, a separate\n function is instantiated for each inferred input signature.\n attributes: dict, extra keyword arguments that will be added as attribute\n of the function.\n autograph: whether to use autograph to compile\n `python_function`. See https://www.tensorflow.org/guide/autograph for\n more information.\n autograph_options: Experimental knobs to control behavior\n `when autograph=True`. See https://www.tensorflow.org/guide/autograph\n for more information.\n experimental_relax_shapes: When true, argument shapes may be relaxed to\n avoid unecessary retracing.\n capture_by_value: Experimental. Whether to capture resource variables by\n value or reference. If None, will inherit from a parent context or\n default to False.\n\n Raises:\n ValueError: if `input_signature` is not None and the `python_function`'s\n argspec has keyword arguments.\n \"\"\"\n self._python_function = python_function\n pure_function = attributes and IMPLEMENTS_ATTRIBUTE_NAME in attributes\n self._function_spec = FunctionSpec.from_function_and_signature(\n python_function, input_signature, is_pure=pure_function)\n self._name = name\n self._autograph = autograph\n self._autograph_options = autograph_options\n self._experimental_relax_shapes = experimental_relax_shapes\n self._function_cache = FunctionCache()\n self._function_attributes = attributes or {}\n self._capture_by_value = capture_by_value\n self.tracing_count = 0\n\n self._lock = threading.Lock()\n # _descriptor_cache is a of instance of a class to an instance-specific\n # `Function`, used to make sure defun-decorated methods create different\n # functions for each instance.\n self._descriptor_cache = weakref.WeakKeyDictionary()\n\n def __call__(self, *args, **kwargs):\n \"\"\"Calls a graph function specialized to the inputs.\"\"\"\n with self._lock:\n graph_function, args, kwargs = self._maybe_define_function(args, kwargs)\n return graph_function._filtered_call(args, kwargs) # pylint: disable=protected-access\n\n @property\n def python_function(self):\n \"\"\"Returns the wrapped Python function.\"\"\"\n return self._python_function # pylint: disable=protected-access\n\n @property\n def function_spec(self):\n return self._function_spec\n\n @property\n def input_signature(self):\n \"\"\"Returns the input signature.\"\"\"\n return self._function_spec.input_signature\n\n @property\n def flat_input_signature(self):\n \"\"\"Returns the flattened input signature.\"\"\"\n return self._function_spec.flat_input_signature\n\n def _get_concrete_function_internal_garbage_collected(self, *args, **kwargs):\n \"\"\"Returns a concrete function which cleans up its graph function.\"\"\"\n if self.input_signature:\n args, kwargs = None, None\n with self._lock:\n graph_function, _, _ = self._maybe_define_function(args, kwargs)\n return graph_function\n\n def _get_concrete_function_internal(self, *args, **kwargs):\n \"\"\"Bypasses error checking when getting a graph function.\"\"\"\n graph_function = self._get_concrete_function_internal_garbage_collected(\n *args, **kwargs)\n # We're returning this concrete function to someone, and they may keep a\n # reference to the FuncGraph without keeping a reference to the\n # ConcreteFunction object. So we won't clean up the reference cycles\n # manually and instead will leave them to Python's garbage collector.\n graph_function._garbage_collector.release() # pylint: disable=protected-access\n return graph_function\n\n def get_concrete_function(self, *args, **kwargs):\n \"\"\"Returns a `ConcreteFunction` specialized to inputs and execution context.\n\n Args:\n *args: inputs to specialize on.\n **kwargs: inputs to specialize on.\n \"\"\"\n if self.input_signature:\n if kwargs:\n raise ValueError(\"Cannot define a TensorFlow function from a Python \"\n \"function with keyword arguments when \"\n \"input_signature is provided.\")\n if args:\n # If args are provided, they must match the input signature.\n if not is_same_structure(self.input_signature, args):\n raise ValueError(\"Structure of Python function inputs does not match \"\n \"input_signature.\")\n flat_inputs = nest.flatten(args, expand_composites=True)\n if any(not isinstance(arg, (ops.Tensor, tensor_spec.DenseSpec,\n resource_variable_ops.BaseResourceVariable))\n for arg in flat_inputs):\n raise ValueError(\"When input_signature is provided, all inputs to \"\n \"the Python function must be Tensors, Variables, \"\n \"tf.TensorSpec or tf.VariableSpec objects.\")\n if any(not spec.is_compatible_with(other)\n for spec, other in zip(self.flat_input_signature, flat_inputs)):\n raise ValueError(\"Python inputs incompatible with input_signature: \"\n \"inputs (%s), input_signature (%s)\" %\n (str(args), str(self.input_signature)))\n args, kwargs = None, None\n with self._lock:\n graph_function, args, kwargs = self._maybe_define_function(args, kwargs)\n if self.input_signature:\n args = self.input_signature\n kwargs = {}\n seen_names = set()\n captured = object_identity.ObjectIdentitySet(\n graph_function.graph.internal_captures)\n # pylint: disable=protected-access\n graph_function._arg_keywords = []\n prefix_counts = {}\n # pylint: enable=protected-access\n num_positional = 0\n for arg in graph_function.graph.inputs:\n if arg in captured:\n break\n num_positional += 1\n user_arg_name = compat.as_str(arg.op.get_attr(\"_user_specified_name\"))\n proposal = user_arg_name\n while proposal in seen_names:\n index = prefix_counts.get(user_arg_name, 1)\n proposal = \"{}_{}\".format(user_arg_name, index)\n prefix_counts[user_arg_name] = index + 1\n seen_names.add(proposal)\n graph_function._arg_keywords.append(proposal) # pylint: disable=protected-access\n # Anything can be a positional argument, in the same order as .inputs\n graph_function._num_positional_args = num_positional # pylint: disable=protected-access\n return graph_function\n\n def __get__(self, instance, owner):\n \"\"\"Makes it possible to defun instance methods.\"\"\"\n del owner\n # `instance` here is the instance that this `Function` was accessed through\n # e.g., for\n #\n # class Foo(object):\n #\n # @function.defun\n # def bar(self):\n # ...\n #\n # foo = Foo()\n # foo.bar() # `foo.bar` is a `Function` instance\n #\n # then `instance` will be `foo` (and `owner` will be `Foo`). We create a\n # new instance of `Function` here to allow different instances each\n # to create variables once, thereby allowing methods to be decorated with\n # defun. Keeps a cache to avoid retracing the function every time the\n # descriptor is accessed.\n if instance not in self._descriptor_cache:\n if instance is None:\n return self\n # If there is no instance-specific `Function` in the cache, we construct\n # an instance-specific `Function` that uses a weak reference to the\n # instance (so that the instance will be correctly gc'd).\n\n # And finally add the wrapped function to the description cache\n self._descriptor_cache[instance] = class_method_to_instance_method(\n self, instance)\n\n # Return the cached `Function` for the instance\n return self._descriptor_cache[instance]\n\n def _cache_key(self, args, kwargs, include_tensor_ranks_only=False):\n \"\"\"Computes the cache key given inputs and execution context.\"\"\"\n if self.input_signature is None:\n inputs = (args, kwargs) if kwargs else args\n input_signature = pywrap_tensorflow.TFE_Py_EncodeArg(\n inputs, include_tensor_ranks_only)\n else:\n del args, kwargs\n assert not include_tensor_ranks_only\n input_signature = self.flat_input_signature\n\n ctx = context.context()\n\n # Don't need to open an init_scope if the _cache_key call is in eager mode\n # already.\n executing_eagerly = ctx.executing_eagerly()\n parent_graph = None\n if not executing_eagerly:\n with ops.init_scope():\n # The graph, or whether we're executing eagerly, should be a part of the\n # cache key so we don't improperly capture tensors such as variables.\n executing_eagerly = ctx.executing_eagerly()\n parent_graph = None if executing_eagerly else ops.get_default_graph()\n\n # pylint: disable=protected-access\n default_graph = ops.get_default_graph()\n # TODO(b/117617952): The current distribution strategy will affect graph\n # building (e.g. accessing different variables from different devices) and\n # so requires retracing for each device.\n strategy_stack = default_graph._distribution_strategy_stack\n uses_distribution_strategy = (\n strategy_stack and\n strategy_stack[-1].strategy.extended._retrace_functions_for_each_device\n )\n if executing_eagerly:\n colocation_stack = ()\n if uses_distribution_strategy:\n device_functions = (pydev.merge_device(ctx.device_name),)\n else:\n device_functions = ()\n\n # We should not be in XLA context in eager mode. So always set\n # `xla_context_id` to 0.\n xla_context_id = 0\n else:\n colocation_stack = tuple(default_graph._colocation_stack.peek_objs())\n if (uses_distribution_strategy\n or func_graph_module.device_stack_has_callable(\n default_graph._device_function_stack)):\n # Putting the device in the cache key ensures that call-site device\n # annotations are respected.\n device_functions = tuple(default_graph._device_functions_outer_to_inner)\n else:\n device_functions = ()\n\n # We want to force function retracing for each different\n # XLAControlFlowContext, so add `xla_context_id` to the cache key.\n tpu_context = _enclosing_xla_context()\n if tpu_context is not None:\n xla_context_id = id(tpu_context)\n else:\n xla_context_id = 0\n\n in_cross_replica_context = False\n try:\n in_cross_replica_context = (strategy_stack[-1].replica_context is None) # pylint: disable=protected-access\n except (AttributeError, IndexError):\n pass\n\n return CacheKey(\n _make_input_signature_hashable(input_signature), parent_graph,\n device_functions, colocation_stack, in_cross_replica_context,\n xla_context_id)\n\n def _create_graph_function(self, args, kwargs, override_flat_arg_shapes=None):\n \"\"\"Create a `ConcreteFunction` from `args` and `kwargs`.\"\"\"\n self.tracing_count += 1\n\n if self.input_signature is None:\n arglen = len(args)\n else:\n arglen = len(self.input_signature)\n base_arg_names = self._function_spec.arg_names[:arglen]\n num_missing_args = arglen - len(self._function_spec.arg_names)\n missing_arg_names = [self._function_spec.vararg_name] * num_missing_args\n # Produce a list of missing args of the form [\"arg_0\", \"arg_1\", ...],\n # where arg is based on the self._function_spec.vararg_name.\n missing_arg_names = [\n \"%s_%d\" % (arg, i) for i, arg in enumerate(missing_arg_names)\n ]\n arg_names = base_arg_names + missing_arg_names\n graph_function = ConcreteFunction(\n func_graph_module.func_graph_from_py_func(\n self._name,\n self._python_function,\n args,\n kwargs,\n self.input_signature,\n autograph=self._autograph,\n autograph_options=self._autograph_options,\n arg_names=arg_names,\n override_flat_arg_shapes=override_flat_arg_shapes,\n capture_by_value=self._capture_by_value),\n self._function_attributes,\n # Tell the ConcreteFunction to clean up its graph once it goes out of\n # scope. This is not the default behavior since it gets used in some\n # places (like Keras) where the FuncGraph lives longer than the\n # ConcreteFunction.\n shared_func_graph=False)\n return graph_function\n\n def _define_function_with_shape_relaxation(self, args, kwargs):\n \"\"\"Define a function, relaxing arg shapes to avoid unecessary retracing.\"\"\"\n\n rank_only_cache_key = self._cache_key(\n args, kwargs, include_tensor_ranks_only=True)\n\n arg_shapes = _flat_shape_list(args, kwargs)\n relaxed_arg_shapes = self._function_cache.arg_relaxed_shapes.get(\n rank_only_cache_key, None)\n relaxed_arg_function = self._function_cache.arg_relaxed.get(\n rank_only_cache_key, None)\n\n if (relaxed_arg_function is not None\n and _compatible_shapes(flat_relaxed=relaxed_arg_shapes,\n flat_to_check=arg_shapes)):\n return relaxed_arg_function, args, kwargs\n\n if relaxed_arg_shapes is None:\n relaxed_arg_shapes = arg_shapes\n else:\n if len(arg_shapes) != len(relaxed_arg_shapes):\n raise RuntimeError(\"Expected arg_shapes len to match \"\n \"relaxed_arg_shapes len: %d vs. %d\"\n % (len(arg_shapes), len(relaxed_arg_shapes)))\n relaxed_arg_shapes = [\n common_shape(x, y) for (x, y) in zip(\n arg_shapes, relaxed_arg_shapes)]\n self._function_cache.arg_relaxed_shapes[rank_only_cache_key] = (\n relaxed_arg_shapes)\n graph_function = self._create_graph_function(\n args, kwargs, override_flat_arg_shapes=relaxed_arg_shapes)\n self._function_cache.arg_relaxed[rank_only_cache_key] = graph_function\n\n return graph_function, args, kwargs\n\n def _maybe_define_function(self, args, kwargs):\n \"\"\"Gets a function for these inputs, defining it if necessary.\n\n `args` and `kwargs` can be None if this `Function` was created with an\n `input_signature`.\n\n Caller must hold self._lock.\n\n Args:\n args: The varargs for the Python function.\n kwargs: The keyword args for the Python function.\n\n Returns:\n A graph function corresponding to the input signature implied by args and\n kwargs, as well as the inputs that the object should be called with.\n\n Raises:\n ValueError: If inputs are incompatible with the input signature.\n TypeError: If the function inputs include non-hashable objects\n RuntimeError: If there's an internal bug (inconsistency) in handling\n shape relaxation retracing.\n \"\"\"\n if self.input_signature is None or args is not None or kwargs is not None:\n args, kwargs = self._function_spec.canonicalize_function_inputs(\n *args, **kwargs)\n\n cache_key = self._cache_key(args, kwargs)\n\n try:\n hash(cache_key)\n except TypeError as e:\n raise TypeError(\n \"Arguments supplied to `defun`-generated functions must be\"\n \" hashable. Original error: %s\" % e)\n\n graph_function = self._function_cache.primary.get(cache_key, None)\n if graph_function is not None:\n return graph_function, args, kwargs\n\n logging.vlog(1,\n \"Creating new FuncGraph for Python function %r (key: %r)\",\n self._python_function, cache_key)\n logging.vlog(2,\n \"Python function signature [args: %s] [kwargs: %s]\",\n args,\n kwargs)\n\n # pylint: disable=protected-access\n call_context_key = cache_key._replace(input_signature=None)\n # pylint: disable=protected-access\n\n ag_status = (\n ag_ctx.Status.ENABLED if self._autograph else ag_ctx.Status.DISABLED)\n with ag_ctx.ControlStatusCtx(\n status=ag_status, options=self._autograph_options):\n\n # Build a function with shape relaxation retracing if:\n # 1. shape relaxation is explicitly enabled\n # and 2. there's no provided input signature\n # and 3. there's been a cache miss for this calling context\n if (self._experimental_relax_shapes\n and self.input_signature is None\n and call_context_key in self._function_cache.missed):\n return self._define_function_with_shape_relaxation(args, kwargs)\n\n self._function_cache.missed.add(call_context_key)\n graph_function = self._create_graph_function(args, kwargs)\n self._function_cache.primary[cache_key] = graph_function\n return graph_function, args, kwargs\n\n\ndef register(func, *args, **kwargs):\n \"\"\"Register a specialization of a `Function` into the graph.\n\n This won't actually call the function with the inputs, and only put the\n function definition into graph. Register function with different input param\n will result into multiple version of functions registered in graph.\n\n Args:\n func: the `Function` instance that generated by a @defun\n *args: input arguments for the Python function.\n **kwargs: input keyword arguments for the Python function.\n\n Returns:\n a `ConcreteFunction` object specialized to inputs and execution context.\n\n Raises:\n ValueError: When the input function is not a defun wrapped python function.\n \"\"\"\n if not isinstance(func, Function):\n raise ValueError(\"Only defun function is allowed to be registered. \"\n \"Got type: %s\" % type(func))\n concrete_func = func.get_concrete_function(*args, **kwargs)\n concrete_func.add_to_graph()\n concrete_func.add_gradient_functions_to_graph()\n return concrete_func\n\n\ndef validate_signature(signature):\n if any(not isinstance(arg, tensor_spec.DenseSpec)\n for arg in nest.flatten(signature, expand_composites=True)):\n raise TypeError(\"Invalid input_signature {}; input_signature must be \"\n \"a possibly nested sequence of TensorSpec objects.\"\n .format(signature))\n\n\ndef defun(func=None,\n input_signature=None,\n autograph=True,\n experimental_autograph_options=None,\n experimental_relax_shapes=False):\n \"\"\"Compiles a Python function into a callable TensorFlow graph.\n\n `defun` (short for \"define function\") compiles a Python function\n composed of TensorFlow operations into a callable that executes a `tf.Graph`\n containing those operations. The callable produced by `defun` contains only\n the subgraph of TensorFlow operations that were executed when the Python\n function was called with a particular input signature, defined as a list\n of the shapes and dtypes of the Python function's Tensor-valued arguments and\n the values of its non-Tensor Python objects.\n\n When eager execution is enabled, the ability to create graphs from Python\n functions makes it possible to incrementally trade off debugability and\n interactivity for performance. Functions compiled with `defun` cannot be\n inspected with `pdb`; however, executing a graph\n generated by `defun` sometimes takes less time and memory than eagerly\n executing the corresponding Python function, since specifying computations as\n graphs allows for optimizations like automatic buffer reuse and\n parallelization among ops. Note that executing a `defun`-compiled function\n incurs a small constant overhead, so eagerly executing sufficiently small\n Python functions might take less time than executing their corresponding\n `defun`-generated graphs.\n\n For a Python function to be compatible with `defun`, all of its arguments must\n be hashable Python objects or lists thereof. The function itself may not\n modify the list/map structure of its arguments. Additionally, it must return\n zero or more `tf.Tensor` objects. If the Python function returns\n a `tf.Variable`, its compiled version will return the value of that variable\n as a `tf.Tensor`.\n\n Executing a graph generated by `defun` respects device annotations (i.e.,\n all `with tf.device` directives present in a Python function will also be\n present in its corresponding graph), but it is not yet possible to execute the\n generated graphs across multiple machines.\n\n _Example Usage_\n\n ```python\n import tensorflow as tf\n\n tf.compat.v1.enable_eager_execution()\n\n # A simple example.\n def f(x, y):\n return tf.reduce_mean(tf.multiply(x ** 2, 3) + y)\n\n g = tf.contrib.eager.defun(f)\n\n x = tf.constant([[2.0, 3.0]])\n y = tf.constant([[3.0, -2.0]])\n\n # `f` and `g` will return the same value, but `g` will be executed as a\n # TensorFlow graph.\n assert f(x, y).numpy() == g(x, y).numpy()\n\n # `defun` is capable of compiling Python functions that close over Python\n # objects, including Tensors and Variables.\n @tf.contrib.eager.defun\n def h():\n return f(x, y)\n\n assert (h().numpy() == f(x, y).numpy()).all()\n\n # `defun` automatically lifts variables out of the graphs it creates,\n # allowing you to compile the `call` methods of `tf.keras.layers.Layer` and\n # `tf.keras.Model` objects.\n class MyModel(tf.keras.Model):\n\n def __init__(self, keep_probability=0.2):\n super(MyModel, self).__init__()\n self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)\n self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)\n self.keep_probability = keep_probability\n\n @tf.contrib.eager.defun\n def call(self, inputs, training=True):\n x = self.dense2(self.dense1(inputs))\n if training:\n return tf.nn.dropout(x, self.keep_probability)\n else:\n return x\n\n model = MyModel()\n model(x, training=True) # executes a graph, with dropout\n model(x, training=False) # executes a graph, without dropout\n\n # `defun`-compiled functions are differentiable.\n optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.01)\n with tf.GradientTape() as tape:\n outputs = model(x)\n gradient = tape.gradient(outputs, model.trainable_variables)\n optimizer.apply_gradients((grad, var) for grad, var in zip(gradient,\n model.trainable_variables))\n ```\n\n When using `defun`, there are subtleties regarding inputs, Python control\n flow, and variable creation that one should be aware of. For concreteness, let\n `f` be a Python function that returns zero or more `tf.Tensor` objects and\n let `F = defun(f)`. `F` builds a graph for each unique input signature it\n sees, Python control flow is baked into graphs, and operations related to\n variable initialization are automatically lifted out of the graphs that `F`\n generates and placed in the eager context if executing eagerly or into an\n outer graph otherwise.\n\n _Input Signatures_\n\n By default, `F = tf.contrib.eager.defun(f)` instantiates a separate graph\n for every unique sequence of the shapes and dtypes of Tensor arguments and\n the values of Python objects it is invoked with. For example, calling\n `F(tf.random.uniform([2])` will execute a different graph than\n `F(tf.random.uniform([3])` because the two inputs have different shapes.\n The first time that `F(*args, **kwargs)` is called with a particular sequence\n of Tensor shapes and dtypes and Python values, it constructs a graph by\n tracing the execution of `f(*args, **kwargs)`; this graph is bound to an\n input signature inferred from `(*args, **kwargs)` and cached for future reuse.\n\n NumPy arrays passed as inputs to `F` are converted to `tf.Tensor` objects\n before being passed to `f`, and are treated as Tensors for caching. This\n allows a function to be called multiple times with NumPy arrays having\n different values but the same shape and dtype without re-tracing each time.\n\n `tf.contrib.eager.defun` caches graphs for your convenience, letting you\n define TensorFlow functions without explicitly specifying their signatures.\n However, this policy is conservative and potentially expensive; for example,\n when different invocations of your function have differently-shaped Tensor\n inputs, this policy might generate more graph functions than necessary. To\n eliminate such costs, `tf.contrib.eager.defun` allows you to supply an\n optional `input_signature` argument specifying the shapes and dtypes of the\n inputs. In particular, the shapes may be partially unspecified, with `None`s\n in the unknown dimensions. When an input signature is provided,\n `tf.contrib.eager.defun` will only instantiate a single graph for the\n decorated Python function. The following is an example:\n\n ```python\n import tensorflow as tf\n\n # The first `TensorSpec` below describes the shape and dtype of `words`,\n # and the second describes the shape and dtype of `another_tensor`. Note that\n # the last dimension of the `words` `TensorSpec` is left unspecified.\n @tf.contrib.eager.defun(input_signature=[\n tf.contrib.eager.TensorSpec(shape=[50, 300, None], dtype=tf.float32),\n tf.contrib.eager.TensorSpec(shape=[300, 100], dtype=tf.float32)\n ])\n def my_sequence_model(words, another_tensor):\n ...\n\n # Note how the third dimension of the first input can vary freely.\n words = tf.random.uniform(([50, 300, 10])\n second_input = tf.random.uniform([300, 100])\n my_sequence_model(words, second_input)\n\n words = tf.random.uniform(([50, 300, 20])\n my_sequence_model(words, second_input)\n\n # Passing an input with an incompatible shape will raise an error.\n words = tf.random.uniform(([50, 100, 20])\n my_sequence_model(words, second_input) # <---- This will raise an error.\n\n ```\n\n Python functions that are compiled with an `input_signature` must only accept\n Tensors as arguments and must not take unnamed keyword arguments (**kwargs).\n\n _Tracing_\n\n Be aware that because `F` only logs TensorFlow operations, all the other\n Python code that `f` executes will only shape the _construction_ of the graphs\n that `F` executes: the Python code won't be executed when the graphs\n themselves are executed, though it will be executed every time the Python\n function is traced (and a given Python function might be traced multiple\n times, once for each input signature it is invoked with). For example, whereas\n the Python function\n\n ```python\n import tensorflow as tf\n import numpy as np\n\n tf.compat.v1.enable_eager_execution()\n\n def add_noise():\n return tf.eye(5) + np.random.randn(5, 5)\n ```\n\n will return a different output everytime it is invoked, the compiled function\n `compiled = tf.contrib.eager.defun(add_noise)` will return the same value\n every time it is called, since a particular random offset generated by NumPy\n will be inserted into the graph as a TensorFlow constant. The solution is to\n replace the call to `np.random.randn` with `tf.random.normal((5, 5))`.\n\n _Python Side-Effects_\n\n A corollary of the previous discussion on tracing is the following: If a\n Python function `f` has Python side-effects, then executing `f` multiple times\n will not necessarily be semantically equivalent to executing `F =\n tf.contrib.eager.defun(f)` multiple times; this difference is due to the fact\n that `defun` only captures the subgraph of TensorFlow operations that is\n constructed when `f` is called in a graph-building context.\n\n _Python Control Flow_\n\n The structure of many machine learning computations depend upon whether one is\n training or validating, and it is common to nest specialized logic under `if\n training:` blocks. By mapping each input signature to a unique graph, `defun`\n lets users transparently compile such code, as the following code snippet\n demonstrates:\n\n ```python\n import tensorflow as tf\n\n tf.compat.v1.enable_eager_execution()\n\n @tf.contrib.eager.defun\n def lossy_matmul(W, x, training=True):\n outputs = tf.matmul(W, x)\n if training:\n outputs = tf.nn.dropout(outputs, keep_probability=0.2)\n return outputs\n\n W = tf.random.normal((3, 5))\n x = tf.random.normal((5, 1))\n\n # Executes a graph that applies dropout.\n lossy_outputs = lossy_matmul(W, x, training=True)\n\n # Executes a graph that does not apply dropout.\n exact_outputs = lossy_matmul(W, x, training=False)\n ```\n\n _TensorFlow Control Flow_\n\n When `autograph` is `True`, data-dependent control flow is allowed as well.\n Control flow statements that depend on `Tensor` values are staged into\n corresponding TensorFlow ops. For example, the following code will work as\n expected:\n\n ```python\n @tf.contrib.eager.defun\n def dynamic_rnn_loop(cell, seq):\n state, output = cell.zero_state()\n for input in seq:\n state, output = cell(input, state)\n return output\n ```\n\n For more information see `tf.autograph`.\n\n _Variables_\n\n TensorFlow operations related to variable creation and initialization are\n automatically lifted out of the graphs generated by `defun`. In practice, this\n implies that variable creation and initialization only happen the first time\n `F` is called, and that variables are reused every time thereafter. Many\n TensorFlow APIs, like `tf.keras.layers.Layer` objects, create variables the\n first time they are called and reuse them thereafter. Automatic variable\n lifting makes it possible to compile these APIs without extra effort, at the\n cost of introducing a discrepancy between the semantics of executing Python\n functions and their corresponding compiled functions. For example:\n\n ```python\n import tensorflow as tf\n\n tf.compat.v1.enable_eager_execution()\n\n def fn():\n x = tf.Variable(0.0)\n x.assign_add(1.0)\n return x.read_value()\n\n # `fn` is a Python function, so x is created, initialized, and destroyed upon\n # every invocation\n assert fn().numpy() == fn().numpy() == 1.0\n\n compiled = tf.contrib.eager.defun(fn)\n\n # Compiling `fn` with `defun` hoists all variables outside of the generated\n # graph, so initialization happens exactly once.\n assert compiled().numpy() == 1.0\n assert compiled().numpy() == 2.0\n ```\n\n Finally, because each input signature is bound to a unique graph, if your\n Python function constructs `tf.Variable` objects, then each graph constructed\n for that Python function will reference a unique set of variables. To\n circumvent this problem, we recommend against compiling Python functions that\n create `tf.Variable` objects. Instead, Python functions should either\n lexically close over `tf.Variable` objects or accept them as arguments,\n preferably encapsulated in an object-oriented container. If you must create\n variables inside your Python function and you want each graph generated for it\n to reference the same set of variables, add logic to your Python function that\n ensures that variables are only created the first time it is called and are\n reused for every subsequent invocation; note that this is precisely what\n `tf.keras.layers.Layer` objects do, so we recommend using them to represent\n variable-bearing computations whenever possible.\n\n Args:\n func: function to be compiled. If `func` is None, returns a\n decorator that can be invoked with a single argument - `func`. The\n end result is equivalent to providing all the arguments up front.\n In other words, defun(input_signature=...)(func) is equivalent to\n defun(func, input_signature=...). The former allows\n the following use case:\n @tf.contrib.eager.defun(input_signature=...)\n def foo(...):\n ...\n\n input_signature: A possibly nested sequence of\n `tf.contrib.eager.TensorSpec` objects specifying the shapes and dtypes of\n the Tensors that will be supplied to this function. If `None`, a separate\n function is instantiated for each inferred input signature. If a\n signature is specified, every input to `func` must be a `Tensor`, and\n `func` cannot accept `**kwargs`.\n autograph: Whether `func` should be compiled before\n constructing the graph. See https://www.tensorflow.org/guide/autograph\n for more information.\n experimental_autograph_options: Experimental knobs (in the form of a tuple\n of tensorflow.autograph.Feature values) to control behavior when\n autograph=True.\n experimental_relax_shapes: When true, argument shapes may be relaxed to\n avoid unecessary retracing.\n\n Returns:\n If `func` is not None, returns a callable that will execute the compiled\n function (and return zero or more `tf.Tensor` objects).\n If `func` is None, returns a decorator that, when invoked with a single\n `func` argument, returns a callable equivalent to the case above.\n\n Raises:\n TypeError: If `input_signature` is neither `None` nor a sequence of\n `tf.contrib.eager.TensorSpec` objects.\n \"\"\"\n return defun_with_attributes(\n func=func,\n input_signature=input_signature,\n autograph=autograph,\n experimental_autograph_options=experimental_autograph_options,\n experimental_relax_shapes=experimental_relax_shapes)\n\n\ndef defun_with_attributes(func=None,\n input_signature=None,\n attributes=None,\n autograph=True,\n experimental_autograph_options=None,\n experimental_relax_shapes=False):\n \"\"\"Compiles a Python function into a callable TensorFlow graph.\n\n This function supports adding extra function attributes. See detailed\n documentation in defun(). Currently this is not exposed in public API since we\n don't expect user to directly use attributes, and attribute won't work by\n itself. This assumption might change in future.\n\n Args:\n func: function to be compiled.\n input_signature: same as defun()'s input_signature.\n attributes: A dictionary of arguments which will be added to function def as\n attributes. Currently only support primitive types as value, and only\n whitelisted attribute name is allowed. Unwhitelisted attribute name or\n unsupported value will result into ValueError. `func_name` is also one of\n the whitelisted argument which is a python string, and sets the name for\n this `ConcreteFunction` in the graph.\n autograph: same as defun()'s autograph.\n experimental_autograph_options: same as defun()'s\n experimental_autograph_options.\n experimental_relax_shapes: same as defun()'s experimental_relax_shapes\n\n Returns:\n Same as the return value of defun, with attributes added to the function in\n graph.\n \"\"\"\n if input_signature is not None:\n validate_signature(input_signature)\n\n # TODO(apassos): deal with captured global state. Deal with control flow.\n def decorated(function):\n try:\n if attributes:\n name = attributes.pop(\"func_name\", function.__name__)\n else:\n name = function.__name__\n except AttributeError:\n name = \"function\"\n return tf_decorator.make_decorator(\n function,\n Function(\n function,\n name,\n input_signature=input_signature,\n attributes=attributes,\n autograph=autograph,\n autograph_options=experimental_autograph_options,\n experimental_relax_shapes=experimental_relax_shapes))\n\n # This code path is for the `foo = tfe.defun(foo, ...)` use case\n if func is not None:\n return decorated(func)\n\n # This code path is for the\n #\n # @tfe.defun(...)\n # def foo(...):\n # ...\n #\n # use case, which is equivalent to `foo = tfe.defun(...)(foo)`\n return decorated\n\n\n# When a method is bound to objects of this type, it allows AutoGraph to\n# recover a weak reference the original method's self pointer, so that it can\n# execute it consistent with class_method_to_instance_method's\n# bound_method_wrapper.\n# TODO(b/119246461): This is not pretty. Use a descriptor instead?\nclass TfMethodTarget(object):\n \"\"\"Binding target for methods replaced by function and defun.\"\"\"\n\n def __init__(self, target, original_python_function):\n self.weakrefself_target__ = target\n self.weakrefself_func__ = weakref.ref(original_python_function)\n\n @property\n def target(self):\n return self.weakrefself_target__()\n\n def call(self, args, kwargs):\n wrapped_fn = self.weakrefself_func__()\n if tf_inspect.ismethod(wrapped_fn):\n wrapped_fn = six.get_unbound_function(wrapped_fn)\n return wrapped_fn(self.weakrefself_target__(), *args, **kwargs)\n\n\ndef class_method_to_instance_method(original_function, instance):\n \"\"\"Constructs a new `Function` with `self` bound.\"\"\"\n weak_instance = weakref.ref(instance)\n\n # Note: while we could bind to a weakref proxy instead, that causes the\n # bound method to be unhashable.\n bound_method = types_lib.MethodType(\n original_function.python_function,\n TfMethodTarget(weak_instance, original_function.python_function))\n\n # original_function is expected to be of one of the two `Function` types\n # (defined either in function.py or def_function.py).\n assert hasattr(original_function, \"_name\")\n assert hasattr(original_function, \"_autograph\")\n assert hasattr(original_function, \"_function_spec\")\n assert hasattr(original_function, \"python_function\")\n\n weak_bound_method_wrapper = None\n def bound_method_wrapper(*args, **kwargs):\n \"\"\"Wraps either a dummy MethodType or a converted AutoGraph function.\"\"\"\n # __wrapped__ allows AutoGraph to swap in a converted function.\n strong_bound_method_wrapper = weak_bound_method_wrapper()\n wrapped_fn = strong_bound_method_wrapper.__wrapped__\n\n if wrapped_fn is strong_bound_method_wrapper.__original_wrapped__:\n # If __wrapped__ was not replaced, then call original_function.\n # TODO(mdan): For better consistency, use the wrapper's call().\n wrapped_fn = original_function.python_function\n if tf_inspect.ismethod(wrapped_fn):\n wrapped_fn = six.get_unbound_function(wrapped_fn)\n return wrapped_fn(weak_instance(), *args, **kwargs)\n\n # If __wrapped__ was replaced, then it is always an unbound function.\n # However, the replacer is still responsible for attaching self properly.\n # TODO(mdan): Is it possible to do it here instead?\n return wrapped_fn(*args, **kwargs)\n weak_bound_method_wrapper = weakref.ref(bound_method_wrapper)\n\n # pylint: disable=protected-access\n # We make a dummy MethodType object to generate the correct bound method\n # signature. The actual call is to a function with a weak reference to\n # `instance`.\n instance_func = type(original_function)(\n tf_decorator.make_decorator(bound_method, bound_method_wrapper),\n name=original_function._name,\n autograph=original_function._autograph,\n input_signature=original_function.input_signature)\n # pylint: enable=protected-access\n\n # And we wrap the function with tf_decorator so inspection works correctly\n wrapped_instance_func = tf_decorator.make_decorator(\n original_function.python_function, instance_func)\n return wrapped_instance_func\n\n\nclass _FunctionGarbageCollector(object):\n \"\"\"Cleans up cycles when a defun goes out of scope.\"\"\"\n\n def __init__(self, cache):\n self._cache = cache\n\n def __del__(self):\n if func_graph_module is None or memory is None:\n return\n try:\n while self._cache:\n self._cache.popitem()\n memory.dismantle_ordered_dict(self._cache)\n except: # pylint: disable=bare-except\n pass\n\n\nclass ConcreteFunctionGarbageCollector(object):\n \"\"\"Cleans up reference cycles when a `ConcreteFunction` goes out of scope.\"\"\"\n\n def __init__(self, func_graph):\n self._func_graph = func_graph\n\n def release(self):\n \"\"\"Call off the FuncGraph deletion.\"\"\"\n self._func_graph = None\n\n def __del__(self):\n if func_graph_module is None or memory is None or self._func_graph is None:\n return\n try:\n func_graph_module.dismantle_func_graph(self._func_graph)\n except: # pylint: disable=bare-except\n pass\n"
]
| [
[
"tensorflow.python.eager.tape.stop_recording",
"tensorflow.python.eager.context.context",
"tensorflow.python.eager.tape.should_record_backprop",
"tensorflow.python.framework.composite_tensor.replace_composites_with_components",
"tensorflow.python.util.tf_inspect.FullArgSpec",
"tensorflow.python.framework.ops.init_scope",
"tensorflow.python.framework.tensor_shape.dimension_value",
"tensorflow.python.eager.forwardprop_util.TangentInfo",
"tensorflow.python.framework.func_graph.dismantle_func_graph",
"tensorflow.python.ops.functional_ops.partitioned_call",
"tensorflow.python.util.nest.flatten",
"tensorflow.python.pywrap_tensorflow.TF_FunctionToFunctionDef",
"tensorflow.python.pywrap_tensorflow.TF_GetBuffer",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.core.framework.function_pb2.FunctionDef",
"tensorflow.python.framework.ops.device",
"tensorflow.python.util.tf_inspect.ismethod",
"tensorflow.python.util.memory.dismantle_ordered_dict",
"tensorflow.python._pywrap_utils.IsTensor",
"tensorflow.python.framework.ops.control_dependencies",
"tensorflow.python.eager.backprop.aggregate_indexed_slices_gradients",
"tensorflow.python.framework.c_api_util.ScopedTFFunction",
"tensorflow.python.pywrap_tensorflow.TFE_Py_TapeSetPossibleGradientTypes",
"tensorflow.python.util.compat.as_text",
"tensorflow.python.framework.error_interpolation.parse_message",
"tensorflow.python.ops.resource_variable_ops.variable_accessed",
"tensorflow.python.eager.context.ensure_initialized",
"tensorflow.python.compat.compat.forward_compatible",
"tensorflow.python.framework.func_graph.device_stack_has_callable",
"tensorflow.python.framework.c_api_util.tf_buffer",
"tensorflow.python.ops.array_ops.placeholder",
"tensorflow.python.framework.device.merge_device",
"tensorflow.python.util.nest.assert_same_structure",
"tensorflow.python.framework.func_graph.func_graph_from_py_func",
"tensorflow.python.ops.gradients_util._GradientsHelper",
"tensorflow.python.util.tf_decorator.make_decorator",
"tensorflow.python.eager.backprop_util.IsTrainable",
"tensorflow.python.ops.custom_gradient.copy_handle_data",
"tensorflow.python.eager.tape.record_operation_backprop_only",
"tensorflow.python.eager.tape.could_possibly_record",
"tensorflow.python.util.nest.pack_sequence_as",
"tensorflow.python.framework.ops.tensor_id",
"tensorflow.python.util.tf_decorator.unwrap",
"tensorflow.python.util.function_utils.get_disabled_rewriter_config",
"tensorflow.python.framework.tensor_spec.TensorSpec",
"tensorflow.python.ops.default_gradient.shape_and_dtype",
"tensorflow.core.framework.attr_value_pb2.AttrValue",
"tensorflow.python.platform.tf_logging.vlog",
"tensorflow.python.eager.forwardprop_util.pack_tangents",
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.python._pywrap_utils.RegisterType",
"tensorflow.python.eager.tape.record_operation",
"tensorflow.python.util.nest.map_structure",
"tensorflow.python.util.object_identity.ObjectIdentitySet",
"tensorflow.python.pywrap_tensorflow.TFE_Py_PackJVPs",
"tensorflow.python.pywrap_tensorflow.TFE_Py_EncodeArg",
"tensorflow.python.eager.context.add_function",
"tensorflow.python.eager.context.remove_function",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.framework.constant_op.constant",
"tensorflow.python.eager.forwardprop_util.push_forwardprop_state",
"tensorflow.python.ops.default_gradient.zeros_like",
"tensorflow.python.util.tf_inspect.getfullargspec",
"tensorflow.python.framework.ops.uid",
"tensorflow.python.eager.graph_only_ops.graph_placeholder",
"tensorflow.python.framework.error_interpolation.interpolate",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.eager.tape.record_operation_forwardprop_only",
"tensorflow.python.util.compat.as_bytes",
"tensorflow.python.util.compat.as_str"
]
]
|
laleph/holoviews | [
"7c06dbd63945fd66e63b17060956634be3ba17fe"
]
| [
"tests/testbokehgraphs.py"
]
| [
"from __future__ import absolute_import\n\nfrom unittest import SkipTest\n\nimport numpy as np\nfrom holoviews.core.data import Dataset\nfrom holoviews.core.options import Store\nfrom holoviews.element import Graph, TriMesh, circular_layout\nfrom holoviews.element.comparison import ComparisonTestCase\nfrom holoviews.plotting import comms\n\ntry:\n from holoviews.plotting.bokeh.util import bokeh_version\n bokeh_renderer = Store.renderers['bokeh']\n from bokeh.models import (NodesAndLinkedEdges, EdgesAndLinkedNodes, Patches)\n from bokeh.models.mappers import CategoricalColorMapper, LinearColorMapper\nexcept :\n bokeh_renderer = None\n\n\nclass BokehGraphPlotTests(ComparisonTestCase):\n \n def setUp(self):\n if not bokeh_renderer:\n raise SkipTest(\"Bokeh required to test plot instantiation\")\n self.previous_backend = Store.current_backend\n Store.current_backend = 'bokeh'\n self.default_comm = bokeh_renderer.comms['default']\n\n N = 8\n self.nodes = circular_layout(np.arange(N, dtype=np.int32))\n self.source = np.arange(N, dtype=np.int32)\n self.target = np.zeros(N, dtype=np.int32)\n self.weights = np.random.rand(N)\n self.graph = Graph(((self.source, self.target),))\n self.node_info = Dataset(['Output']+['Input']*(N-1), vdims=['Label'])\n self.node_info2 = Dataset(self.weights, vdims='Weight')\n self.graph2 = Graph(((self.source, self.target), self.node_info))\n self.graph3 = Graph(((self.source, self.target), self.node_info2))\n self.graph4 = Graph(((self.source, self.target, self.weights),), vdims='Weight')\n\n def tearDown(self):\n Store.current_backend = self.previous_backend\n bokeh_renderer.comms['default'] = self.default_comm\n \n def test_plot_simple_graph(self):\n plot = bokeh_renderer.get_plot(self.graph)\n node_source = plot.handles['scatter_1_source']\n edge_source = plot.handles['multi_line_1_source']\n layout_source = plot.handles['layout_source']\n self.assertEqual(node_source.data['index'], self.source)\n self.assertEqual(edge_source.data['start'], self.source)\n self.assertEqual(edge_source.data['end'], self.target)\n layout = {str(int(z)): (x, y) for x, y, z in self.graph.nodes.array()}\n self.assertEqual(layout_source.graph_layout, layout)\n\n def test_plot_graph_with_paths(self):\n graph = self.graph.clone((self.graph.data, self.graph.nodes, self.graph.edgepaths))\n plot = bokeh_renderer.get_plot(graph)\n node_source = plot.handles['scatter_1_source']\n edge_source = plot.handles['multi_line_1_source']\n layout_source = plot.handles['layout_source']\n self.assertEqual(node_source.data['index'], self.source)\n self.assertEqual(edge_source.data['start'], self.source)\n self.assertEqual(edge_source.data['end'], self.target)\n edges = graph.edgepaths.split()\n self.assertEqual(edge_source.data['xs'], [path.dimension_values(0) for path in edges])\n self.assertEqual(edge_source.data['ys'], [path.dimension_values(1) for path in edges])\n layout = {str(int(z)): (x, y) for x, y, z in self.graph.nodes.array()}\n self.assertEqual(layout_source.graph_layout, layout)\n\n def test_graph_inspection_policy_nodes(self):\n plot = bokeh_renderer.get_plot(self.graph)\n renderer = plot.handles['glyph_renderer']\n hover = plot.handles['hover']\n self.assertIsInstance(renderer.inspection_policy, NodesAndLinkedEdges)\n self.assertEqual(hover.tooltips, [('index', '@{index_hover}')])\n self.assertIn(renderer, hover.renderers)\n\n def test_graph_inspection_policy_edges(self):\n plot = bokeh_renderer.get_plot(self.graph.opts(plot=dict(inspection_policy='edges')))\n renderer = plot.handles['glyph_renderer']\n hover = plot.handles['hover']\n self.assertIsInstance(renderer.inspection_policy, EdgesAndLinkedNodes)\n self.assertEqual(hover.tooltips, [('start', '@{start}'), ('end', '@{end}')])\n self.assertIn(renderer, hover.renderers)\n\n def test_graph_inspection_policy_edges_non_default_names(self):\n graph = self.graph.redim(start='source', end='target')\n plot = bokeh_renderer.get_plot(graph.opts(plot=dict(inspection_policy='edges')))\n renderer = plot.handles['glyph_renderer']\n hover = plot.handles['hover']\n self.assertIsInstance(renderer.inspection_policy, EdgesAndLinkedNodes)\n self.assertEqual(hover.tooltips, [('source', '@{source}'), ('target', '@{target}')])\n self.assertIn(renderer, hover.renderers)\n\n def test_graph_inspection_policy_none(self):\n plot = bokeh_renderer.get_plot(self.graph.opts(plot=dict(inspection_policy=None)))\n renderer = plot.handles['glyph_renderer']\n hover = plot.handles['hover']\n self.assertIs(renderer.inspection_policy, None)\n\n def test_graph_selection_policy_nodes(self):\n plot = bokeh_renderer.get_plot(self.graph)\n renderer = plot.handles['glyph_renderer']\n hover = plot.handles['hover']\n self.assertIsInstance(renderer.selection_policy, NodesAndLinkedEdges)\n self.assertIn(renderer, hover.renderers)\n\n def test_graph_selection_policy_edges(self):\n plot = bokeh_renderer.get_plot(self.graph.opts(plot=dict(selection_policy='edges')))\n renderer = plot.handles['glyph_renderer']\n hover = plot.handles['hover']\n self.assertIsInstance(renderer.selection_policy, EdgesAndLinkedNodes)\n self.assertIn(renderer, hover.renderers)\n\n def test_graph_selection_policy_none(self):\n plot = bokeh_renderer.get_plot(self.graph.opts(plot=dict(selection_policy=None)))\n renderer = plot.handles['glyph_renderer']\n hover = plot.handles['hover']\n self.assertIs(renderer.selection_policy, None)\n\n def test_graph_nodes_categorical_colormapped(self):\n g = self.graph2.opts(plot=dict(color_index='Label'), style=dict(cmap='Set1'))\n plot = bokeh_renderer.get_plot(g)\n cmapper = plot.handles['color_mapper']\n node_source = plot.handles['scatter_1_source']\n glyph = plot.handles['scatter_1_glyph']\n self.assertIsInstance(cmapper, CategoricalColorMapper)\n self.assertEqual(cmapper.factors, ['Output', 'Input'])\n self.assertEqual(node_source.data['Label'], self.node_info['Label'])\n self.assertEqual(glyph.fill_color, {'field': 'Label', 'transform': cmapper})\n \n def test_graph_nodes_numerically_colormapped(self):\n g = self.graph3.opts(plot=dict(color_index='Weight'), style=dict(cmap='viridis'))\n plot = bokeh_renderer.get_plot(g)\n cmapper = plot.handles['color_mapper']\n node_source = plot.handles['scatter_1_source']\n glyph = plot.handles['scatter_1_glyph']\n self.assertIsInstance(cmapper, LinearColorMapper)\n self.assertEqual(cmapper.low, self.weights.min())\n self.assertEqual(cmapper.high, self.weights.max())\n self.assertEqual(node_source.data['Weight'], self.node_info2['Weight'])\n self.assertEqual(glyph.fill_color, {'field': 'Weight', 'transform': cmapper})\n\n def test_graph_edges_categorical_colormapped(self):\n g = self.graph3.opts(plot=dict(edge_color_index='start'),\n style=dict(edge_cmap=['#FFFFFF', '#000000']))\n plot = bokeh_renderer.get_plot(g)\n cmapper = plot.handles['edge_colormapper']\n edge_source = plot.handles['multi_line_1_source']\n glyph = plot.handles['multi_line_1_glyph']\n self.assertIsInstance(cmapper, CategoricalColorMapper)\n factors = ['0', '1', '2', '3', '4', '5', '6', '7']\n self.assertEqual(cmapper.factors, factors)\n self.assertEqual(edge_source.data['start_str'], factors)\n self.assertEqual(glyph.line_color, {'field': 'start_str', 'transform': cmapper})\n\n def test_graph_nodes_numerically_colormapped(self):\n g = self.graph4.opts(plot=dict(edge_color_index='Weight'),\n style=dict(edge_cmap=['#FFFFFF', '#000000']))\n plot = bokeh_renderer.get_plot(g)\n cmapper = plot.handles['edge_colormapper']\n edge_source = plot.handles['multi_line_1_source']\n glyph = plot.handles['multi_line_1_glyph']\n self.assertIsInstance(cmapper, LinearColorMapper)\n self.assertEqual(cmapper.low, self.weights.min())\n self.assertEqual(cmapper.high, self.weights.max())\n self.assertEqual(edge_source.data['Weight'], self.node_info2['Weight'])\n self.assertEqual(glyph.line_color, {'field': 'Weight', 'transform': cmapper})\n\n\nclass TestBokehTriMeshPlots(ComparisonTestCase):\n\n def setUp(self):\n if not bokeh_renderer:\n raise SkipTest(\"Bokeh required to test plot instantiation\")\n self.previous_backend = Store.current_backend\n Store.current_backend = 'bokeh'\n self.default_comm = bokeh_renderer.comms['default']\n\n self.nodes = [(0, 0, 0), (0.5, 1, 1), (1., 0, 2), (1.5, 1, 3)]\n self.simplices = [(0, 1, 2, 0), (1, 2, 3, 1)]\n self.trimesh = TriMesh((self.simplices, self.nodes))\n self.trimesh_weighted = TriMesh((self.simplices, self.nodes), vdims='weight')\n\n def tearDown(self):\n Store.current_backend = self.previous_backend\n bokeh_renderer.comms['default'] = self.default_comm\n\n def test_plot_simple_trimesh(self):\n plot = bokeh_renderer.get_plot(self.trimesh)\n node_source = plot.handles['scatter_1_source']\n edge_source = plot.handles['multi_line_1_source']\n layout_source = plot.handles['layout_source']\n self.assertEqual(node_source.data['index'], np.arange(4))\n self.assertEqual(edge_source.data['start'], np.arange(2))\n self.assertEqual(edge_source.data['end'], np.arange(1, 3))\n layout = {str(int(z)): (x, y) for x, y, z in self.trimesh.nodes.array()}\n self.assertEqual(layout_source.graph_layout, layout)\n\n def test_plot_simple_trimesh_filled(self):\n plot = bokeh_renderer.get_plot(self.trimesh.opts(plot=dict(filled=True)))\n node_source = plot.handles['scatter_1_source']\n edge_source = plot.handles['patches_1_source']\n layout_source = plot.handles['layout_source']\n self.assertIsInstance(plot.handles['patches_1_glyph'], Patches)\n self.assertEqual(node_source.data['index'], np.arange(4))\n self.assertEqual(edge_source.data['start'], np.arange(2))\n self.assertEqual(edge_source.data['end'], np.arange(1, 3))\n layout = {str(int(z)): (x, y) for x, y, z in self.trimesh.nodes.array()}\n self.assertEqual(layout_source.graph_layout, layout)\n\n def test_graph_edges_categorical_colormapped(self):\n g = self.trimesh.opts(plot=dict(edge_color_index='node1'),\n style=dict(edge_cmap=['#FFFFFF', '#000000']))\n plot = bokeh_renderer.get_plot(g)\n cmapper = plot.handles['edge_colormapper']\n edge_source = plot.handles['multi_line_1_source']\n glyph = plot.handles['multi_line_1_glyph']\n self.assertIsInstance(cmapper, CategoricalColorMapper)\n factors = ['0', '1', '2', '3']\n self.assertEqual(cmapper.factors, factors)\n self.assertEqual(edge_source.data['node1_str'], ['0', '1'])\n self.assertEqual(glyph.line_color, {'field': 'node1_str', 'transform': cmapper})\n\n def test_graph_nodes_numerically_colormapped(self):\n g = self.trimesh_weighted.opts(plot=dict(edge_color_index='weight'),\n style=dict(edge_cmap=['#FFFFFF', '#000000']))\n plot = bokeh_renderer.get_plot(g)\n cmapper = plot.handles['edge_colormapper']\n edge_source = plot.handles['multi_line_1_source']\n glyph = plot.handles['multi_line_1_glyph']\n self.assertIsInstance(cmapper, LinearColorMapper)\n self.assertEqual(cmapper.low, 0)\n self.assertEqual(cmapper.high, 1)\n self.assertEqual(edge_source.data['weight'], np.array([0, 1]))\n self.assertEqual(glyph.line_color, {'field': 'weight', 'transform': cmapper})\n"
]
| [
[
"numpy.array",
"numpy.arange",
"numpy.random.rand",
"numpy.zeros"
]
]
|
tingsyo/dlgridsat | [
"2d94808df663c39931b404deee44849aad104e52"
]
| [
"utils/pretrained2_encode_preproc_gridsatb1.py"
]
| [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nThis script provide functions which encode pre-processed NOAA-GridSat-B1 \ndataset into vectors of length 2048.\n\nThe autoencoder is developed and teset with Tensorflow(2.5.0), \nCUDA 11.1/11.3 with cuDNN 8.1.0/8.2.0.\n'''\nimport numpy as np\nimport pandas as pd\nimport os, argparse, logging, csv, h5py\nimport tensorflow as tf\nimport tensorflow_hub as hub\n\n__author__ = \"Ting-Shuo Yo\"\n__copyright__ = \"Copyright 2020~2022, DataQualia Lab Co. Ltd.\"\n__credits__ = [\"Ting-Shuo Yo\"]\n__license__ = \"Apache License 2.0\"\n__version__ = \"0.1.0\"\n__maintainer__ = \"Ting-Shuo Yo\"\n__email__ = \"[email protected]\"\n__status__ = \"development\"\n__date__ = '2021-06-15'\n\n# Parameters\nNY = 256\nNX = 256\nNC = 1\n\n# Utility functions\ndef list_preprocessed_gridsatb1_files(dir, suffix='.npy', to_remove=['.npy']):\n ''' To scan through the sapecified dir and get the corresponding file with suffix. '''\n import os\n import pandas as pd\n xfiles = []\n for root, dirs, files in os.walk(dir, followlinks=True): # Loop through the directory\n for fn in files:\n if fn.endswith(suffix): # Filter files with suffix\n timestamp = fn\n for s in to_remove: # Removing prefix and suffix to get time-stamp\n timestamp = timestamp.replace(s,'')\n xfiles.append({'timestamp':timestamp, 'xuri':os.path.join(root, fn)})\n return(pd.DataFrame(xfiles).sort_values('timestamp').reset_index(drop=True))\n\n# Binary reader\ndef read_preprocessed_gridsatb1(furi):\n import numpy as np\n tmp = np.load(furi)\n image = np.stack([tmp,tmp,tmp], axis=2)\n return(image)\n\ndef read_multiple_preprocessed_noaagridsatb1(flist):\n ''' This method reads in a list of NOAA-GridSat-B1 images and returns a numpy array. '''\n import numpy as np\n data = []\n for f in flist:\n tmp = read_preprocessed_gridsatb1(f)\n data.append(tmp)\n return(np.array(data))\n\ndef encode_preprocessed_noaagridsatb1(model, flist, batch_size):\n ''' Encode the data with pre-trained-model. '''\n nSample = len(flist)\n # Prepare for results\n results =None\n # Read in and encode data by batch\n batch_start = 0\n batch_end = batch_size\n while batch_start < nSample:\n limit = min(batch_end, nSample)\n logging.info('Encoding batch: '+str(batch_start)+' - '+str(limit)+' of '+str(nSample)+'.')\n X = read_multiple_preprocessed_noaagridsatb1(flist['xuri'].iloc[batch_start:limit])\n features = model.signatures['serving_default'](tf.convert_to_tensor(X))\n if results is None:\n results = features['reduce_mean'].numpy()\n else:\n results = np.vstack([results, features['reduce_mean'].numpy()])\n # Increment the loop \n batch_start += batch_size\n batch_end += batch_size\n # Return results as an numpy array\n return(results)\n\n#-----------------------------------------------------------------------\ndef main():\n # Configure Argument Parser\n parser = argparse.ArgumentParser(description='Building convolutional autoencoder .')\n parser.add_argument('--datapath', '-i', help='the directory containing NOAA-GridSat-B1 data in numpy array.')\n parser.add_argument('--model', '-m', default='https://tfhub.dev/tensorflow/resnet_50/feature_vector/1', help='the pre-trained model directory.')\n parser.add_argument('--output', '-o', help='the prefix of output files.')\n parser.add_argument('--logfile', '-l', default=None, help='the log file.')\n parser.add_argument('--batch_size', '-b', default=64, type=int, help='the batch size.')\n\n args = parser.parse_args()\n # Set up logging\n if not args.logfile is None:\n logging.basicConfig(level=logging.DEBUG, filename=args.logfile, filemode='w')\n else:\n logging.basicConfig(level=logging.DEBUG)\n logging.debug(args)\n # Get data files\n logging.info('Scanning data files.')\n datainfo = list_preprocessed_gridsatb1_files(args.datapath)\n # Load model\n logging.info(\"Load pre-trained model from \" + str(args.model))\n model = hub.load(args.model)\n # Debug info\n nSample = datainfo.shape[0]\n logging.info(\"Ecnoding total data size: \"+str(nSample))\n # Encode data with the autoencoder\n features = encode_preprocessed_noaagridsatb1(model, datainfo, args.batch_size)\n # Prepare output\n pd.DataFrame(features, index=datainfo['timestamp']).to_csv(args.output+'_features.csv')\n np.save(args.output+'_features.npy', features)\n # done\n return(0)\n \n#==========\n# Script\n#==========\nif __name__==\"__main__\":\n main()\n\n"
]
| [
[
"numpy.array",
"tensorflow.convert_to_tensor",
"pandas.DataFrame",
"numpy.load",
"numpy.save",
"numpy.stack"
]
]
|
luhouxiang/rqrobot | [
"0b0094b0e2d061e628c570a06a7620e5fb48d342"
]
| [
"rqrobot/model/instrument.py"
]
| [
"# -*- coding: utf-8 -*-\n#\n# Copyright 2017 Ricequant, Inc\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport datetime\n\nimport six\nimport numpy as np\n\nfrom rqrobot.environment import Environment\nfrom rqrobot.utils import instrument_type_str2enum\nfrom rqrobot.utils.repr import property_repr\n\n\nclass Instrument(object):\n DEFAULT_LISTED_DATE = datetime.datetime(1990, 1, 1)\n DEFAULT_DE_LISTED_DATE = datetime.datetime(2999, 12, 31)\n\n @staticmethod\n def _fix_date(ds, dflt):\n if ds == '0000-00-00':\n return dflt\n year, month, day = ds.split('-')\n return datetime.datetime(int(year), int(month), int(day))\n\n __repr__ = property_repr\n\n def __init__(self, dic):\n self._ins_dict = dic\n\n if \"listed_date\" in dic:\n self._ins_dict[\"listed_date\"] = self._fix_date(dic[\"listed_date\"], self.DEFAULT_LISTED_DATE)\n if \"de_listed_date\" in dic:\n self._ins_dict[\"de_listed_date\"] = self._fix_date(dic[\"de_listed_date\"], self.DEFAULT_DE_LISTED_DATE)\n if \"maturity_date\" in self._ins_dict:\n self._ins_dict[\"maturity_date\"] = self._fix_date(dic[\"maturity_date\"], self.DEFAULT_DE_LISTED_DATE)\n\n if 'contract_multiplier' in dic:\n if np.isnan(self.contract_multiplier):\n raise RuntimeError(\"Contract multiplier of {} is not supposed to be nan\".format(self.order_book_id))\n\n @property\n def order_book_id(self):\n \"\"\"\n [str] 股票:证券代码,证券的独特的标识符。应以’.XSHG’或’.XSHE’结尾,前者代表上证,后者代表深证。\n 期货:期货代码,期货的独特的标识符(郑商所期货合约数字部分进行了补齐。例如原有代码’ZC609’补齐之后变为’ZC1609’)。\n 主力连续合约UnderlyingSymbol+88,例如’IF88’ ;指数连续合约命名规则为UnderlyingSymbol+99\n \"\"\"\n return self._ins_dict[\"order_book_id\"]\n\n @property\n def symbol(self):\n \"\"\"\n [str] 股票:证券的简称,例如’平安银行’。期货:期货的简称,例如’沪深1005’。\n \"\"\"\n return self._ins_dict[\"symbol\"]\n\n @property\n def round_lot(self):\n \"\"\"\n [int] 股票:一手对应多少股,中国A股一手是100股。期货:一律为1。\n \"\"\"\n return self._ins_dict[\"round_lot\"]\n\n @property\n def listed_date(self):\n \"\"\"\n [datetime] 股票:该证券上市日期。期货:期货的上市日期,主力连续合约与指数连续合约都为 datetime(1990, 1, 1)。\n \"\"\"\n return self._ins_dict[\"listed_date\"]\n\n @property\n def de_listed_date(self):\n \"\"\"\n [datetime] 股票:退市日期。期货:交割日期。\n \"\"\"\n return self._ins_dict[\"de_listed_date\"]\n\n @property\n def type(self):\n \"\"\"\n [sty] 合约类型,目前支持的类型有: ‘CS’, ‘INDX’, ‘LOF’, ‘ETF’, ‘FenjiMu’, ‘FenjiA’, ‘FenjiB’, ‘Future’\n \"\"\"\n return self._ins_dict[\"type\"]\n\n @property\n def exchange(self):\n \"\"\"\n [str] 交易所。股票:’XSHE’ - 深交所, ‘XSHG’ - 上交所。期货:’DCE’ - 大连商品交易所, ‘SHFE’ - 上海期货交易所,\n ’CFFEX’ - 中国金融期货交易所, ‘CZCE’- 郑州商品交易所\n \"\"\"\n return self._ins_dict[\"exchange\"]\n\n @property\n def market_tplus(self):\n \"\"\"\n [int] 合约卖出和买入操作需要间隔的最小交易日数,如A股为 1\n \"\"\"\n return self._ins_dict[\"market_tplus\"]\n\n @property\n def sector_code(self):\n \"\"\"\n [str] 板块缩写代码,全球通用标准定义(股票专用)\n \"\"\"\n try:\n return self._ins_dict[\"sector_code\"]\n except (KeyError, ValueError):\n raise AttributeError(\n \"Instrument(order_book_id={}) has no attribute 'sector_code' \".format(self.order_book_id)\n )\n\n @property\n def sector_code_name(self):\n \"\"\"\n [str] 以当地语言为标准的板块代码名(股票专用)\n \"\"\"\n try:\n return self._ins_dict[\"sector_code_name\"]\n except (KeyError, ValueError):\n raise AttributeError(\n \"Instrument(order_book_id={}) has no attribute 'sector_code_name' \".format(self.order_book_id)\n )\n\n @property\n def industry_code(self):\n \"\"\"\n [str] 国民经济行业分类代码,具体可参考“Industry列表” (股票专用)\n \"\"\"\n try:\n return self._ins_dict[\"industry_code\"]\n except (KeyError, ValueError):\n raise AttributeError(\n \"Instrument(order_book_id={}) has no attribute 'industry_code' \".format(self.order_book_id)\n )\n\n @property\n def industry_name(self):\n \"\"\"\n [str] 国民经济行业分类名称(股票专用)\n \"\"\"\n try:\n return self._ins_dict[\"industry_name\"]\n except (KeyError, ValueError):\n raise AttributeError(\n \"Instrument(order_book_id={}) has no attribute 'industry_name' \".format(self.order_book_id)\n )\n\n @property\n def concept_names(self):\n \"\"\"\n [str] 概念股分类,例如:’铁路基建’,’基金重仓’等(股票专用)\n \"\"\"\n try:\n return self._ins_dict[\"concept_names\"]\n except (KeyError, ValueError):\n raise AttributeError(\n \"Instrument(order_book_id={}) has no attribute 'concept_names' \".format(self.order_book_id)\n )\n\n @property\n def board_type(self):\n \"\"\"\n [str] 板块类别,’MainBoard’ - 主板,’GEM’ - 创业板(股票专用)\n \"\"\"\n try:\n return self._ins_dict[\"board_type\"]\n except (KeyError, ValueError):\n raise AttributeError(\n \"Instrument(order_book_id={}) has no attribute 'board_type' \".format(self.order_book_id)\n )\n\n @property\n def status(self):\n \"\"\"\n [str] 合约状态。’Active’ - 正常上市, ‘Delisted’ - 终止上市, ‘TemporarySuspended’ - 暂停上市,\n ‘PreIPO’ - 发行配售期间, ‘FailIPO’ - 发行失败(股票专用)\n \"\"\"\n try:\n return self._ins_dict[\"status\"]\n except (KeyError, ValueError):\n raise AttributeError(\n \"Instrument(order_book_id={}) has no attribute 'status' \".format(self.order_book_id)\n )\n\n @property\n def special_type(self):\n \"\"\"\n [str] 特别处理状态。’Normal’ - 正常上市, ‘ST’ - ST处理, ‘StarST’ - *ST代表该股票正在接受退市警告,\n ‘PT’ - 代表该股票连续3年收入为负,将被暂停交易, ‘Other’ - 其他(股票专用)\n \"\"\"\n try:\n return self._ins_dict[\"special_type\"]\n except (KeyError, ValueError):\n raise AttributeError(\n \"Instrument(order_book_id={}) has no attribute 'special_type' \".format(self.order_book_id)\n )\n\n @property\n def contract_multiplier(self):\n \"\"\"\n [float] 合约乘数,例如沪深300股指期货的乘数为300.0(期货专用)\n \"\"\"\n try:\n return self._ins_dict[\"contract_multiplier\"]\n except (KeyError, ValueError):\n raise AttributeError(\n \"Instrument(order_book_id={}) has no attribute 'contract_multiplier' \".format(self.order_book_id)\n )\n\n @property\n def margin_rate(self):\n \"\"\"\n [float] 合约最低保证金率(期货专用)\n \"\"\"\n try:\n return self._ins_dict[\"margin_rate\"]\n except (KeyError, ValueError):\n raise AttributeError(\n \"Instrument(order_book_id={}) has no attribute 'margin_rate' \".format(self.order_book_id)\n )\n\n @property\n def underlying_order_book_id(self):\n \"\"\"\n [str] 合约标的代码,目前除股指期货(IH, IF, IC)之外的期货合约,这一字段全部为’null’(期货专用)\n \"\"\"\n try:\n return self._ins_dict[\"underlying_order_book_id\"]\n except (KeyError, ValueError):\n raise AttributeError(\n \"Instrument(order_book_id={}) has no attribute 'underlying_order_book_id' \".format(self.order_book_id)\n )\n\n @property\n def underlying_symbol(self):\n \"\"\"\n [str] 合约标的代码,目前除股指期货(IH, IF, IC)之外的期货合约,这一字段全部为’null’(期货专用)\n \"\"\"\n try:\n return self._ins_dict[\"underlying_symbol\"]\n except (KeyError, ValueError):\n raise AttributeError(\n \"Instrument(order_book_id={}) has no attribute 'underlying_symbol' \".format(self.order_book_id)\n )\n\n @property\n def maturity_date(self):\n \"\"\"\n [datetime] 期货到期日。主力连续合约与指数连续合约都为 datetime(2999, 12, 31)(期货专用)\n \"\"\"\n try:\n return self._ins_dict[\"maturity_date\"]\n except (KeyError, ValueError):\n raise AttributeError(\n \"Instrument(order_book_id={}) has no attribute 'maturity_date' \".format(self.order_book_id)\n )\n\n @property\n def settlement_method(self):\n \"\"\"\n [str] 交割方式,’CashSettlementRequired’ - 现金交割, ‘PhysicalSettlementRequired’ - 实物交割(期货专用)\n \"\"\"\n try:\n return self._ins_dict[\"settlement_method\"]\n except (KeyError, ValueError):\n raise AttributeError(\n \"Instrument(order_book_id={}) has no attribute 'settlement_method' \".format(self.order_book_id)\n )\n\n @property\n def listing(self):\n \"\"\"\n [bool] 该合约当前日期是否在交易\n \"\"\"\n\n now = Environment.get_instance().calendar_dt\n return self.listed_date <= now <= self.de_listed_date\n\n def days_from_listed(self):\n if self.listed_date == self.DEFAULT_LISTED_DATE:\n return -1\n\n date = Environment.get_instance().trading_dt.date()\n if self.de_listed_date.date() < date:\n return -1\n\n ipo_days = (date - self.listed_date.date()).days\n return ipo_days if ipo_days >= 0 else -1\n\n @property\n def enum_type(self):\n return instrument_type_str2enum(self.type)\n\n def days_to_expire(self):\n if self.type != 'Future' or self.order_book_id[-2:] == '88' or self.order_book_id[-2:] == '99':\n return -1\n\n date = Environment.get_instance().trading_dt.date()\n days = (self.maturity_date.date() - date).days\n return -1 if days < 0 else days\n\n def tick_size(self):\n return Environment.get_instance().data_proxy.get_tick_size(self.order_book_id)\n\n\nclass SectorCodeItem(object):\n def __init__(self, cn, en, name):\n self.__cn = cn\n self.__en = en\n self.__name = name\n\n @property\n def cn(self):\n return self.__cn\n\n @property\n def en(self):\n return self.__en\n\n @property\n def name(self):\n return self.__name\n\n def __repr__(self):\n return \"{}: {}, {}\".format(self.__name, self.__en, self.__cn)\n\n\nclass SectorCode(object):\n Energy = SectorCodeItem(\"能源\", \"energy\", 'Energy')\n Materials = SectorCodeItem(\"原材料\", \"materials\", 'Materials')\n ConsumerDiscretionary = SectorCodeItem(\"非必需消费品\", \"consumer discretionary\", 'ConsumerDiscretionary')\n ConsumerStaples = SectorCodeItem(\"必需消费品\", \"consumer staples\", 'ConsumerStaples')\n HealthCare = SectorCodeItem(\"医疗保健\", \"health care\", 'HealthCare')\n Financials = SectorCodeItem(\"金融\", \"financials\", 'Financials')\n InformationTechnology = SectorCodeItem(\"信息技术\", \"information technology\", 'InformationTechnology')\n TelecommunicationServices = SectorCodeItem(\"电信服务\", \"telecommunication services\", 'TelecommunicationServices')\n Utilities = SectorCodeItem(\"公共服务\", \"utilities\", 'Utilities')\n Industrials = SectorCodeItem(\"工业\", \"industrials\", \"Industrials\")\n\n\nclass IndustryCodeItem(object):\n def __init__(self, code, name):\n self.__code = code\n self.__name = name\n\n @property\n def code(self):\n return self.__code\n\n @property\n def name(self):\n return self.__name\n\n def __repr__(self):\n return \"{0}:{1}\".format(self.__code, self.__name)\n\n\nclass IndustryCode(object):\n A01 = IndustryCodeItem(\"A01\", \"农业\")\n A02 = IndustryCodeItem(\"A02\", \"林业\")\n A03 = IndustryCodeItem(\"A03\", \"畜牧业\")\n A04 = IndustryCodeItem(\"A04\", \"渔业\")\n A05 = IndustryCodeItem(\"A05\", \"农、林、牧、渔服务业\")\n B06 = IndustryCodeItem(\"B06\", \"煤炭开采和洗选业\")\n B07 = IndustryCodeItem(\"B07\", \"石油和天然气开采业\")\n B08 = IndustryCodeItem(\"B08\", \"黑色金属矿采选业\")\n B09 = IndustryCodeItem(\"B09\", \"有色金属矿采选业\")\n B10 = IndustryCodeItem(\"B10\", \"非金属矿采选业\")\n B11 = IndustryCodeItem(\"B11\", \"开采辅助活动\")\n B12 = IndustryCodeItem(\"B12\", \"其他采矿业\")\n C13 = IndustryCodeItem(\"C13\", \"农副食品加工业\")\n C14 = IndustryCodeItem(\"C14\", \"食品制造业\")\n C15 = IndustryCodeItem(\"C15\", \"酒、饮料和精制茶制造业\")\n C16 = IndustryCodeItem(\"C16\", \"烟草制品业\")\n C17 = IndustryCodeItem(\"C17\", \"纺织业\")\n C18 = IndustryCodeItem(\"C18\", \"纺织服装、服饰业\")\n C19 = IndustryCodeItem(\"C19\", \"皮革、毛皮、羽毛及其制品和制鞋业\")\n C20 = IndustryCodeItem(\"C20\", \"木材加工及木、竹、藤、棕、草制品业\")\n C21 = IndustryCodeItem(\"C21\", \"家具制造业\")\n C22 = IndustryCodeItem(\"C22\", \"造纸及纸制品业\")\n C23 = IndustryCodeItem(\"C23\", \"印刷和记录媒介复制业\")\n C24 = IndustryCodeItem(\"C24\", \"文教、工美、体育和娱乐用品制造业\")\n C25 = IndustryCodeItem(\"C25\", \"石油加工、炼焦及核燃料加工业\")\n C26 = IndustryCodeItem(\"C26\", \"化学原料及化学制品制造业\")\n C27 = IndustryCodeItem(\"C27\", \"医药制造业\")\n C28 = IndustryCodeItem(\"C28\", \"化学纤维制造业\")\n C29 = IndustryCodeItem(\"C29\", \"橡胶和塑料制品业\")\n C30 = IndustryCodeItem(\"C30\", \"非金属矿物制品业\")\n C31 = IndustryCodeItem(\"C31\", \"黑色金属冶炼及压延加工业\")\n C32 = IndustryCodeItem(\"C32\", \"有色金属冶炼和压延加工业\")\n C33 = IndustryCodeItem(\"C33\", \"金属制品业\")\n C34 = IndustryCodeItem(\"C34\", \"通用设备制造业\")\n C35 = IndustryCodeItem(\"C35\", \"专用设备制造业\")\n C36 = IndustryCodeItem(\"C36\", \"汽车制造业\")\n C37 = IndustryCodeItem(\"C37\", \"铁路、船舶、航空航天和其它运输设备制造业\")\n C38 = IndustryCodeItem(\"C38\", \"电气机械及器材制造业\")\n C39 = IndustryCodeItem(\"C39\", \"计算机、通信和其他电子设备制造业\")\n C40 = IndustryCodeItem(\"C40\", \"仪器仪表制造业\")\n C41 = IndustryCodeItem(\"C41\", \"其他制造业\")\n C42 = IndustryCodeItem(\"C42\", \"废弃资源综合利用业\")\n C43 = IndustryCodeItem(\"C43\", \"金属制品、机械和设备修理业\")\n D44 = IndustryCodeItem(\"D44\", \"电力、热力生产和供应业\")\n D45 = IndustryCodeItem(\"D45\", \"燃气生产和供应业\")\n D46 = IndustryCodeItem(\"D46\", \"水的生产和供应业\")\n E47 = IndustryCodeItem(\"E47\", \"房屋建筑业\")\n E48 = IndustryCodeItem(\"E48\", \"土木工程建筑业\")\n E49 = IndustryCodeItem(\"E49\", \"建筑安装业\")\n E50 = IndustryCodeItem(\"E50\", \"建筑装饰和其他建筑业\")\n F51 = IndustryCodeItem(\"F51\", \"批发业\")\n F52 = IndustryCodeItem(\"F52\", \"零售业\")\n G53 = IndustryCodeItem(\"G53\", \"铁路运输业\")\n G54 = IndustryCodeItem(\"G54\", \"道路运输业\")\n G55 = IndustryCodeItem(\"G55\", \"水上运输业\")\n G56 = IndustryCodeItem(\"G56\", \"航空运输业\")\n G57 = IndustryCodeItem(\"G57\", \"管道运输业\")\n G58 = IndustryCodeItem(\"G58\", \"装卸搬运和运输代理业\")\n G59 = IndustryCodeItem(\"G59\", \"仓储业\")\n G60 = IndustryCodeItem(\"G60\", \"邮政业\")\n H61 = IndustryCodeItem(\"H61\", \"住宿业\")\n H62 = IndustryCodeItem(\"H62\", \"餐饮业\")\n I63 = IndustryCodeItem(\"I63\", \"电信、广播电视和卫星传输服务\")\n I64 = IndustryCodeItem(\"I64\", \"互联网和相关服务\")\n I65 = IndustryCodeItem(\"I65\", \"软件和信息技术服务业\")\n J66 = IndustryCodeItem(\"J66\", \"货币金融服务\")\n J67 = IndustryCodeItem(\"J67\", \"资本市场服务\")\n J68 = IndustryCodeItem(\"J68\", \"保险业\")\n J69 = IndustryCodeItem(\"J69\", \"其他金融业\")\n K70 = IndustryCodeItem(\"K70\", \"房地产业\")\n L71 = IndustryCodeItem(\"L71\", \"租赁业\")\n L72 = IndustryCodeItem(\"L72\", \"商务服务业\")\n M73 = IndustryCodeItem(\"M73\", \"研究和试验发展\")\n M74 = IndustryCodeItem(\"M74\", \"专业技术服务业\")\n M75 = IndustryCodeItem(\"M75\", \"科技推广和应用服务业\")\n N76 = IndustryCodeItem(\"N76\", \"水利管理业\")\n N77 = IndustryCodeItem(\"N77\", \"生态保护和环境治理业\")\n N78 = IndustryCodeItem(\"N78\", \"公共设施管理业\")\n O79 = IndustryCodeItem(\"O79\", \"居民服务业\")\n O80 = IndustryCodeItem(\"O80\", \"机动车、电子产品和日用产品修理业\")\n O81 = IndustryCodeItem(\"O81\", \"其他服务业\")\n P82 = IndustryCodeItem(\"P82\", \"教育\")\n Q83 = IndustryCodeItem(\"Q83\", \"卫生\")\n Q84 = IndustryCodeItem(\"Q84\", \"社会工作\")\n R85 = IndustryCodeItem(\"R85\", \"新闻和出版业\")\n R86 = IndustryCodeItem(\"R86\", \"广播、电视、电影和影视录音制作业\")\n R87 = IndustryCodeItem(\"R87\", \"文化艺术业\")\n R88 = IndustryCodeItem(\"R88\", \"体育\")\n R89 = IndustryCodeItem(\"R89\", \"娱乐业\")\n S90 = IndustryCodeItem(\"S90\", \"综合\")\n"
]
| [
[
"numpy.isnan"
]
]
|
tambetm/playground | [
"606b568ea1e4fe82b93d93f482e96b585fc69de7"
]
| [
"pommerman/forward_model.py"
]
| [
"from collections import defaultdict\n\nimport numpy as np\n\nfrom . import constants\nfrom . import characters\nfrom . import utility\n\n\nclass ForwardModel(object):\n \"\"\"Class for helping with the [forward] modeling of the game state.\"\"\"\n\n def run(self, num_times, board, agents, bombs, items, flames, is_partially_observable, agent_view_size, action_space, training_agent=None, is_communicative=False):\n \"\"\"Run the forward model.\n\n Args:\n num_times: The number of times to run it for. This is a maximum and it will stop early if we reach a done.\n board: The board state to run it from.\n agents: The agents to use to run it.\n bombs: The starting bombs.\n items: The starting items.\n flames: The starting flames.\n is_partially_observable: Whether the board is partially observable or not. Only applies to TeamRadio.\n agent_view_size: If it's partially observable, then the size of the square that the agent can view.\n action_space: The actions that each agent can take.\n training_agent: The training agent to pass to done.\n is_communicative: Whether the action depends on communication observations as well.\n\n Returns:\n steps: The list of step results, which are each a dict of \"obs\", \"next_obs\", \"reward\", \"action\".\n board: Updated board.\n agents: Updated agents, same models though.\n bombs: Updated bombs.\n items: Updated items.\n flames: Updated flames.\n done: Whether we completed the game in these steps.\n info: The result of the game if it's completed.\n \"\"\"\n steps = []\n for _ in num_times:\n obs = self.get_observations(\n board, agents, bombs, is_partially_observable, agent_view_size)\n actions = self.act(agents, obs, action_space,\n is_communicative=is_communicative)\n board, agents, bombs, items, flames = self.step(\n actions, board, agents, bombs, items, flames)\n next_obs = self.get_observations(\n board, agents, bombs, is_partially_observable, agent_view_size)\n reward = self.get_rewards(agents, game_type, step_count, max_steps)\n done = self.get_done(agents, game_type, step_count, max_steps,\n training_agent)\n info = self.get_info(done, rewards, game_type, agents)\n\n steps.append({\n \"obs\": obs,\n \"next_obs\": next_obs,\n \"reward\": reward,\n \"actions\": actions,\n })\n if done:\n break\n return steps, board, agents, bombs, items, flames, done, info\n\n @staticmethod\n def act(agents, obs, action_space, is_communicative=False):\n \"\"\"Returns actions for each agent in this list.\n\n Args:\n agents: A list of agent objects.\n obs: A list of matching observations per agent.\n action_space: The action space for the environment using this model.\n is_communicative: Whether the action depends on communication observations as well.\n\n Returns a list of actions.\n \"\"\"\n def act_ex_communication(agent):\n if agent.is_alive:\n return agent.act(obs[agent.agent_id], action_space=action_space)\n else:\n return constants.Action.Stop.value\n\n def act_with_communication(agent):\n if agent.is_alive:\n action = agent.act(obs[agent.agent_id], action_space=action_space)\n if type(action) == int:\n action = [action] + [0, 0]\n assert(type(action) == list)\n return action\n else:\n return [constants.Action.Stop.value, 0, 0]\n\n ret = []\n for agent in agents:\n if is_communicative:\n ret.append(act_with_communication(agent))\n else:\n ret.append(act_ex_communication(agent))\n return ret\n\n @staticmethod\n def step(actions, curr_board, curr_agents, curr_bombs, curr_items,\n curr_flames):\n board_size = len(curr_board)\n\n # Tick the flames. Replace any dead ones with passages. If there is an item there, then reveal that item.\n flames = []\n for flame in curr_flames:\n position = flame.position\n if flame.is_dead():\n item_value = curr_items.get(position)\n if item_value:\n del curr_items[position]\n else:\n item_value = constants.Item.Passage.value\n curr_board[position] = item_value\n else:\n flame.tick()\n flames.append(flame)\n curr_flames = flames\n\n # Step the living agents.\n # If two agents try to go to the same spot, they should bounce back to their previous spots.\n # This is a little complicated because what if there are three agents all in a row.\n # If the one in the middle tries to go to the left and bounces with the one on the left,\n # and then the one on the right tried to go to the middle one's position, she should also bounce.\n # A way of doing this is to gather all the new positions before taking any actions.\n # Then, if there are disputes, correct those disputes iteratively.\n def make_counter(next_positions):\n counter = defaultdict(list)\n for num, next_position in enumerate(next_positions):\n if next_position is not None:\n counter[next_position].append(num)\n return counter\n\n def has_position_conflict(counter):\n return any([len(agent_ids) > 1 for next_position, agent_ids in counter.items() if next_position])\n\n curr_positions = [agent.position for agent in curr_agents]\n next_positions = [agent.position for agent in curr_agents]\n for agent, action in zip(curr_agents, actions):\n if agent.is_alive:\n position = agent.position\n\n if action == constants.Action.Stop.value:\n agent.stop()\n elif action == constants.Action.Bomb.value:\n bomb = agent.maybe_lay_bomb()\n if bomb:\n curr_bombs.append(bomb)\n elif utility.is_valid_direction(curr_board, position, action):\n next_position = agent.get_next_position(action)\n\n # This might be a bomb position. Only move in that case if the agent can kick.\n if not utility.position_is_bomb(curr_board, next_position):\n next_positions[agent.agent_id] = next_position\n elif not agent.can_kick:\n agent.stop()\n else:\n next_positions[agent.agent_id] = next_position\n else:\n # The agent made an invalid direction.\n agent.stop()\n else:\n next_positions[agent.agent_id] = None\n\n counter = make_counter(next_positions)\n while has_position_conflict(counter):\n for next_position, agent_ids in counter.items():\n if next_position and len(agent_ids) > 1:\n for agent_id in agent_ids:\n next_positions[agent_id] = curr_positions[agent_id]\n counter = make_counter(next_positions)\n\n for agent, curr_position, next_position, direction in zip(curr_agents, curr_positions, next_positions, actions):\n if not agent.is_alive:\n continue\n\n if curr_position != next_position:\n agent.move(direction)\n if agent.can_kick:\n bombs = [bomb for bomb in curr_bombs if bomb.position == agent.position]\n if bombs:\n bombs[0].moving_direction = constants.Action(direction)\n\n if utility.position_is_powerup(curr_board, agent.position):\n agent.pick_up(constants.Item(curr_board[agent.position]))\n curr_board[agent.position] = constants.Item.Passage.value\n\n # Explode bombs.\n next_bombs = []\n exploded_map = np.zeros_like(curr_board)\n for bomb in curr_bombs:\n bomb.tick()\n if bomb.is_moving():\n invalid_values = list(range(len(constants.Item)+1))[1:]\n if utility.is_valid_direction(curr_board, bomb.position, bomb.moving_direction.value, invalid_values=invalid_values):\n curr_board[bomb.position] = constants.Item.Passage.value\n bomb.move()\n else:\n bomb.stop()\n\n if bomb.exploded():\n bomb.bomber.incr_ammo()\n for _, indices in bomb.explode().items():\n for r, c in indices:\n if not all([r >= 0, c >= 0, r < board_size, c < board_size]):\n break\n if curr_board[r][c] == constants.Item.Rigid.value:\n break\n exploded_map[r][c] = 1\n if curr_board[r][c] == constants.Item.Wood.value:\n break\n else:\n next_bombs.append(bomb)\n\n # Remove bombs that were in the blast radius.\n curr_bombs = []\n for bomb in next_bombs:\n if bomb.in_range(exploded_map):\n bomb.bomber.incr_ammo()\n else:\n curr_bombs.append(bomb)\n\n # Kill these agents.\n for agent in curr_agents:\n if agent.in_range(exploded_map):\n agent.die()\n exploded_map = np.array(exploded_map)\n\n # Update the board\n for bomb in curr_bombs:\n curr_board[bomb.position] = constants.Item.Bomb.value\n\n for agent in curr_agents:\n position = np.where(curr_board == utility.agent_value(agent.agent_id))\n curr_board[position] = constants.Item.Passage.value\n if agent.is_alive:\n curr_board[agent.position] = utility.agent_value(agent.agent_id)\n\n flame_positions = np.where(exploded_map == 1)\n for row, col in zip(flame_positions[0], flame_positions[1]):\n curr_flames.append(characters.Flame((row, col)))\n for flame in curr_flames:\n curr_board[flame.position] = constants.Item.Flames.value\n\n return curr_board, curr_agents, curr_bombs, curr_items, curr_flames\n\n def get_observations(self, curr_board, agents, bombs, is_partially_observable, agent_view_size):\n \"\"\"Gets the observations as an np.array of the visible squares.\n\n The agent gets to choose whether it wants to keep the fogged part in memory.\n \"\"\"\n board_size = len(curr_board)\n\n def make_bomb_maps(position):\n blast_strengths = np.zeros((board_size, board_size))\n life = np.zeros((board_size, board_size))\n\n for bomb in bombs:\n x, y = bomb.position\n if not is_partially_observable or in_view_range(position, x, y):\n blast_strengths[(x, y)] = bomb.blast_strength\n life[(x, y)] = bomb.life\n return blast_strengths, life\n\n def in_view_range(position, vrow, vcol):\n row, col = position\n return all([\n row >= vrow - agent_view_size, row < vrow + agent_view_size,\n col >= vcol - agent_view_size, col < vcol + agent_view_size])\n\n attrs = ['position', 'blast_strength', 'can_kick', 'teammate', 'ammo',\n 'enemies']\n\n observations = []\n for agent in agents:\n agent_obs = {}\n board = curr_board\n if is_partially_observable:\n board = board.copy()\n for row in range(board_size):\n for col in range(board_size):\n if not in_view_range(agent.position, row, col):\n board[row, col] = constants.Item.Fog.value\n agent_obs['board'] = board\n\n bomb_blast_strengths, bomb_life = make_bomb_maps(agent.position)\n agent_obs['bomb_blast_strength'] = bomb_blast_strengths\n agent_obs['bomb_life'] = bomb_life\n\n for attr in attrs:\n assert hasattr(agent, attr)\n agent_obs[attr] = getattr(agent, attr)\n observations.append(agent_obs)\n return observations\n\n @staticmethod\n def get_done(agents, step_count, max_steps, game_type, training_agent):\n alive = [agent for agent in agents if agent.is_alive]\n alive_ids = sorted([agent.agent_id for agent in alive])\n if step_count >= max_steps:\n return True\n elif game_type == constants.GameType.FFA:\n if training_agent is not None and training_agent not in alive_ids:\n return True\n return len(alive) <= 1\n elif any([\n len(alive_ids) <= 1,\n alive_ids == [0, 2],\n alive_ids == [1, 3],\n ]):\n return True\n return False\n\n @staticmethod\n def get_info(done, rewards, game_type, agents):\n if game_type == constants.GameType.FFA:\n alive = [agent for agent in agents if agent.is_alive]\n if done and len(alive) > 1:\n return {\n 'result': constants.Result.Tie,\n }\n elif done:\n return {\n 'result': constants.Result.Win,\n 'winners': [num for num, reward in enumerate(rewards) \\\n if reward == 1],\n }\n else:\n return {\n 'result': constants.Result.Incomplete,\n }\n elif done:\n if rewards == [1]*4:\n return {\n 'result': constants.Result.Tie,\n }\n else:\n return {\n 'result': constants.Result.Win,\n 'winners': [num for num, reward in enumerate(rewards) \\\n if reward == 1],\n }\n else:\n return {\n 'result': constants.Result.Incomplete,\n }\n\n @staticmethod\n def get_rewards(agents, game_type, step_count, max_steps):\n def any_lst_equal(lst, values):\n return any([lst == v for v in values])\n\n alive_agents = [num for num, agent in enumerate(agents) \\\n if agent.is_alive]\n if game_type == constants.GameType.FFA:\n if len(alive_agents) == 1 or step_count >= max_steps:\n # Game is over. All of the alive agents get reward.\n return [2*int(agent.is_alive) - 1 for agent in agents]\n else:\n # Game running: 0 for alive, -1 for dead.\n return [int(agent.is_alive) - 1 for agent in agents]\n else:\n # We are playing a team game.\n if any_lst_equal(alive_agents, [[0, 2], [0], [2]]):\n # Team [0, 2] wins.\n return [1, -1, 1, -1]\n elif any_lst_equal(alive_agents, [[1, 3], [1], [3]]):\n # Team [1, 3] wins.\n return [-1, 1, -1, 1]\n elif step_count >= max_steps:\n # Game is over by max_steps. All agents tie.\n return [1]*4\n else:\n # No team has yet won or lost.\n return [0]*4\n"
]
| [
[
"numpy.array",
"numpy.zeros_like",
"numpy.zeros",
"numpy.where"
]
]
|
maxsch3/batchflow | [
"2d36fad3f4a816cef82c1902e52a43a051ea1892"
]
| [
"keras_batchflow/base/batch_shapers/var_shaper.py"
]
| [
"import numpy as np\nimport pandas as pd\nfrom numbers import Number\n\nfrom .encoder_adaptor import IEncoderAdaptor\nfrom .numpy_encoder_adaptor import NumpyEncoderAdaptor\nfrom .pandas_encoder_adaptor import PandasEncoderAdaptor\n\n\nclass VarShaper:\n\n \"\"\"\n This class is a wrapper around encoder. It abstracts away the encoding of a single column into a\n model-ready data. This class is used in BatchShaper where all leaves (a tuple (column name, encoder))\n in a structure are replaced with equivalent VarShaper objects in a BatchShaper's constructor method\n After that, BatchShaper use this equivalent structure of VarShaper objects rather than original\n \"human-readable\" structure of tuples.\n\n This class is a backend class and you normally would not need to use it manually.\n\n It implements core interface functions like transform, inverse_transform,\n as well as additional metadata functions like, shape, n_classes, dtype, etc.\n \"\"\"\n\n _dummy_constant_counter = 0\n\n def __init__(self, var_name, encoder, data_sample=None, encoder_adaptor=None):\n self._var_name = var_name\n # _name will be included in metadata for using in ML models, e.g. for naming input layers in Keras\n self._name = var_name\n self._encoder_adaptor = self._build_encoder_adaptor(encoder_adaptor)\n self._encoder = encoder\n self._class = self._self_classify(var_name, encoder)\n self._decoded_dtype, self._dtype = self._get_dtypes(data_sample)\n if self._class == \"constant\":\n # this is a class level counter to count all instances of constant class\n self._name = 'dummy_constant_' + str(self._dummy_constant_counter)\n type(self)._dummy_constant_counter += 1\n self._shape = self._get_shape(var_name, encoder, data_sample)\n self._n_classes = self._get_n_classes(encoder)\n\n def _build_encoder_adaptor(self, encoder_adaptor):\n \"\"\"\n This method makes encoder adaptor class that utilises polymorphism to accommodate encoders that require\n different data types. The encoder adaptor instance takes care of\n :param encoder_adaptor: str ('numpy' or 'pandas') or a custom class derived from IEncoderAdaptor\n :return: instance of IEncoderAdaptor\n \"\"\"\n if (encoder_adaptor == 'numpy') or (encoder_adaptor is None):\n adaptor = NumpyEncoderAdaptor()\n elif encoder_adaptor == 'pandas':\n adaptor = PandasEncoderAdaptor()\n elif isinstance(encoder_adaptor, IEncoderAdaptor):\n adaptor = encoder_adaptor\n else:\n raise TypeError(f\"Error: The encoder adaptor must be a string ('numpy' or 'pandas') or an instance of a \"\n f\"custom class derived from IEncoderAdaptor\")\n return adaptor\n\n @staticmethod\n def _self_classify(var_name, encoder):\n \"\"\"\n This method identifies what type of variable the class is responsible for:\n - encoded typical scenario when encoder is used to change the original value to some encoded representation\n - constant when variable is made up by the batch generator. This variable has constant value specified\n in encoder parameter. e.g. 0.\n - directly mapped when a value passed from a dataframe to the output without any changes\n :param var_name: a str or None. Str is used for encoded or directly mapped classes of variables. None is only\n used for constant\n :param encoder: None, scalar value or encoder class (any class having transform and inverse_transform methods)\n :return: onr of the following strings: \"constant\", \"direct\" or \"encoder\"\n \"\"\"\n if var_name is None:\n if isinstance(encoder, Number) or isinstance(encoder, str):\n return \"constant\"\n else:\n raise ValueError(f\"Error: for variables = None correct format of a structure element is \"\n f\"(None, any_constant), got (None, {encoder})\")\n elif isinstance(var_name, str):\n if encoder is None:\n return \"direct\"\n if not hasattr(encoder, \"transform\"):\n raise ValueError(f\"Error: encoder provided for column '{var_name}' has no 'transform' method\")\n if not hasattr(encoder, \"inverse_transform\"):\n raise ValueError(f\"Error: encoder provided for column '{var_name}' has no 'inverse_transform' method\")\n return \"encoder\"\n else:\n raise ValueError(f\"Error: variable name must be a str or None. Got {type(var_name)}\")\n\n @property\n def metadata(self):\n metadata = {}\n metadata['name'] = self._name\n if np.isscalar(self._encoder):\n metadata['encoder'] = None\n else:\n metadata['encoder'] = self._encoder\n metadata['shape'] = self._shape\n metadata['dtype'] = self._dtype\n metadata['n_classes'] = self._n_classes\n return metadata\n\n @property\n def shape(self):\n return self._shape\n\n @property\n def n_classes(self):\n return self._n_classes\n\n def _get_shape(self, var_name, encoder, sample):\n if self._class in [\"constant\", \"direct\"]:\n return 1,\n else:\n if hasattr(encoder, 'shape'):\n return encoder.shape\n if sample is not None:\n x = self._reshape(self.transform(sample))\n if x.ndim == 1:\n raise RuntimeError('This should not have happened. Please report this issue')\n return tuple(x.shape[1:])\n else:\n raise ValueError(f\"Error: unable to determine encoded shape of variable {var_name} because neither \"\n f\"encoder {encoder} provided has attribute 'shape' nor data sample \"\n f\"provided to evaluate\")\n\n def _get_dtypes(self, sample):\n \"\"\"\n This method identifies dtype of encoded format and original decoded dtype of the variable stored in\n the original dataframe\n :param encoder: None, scalar constant or encoder object\n :param sample:\n :return: a tuple (original dtype, encoded dtype)\n \"\"\"\n if self._class in [\"encoder\", \"direct\"]:\n if sample is None:\n raise ValueError(f\"Error: Unable to determine encoded and original data types without a data sample. \"\n f\"Please provide a data sample in init\")\n if self._class == \"encoder\":\n x = self._reshape(self.transform(sample))\n return sample[self._var_name].dtype, x.dtype\n elif self._class == \"direct\":\n return sample[self._var_name].dtype, sample[self._var_name].dtype\n elif self._class == \"constant\":\n original_dtype = self._encoder.dtype if hasattr(self._encoder, \"dtype\") else type(self._encoder)\n return original_dtype, np.array([self._encoder]).dtype\n else:\n RuntimeError(f\"Error: the class type {self._encoder} is not supported in '_get_dtypes' method\")\n\n def _get_n_classes(self, encoder):\n \"\"\"\n Calculates number of classes provided by the encoder. This is required for creating embedding layer for\n the variable\n :param encoder: None, scalar constant or encoder object\n :return: integer scalar\n \"\"\"\n if self._class in [\"constant\", \"direct\"]:\n return None\n elif self._class == \"encoder\":\n if hasattr(encoder, 'n_classes'):\n return encoder.n_classes\n if hasattr(encoder, 'classes_'): # trying LabelEncoder compatible transformers\n return len(encoder.classes_)\n if hasattr(encoder, 'vocabulary_'): # trying CountVectorizer type of transformers\n return len(encoder.vocabulary_)\n else:\n raise RuntimeError(f\"Error: '_class' is None. This should not have happened. Please report this error.\")\n\n def transform(self, data):\n if self._class in [\"encoder\", \"direct\"]:\n if self._var_name not in data:\n raise KeyError(f\"Error: column '{self._var_name}' is not available in data\")\n # if self._decoded_dtype is None:\n # self._decoded_dtype = data[self._var_name].dtype\n # else:\n # # if constant, pick dtype from self._encoder type\n # self._decoded_dtype = self._encoder.dtype if hasattr(self._encoder, 'dtype') else type(self._encoder)\n if self._class == \"encoder\":\n # it has already been checked at init stage. It is redundant here\n # if not hasattr(self._encoder, 'transform'):\n # raise ValueError(f\"Error: encoders of class {type(self._encoder).__name__} provided in structure \"\n # f\"definition has no 'transform' method\")\n encoder_input = self._encoder_adaptor.transform(data[self._var_name])\n try:\n x = self._encoder.transform(encoder_input)\n except ValueError as e:\n raise ValueError(f'Error: ValueError exception occured while calling '\n f'{type(self._encoder).__name__}.transform method. Most likely you used'\n f' 2D encoders. At the moment, only 1D transformers are supported. Please use 1D '\n f'variant or use wrapper. The error was: {e}')\n # except Exception as e:\n # raise RuntimeError(f'Error: unknown error while calling transform method of '\n # f'{type(self._encoder).__name__} class provided in structure. The error was: {e}')\n elif self._class == \"constant\":\n x = np.repeat(self._encoder, data.shape[0])\n elif self._class == \"direct\":\n x = data[self._var_name].to_numpy()\n else:\n raise RuntimeError('Error: this should not have happened. Maybe it needs to be reported')\n # if self._dtype is None:\n # self._dtype = x.dtype\n return self._reshape(x)\n\n def inverse_transform(self, df, encoded_data):\n \"\"\"\n This method is used for converting encoded data returned by a predicting model back into a dataframe.\n :param df: A dataframe into which the decoded data are collected\n :param encoded_data: a numpy array which is returned by an ML model\n :return: None\n \"\"\"\n if self._class == \"constant\":\n return\n if self._decoded_dtype is None:\n raise RuntimeError(f\"Error: original data type is undefined. Please call transform before invoking \"\n f\"inverse_transform.\")\n if self._class == \"direct\":\n # This covers the case when a variable is not encoded and passed to and from X,Y structure without\n # changes. These cases have structure entry like this ('col_name', None)\n df[self._var_name] = pd.Series(np.squeeze(encoded_data), dtype=self._decoded_dtype)\n elif self._class == \"encoder\":\n # it has already been checked at init stage. It is redundant here\n # if not hasattr(self._encoder, \"inverse_transform\"):\n # raise ValueError(f\"Error: encoder provided for column '{self._var_name}' has no \"\n # \"'inverse_transform' method\")\n it = self._encoder_adaptor.inverse_transform(self._encoder.inverse_transform(encoded_data),\n dtype=self._decoded_dtype)\n df[self._var_name] = it\n\n def _reshape(self, x: np.ndarray):\n if x.ndim == 1:\n return np.expand_dims(x, axis=-1)\n return x\n"
]
| [
[
"numpy.array",
"numpy.isscalar",
"numpy.repeat",
"numpy.squeeze",
"numpy.expand_dims"
]
]
|
ERIGrid/NA4-Summerschool_Aug18 | [
"270cde89393b8fb96f3c620316db198c25d7ee87"
]
| [
"DoE-exercises/dtu_mosaik/mosaik_building.py"
]
| [
"\"\"\"\n An entity which mimics a building with an internal temperature and constant proportional heat loss.\n Note that parameters which couple to the temperature (proportional to x, zs) are expressed in degrees celcius per hour.\n That is, they state how much a value of, e.g. x=1.0 will cause the temperature to change over the course of 1 hour.\n\n @inputs & outputs:\n x: Current heater setting (in [0,1])\n T_amb: Ambient temperature [degC]\n zs: Solar irradiation (in [0,1], 1 => full sun)\n @outputs:\n P: Current power draw from electric heater\n T_int: Current internal temperature\n\"\"\"\n\nimport mosaik_api\nimport os\nimport pandas as pd\nfrom numpy import roll\nfrom itertools import count\nfrom util import MyBuildingSim\n\nMETA = {\n 'models': {\n 'BuildingModel': {\n 'public': True,\n 'params': [\n 'heat_coeff', 'solar_heat_coeff', 'insulation_coeff',\n 'init_T_int', 'init_T_amb', 'heater_power'],\n 'attrs': ['P', 'x', 'T_int', 'zs', 'T_amb'],\n },\n },\n}\n\nMY_DIR = os.path.abspath(os.path.dirname(__file__))\n\nclass BuildingSim(mosaik_api.Simulator):\n def __init__(self, META=META):\n super().__init__(META)\n\n # Per-entity dicts\n self.eid_counters = {}\n self.simulators = {}\n self.entityparams = {}\n\n def init(self, sid, step_size=5, eid_prefix=\"PVe\", storefilename=None):\n self.step_size = step_size\n self.eid_prefix = eid_prefix\n if storefilename is None:\n # Load default signal store\n self.storefilename = os.path.join(MY_DIR, 'signals.h5')\n else:\n self.storefilename = storefilename\n self.store = pd.HDFStore(self.storefilename)\n self.store.close()\n return self.meta\n\n def create(\n self, num, model,\n heat_coeff=9.0, solar_heat_coeff=6.0,\n insulation_coeff=0.2, init_T_int=12.0,\n init_T_amb=12.0, heater_power=5.0):\n counter = self.eid_counters.setdefault(model, count())\n entities = []\n\n for _ in range(num):\n eid = '%s_%s' % (self.eid_prefix, next(counter))\n\n esim = HouseSim(\n heat_coeff=heat_coeff,\n solar_heat_coeff=solar_heat_coeff,\n insulation_coeff=insulation_coeff,\n init_T_int=init_T_int,\n init_T_amb=init_T_amb,\n heater_power=heater_power)\n self.simulators[eid] = esim\n\n entities.append({'eid': eid, 'type': model})\n\n return entities\n\n ###\n # Functions used online\n ###\n\n def step(self, time, inputs):\n for eid, esim in self.simulators.items():\n data = inputs.get(eid, {})\n for attr, incoming in data.items():\n if attr == 'x':\n newX = min(val for val in incoming.values())\n esim.x = newX\n elif attr == 'T_amb':\n newT_amb = min(val for val in incoming.values())\n esim.T_amb = newT_amb\n elif attr == 'zs':\n newzs = min(val for val in incoming.values())\n esim.zs = newzs\n esim.calc_val(time)\n\n return time + self.step_size\n\n def get_data(self, outputs):\n data = {}\n for eid, esim in self.simulators.items():\n requests = outputs.get(eid, [])\n mydata = {}\n for attr in requests:\n if attr == 'P':\n mydata[attr] = esim.P\n elif attr == 'x':\n mydata[attr] = esim.x\n elif attr == 'T_int':\n mydata[attr] = esim.T_int\n elif attr == 'zs':\n mydata[attr] = esim.zs\n elif attr == 'T_amb':\n mydata[attr] = esim.T_amb\n else:\n raise RuntimeError(\"PVSim {0} has no attribute {1}.\".format(eid, attr))\n data[eid] = mydata\n return data\n\nif __name__ == '__main__':\n # mosaik_api.start_simulation(PVSim())\n\n test = BuildingSim()\n"
]
| [
[
"pandas.HDFStore"
]
]
|
racinger/PySyft | [
"dc0ba29df83de3bd0cf59956b433b418a9731baa"
]
| [
"syft/frameworks/torch/tensors/interpreters/multi_pointer.py"
]
| [
"import torch\nfrom typing import List\nfrom typing import Union\n\nimport syft as sy\nfrom syft.frameworks.torch.tensors.interpreters.abstract import AbstractTensor\nfrom syft.frameworks.torch.tensors.interpreters import AdditiveSharingTensor\nfrom syft.workers import BaseWorker\nfrom syft.frameworks.torch.overload_torch import overloaded\n\n\nclass MultiPointerTensor(AbstractTensor):\n \"\"\n\n def __init__(\n self,\n location: BaseWorker = None,\n id_at_location: Union[str, int] = None,\n register: bool = False,\n owner: BaseWorker = None,\n id: Union[str, int] = None,\n garbage_collect_data: bool = True,\n point_to_attr: str = None,\n tags: List[str] = None,\n description: str = None,\n children: List[AbstractTensor] = [],\n ):\n\n super().__init__(tags, description)\n\n self.location = location\n self.id_at_location = id_at_location\n self.owner = owner\n self.id = id\n self.garbage_collect_data = garbage_collect_data\n self.point_to_attr = point_to_attr\n\n self.child = {}\n for c in children:\n assert c.shape == children[0].shape\n self.child[c.location.id] = c\n\n def __str__(self):\n type_name = type(self).__name__\n out = f\"[\" f\"{type_name}]\"\n for v in self.child.values():\n out += \"\\n\\t-> \" + str(v)\n return out\n\n def __eq__(self, other):\n return torch.eq(self, other)\n\n def __add__(self, other):\n \"\"\"\n Adding a MultiPointer (MPT) and an AdditiveShared Tensor (AST) should return an\n AdditiveShared Tensor, so if we have this configuration, we permute self and\n other to use the fact that other.__add__(...) return an object of type other\n\n Else, we just redirect to .add which works well\n \"\"\"\n if isinstance(other, AdditiveSharingTensor):\n return other.__add__(self)\n else:\n return self.add(other)\n\n def __mul__(self, other):\n \"\"\"\n See __add__ for details but, MPT * AST should return AST\n \"\"\"\n if isinstance(other, AdditiveSharingTensor):\n return other.__mul__(self)\n else:\n return self.mul(other)\n\n @property\n def shape(self) -> torch.Size:\n \"\"\"This method returns the shape of the data being pointed to.\n This shape information SHOULD be cached on self._shape, but\n occasionally this information may not be present. If this is the\n case, then it requests the shape information from the remote object\n directly (which is inefficient and should be avoided).\"\"\"\n\n return list(self.child.values())[0].shape\n\n def get(self, sum_results: bool = False) -> torch.Tensor:\n\n results = list()\n for v in self.child.values():\n results.append(v.get())\n\n if sum_results:\n return sum(results)\n\n return results\n\n def virtual_get(self, sum_results: bool = False):\n \"\"\"Get the value of the tensor without calling get - Only for VirtualWorkers\"\"\"\n\n results = list()\n for v in self.child.values():\n value = v.location._objects[v.id_at_location]\n results.append(value)\n\n if sum_results:\n return sum(results)\n\n return results\n\n @staticmethod\n def dispatch(args, worker):\n \"\"\"\n utility function for handle_func_command which help to select\n shares (seen as elements of dict) in an argument set. It could\n perhaps be put elsewhere\n\n Args:\n args: arguments to give to a functions\n worker: owner of the shares to select\n\n Return:\n args where the MultiPointerTensor are replaced by\n the appropriate share\n \"\"\"\n return map(lambda x: x[worker] if isinstance(x, dict) else x, args)\n\n @classmethod\n def handle_func_command(cls, command):\n \"\"\"\n Receive an instruction for a function to be applied on a Syft Tensor,\n Replace in the args all the LogTensors with\n their child attribute, forward the command instruction to the\n handle_function_command of the type of the child attributes, get the\n response and replace a Syft Tensor on top of all tensors found in\n the response.\n\n Args:\n command: instruction of a function command: (command name,\n <no self>, arguments[, kwargs])\n\n Returns:\n the response of the function command\n \"\"\"\n\n cmd, _, args, kwargs = command\n\n tensor = args[0]\n\n # Check that the function has not been overwritten\n try:\n # Try to get recursively the attributes in cmd = \"<attr1>.<attr2>.<attr3>...\"\n cmd = cls.rgetattr(cls, cmd)\n return cmd(*args, **kwargs)\n except AttributeError:\n pass\n\n # TODO: I can't manage the import issue, can you?\n # Replace all LoggingTensor with their child attribute\n new_args, new_kwargs, new_type = sy.frameworks.torch.hook_args.hook_function_args(\n cmd, args, kwargs\n )\n\n results = {}\n for worker, share in new_args[0].items():\n new_type = type(share)\n new_args_worker = tuple(MultiPointerTensor.dispatch(new_args, worker))\n\n # build the new command\n new_command = (cmd, None, new_args_worker, new_kwargs)\n\n # Send it to the appropriate class and get the response\n results[worker] = new_type.handle_func_command(new_command)\n\n # Put back MultiPointerTensor on the tensors found in the response\n response = sy.frameworks.torch.hook_args.hook_response(\n cmd, results, wrap_type=cls, wrap_args=tensor.get_class_attributes()\n )\n\n return response\n\n def set_garbage_collect_data(self, value):\n shares = self.child\n for _, share in shares.items():\n share.child.garbage_collect_data = value\n"
]
| [
[
"torch.eq"
]
]
|
autopawn/meanpress | [
"ae9f94ab3b7b2ac136124f710d08790d4d510ee8"
]
| [
"meanpress/compression_maxv.py"
]
| [
"import sys\n\nimport numpy as np\n\nfrom numba import jit\n\nfrom .compression_general import *\n\n@jit(nopython=True)\ndef bit_cost(xs):\n \"\"\"\n Max bits required to represent up to the given numbers\n \"\"\"\n bits = np.zeros(xs.shape,dtype=np.int32)\n bits[xs>=1] = 1\n bits[xs>=2] = 2\n bits[xs>=4] = 3\n bits[xs>=8] = 4\n bits[xs>=16] = 5\n bits[xs>=32] = 6\n bits[xs>=64] = 7\n return bits\n\n@jit(nopython=True)\ndef s_bit_cost(v):\n \"\"\"\n Max bits required to represent up to the given number\n \"\"\"\n if v>=64: return 7\n if v>=32: return 6\n if v>=16: return 5\n if v>=8: return 4\n if v>=4: return 3\n if v>=2: return 2\n if v>=1: return 1\n return 0\n\n@jit(nopython=True)\ndef maxes_from_means(mean):\n \"\"\"\n From the mean values, the maximum value that the delta may have for each cell\n \"\"\"\n shape = mean.shape\n mean = mean.flatten()\n maxv = np.zeros(mean.shape,dtype=np.int32)\n maxv[mean<=127] = mean[mean<=127]\n maxv[mean>=128] = 255-mean[mean>=128]\n maxv = maxv.reshape(shape)\n return maxv\n\n@jit(nopython=True)\ndef compress_delta_nexts(delta,maxv):\n \"\"\"\n Compress some of the values in delta in one word,\n retuns grabs: how many values were added\n retuns final: the final word\n retuns outl_arrays: arrays of the outlier bit values\n \"\"\"\n GRABS_PER_MODE = (0,28,14,10,7,6,5,4)\n PREFIX_HEADER = (0,0b1100,0b1101,0b0000,0b1110,0b0100,0b1000,0b1111) # [3],[5], and [6], just use the first 2 bits\n FULLMASK = (0,0b1,0b11,0b111,0b1111,0b11111,0b111111,0b1111111)\n max_density = 0.0\n final_mode = 0\n # Identify mode that results in more density\n for mode in range(1,8):\n grabs = min(delta.shape[0],GRABS_PER_MODE[mode])\n outlier_maxv = maxv[:grabs]-((1<<mode)-1)\n outliers = (delta[:grabs]>=((1<<mode)-1))\n outlier_bitcost = outliers*bit_cost(outlier_maxv)\n density = grabs/(32.0+np.sum(outlier_bitcost))\n if density > max_density:\n max_density = density\n final_mode = mode\n # binary encoding and outlier string\n mode = final_mode\n final = np.uint32(0)\n final |= (PREFIX_HEADER[mode]<<28)\n #\n outl_arrays = [] # outlayer binary representation\n grabs = min(delta.shape[0],GRABS_PER_MODE[mode])\n outlier_maxv = maxv[:grabs]-((1<<mode)-1)\n outliers = (delta[:grabs]>=((1<<mode)-1))\n outlier_bitcost = outliers*bit_cost(outlier_maxv)\n for i in range(grabs):\n despl = GRABS_PER_MODE[mode]-1-i\n if outliers[i]:\n # Put value that represets outlier\n final |= FULLMASK[mode]<<(mode*despl)\n # Get binary representation of outlier\n extra = delta[i]-((1<<mode)-1)\n out_bits = outlier_bitcost[i]\n bitsp = np.zeros(out_bits,dtype=np.uint8)\n for i in range(out_bits):\n bitsp[out_bits-1-i] = (extra & 1)\n extra >>= 1\n assert(extra==0)\n outl_arrays.append(bitsp)\n else:\n final |= delta[i]<<(mode*despl)\n return grabs,final,outl_arrays\n\n@jit(nopython=True)\ndef decompress_word(word):\n \"\"\"\n Returns the delta values stored on a word.\n Outliers are retrieved as -((1<<mode)-1)\n \"\"\"\n GRABS_PER_MODE = (0,28,14,10,7,6,5,4)\n FULLMASK = (0,0b1,0b11,0b111,0b1111,0b11111,0b111111,0b1111111)\n if (word>>30)==0b00:\n mode = 3\n elif (word>>30)==0b01:\n mode = 5\n elif (word>>30)==0b10:\n mode = 6\n elif (word>>30)==0b11:\n if (word>>28)==0b1100:\n mode = 1\n elif (word>>28)==0b1101:\n mode = 2\n elif (word>>28)==0b1110:\n mode = 4\n elif (word>>28)==0b1111:\n mode = 7\n # Get each number from the word\n grabs = GRABS_PER_MODE[mode]\n numbs = np.zeros(grabs,dtype=np.int32)\n for i in range(grabs):\n ii = grabs-1-i\n numbs[i] = (word & (FULLMASK[mode]<<(ii*mode)) )>>(ii*mode)\n # FULLMASK[mode]<<(32-mode*(grabs-1-i))\n # s = 32-(grabs-i)*mode\n # numbs[i] = (word<<s)>>(32-mode)\n assert(np.all(numbs<=((1<<mode)-1)))\n numbs[numbs==((1<<mode)-1)] = -((1<<mode)-1) # t.b.d. outliers.\n return numbs\n\n@jit(nopython=True)\ndef compress_deltas(delta,means):\n \"\"\"\n Compresses a matrix of deltas,\n the matrix of means is used to know the maximum values that the deltas can\n aquire.\n \"\"\"\n # Flatten deltas and means\n means = means[:delta.shape[0],:delta.shape[1]]\n delta = delta.flatten().astype(np.int32)\n means = means.flatten().astype(np.int32)\n # Compute maxes from means\n maxv = maxes_from_means(means)\n # Discard cells that require 0 bits\n delta = delta[maxv>0]\n means = means[maxv>0]\n maxv = maxv[maxv>0]\n # Until there is no more to compress\n numvalues = []\n outlbinseq = []\n n = 0\n while n<means.shape[0]:\n # Compress\n g,i32,outls = compress_delta_nexts(delta[n:],maxv[n:])\n n += g\n numvalues.append(i32)\n for ou in outls:\n for v in ou:\n outlbinseq.append(v)\n numvalues = np.array(numvalues,dtype=np.uint32)\n # Get uint32s for outlbindseqs\n outlbinseq = np.array(outlbinseq,dtype=np.uint32)\n outl_ints = np.zeros((outlbinseq.shape[0]+31)//32,dtype=np.uint32)\n for i in range(outlbinseq.shape[0]):\n outl_ints[i//32] |= outlbinseq[i]<<(31-(i%32))\n # Done compressing\n return numvalues,outl_ints\n\n@jit(nopython=True)\ndef decompress_deltas(shape,means,bytesec):\n \"\"\"\n Reads a matrix of deltas of the given shape considering the\n previous matrix of means, bytesec is the sequence of uint32 to read.\n Returns the matrix of deltas and the number of uint32 read.\n \"\"\"\n w_read = 0\n means = means[:shape[0],:shape[1]]\n means = means.flatten().astype(np.int32)\n # Compute maxes from means\n maxv = maxes_from_means(means)\n # The array of deltas:\n deltas = np.zeros(means.shape,dtype=np.int32)\n n = 0\n nmbs = np.array([np.int32(0)])[:0]\n i = 0\n for n in range(means.size):\n if maxv[n]==0: continue\n if i==nmbs.size:\n nmbs = decompress_word(bytesec[w_read])\n w_read += 1\n i = 0\n deltas[n] = nmbs[i]\n i += 1\n # Indentify outliers\n bit_buffer = [np.int32(0)][:0]\n for i in range(means.size):\n # If outlier\n if deltas[i]<0:\n max_outside = maxv[i]+deltas[i]\n bits = s_bit_cost(max_outside)\n # Read more outlier bits if needed\n if len(bit_buffer)<bits:\n bit_buffer += divide_word(bytesec[w_read])\n w_read += 1\n # Rediscover outliers\n if bits==0:\n num = 0\n else:\n num = recompose_number(bit_buffer[:bits])\n bit_buffer = bit_buffer[bits:]\n deltas[i] = num-deltas[i]\n assert(deltas[i]<=maxv[i])\n # Retrieve deltas\n assert(np.all(deltas<128))\n assert(np.all(deltas>=0))\n deltasx = deltas.reshape(shape)\n return deltasx,w_read\n\nif __name__ == '__main__':\n VERBOSE = 0\n #\n assert(len(sys.argv)==2)\n SEED = int(sys.argv[1])\n np.random.seed(SEED)\n shap = np.random.randint(40,size=2)\n ms = (np.random.random(shap)*256).astype(np.int32)\n ds = maxes_from_means(ms)\n ds = (ds.astype(np.float64)*np.random.random(ds.shape)).astype(np.int32)\n if VERBOSE>=1:\n print(\"-- ds:\")\n print(ds.shape)\n print(ds)\n nums,outls = compress_deltas(ds,ms)\n bytesec = np.concatenate((nums,outls))\n assert(bytesec.dtype==np.uint32)\n if VERBOSE>=2:\n print([bin(x)[2:].zfill(32) for x in bytesec])\n ds2,w_read = decompress_deltas(ds.shape,ms,bytesec)\n # Result\n if VERBOSE>=1:\n print(\"-- ds2:\")\n print(ds2.shape)\n print(ds2)\n maxs = maxes_from_means(ms)\n # Moment of truth\n for i in range(ds.shape[0]):\n for j in range(ds.shape[1]):\n if ds[i,j] != ds2[i,j]:\n print(\"-- error: --\")\n print(\"%d,%d\"%(i,j))\n print(\"ds[i,j]\")\n print(ds[i,j])\n print(\"ds2[i,j]\")\n print(ds2[i,j])\n print(\"ms[i,j]\")\n print(ms[i,j])\n print(\"maxs[i,j]\")\n print(maxs[i,j])\n assert(np.all(ds==ds2))\n print(\"%d same.\"%SEED)\n"
]
| [
[
"numpy.concatenate",
"numpy.array",
"numpy.uint32",
"numpy.zeros",
"numpy.random.seed",
"numpy.sum",
"numpy.random.randint",
"numpy.all",
"numpy.int32",
"numpy.random.random"
]
]
|
Danxuan-Liu/diversification-code | [
"53a2e0216e731d7d693086b81e32e2a61b322b4e"
]
| [
"Experiment_letor/greedy_ls.py"
]
| [
"# This is a sample Python script.\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\nimport datetime\nimport os\nimport random\nimport argparse\nimport numpy as np\nimport sys\nimport copy\n\nfrom os import listdir\nfrom os.path import isfile, join\nclass Problem:\n def __init__(self, **kwargs):\n self.weight = []\n self.vector = []\n if \"text\" in kwargs:\n it = -1\n for line in kwargs[\"text\"].split(\"\\n\"):\n tokens = line.split()\n size = len(tokens)\n if size >= 3:\n self.weight.append(float(tokens[0]))\n self.name = tokens[1]\n change = tokens[2:]\n f_vector = [float(i) for i in change]\n self.vector.append(f_vector)\n self.k = kwargs[\"k\"]\n self.n = kwargs[\"n\"]\n self.mylambda = kwargs[\"mylambda\"]\n\n self.distance = [[0 for col in range(self.n)] for row in range(self.n)]\n for u in range(len(self.vector)):\n for v in range(len(self.vector)):\n if u == v:\n self.distance[u][v] = 0\n elif v < u:\n self.distance[u][v] = self.distance[v][u]\n else:\n self.distance[u][v] = self.cosine_similarity(self.vector[u], self.vector[v])\n\n def bit_product_sum(self, x, y):\n return sum([item[0] * item[1] for item in zip(x, y)])\n\n def cosine_similarity(self, x, y, norm=False):\n # compute cosine similarity of vector x and vector y\n assert len(x) == len(y), \"len(x) != len(y)\"\n zero_list = [0] * len(x)\n if x == zero_list or y == zero_list:\n return float(1) if x == y else float(0)\n res = np.array([[x[i] * y[i], x[i] * x[i], y[i] * y[i]] for i in range(len(x))])\n cos = sum(res[:, 0]) / (np.sqrt(sum(res[:, 1])) * np.sqrt(sum(res[:, 2])))\n return 0.5 * cos + 0.5 if norm else cos # Normalized to the interval [0, 1]\n\n\n def evaluateObjective(self,temp,new_item):\n size=len(temp)\n f=0\n div=0\n f=self.weight[new_item]\n for i in range(size):\n div+=self.distance[temp[i]][new_item]\n res=0.5*f+self.mylambda*div\n return res\n\n def select_best_item(self,res, items):\n evaluations = [self.evaluateObjective(res,s) for s in items]\n index = np.argmax(evaluations)\n return res + [items.pop(index)],items\n\n def greedy(self):\n items=[]\n res=[]\n for i in range(self.n):\n items.append(i)\n while len(res) < self.k:\n new_res,left_items = self.select_best_item(res, items)\n items=left_items\n res=new_res\n return res\n\n def exchange(self,solution,items):\n exits=False\n temp_solution = copy.deepcopy(solution)\n max_fitness=self.Calculate_true_value(temp_solution)\n max_solution = solution\n exchang_item=[0,0]\n for add_item in items:\n for del_item in solution:\n temp_solution = copy.deepcopy(solution)\n temp_solution.pop(temp_solution.index(del_item))\n temp_solution.append(add_item)\n new_solution =temp_solution\n new_fitness=self.Calculate_true_value(new_solution)\n if(new_fitness>max_fitness):\n exits=True\n max_fitness=new_fitness\n max_solution=new_solution\n exchang_item[0]=add_item\n exchang_item[1]=del_item\n\n return exits,max_fitness,max_solution,exchang_item\n\n def LocalSearch(self,init_res):\n items = []\n res=init_res\n value = 0\n for i in range(self.n):\n items.append(i)\n for i in init_res:\n items.pop(items.index(i))\n # start with greedy solution\n while True:\n flag,value,res,exchang_item=self.exchange(res,items)\n if flag==False:\n break\n else:\n items.pop(items.index(exchang_item[0])) # delete exchange_item[0] from V\\X\n items.append(exchang_item[1])# add exchang_item[1] in V\\X\n return res,value\n\n def Calculate_true_value(self,res):\n size = len(res)\n f = 0\n div = 0\n for i in res:\n f += self.weight[i]\n for i in range(size):\n for j in range(i + 1, size):\n div += self.distance[res[i]][res[j]]\n res = f + self.mylambda * div\n return res\n\ndef OutputResult(res,value,log):\n log.write(str(value))\n log.write(\"\\n\")\n for item in res:\n log.write(str(item+1))\n log.write(' ')\n log.write(\"\\n\")\n log.close()\n\ndef OutputAvg(all_greedy,all_ls,log):\n log.write(\"Greedy: \")\n log.write(str(np.mean(all_greedy)))\n log.write(\"\\n\")\n log.write(\"LocalSearch: \")\n log.write(str(np.mean(all_ls)))\n log.write(\"\\n\")\n log.close()\n\ndef run_experiments(args):\n\n new_address=args.folder\n files = [f for f in listdir(new_address) if isfile(join(new_address, f))]\n all_greedy=[]\n all_ls=[]\n for file in files:\n print(\"run \" + str(args.constraint)+\":\"+str(file))\n f = open(new_address + \"/\" + file, \"r\")\n instance = text = f.read()\n save_address=args.save_file+\"/\"+str(args.constraint)\n if not os.path.exists(save_address):\n os.makedirs(save_address)\n problem = Problem(text=instance, k=args.constraint, n=args.n_items, mylambda=args.mylambda)\n print(\"doing greedy...\")\n res=problem.greedy()\n value = problem.Calculate_true_value(res)\n all_greedy.append(value)\n\n print(\"saving greedy...\")\n save_address = args.save_file + \"/\" + str(args.constraint)\n if not os.path.exists(save_address):\n os.makedirs(save_address)\n\n log = open(save_address + \"/greedy_\" + file + \".txt\", \"w\")\n OutputResult(res, value, log)\n\n print(\"doing LS...\")\n res,value=problem.LocalSearch(res)\n all_ls.append(value)\n\n print(\"saving LS...\")\n log = open(save_address + \"/LS_\" + file + \".txt\", \"w\")\n OutputResult(res, value, log)\n\n\n save_address = args.save_file+\"/\"+str(args.constraint)\n if not os.path.exists(save_address):\n os.makedirs(save_address)\n log = open(save_address+ \"/Average.txt\" , \"w\") if args.save_file else sys.stdout\n OutputAvg(all_greedy,all_ls,log)\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n argparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n argparser.add_argument('-f', '--folder', default='Experiment_Data/370')\n argparser.add_argument('-n', '--new', help=\"create new dataset\", default=\"false\")\n argparser.add_argument('-p', '--save_file', help=\"save_result\", default='Result_GreedyLS/370',type=str)\n argparser.add_argument('-n_instances', help=\"number of instances\", default=50, type=int)\n argparser.add_argument('-n_items', help=\"number of items\", default=370, type=int)\n argparser.add_argument('-constraint', help=\"max size of subset\", default=5, type=int)\n argparser.add_argument('-mylambda', help=\"trade_off\", type=float, default=1)\n\n args = argparser.parse_args()\n args.save_file = f'Result_GreedyLS/{args.mylambda}'\n args.folder = f'Experiment_Data/{args.n_items}'\n run_experiments(args)\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n"
]
| [
[
"numpy.argmax",
"numpy.mean"
]
]
|
yannra/netket | [
"7adc7ba04ff8e912629952cf4fa0e3f27148c424",
"7adc7ba04ff8e912629952cf4fa0e3f27148c424"
]
| [
"scripts/qgps_2d_36_j1_j2_no_msr.py",
"netket/custom/sweep_opt.py"
]
| [
"import numpy as np\nimport netket as nk\nimport sys\nimport mpi4py.MPI as mpi\nimport symmetries\n\n\nN = int(sys.argv[1])\nJ2 = float(sys.argv[2])\n\nJ1 = 1.0\n\nif mpi.COMM_WORLD.Get_rank() == 0:\n with open(\"result.txt\", \"w\") as fl:\n fl.write(\"N, energy (real), energy (imag), energy_error\\n\")\n\nL = 6\ng = nk.graph.Hypercube(length=L, n_dim=2, pbc=True)\n\nha = nk.custom.J1J2(g, J2=J2, msr=False)\n\ntransl = symmetries.get_symms_square_lattice(L)\n\nma = nk.machine.QGPSSumSym(ha.hilbert, n_bond=N, automorphisms=transl, spin_flip_sym=True, dtype=complex)\n\nma.init_random_parameters(sigma=0.05, start_from_uniform=False)\n\n# Optimizer\nop = nk.optimizer.Sgd(ma, learning_rate=0.02)\n\n# Sampler\nsa = nk.sampler.MetropolisExchange(machine=ma,graph=g,d_max=2, n_chains=1)\nsa.reset(True)\n\n# Stochastic Reconfiguration\nsr = nk.optimizer.SR(ma)\n\nsamples = 7500\n\ngs = nk.custom.SweepOpt(hamiltonian=ha, sampler=sa, optimizer=op, n_samples=samples, sr=sr, n_discard=50, sweep_by_bonds=True)\n\n\nif mpi.COMM_WORLD.Get_rank() == 0:\n with open(\"out.txt\", \"w\") as fl:\n fl.write(\"\")\n\nsamp = max(2450, ma._epsilon.size//2)\n\nfor it in gs.iter(samp,1):\n if mpi.COMM_WORLD.Get_rank() == 0:\n np.save(\"epsilon.npy\", ma._epsilon)\n print(it,gs.energy)\n with open(\"out.txt\", \"a\") as fl:\n fl.write(\"{} {} {}\\n\".format(np.real(gs.energy.mean), np.imag(gs.energy.mean), gs.energy.error_of_mean))\n\nepsilon_avg = np.zeros(ma._epsilon.shape, dtype=ma._epsilon.dtype)\n\nfor it in gs.iter(50,1):\n epsilon_avg += ma._epsilon\n if mpi.COMM_WORLD.Get_rank() == 0:\n np.save(\"epsilon.npy\", ma._epsilon)\n print(it,gs.energy)\n with open(\"out.txt\", \"a\") as fl:\n fl.write(\"{} {} {}\\n\".format(np.real(gs.energy.mean), np.imag(gs.energy.mean), gs.energy.error_of_mean))\n\nepsilon_avg /= 50\n\nma._epsilon = epsilon_avg\n\nest = nk.variational.estimate_expectations(ha, sa, 50000, n_discard=100)\n\nif mpi.COMM_WORLD.Get_rank() == 0:\n np.save(\"epsilon_avg.npy\", ma._epsilon)\n with open(\"result.txt\", \"a\") as fl:\n fl.write(\"{} {} {} {}\\n\".format(N, np.real(est.mean), np.imag(est.mean), est.error_of_mean))\n\n\n",
"import netket as nk\nimport numpy as np\nfrom .linear_method import LinMethod\nfrom .stabilised_sr import SRStab\nfrom .stabilised_lin_method import LinMethodStab\n\nfrom netket.stats import (\n statistics as _statistics,\n mean as _mean,\n sum_inplace as _sum_inplace,\n)\n\nfrom netket.utils import (\n MPI_comm as _MPI_comm,\n n_nodes as _n_nodes,\n node_number as _rank\n)\n\nfrom mpi4py import MPI\n\nfrom netket.vmc_common import info, tree_map\n\n\nclass SweepOpt(nk.Vmc):\n def __init__(\n self,\n hamiltonian,\n sampler,\n optimizer,\n n_samples,\n n_discard=None,\n sr=None,\n max_opt = 3000,\n sweep_by_bonds = True,\n check_improvement = True,\n reset_bias = True\n ):\n super().__init__(hamiltonian, sampler, optimizer, n_samples, n_discard=n_discard, sr=sr)\n self.max_opt = max_opt\n\n self.opt_arr = np.zeros(self._sampler._machine._epsilon.size, dtype=bool)\n self.opt_arr[:self.max_opt] = True\n self.max_id = min(self.max_opt, self.opt_arr.size)\n self.sweep_by_bonds = sweep_by_bonds\n self._valid_par = None\n self._valid_samps = None\n assert(isinstance(self.optimizer, nk.optimizer.numpy.Sgd))\n self._default_timestep = self.optimizer._learning_rate\n if self._sr is not None:\n self._default_shift = self._sr._diag_shift\n self._check_improvement = check_improvement\n self._previous_mean = None\n self._previous_error = None\n self._reset_bias = reset_bias\n\n def iter(self, n_steps, step=1):\n for count in range(0, n_steps, step):\n for i in range(0, step):\n if self.sweep_by_bonds:\n opt_tensor = np.zeros(self._sampler._machine._epsilon.shape, dtype=bool)\n arr_count = 0\n for k in range(self._sampler._machine._epsilon.shape[1]):\n for j in range(self._sampler._machine._epsilon.shape[0]):\n for l in range(self._sampler._machine._epsilon.shape[2]):\n opt_tensor[j,k,l] = self.opt_arr[arr_count]\n arr_count += 1\n else:\n opt_tensor = self.opt_arr.reshape(self._sampler._machine._epsilon.shape)\n\n self._sampler._machine.change_opt_ids(opt_tensor)\n if self.sr is not None and self.max_opt < self.opt_arr.size:\n self.sr._x0 = None\n err = 0\n try:\n dp = self._forward_and_backward()\n except:\n err = 1\n\n error = _MPI_comm.allreduce(err)\n _MPI_comm.barrier()\n\n if error == 0:\n if self._valid_par is None:\n self._valid_par = self._sampler._machine._epsilon.copy()\n self._valid_samps = self._sampler._state.copy()\n else:\n np.copyto(self._valid_par, self._sampler._machine._epsilon)\n np.copyto(self._valid_samps, self._sampler._state)\n self._previous_mean = self._loss_stats.mean.real\n self._previous_error = self._loss_stats.error_of_mean\n if self._sr is not None:\n self._sr._diag_shift = self._default_shift\n self.optimizer._learning_rate = self._default_timestep\n\n self.opt_arr.fill(False)\n self.opt_arr[self.max_id:(self.max_id+self.max_opt)] = True\n if self.max_id + self.max_opt > self.opt_arr.size:\n self.opt_arr[:(self.max_id + self.max_opt - self.opt_arr.size)] = True\n self.max_id = min((self.max_id + self.max_opt - self.opt_arr.size), self.opt_arr.size)\n else:\n self.max_id = min((self.max_id + self.max_opt), self.opt_arr.size)\n else:\n assert(self._valid_par is not None)\n if self.sr is not None:\n self.sr._x0 = None\n np.copyto(self._sampler._machine._epsilon, self._valid_par)\n np.copyto(self._sampler._machine._opt_params, self._sampler._machine._epsilon[self._sampler._machine._der_ids >= 0])\n np.copyto(self._sampler._state, self._valid_samps)\n self._sampler._machine.reset()\n self.optimizer._learning_rate /= 2\n if self._sr is not None:\n self._sr._diag_shift *= 2\n if _rank == 0:\n print(count, \"reset applied, learning rate:\", self.optimizer._learning_rate, flush = True)\n if self._sr is not None:\n print(\"diag shift:\", self._sr._diag_shift, flush=True)\n check_improvement = self._check_improvement\n self._check_improvement = False\n dp = self._forward_and_backward()\n self._previous_mean = self._loss_stats.mean.real\n self._previous_error = self._loss_stats.error_of_mean\n self._check_improvement = check_improvement\n\n if self._reset_bias:\n vals = self._sampler._machine.log_val(self._samples.reshape((-1, self._samples.shape[-1])))\n bias = vals.real.max()\n bias_update = _MPI_comm.allreduce(bias, op=MPI.MAX)\n _MPI_comm.barrier()\n self._sampler._machine.bias -= bias_update\n\n if i == 0:\n yield self.step_count\n self.update_parameters(dp)\n\n\n def _forward_and_backward(self):\n \"\"\"\n Performs a number of VMC optimization steps.\n\n Args:\n n_steps (int): Number of steps to perform.\n \"\"\"\n\n err = 0\n try:\n self._sampler.reset()\n # Burnout phase\n self._sampler.generate_samples(self._n_discard)\n\n # Generate samples and store them\n self._samples = self._sampler.generate_samples(\n self._n_samples_node, samples=self._samples\n )\n except:\n err = 1\n\n error = _MPI_comm.allreduce(err)\n _MPI_comm.barrier()\n assert(error == 0)\n\n err = 0\n try:\n # Compute the local energy estimator and average Energy\n eloc, self._loss_stats = self._get_mc_stats(self._ham)\n\n assert(abs(self._loss_stats.mean.imag) < 1.0)\n assert(np.isfinite(eloc).all())\n if self._check_improvement and self._previous_mean is not None:\n if (self._loss_stats.mean.real - self._loss_stats.error_of_mean) >= (self._previous_mean + self._previous_error):\n if _rank == 0:\n print(\"En improvement fail\", flush=True)\n assert((self._loss_stats.mean.real - self._loss_stats.error_of_mean) < (self._previous_mean + self._previous_error))\n except:\n err = 1\n\n error = _MPI_comm.allreduce(err)\n _MPI_comm.barrier()\n assert(error == 0)\n\n # Center the local energy\n eloc -= _mean(eloc)\n\n samples_r = self._samples.reshape((-1, self._samples.shape[-1]))\n eloc_r = eloc.reshape(-1, 1)\n\n # Perform update\n if self._sr:\n if self._sr.onthefly:\n\n err = 0\n try:\n self._grads = self._machine.vector_jacobian_prod(\n samples_r, eloc_r / self._n_samples, self._grads\n )\n assert(np.isfinite(self._grads).all())\n except:\n err = 1\n\n error = _MPI_comm.allreduce(err)\n _MPI_comm.barrier()\n assert(error == 0)\n\n self._grads = tree_map(_sum_inplace, self._grads)\n\n self._dp = self._sr.compute_update_onthefly(\n samples_r, self._grads, self._dp\n )\n\n else:\n err = 0\n try:\n # When using the SR (Natural gradient) we need to have the full jacobian\n self._grads, self._jac = self._machine.vector_jacobian_prod(\n samples_r,\n eloc_r / self._n_samples,\n self._grads,\n return_jacobian=True,\n )\n assert(np.isfinite(self._grads).all())\n assert(np.isfinite(self._jac).all())\n except:\n err = 1\n \n error = _MPI_comm.allreduce(err)\n _MPI_comm.barrier()\n assert(error == 0)\n\n self._grads = tree_map(_sum_inplace, self._grads)\n\n self._dp = self._sr.compute_update(self._jac, self._grads, self._dp)\n\n else:\n err = 0\n try:\n # Computing updates using the simple gradient\n self._grads = self._machine.vector_jacobian_prod(\n samples_r, eloc_r / self._n_samples, self._grads\n )\n assert(np.isfinite(self._grads).all())\n except:\n err = 1\n\n error = _MPI_comm.allreduce(err)\n _MPI_comm.barrier()\n assert(error == 0)\n\n self._grads = tree_map(_sum_inplace, self._grads)\n\n # if Real pars but complex gradient, take only real part\n # not necessary for SR because sr already does it.\n if not self._machine.has_complex_parameters:\n self._dp = tree_map(lambda x: x.real, self._grads)\n else:\n self._dp = self._grads\n\n return self._dp\n\n\nclass SweepOptLinMethod(LinMethod):\n def __init__(\n self,\n hamiltonian,\n sampler,\n n_samples,\n shift = 1,\n epsilon = 0.5,\n timestep = 1.0,\n update_shift = True,\n corr_samp = None,\n rescale_update=True,\n n_discard=None,\n reestimate_shift=True,\n max_opt = 3000,\n sweep_by_bonds = True,\n ):\n super().__init__(hamiltonian, sampler, n_samples, shift=shift, epsilon=epsilon, timestep=timestep,\n update_shift=update_shift, corr_samp=corr_samp, rescale_update=rescale_update,\n n_discard=n_discard)\n self.max_opt = max_opt\n\n self.opt_arr = np.zeros(self._sampler._machine._epsilon.size, dtype=bool)\n self.opt_arr[:self.max_opt] = True\n self.max_id = min(self.max_opt, self.opt_arr.size)\n self.sweep_by_bonds = sweep_by_bonds\n\n def iter(self, n_steps, step=1):\n for _ in range(0, n_steps, step):\n for i in range(0, step):\n if self.sweep_by_bonds:\n opt_tensor = np.zeros(self._sampler._machine._epsilon.shape, dtype=bool)\n arr_count = 0\n for k in range(self._sampler._machine._epsilon.shape[1]):\n for j in range(self._sampler._machine._epsilon.shape[0]):\n for l in range(self._sampler._machine._epsilon.shape[2]):\n opt_tensor[j,k,l] = self.opt_arr[arr_count]\n arr_count += 1\n else:\n opt_tensor = self.opt_arr.reshape(self._sampler._machine._epsilon.shape)\n\n self._sampler._machine.change_opt_ids(opt_tensor)\n dp = self._forward_and_backward()\n if i == 0:\n yield self.step_count\n self.update_parameters(dp)\n self.opt_arr.fill(False)\n self.opt_arr[self.max_id:(self.max_id+self.max_opt)] = True\n if self.max_id + self.max_opt > self.opt_arr.size:\n self.opt_arr[:(self.max_id + self.max_opt - self.opt_arr.size)] = True\n self.max_id = min((self.max_id + self.max_opt - self.opt_arr.size), self.opt_arr.size)\n else:\n self.max_id = min((self.max_id + self.max_opt), self.opt_arr.size)\n\n\nclass SweepOptStabSR(SRStab):\n def __init__(\n self,\n hamiltonian,\n sampler,\n n_samples,\n sr,\n diag_shift = 0.01,\n time_step = 0.02,\n corr_samp = None,\n n_discard=None,\n search_radius=3,\n par_samples=4,\n max_opt = 3000,\n sweep_by_bonds = True,\n ):\n super().__init__(hamiltonian, sampler, n_samples, sr, diag_shift=diag_shift, time_step=time_step,\n corr_samp=corr_samp, n_discard=n_discard, search_radius=search_radius, par_samples=par_samples)\n self.max_opt = max_opt\n\n self.opt_arr = np.zeros(self._sampler._machine._epsilon.size, dtype=bool)\n self.opt_arr[:self.max_opt] = True\n self.max_id = min(self.max_opt, self.opt_arr.size)\n self.sweep_by_bonds = sweep_by_bonds\n\n def iter(self, n_steps, step=1):\n for _ in range(0, n_steps, step):\n for i in range(0, step):\n if self.sweep_by_bonds:\n opt_tensor = np.zeros(self._sampler._machine._epsilon.shape, dtype=bool)\n arr_count = 0\n for k in range(self._sampler._machine._epsilon.shape[1]):\n for j in range(self._sampler._machine._epsilon.shape[0]):\n for l in range(self._sampler._machine._epsilon.shape[2]):\n opt_tensor[j,k,l] = self.opt_arr[arr_count]\n arr_count += 1\n else:\n opt_tensor = self.opt_arr.reshape(self._sampler._machine._epsilon.shape)\n\n self._sampler._machine.change_opt_ids(opt_tensor)\n if self.sr is not None and self.max_opt < self.opt_arr.size:\n self.sr._x0 = None\n dp = self._forward_and_backward()\n if i == 0:\n yield self.step_count\n self.update_parameters(dp)\n self.opt_arr.fill(False)\n self.opt_arr[self.max_id:(self.max_id+self.max_opt)] = True\n if self.max_id + self.max_opt > self.opt_arr.size:\n self.opt_arr[:(self.max_id + self.max_opt - self.opt_arr.size)] = True\n self.max_id = min((self.max_id + self.max_opt - self.opt_arr.size), self.opt_arr.size)\n else:\n self.max_id = min((self.max_id + self.max_opt), self.opt_arr.size)\n\nclass SweepOptStabLinMethod(LinMethodStab):\n def __init__(\n self,\n hamiltonian,\n sampler,\n n_samples,\n diag_shift = 0.01,\n time_step = 1.0,\n corr_samp = None,\n n_discard=None,\n search_radius=3,\n par_samples=10,\n max_opt = 3000,\n sweep_by_bonds = True,\n ):\n super().__init__(hamiltonian, sampler, n_samples, diag_shift=diag_shift, time_step=time_step,\n corr_samp=corr_samp, n_discard=n_discard, search_radius=search_radius, par_samples=par_samples)\n self.max_opt = max_opt\n\n self.opt_arr = np.zeros(self._sampler._machine._epsilon.size, dtype=bool)\n self.opt_arr[:self.max_opt] = True\n self.max_id = min(self.max_opt, self.opt_arr.size)\n self.sweep_by_bonds = sweep_by_bonds\n\n def iter(self, n_steps, step=1):\n for _ in range(0, n_steps, step):\n for i in range(0, step):\n if self.sweep_by_bonds:\n opt_tensor = np.zeros(self._sampler._machine._epsilon.shape, dtype=bool)\n arr_count = 0\n for k in range(self._sampler._machine._epsilon.shape[1]):\n for j in range(self._sampler._machine._epsilon.shape[0]):\n for l in range(self._sampler._machine._epsilon.shape[2]):\n opt_tensor[j,k,l] = self.opt_arr[arr_count]\n arr_count += 1\n else:\n opt_tensor = self.opt_arr.reshape(self._sampler._machine._epsilon.shape)\n\n self._sampler._machine.change_opt_ids(opt_tensor)\n if self.sr is not None and self.max_opt < self.opt_arr.size:\n self.sr._x0 = None\n dp = self._forward_and_backward()\n if i == 0:\n yield self.step_count\n self.update_parameters(dp)\n self.opt_arr.fill(False)\n self.opt_arr[self.max_id:(self.max_id+self.max_opt)] = True\n if self.max_id + self.max_opt > self.opt_arr.size:\n self.opt_arr[:(self.max_id + self.max_opt - self.opt_arr.size)] = True\n self.max_id = min((self.max_id + self.max_opt - self.opt_arr.size), self.opt_arr.size)\n else:\n self.max_id = min((self.max_id + self.max_opt), self.opt_arr.size)"
]
| [
[
"numpy.imag",
"numpy.save",
"numpy.real",
"numpy.zeros"
],
[
"numpy.copyto",
"numpy.isfinite",
"numpy.zeros"
]
]
|
ilyamirin/OrganGrinder | [
"7cff1a399d1439a06ee0ba90428a6542ebddb966"
]
| [
"src/lstm.py"
]
| [
"import numpy\nfrom keras.utils import np_utils\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras.layers import Activation\nfrom tensorflow.keras.layers import BatchNormalization as BatchNorm\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import LSTM\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.utils import plot_model\nfrom tensorflow.python.keras.callbacks import TensorBoard\n\nfrom ds_utils import load_dataset\nfrom midi_utils import generate_notes, convert_to_midi\n\n\ndef prepare_sequences(notes, pitch_names, latent_dim):\n \"\"\" Prepare the sequences used by the Neural Network \"\"\"\n\n # Create a dictionary to map pitches to integers\n note_to_int = dict((note, number) for number, note in enumerate(pitch_names))\n\n network_input = []\n network_output = []\n\n sequence_length = 100\n # Create input sequences and the corresponding outputs\n for i in range(0, len(notes) - sequence_length, 1):\n sequence_in = notes[i:i + sequence_length]\n sequence_out = notes[i + sequence_length]\n network_input.append([note_to_int[char] for char in sequence_in])\n network_output.append(note_to_int[sequence_out])\n\n n_patterns = len(network_input)\n\n # Reshape the input into a format compatible with LSTM layers\n # network_input = numpy.reshape(network_input, (n_patterns, sequence_length, 1))\n normalized_input = numpy.reshape(network_input, (n_patterns, sequence_length, 1))\n # Normalize input\n # network_input = network_input / float(latent_dim)\n normalized_input = normalized_input / float(latent_dim)\n\n network_output = np_utils.to_categorical(network_output)\n\n return network_input, normalized_input, network_output\n\n\ndef build_net(input, latent_dim):\n \"\"\" Create the structure of the neural network \"\"\"\n model = Sequential()\n model.add(LSTM(\n 512,\n input_shape=(input.shape[1], input.shape[2]),\n recurrent_dropout=0.3,\n return_sequences=True\n ))\n model.add(LSTM(512, return_sequences=True, recurrent_dropout=0.3, ))\n model.add(LSTM(512))\n model.add(BatchNorm())\n model.add(Dropout(0.3))\n model.add(Dense(256))\n model.add(Activation('relu'))\n model.add(BatchNorm())\n model.add(Dropout(0.3))\n model.add(Dense(latent_dim))\n model.add(Activation('softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='rmsprop')\n\n return model\n\n\ndef train(model, x, y, epochs, batch_size, save_period):\n \"\"\" Train the neural network \"\"\"\n filepath = './weights/model-{epoch:02d}-{loss:.3f}.h5'\n checkpoint = ModelCheckpoint(\n filepath,\n monitor='loss',\n verbose=0,\n save_best_only=True,\n mode='min',\n period=save_period\n )\n tensorboard = TensorBoard(\n log_dir='./logs',\n histogram_freq=0,\n write_graph=True,\n write_images=False\n )\n callbacks_list = [checkpoint, tensorboard]\n\n model.fit(x, y, epochs=epochs, batch_size=batch_size, callbacks=callbacks_list)\n\n\ndef plot_model_architecture(model):\n plot_model(model, 'model_architecture.png', show_shapes=True)\n\n\nif __name__ == '__main__':\n # First of all, we need to prepare dataset and dumps it on disk, only one time!\n # notes = dump_dataset('kaggle_ds_dump.notes')\n\n # Or, if dataset already created\n notes = load_dataset('kaggle_ds_dump.notes')\n latent_dim = len(set(notes))\n pitch_names = sorted(set(item for item in notes))\n x, x_normalized, y = prepare_sequences(notes, pitch_names, latent_dim)\n\n # Build model\n model = build_net(x_normalized, latent_dim)\n\n # If you want contain training from current weights\n model.load_weights('./best/best.h5')\n\n # Train model\n # train(model, x_normalized, y, epochs=4500, batch_size=128, save_period=250)\n\n # And finally generate sample\n raw_notes = generate_notes(model, x, pitch_names, latent_dim, generated_notes_number=500)\n convert_to_midi('lstm_samples', raw_notes)\n"
]
| [
[
"numpy.reshape",
"tensorflow.keras.layers.Activation",
"tensorflow.keras.callbacks.ModelCheckpoint",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.models.Sequential",
"tensorflow.keras.layers.LSTM",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.python.keras.callbacks.TensorBoard",
"tensorflow.keras.utils.plot_model"
]
]
|
rldejournett1/great_expectations | [
"57dcf939df8f8b77be55ef03ff99a98687acb407"
]
| [
"tests/checkpoint/test_checkpoint.py"
]
| [
"import logging\nimport os\nimport unittest.mock as mock\nfrom typing import List, Union\n\nimport pandas as pd\nimport pytest\nfrom ruamel.yaml import YAML\nfrom ruamel.yaml.comments import CommentedMap\n\nimport great_expectations as ge\nimport great_expectations.exceptions as ge_exceptions\nfrom great_expectations.checkpoint.checkpoint import Checkpoint, LegacyCheckpoint\nfrom great_expectations.checkpoint.types.checkpoint_result import CheckpointResult\nfrom great_expectations.data_context.data_context import DataContext\nfrom great_expectations.data_context.types.base import CheckpointConfig\nfrom great_expectations.data_context.types.resource_identifiers import (\n ConfigurationIdentifier,\n)\nfrom great_expectations.util import filter_properties_dict\nfrom great_expectations.validation_operators.types.validation_operator_result import (\n ValidationOperatorResult,\n)\n\nyaml = YAML()\n\nlogger = logging.getLogger(__name__)\n\n\ndef test_checkpoint_raises_typeerror_on_incorrect_data_context():\n with pytest.raises(TypeError):\n Checkpoint(name=\"my_checkpoint\", data_context=\"foo\", config_version=1)\n\n\ndef test_checkpoint_with_no_config_version_has_no_action_list(empty_data_context):\n checkpoint = Checkpoint(\"foo\", empty_data_context, config_version=None)\n with pytest.raises(AttributeError):\n checkpoint.action_list\n\n\ndef test_checkpoint_with_config_version_has_action_list(empty_data_context):\n checkpoint = Checkpoint(\n \"foo\", empty_data_context, config_version=1, action_list=[{\"foo\": \"bar\"}]\n )\n obs = checkpoint.action_list\n assert isinstance(obs, list)\n assert obs == [{\"foo\": \"bar\"}]\n\n\ndef test_basic_checkpoint_config_validation(\n empty_data_context,\n caplog,\n capsys,\n):\n yaml_config_erroneous: str\n config_erroneous: CommentedMap\n checkpoint_config: Union[CheckpointConfig, dict]\n checkpoint: Checkpoint\n\n yaml_config_erroneous = f\"\"\"\n name: misconfigured_checkpoint\n unexpected_property: UNKNOWN_PROPERTY_VALUE\n \"\"\"\n config_erroneous = yaml.load(yaml_config_erroneous)\n with pytest.raises(TypeError):\n # noinspection PyUnusedLocal\n checkpoint_config = CheckpointConfig(**config_erroneous)\n with pytest.raises(KeyError):\n # noinspection PyUnusedLocal\n checkpoint = empty_data_context.test_yaml_config(\n yaml_config=yaml_config_erroneous,\n name=\"my_erroneous_checkpoint\",\n )\n\n yaml_config_erroneous = f\"\"\"\n config_version: 1\n \"\"\"\n config_erroneous = yaml.load(yaml_config_erroneous)\n with pytest.raises(ge_exceptions.InvalidConfigError):\n # noinspection PyUnusedLocal\n checkpoint_config = CheckpointConfig.from_commented_map(\n commented_map=config_erroneous\n )\n with pytest.raises(KeyError):\n # noinspection PyUnusedLocal\n checkpoint = empty_data_context.test_yaml_config(\n yaml_config=yaml_config_erroneous,\n name=\"my_erroneous_checkpoint\",\n )\n with pytest.raises(ge_exceptions.InvalidConfigError):\n # noinspection PyUnusedLocal\n checkpoint = empty_data_context.test_yaml_config(\n yaml_config=yaml_config_erroneous,\n name=\"my_erroneous_checkpoint\",\n class_name=\"Checkpoint\",\n )\n\n yaml_config_erroneous = f\"\"\"\n config_version: 1\n name: my_erroneous_checkpoint\n class_name: Checkpoint\n \"\"\"\n # noinspection PyUnusedLocal\n checkpoint = empty_data_context.test_yaml_config(\n yaml_config=yaml_config_erroneous,\n name=\"my_erroneous_checkpoint\",\n class_name=\"Checkpoint\",\n )\n captured = capsys.readouterr()\n assert any(\n [\n 'Your current Checkpoint configuration has an empty or missing \"validations\" attribute'\n in message\n for message in [caplog.text, captured.out]\n ]\n )\n assert any(\n [\n 'Your current Checkpoint configuration has an empty or missing \"action_list\" attribute'\n in message\n for message in [caplog.text, captured.out]\n ]\n )\n\n assert len(empty_data_context.list_checkpoints()) == 1\n\n yaml_config: str = f\"\"\"\n name: my_checkpoint\n config_version: 1\n class_name: Checkpoint\n validations: []\n action_list:\n - name: store_validation_result\n action:\n class_name: StoreValidationResultAction\n - name: store_evaluation_params\n action:\n class_name: StoreEvaluationParametersAction\n - name: update_data_docs\n action:\n class_name: UpdateDataDocsAction\n \"\"\"\n\n expected_checkpoint_config: dict = {\n \"name\": \"my_checkpoint\",\n \"config_version\": 1.0,\n \"class_name\": \"Checkpoint\",\n \"module_name\": \"great_expectations.checkpoint\",\n \"action_list\": [\n {\n \"name\": \"store_validation_result\",\n \"action\": {\"class_name\": \"StoreValidationResultAction\"},\n },\n {\n \"name\": \"store_evaluation_params\",\n \"action\": {\"class_name\": \"StoreEvaluationParametersAction\"},\n },\n {\n \"name\": \"update_data_docs\",\n \"action\": {\"class_name\": \"UpdateDataDocsAction\"},\n },\n ],\n }\n\n config: CommentedMap = yaml.load(yaml_config)\n checkpoint_config = CheckpointConfig(**config)\n checkpoint_config = checkpoint_config.to_json_dict()\n checkpoint = Checkpoint(data_context=empty_data_context, **checkpoint_config)\n assert (\n filter_properties_dict(\n properties=checkpoint.self_check()[\"config\"],\n )\n == expected_checkpoint_config\n )\n assert (\n filter_properties_dict(\n properties=checkpoint.config.to_json_dict(),\n )\n == expected_checkpoint_config\n )\n\n checkpoint = empty_data_context.test_yaml_config(\n yaml_config=yaml_config,\n name=\"my_checkpoint\",\n )\n assert (\n filter_properties_dict(\n properties=checkpoint.self_check()[\"config\"],\n )\n == expected_checkpoint_config\n )\n assert (\n filter_properties_dict(\n properties=checkpoint.config.to_json_dict(),\n )\n == expected_checkpoint_config\n )\n\n assert len(empty_data_context.list_checkpoints()) == 2\n\n empty_data_context.create_expectation_suite(\n expectation_suite_name=\"my_expectation_suite\"\n )\n result: CheckpointResult = empty_data_context.run_checkpoint(\n checkpoint_name=checkpoint.config.name,\n )\n assert len(result.list_validation_results()) == 0\n\n\ndef test_checkpoint_configuration_no_nesting_using_test_yaml_config(\n titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store,\n monkeypatch,\n):\n monkeypatch.setenv(\"VAR\", \"test\")\n monkeypatch.setenv(\"MY_PARAM\", \"1\")\n monkeypatch.setenv(\"OLD_PARAM\", \"2\")\n\n checkpoint: Checkpoint\n\n data_context: DataContext = titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store\n\n yaml_config: str = f\"\"\"\n name: my_fancy_checkpoint\n config_version: 1\n class_name: Checkpoint\n run_name_template: \"%Y-%M-foo-bar-template-$VAR\"\n validations:\n - batch_request:\n datasource_name: my_datasource\n data_connector_name: my_special_data_connector\n data_asset_name: users\n partition_request:\n index: -1\n expectation_suite_name: users.delivery\n action_list:\n - name: store_validation_result\n action:\n class_name: StoreValidationResultAction\n - name: store_evaluation_params\n action:\n class_name: StoreEvaluationParametersAction\n - name: update_data_docs\n action:\n class_name: UpdateDataDocsAction\n evaluation_parameters:\n # TODO: <Alex>The EvaluationParameters substitution and/or operations capabilities do not work for Checkpoints yet.</Alex>\n # param1: \"$MY_PARAM\"\n # param2: 1 + \"$OLD_PARAM\"\n param1: 1\n param2: 2\n runtime_configuration:\n result_format:\n result_format: BASIC\n partial_unexpected_count: 20\n \"\"\"\n\n expected_checkpoint_config: dict = {\n \"name\": \"my_fancy_checkpoint\",\n \"config_version\": 1.0,\n \"class_name\": \"Checkpoint\",\n \"validations\": [\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_special_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\n \"index\": -1,\n },\n },\n \"expectation_suite_name\": \"users.delivery\",\n \"action_list\": [\n {\n \"name\": \"store_validation_result\",\n \"action\": {\"class_name\": \"StoreValidationResultAction\"},\n },\n {\n \"name\": \"store_evaluation_params\",\n \"action\": {\"class_name\": \"StoreEvaluationParametersAction\"},\n },\n {\n \"name\": \"update_data_docs\",\n \"action\": {\"class_name\": \"UpdateDataDocsAction\"},\n },\n ],\n \"evaluation_parameters\": {\"param1\": 1, \"param2\": 2},\n \"runtime_configuration\": {\n \"result_format\": {\n \"result_format\": \"BASIC\",\n \"partial_unexpected_count\": 20,\n }\n },\n }\n ],\n \"template_name\": None,\n \"module_name\": \"great_expectations.checkpoint\",\n \"run_name_template\": \"%Y-%M-foo-bar-template-test\",\n \"expectation_suite_name\": None,\n \"batch_request\": None,\n \"action_list\": [],\n \"evaluation_parameters\": {},\n \"runtime_configuration\": {},\n \"profilers\": [],\n }\n\n checkpoint = data_context.test_yaml_config(\n yaml_config=yaml_config,\n name=\"my_fancy_checkpoint\",\n )\n assert filter_properties_dict(\n properties=checkpoint.config.to_json_dict(),\n ) == filter_properties_dict(\n properties=expected_checkpoint_config,\n )\n\n assert len(data_context.list_checkpoints()) == 1\n\n data_context.create_expectation_suite(expectation_suite_name=\"users.delivery\")\n result: CheckpointResult = data_context.run_checkpoint(\n checkpoint_name=checkpoint.config.name,\n )\n assert len(result.list_validation_results()) == 1\n assert len(data_context.validations_store.list_keys()) == 1\n assert result.success\n\n monkeypatch.delenv(\"VAR\")\n monkeypatch.delenv(\"MY_PARAM\")\n monkeypatch.delenv(\"OLD_PARAM\")\n\n\ndef test_checkpoint_configuration_nesting_provides_defaults_for_most_elements_test_yaml_config(\n titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store,\n monkeypatch,\n):\n monkeypatch.setenv(\"VAR\", \"test\")\n monkeypatch.setenv(\"MY_PARAM\", \"1\")\n monkeypatch.setenv(\"OLD_PARAM\", \"2\")\n\n checkpoint: Checkpoint\n\n data_context: DataContext = titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store\n\n yaml_config: str = f\"\"\"\n name: my_fancy_checkpoint\n config_version: 1\n class_name: Checkpoint\n run_name_template: \"%Y-%M-foo-bar-template-$VAR\"\n validations:\n - batch_request:\n datasource_name: my_datasource\n data_connector_name: my_special_data_connector\n data_asset_name: users\n partition_request:\n index: -1\n - batch_request:\n datasource_name: my_datasource\n data_connector_name: my_other_data_connector\n data_asset_name: users\n partition_request:\n index: -2\n expectation_suite_name: users.delivery\n action_list:\n - name: store_validation_result\n action:\n class_name: StoreValidationResultAction\n - name: store_evaluation_params\n action:\n class_name: StoreEvaluationParametersAction\n - name: update_data_docs\n action:\n class_name: UpdateDataDocsAction\n evaluation_parameters:\n # TODO: <Alex>The EvaluationParameters substitution and/or operations capabilities do not work for Checkpoints yet.</Alex>\n # param1: \"$MY_PARAM\"\n # param2: 1 + \"$OLD_PARAM\"\n param1: 1\n param2: 2\n runtime_configuration:\n result_format:\n result_format: BASIC\n partial_unexpected_count: 20\n \"\"\"\n\n expected_checkpoint_config: dict = {\n \"name\": \"my_fancy_checkpoint\",\n \"config_version\": 1.0,\n \"class_name\": \"Checkpoint\",\n \"validations\": [\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_special_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\n \"index\": -1,\n },\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\n \"index\": -2,\n },\n }\n },\n ],\n \"expectation_suite_name\": \"users.delivery\",\n \"action_list\": [\n {\n \"name\": \"store_validation_result\",\n \"action\": {\"class_name\": \"StoreValidationResultAction\"},\n },\n {\n \"name\": \"store_evaluation_params\",\n \"action\": {\"class_name\": \"StoreEvaluationParametersAction\"},\n },\n {\n \"name\": \"update_data_docs\",\n \"action\": {\"class_name\": \"UpdateDataDocsAction\"},\n },\n ],\n \"evaluation_parameters\": {\"param1\": 1, \"param2\": 2},\n \"runtime_configuration\": {\n \"result_format\": {\"result_format\": \"BASIC\", \"partial_unexpected_count\": 20}\n },\n \"template_name\": None,\n \"module_name\": \"great_expectations.checkpoint\",\n \"run_name_template\": \"%Y-%M-foo-bar-template-test\",\n \"batch_request\": None,\n \"profilers\": [],\n }\n\n checkpoint = data_context.test_yaml_config(\n yaml_config=yaml_config,\n name=\"my_fancy_checkpoint\",\n )\n assert filter_properties_dict(\n properties=checkpoint.config.to_json_dict(),\n ) == filter_properties_dict(\n properties=expected_checkpoint_config,\n )\n\n assert len(data_context.list_checkpoints()) == 1\n\n data_context.create_expectation_suite(expectation_suite_name=\"users.delivery\")\n result: CheckpointResult = data_context.run_checkpoint(\n checkpoint_name=checkpoint.config.name,\n )\n assert len(result.list_validation_results()) == 2\n assert len(data_context.validations_store.list_keys()) == 2\n assert result.success\n\n monkeypatch.delenv(\"VAR\")\n monkeypatch.delenv(\"MY_PARAM\")\n monkeypatch.delenv(\"OLD_PARAM\")\n\n\ndef test_checkpoint_configuration_using_RuntimeDataConnector_with_Airflow_test_yaml_config(\n titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store,\n):\n checkpoint: Checkpoint\n\n data_context: DataContext = titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store\n\n yaml_config: str = f\"\"\"\n name: airflow_checkpoint\n config_version: 1\n class_name: Checkpoint\n validations:\n - batch_request:\n datasource_name: my_datasource\n data_connector_name: my_runtime_data_connector\n data_asset_name: IN_MEMORY_DATA_ASSET\n expectation_suite_name: users.delivery\n action_list:\n - name: store_validation_result\n action:\n class_name: StoreValidationResultAction\n - name: store_evaluation_params\n action:\n class_name: StoreEvaluationParametersAction\n - name: update_data_docs\n action:\n class_name: UpdateDataDocsAction\n \"\"\"\n\n expected_checkpoint_config: dict = {\n \"name\": \"airflow_checkpoint\",\n \"config_version\": 1.0,\n \"class_name\": \"Checkpoint\",\n \"validations\": [\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_runtime_data_connector\",\n \"data_asset_name\": \"IN_MEMORY_DATA_ASSET\",\n }\n }\n ],\n \"expectation_suite_name\": \"users.delivery\",\n \"action_list\": [\n {\n \"name\": \"store_validation_result\",\n \"action\": {\"class_name\": \"StoreValidationResultAction\"},\n },\n {\n \"name\": \"store_evaluation_params\",\n \"action\": {\"class_name\": \"StoreEvaluationParametersAction\"},\n },\n {\n \"name\": \"update_data_docs\",\n \"action\": {\"class_name\": \"UpdateDataDocsAction\"},\n },\n ],\n \"template_name\": None,\n \"module_name\": \"great_expectations.checkpoint\",\n \"run_name_template\": None,\n \"batch_request\": None,\n \"evaluation_parameters\": {},\n \"runtime_configuration\": {},\n \"profilers\": [],\n }\n\n checkpoint = data_context.test_yaml_config(\n yaml_config=yaml_config,\n name=\"airflow_checkpoint\",\n )\n assert filter_properties_dict(\n properties=checkpoint.config.to_json_dict(),\n ) == filter_properties_dict(\n properties=expected_checkpoint_config,\n )\n\n assert len(data_context.list_checkpoints()) == 1\n\n data_context.create_expectation_suite(expectation_suite_name=\"users.delivery\")\n test_df: pd.DataFrame = pd.DataFrame(data={\"col1\": [1, 2], \"col2\": [3, 4]})\n result: CheckpointResult = data_context.run_checkpoint(\n checkpoint_name=checkpoint.config.name,\n batch_request={\n \"batch_data\": test_df,\n \"partition_request\": {\n \"partition_identifiers\": {\n \"airflow_run_id\": 1234567890,\n }\n },\n },\n run_name=\"airflow_run_1234567890\",\n )\n assert len(result.list_validation_results()) == 1\n assert len(data_context.validations_store.list_keys()) == 1\n assert result.success\n\n\ndef test_checkpoint_configuration_warning_error_quarantine_test_yaml_config(\n titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store,\n monkeypatch,\n):\n monkeypatch.setenv(\"GE_ENVIRONMENT\", \"my_ge_environment\")\n\n checkpoint: Checkpoint\n\n data_context: DataContext = titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store\n\n yaml_config: str = f\"\"\"\n name: airflow_users_node_3\n config_version: 1\n class_name: Checkpoint\n batch_request:\n datasource_name: my_datasource\n data_connector_name: my_special_data_connector\n data_asset_name: users\n partition_request:\n index: -1\n validations:\n - expectation_suite_name: users.warning # runs the top-level action list against the top-level batch_request\n - expectation_suite_name: users.error # runs the locally-specified_action_list (?UNION THE TOP LEVEL?) against the top-level batch_request\n action_list:\n - name: quarantine_failed_data\n action:\n class_name: CreateQuarantineData\n - name: advance_passed_data\n action:\n class_name: CreatePassedData\n action_list:\n - name: store_validation_result\n action:\n class_name: StoreValidationResultAction\n - name: store_evaluation_params\n action:\n class_name: StoreEvaluationParametersAction\n - name: update_data_docs\n action:\n class_name: UpdateDataDocsAction\n evaluation_parameters:\n environment: $GE_ENVIRONMENT\n tolerance: 0.01\n runtime_configuration:\n result_format:\n result_format: BASIC\n partial_unexpected_count: 20\n \"\"\"\n\n mock_create_quarantine_data = mock.MagicMock()\n mock_create_quarantine_data.run.return_value = True\n ge.validation_operators.CreateQuarantineData = mock_create_quarantine_data\n\n mock_create_passed_data = mock.MagicMock()\n mock_create_passed_data.run.return_value = True\n ge.validation_operators.CreatePassedData = mock_create_passed_data\n\n expected_checkpoint_config: dict = {\n \"name\": \"airflow_users_node_3\",\n \"config_version\": 1.0,\n \"class_name\": \"Checkpoint\",\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_special_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\n \"index\": -1,\n },\n },\n \"validations\": [\n {\"expectation_suite_name\": \"users.warning\"},\n {\n \"expectation_suite_name\": \"users.error\",\n \"action_list\": [\n {\n \"name\": \"quarantine_failed_data\",\n \"action\": {\"class_name\": \"CreateQuarantineData\"},\n },\n {\n \"name\": \"advance_passed_data\",\n \"action\": {\"class_name\": \"CreatePassedData\"},\n },\n ],\n },\n ],\n \"action_list\": [\n {\n \"name\": \"store_validation_result\",\n \"action\": {\"class_name\": \"StoreValidationResultAction\"},\n },\n {\n \"name\": \"store_evaluation_params\",\n \"action\": {\"class_name\": \"StoreEvaluationParametersAction\"},\n },\n {\n \"name\": \"update_data_docs\",\n \"action\": {\"class_name\": \"UpdateDataDocsAction\"},\n },\n ],\n \"evaluation_parameters\": {\n \"environment\": \"my_ge_environment\",\n \"tolerance\": 0.01,\n },\n \"runtime_configuration\": {\n \"result_format\": {\"result_format\": \"BASIC\", \"partial_unexpected_count\": 20}\n },\n \"template_name\": None,\n \"module_name\": \"great_expectations.checkpoint\",\n \"run_name_template\": None,\n \"expectation_suite_name\": None,\n \"profilers\": [],\n }\n\n checkpoint = data_context.test_yaml_config(\n yaml_config=yaml_config,\n name=\"airflow_users_node_3\",\n )\n assert filter_properties_dict(\n properties=checkpoint.config.to_json_dict(),\n ) == filter_properties_dict(\n properties=expected_checkpoint_config,\n )\n\n assert len(data_context.list_checkpoints()) == 1\n\n data_context.create_expectation_suite(expectation_suite_name=\"users.warning\")\n data_context.create_expectation_suite(expectation_suite_name=\"users.error\")\n result: CheckpointResult = data_context.run_checkpoint(\n checkpoint_name=checkpoint.config.name,\n )\n assert len(result.list_validation_results()) == 2\n assert len(data_context.validations_store.list_keys()) == 2\n assert result.success\n\n monkeypatch.delenv(\"GE_ENVIRONMENT\")\n\n\ndef test_checkpoint_configuration_template_parsing_and_usage_test_yaml_config(\n titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store,\n monkeypatch,\n):\n monkeypatch.setenv(\"VAR\", \"test\")\n monkeypatch.setenv(\"MY_PARAM\", \"1\")\n monkeypatch.setenv(\"OLD_PARAM\", \"2\")\n\n checkpoint: Checkpoint\n yaml_config: str\n expected_checkpoint_config: dict\n result: CheckpointResult\n\n data_context: DataContext = titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store\n\n yaml_config = f\"\"\"\n name: my_base_checkpoint\n config_version: 1\n class_name: Checkpoint\n run_name_template: \"%Y-%M-foo-bar-template-$VAR\"\n action_list:\n - name: store_validation_result\n action:\n class_name: StoreValidationResultAction\n - name: store_evaluation_params\n action:\n class_name: StoreEvaluationParametersAction\n - name: update_data_docs\n action:\n class_name: UpdateDataDocsAction\n evaluation_parameters:\n # TODO: <Alex>The EvaluationParameters substitution and/or operations capabilities do not work for Checkpoints yet.</Alex>\n # param1: \"$MY_PARAM\"\n # param2: 1 + \"$OLD_PARAM\"\n param1: 1\n param2: 2\n runtime_configuration:\n result_format:\n result_format: BASIC\n partial_unexpected_count: 20\n \"\"\"\n\n expected_checkpoint_config = {\n \"name\": \"my_base_checkpoint\",\n \"config_version\": 1.0,\n \"template_name\": None,\n \"module_name\": \"great_expectations.checkpoint\",\n \"class_name\": \"Checkpoint\",\n \"run_name_template\": \"%Y-%M-foo-bar-template-test\",\n \"expectation_suite_name\": None,\n \"batch_request\": None,\n \"action_list\": [\n {\n \"name\": \"store_validation_result\",\n \"action\": {\"class_name\": \"StoreValidationResultAction\"},\n },\n {\n \"name\": \"store_evaluation_params\",\n \"action\": {\"class_name\": \"StoreEvaluationParametersAction\"},\n },\n {\n \"name\": \"update_data_docs\",\n \"action\": {\"class_name\": \"UpdateDataDocsAction\"},\n },\n ],\n \"evaluation_parameters\": {\"param1\": 1, \"param2\": 2},\n \"runtime_configuration\": {\n \"result_format\": {\"result_format\": \"BASIC\", \"partial_unexpected_count\": 20}\n },\n \"validations\": [],\n \"profilers\": [],\n }\n\n checkpoint = data_context.test_yaml_config(\n yaml_config=yaml_config,\n name=\"my_base_checkpoint\",\n )\n assert filter_properties_dict(\n properties=checkpoint.config.to_json_dict(),\n ) == filter_properties_dict(\n properties=expected_checkpoint_config,\n )\n\n assert len(data_context.list_checkpoints()) == 1\n\n data_context.create_expectation_suite(expectation_suite_name=\"users.delivery\")\n\n result = data_context.run_checkpoint(\n checkpoint_name=\"my_base_checkpoint\",\n validations=[\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_special_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\n \"index\": -1,\n },\n },\n \"expectation_suite_name\": \"users.delivery\",\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\n \"index\": -2,\n },\n },\n \"expectation_suite_name\": \"users.delivery\",\n },\n ],\n )\n assert len(result.list_validation_results()) == 2\n assert len(data_context.validations_store.list_keys()) == 2\n assert result.success\n\n yaml_config = f\"\"\"\n name: my_fancy_checkpoint\n config_version: 1\n class_name: Checkpoint\n template_name: my_base_checkpoint\n validations:\n - batch_request:\n datasource_name: my_datasource\n data_connector_name: my_special_data_connector\n data_asset_name: users\n partition_request:\n index: -1\n - batch_request:\n datasource_name: my_datasource\n data_connector_name: my_other_data_connector\n data_asset_name: users\n partition_request:\n index: -2\n expectation_suite_name: users.delivery\n \"\"\"\n\n expected_checkpoint_config = {\n \"name\": \"my_fancy_checkpoint\",\n \"config_version\": 1.0,\n \"class_name\": \"Checkpoint\",\n \"template_name\": \"my_base_checkpoint\",\n \"validations\": [\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_special_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\n \"index\": -1,\n },\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\n \"index\": -2,\n },\n }\n },\n ],\n \"expectation_suite_name\": \"users.delivery\",\n \"module_name\": \"great_expectations.checkpoint\",\n \"run_name_template\": None,\n \"batch_request\": None,\n \"action_list\": [],\n \"evaluation_parameters\": {},\n \"runtime_configuration\": {},\n \"profilers\": [],\n }\n\n checkpoint = data_context.test_yaml_config(\n yaml_config=yaml_config,\n name=\"my_fancy_checkpoint\",\n )\n assert filter_properties_dict(\n properties=checkpoint.config.to_json_dict(),\n ) == filter_properties_dict(\n properties=expected_checkpoint_config,\n )\n\n assert len(data_context.list_checkpoints()) == 2\n\n result: CheckpointResult = data_context.run_checkpoint(\n checkpoint_name=checkpoint.config.name,\n )\n assert len(result.list_validation_results()) == 2\n assert len(data_context.validations_store.list_keys()) == 4\n assert result.success\n\n monkeypatch.delenv(\"VAR\")\n monkeypatch.delenv(\"MY_PARAM\")\n monkeypatch.delenv(\"OLD_PARAM\")\n\n\ndef test_legacy_checkpoint_instantiates_and_produces_a_validation_result_when_run(\n filesystem_csv_data_context_with_validation_operators,\n):\n rad_datasource = list(\n filter(\n lambda element: element[\"name\"] == \"rad_datasource\",\n filesystem_csv_data_context_with_validation_operators.list_datasources(),\n )\n )[0]\n base_directory = rad_datasource[\"batch_kwargs_generators\"][\"subdir_reader\"][\n \"base_directory\"\n ]\n batch_kwargs = {\n \"path\": base_directory + \"/f1.csv\",\n \"datasource\": \"rad_datasource\",\n \"reader_method\": \"read_csv\",\n }\n\n checkpoint_config_dict = {\n \"name\": \"my_checkpoint\",\n \"validation_operator_name\": \"action_list_operator\",\n \"batches\": [\n {\"batch_kwargs\": batch_kwargs, \"expectation_suite_names\": [\"my_suite\"]}\n ],\n }\n\n checkpoint = LegacyCheckpoint(\n data_context=filesystem_csv_data_context_with_validation_operators,\n **checkpoint_config_dict,\n )\n\n with pytest.raises(\n ge_exceptions.DataContextError, match=r\"expectation_suite .* not found\"\n ):\n checkpoint.run()\n\n assert (\n len(\n filesystem_csv_data_context_with_validation_operators.validations_store.list_keys()\n )\n == 0\n )\n\n filesystem_csv_data_context_with_validation_operators.create_expectation_suite(\n \"my_suite\"\n )\n # noinspection PyUnusedLocal\n results = checkpoint.run()\n\n assert (\n len(\n filesystem_csv_data_context_with_validation_operators.validations_store.list_keys()\n )\n == 1\n )\n\n\n# TODO: add more test cases\ndef test_newstyle_checkpoint_instantiates_and_produces_a_validation_result_when_run(\n titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store,\n):\n context = titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store\n # add checkpoint config\n checkpoint_config = CheckpointConfig(\n name=\"my_checkpoint\",\n config_version=1,\n run_name_template=\"%Y-%M-foo-bar-template\",\n expectation_suite_name=\"my_expectation_suite\",\n action_list=[\n {\n \"name\": \"store_validation_result\",\n \"action\": {\n \"class_name\": \"StoreValidationResultAction\",\n },\n },\n {\n \"name\": \"store_evaluation_params\",\n \"action\": {\n \"class_name\": \"StoreEvaluationParametersAction\",\n },\n },\n {\n \"name\": \"update_data_docs\",\n \"action\": {\n \"class_name\": \"UpdateDataDocsAction\",\n },\n },\n ],\n validations=[\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_basic_data_connector\",\n \"data_asset_name\": \"Titanic_1911\",\n }\n }\n ],\n )\n checkpoint_config_key = ConfigurationIdentifier(\n configuration_key=checkpoint_config.name\n )\n context.checkpoint_store.set(key=checkpoint_config_key, value=checkpoint_config)\n checkpoint = context.get_checkpoint(checkpoint_config.name)\n\n with pytest.raises(\n ge_exceptions.DataContextError, match=r\"expectation_suite .* not found\"\n ):\n checkpoint.run()\n\n assert len(context.validations_store.list_keys()) == 0\n\n context.create_expectation_suite(\"my_expectation_suite\")\n # noinspection PyUnusedLocal\n results = checkpoint.run()\n\n assert len(context.validations_store.list_keys()) == 1\n\n\ndef test_newstyle_checkpoint_config_substitution_simple(\n titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_templates,\n monkeypatch,\n):\n monkeypatch.setenv(\"GE_ENVIRONMENT\", \"my_ge_environment\")\n monkeypatch.setenv(\"VAR\", \"test\")\n monkeypatch.setenv(\"MY_PARAM\", \"1\")\n monkeypatch.setenv(\"OLD_PARAM\", \"2\")\n\n context = titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_templates\n\n simplified_checkpoint_config = CheckpointConfig(\n name=\"my_simplified_checkpoint\",\n config_version=1,\n template_name=\"my_simple_template_checkpoint\",\n expectation_suite_name=\"users.delivery\",\n validations=[\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_special_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -1},\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -2},\n }\n },\n ],\n )\n simplified_checkpoint = Checkpoint(\n data_context=context, **simplified_checkpoint_config.to_json_dict()\n )\n\n # template only\n expected_substituted_checkpoint_config_template_only = CheckpointConfig(\n name=\"my_simplified_checkpoint\",\n config_version=1,\n run_name_template=\"%Y-%M-foo-bar-template-test\",\n expectation_suite_name=\"users.delivery\",\n action_list=[\n {\n \"name\": \"store_validation_result\",\n \"action\": {\n \"class_name\": \"StoreValidationResultAction\",\n },\n },\n {\n \"name\": \"store_evaluation_params\",\n \"action\": {\n \"class_name\": \"StoreEvaluationParametersAction\",\n },\n },\n {\n \"name\": \"update_data_docs\",\n \"action\": {\n \"class_name\": \"UpdateDataDocsAction\",\n },\n },\n ],\n evaluation_parameters={\n \"environment\": \"my_ge_environment\",\n \"tolerance\": 1.0e-2,\n \"aux_param_0\": \"1\",\n \"aux_param_1\": \"1 + 1\",\n },\n runtime_configuration={\n \"result_format\": {\n \"result_format\": \"BASIC\",\n \"partial_unexpected_count\": 20,\n }\n },\n validations=[\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_special_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -1},\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -2},\n }\n },\n ],\n )\n\n substituted_config_template_only = simplified_checkpoint.get_substituted_config()\n assert (\n substituted_config_template_only.to_json_dict()\n == expected_substituted_checkpoint_config_template_only.to_json_dict()\n )\n # make sure operation is idempotent\n simplified_checkpoint.get_substituted_config()\n assert (\n substituted_config_template_only.to_json_dict()\n == expected_substituted_checkpoint_config_template_only.to_json_dict()\n )\n\n # template and runtime kwargs\n expected_substituted_checkpoint_config_template_and_runtime_kwargs = (\n CheckpointConfig(\n name=\"my_simplified_checkpoint\",\n config_version=1,\n run_name_template=\"runtime_run_template\",\n expectation_suite_name=\"runtime_suite_name\",\n action_list=[\n {\n \"name\": \"store_validation_result\",\n \"action\": {\n \"class_name\": \"StoreValidationResultAction\",\n },\n },\n {\n \"name\": \"store_evaluation_params\",\n \"action\": {\n \"class_name\": \"MyCustomStoreEvaluationParametersAction\",\n },\n },\n {\n \"name\": \"update_data_docs_deluxe\",\n \"action\": {\n \"class_name\": \"UpdateDataDocsAction\",\n },\n },\n ],\n evaluation_parameters={\n \"environment\": \"runtime-my_ge_environment\",\n \"tolerance\": 1.0e-2,\n \"aux_param_0\": \"runtime-1\",\n \"aux_param_1\": \"1 + 1\",\n \"new_runtime_eval_param\": \"bloopy!\",\n },\n runtime_configuration={\n \"result_format\": {\n \"result_format\": \"BASIC\",\n \"partial_unexpected_count\": 999,\n \"new_runtime_config_key\": \"bleepy!\",\n }\n },\n validations=[\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_special_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -1},\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -2},\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector_2\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -3},\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector_3\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -4},\n }\n },\n ],\n )\n )\n\n substituted_config_template_and_runtime_kwargs = (\n simplified_checkpoint.get_substituted_config(\n runtime_kwargs={\n \"expectation_suite_name\": \"runtime_suite_name\",\n \"validations\": [\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector_2\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -3},\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector_3\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -4},\n }\n },\n ],\n \"run_name_template\": \"runtime_run_template\",\n \"action_list\": [\n {\n \"name\": \"store_validation_result\",\n \"action\": {\n \"class_name\": \"StoreValidationResultAction\",\n },\n },\n {\n \"name\": \"store_evaluation_params\",\n \"action\": {\n \"class_name\": \"MyCustomStoreEvaluationParametersAction\",\n },\n },\n {\n \"name\": \"update_data_docs\",\n \"action\": None,\n },\n {\n \"name\": \"update_data_docs_deluxe\",\n \"action\": {\n \"class_name\": \"UpdateDataDocsAction\",\n },\n },\n ],\n \"evaluation_parameters\": {\n \"environment\": \"runtime-$GE_ENVIRONMENT\",\n \"tolerance\": 1.0e-2,\n \"aux_param_0\": \"runtime-$MY_PARAM\",\n \"aux_param_1\": \"1 + $MY_PARAM\",\n \"new_runtime_eval_param\": \"bloopy!\",\n },\n \"runtime_configuration\": {\n \"result_format\": {\n \"result_format\": \"BASIC\",\n \"partial_unexpected_count\": 999,\n \"new_runtime_config_key\": \"bleepy!\",\n }\n },\n }\n )\n )\n assert (\n substituted_config_template_and_runtime_kwargs.to_json_dict()\n == expected_substituted_checkpoint_config_template_and_runtime_kwargs.to_json_dict()\n )\n\n monkeypatch.delenv(\"GE_ENVIRONMENT\")\n monkeypatch.delenv(\"VAR\")\n monkeypatch.delenv(\"MY_PARAM\")\n monkeypatch.delenv(\"OLD_PARAM\")\n\n\ndef test_newstyle_checkpoint_config_substitution_nested(\n titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_templates,\n monkeypatch,\n):\n monkeypatch.setenv(\"GE_ENVIRONMENT\", \"my_ge_environment\")\n monkeypatch.setenv(\"VAR\", \"test\")\n monkeypatch.setenv(\"MY_PARAM\", \"1\")\n monkeypatch.setenv(\"OLD_PARAM\", \"2\")\n\n context = titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_templates\n\n nested_checkpoint_config = CheckpointConfig(\n name=\"my_nested_checkpoint\",\n config_version=1,\n template_name=\"my_nested_checkpoint_template_2\",\n expectation_suite_name=\"users.delivery\",\n validations=[\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_special_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -1},\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -2},\n }\n },\n ],\n )\n nested_checkpoint = Checkpoint(\n data_context=context, **nested_checkpoint_config.to_json_dict()\n )\n\n # template only\n expected_nested_checkpoint_config_template_only = CheckpointConfig(\n name=\"my_nested_checkpoint\",\n config_version=1,\n run_name_template=\"%Y-%M-foo-bar-template-test-template-2\",\n expectation_suite_name=\"users.delivery\",\n action_list=[\n {\n \"name\": \"store_validation_result\",\n \"action\": {\n \"class_name\": \"StoreValidationResultAction\",\n },\n },\n {\n \"name\": \"store_evaluation_params\",\n \"action\": {\n \"class_name\": \"MyCustomStoreEvaluationParametersActionTemplate2\",\n },\n },\n {\n \"name\": \"update_data_docs\",\n \"action\": {\n \"class_name\": \"UpdateDataDocsAction\",\n },\n },\n {\n \"name\": \"new_action_from_template_2\",\n \"action\": {\"class_name\": \"Template2SpecialAction\"},\n },\n ],\n evaluation_parameters={\n \"environment\": \"my_ge_environment\",\n \"tolerance\": 1.0e-2,\n \"aux_param_0\": \"1\",\n \"aux_param_1\": \"1 + 1\",\n \"template_1_key\": 456,\n },\n runtime_configuration={\n \"result_format\": \"BASIC\",\n \"partial_unexpected_count\": 20,\n \"template_1_key\": 123,\n },\n validations=[\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource_template_1\",\n \"data_connector_name\": \"my_special_data_connector_template_1\",\n \"data_asset_name\": \"users_from_template_1\",\n \"partition_request\": {\"partition_index\": -999},\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_special_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -1},\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -2},\n }\n },\n ],\n )\n\n substituted_config_template_only = nested_checkpoint.get_substituted_config()\n assert (\n substituted_config_template_only.to_json_dict()\n == expected_nested_checkpoint_config_template_only.to_json_dict()\n )\n # make sure operation is idempotent\n nested_checkpoint.get_substituted_config()\n assert (\n substituted_config_template_only.to_json_dict()\n == expected_nested_checkpoint_config_template_only.to_json_dict()\n )\n\n # runtime kwargs with new checkpoint template name passed at runtime\n expected_nested_checkpoint_config_template_and_runtime_template_name = (\n CheckpointConfig(\n name=\"my_nested_checkpoint\",\n config_version=1,\n run_name_template=\"runtime_run_template\",\n expectation_suite_name=\"runtime_suite_name\",\n action_list=[\n {\n \"name\": \"store_validation_result\",\n \"action\": {\n \"class_name\": \"StoreValidationResultAction\",\n },\n },\n {\n \"name\": \"store_evaluation_params\",\n \"action\": {\n \"class_name\": \"MyCustomRuntimeStoreEvaluationParametersAction\",\n },\n },\n {\n \"name\": \"new_action_from_template_2\",\n \"action\": {\"class_name\": \"Template2SpecialAction\"},\n },\n {\n \"name\": \"new_action_from_template_3\",\n \"action\": {\"class_name\": \"Template3SpecialAction\"},\n },\n {\n \"name\": \"update_data_docs_deluxe_runtime\",\n \"action\": {\n \"class_name\": \"UpdateDataDocsAction\",\n },\n },\n ],\n evaluation_parameters={\n \"environment\": \"runtime-my_ge_environment\",\n \"tolerance\": 1.0e-2,\n \"aux_param_0\": \"runtime-1\",\n \"aux_param_1\": \"1 + 1\",\n \"template_1_key\": 456,\n \"template_3_key\": 123,\n \"new_runtime_eval_param\": \"bloopy!\",\n },\n runtime_configuration={\n \"result_format\": \"BASIC\",\n \"partial_unexpected_count\": 999,\n \"template_1_key\": 123,\n \"template_3_key\": \"bloopy!\",\n \"new_runtime_config_key\": \"bleepy!\",\n },\n validations=[\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource_template_1\",\n \"data_connector_name\": \"my_special_data_connector_template_1\",\n \"data_asset_name\": \"users_from_template_1\",\n \"partition_request\": {\"partition_index\": -999},\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_special_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -1},\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -2},\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector_2_runtime\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -3},\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector_3_runtime\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -4},\n }\n },\n ],\n )\n )\n\n substituted_config_template_and_runtime_kwargs = nested_checkpoint.get_substituted_config(\n runtime_kwargs={\n \"expectation_suite_name\": \"runtime_suite_name\",\n \"template_name\": \"my_nested_checkpoint_template_3\",\n \"validations\": [\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector_2_runtime\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -3},\n }\n },\n {\n \"batch_request\": {\n \"datasource_name\": \"my_datasource\",\n \"data_connector_name\": \"my_other_data_connector_3_runtime\",\n \"data_asset_name\": \"users\",\n \"partition_request\": {\"partition_index\": -4},\n }\n },\n ],\n \"run_name_template\": \"runtime_run_template\",\n \"action_list\": [\n {\n \"name\": \"store_validation_result\",\n \"action\": {\n \"class_name\": \"StoreValidationResultAction\",\n },\n },\n {\n \"name\": \"store_evaluation_params\",\n \"action\": {\n \"class_name\": \"MyCustomRuntimeStoreEvaluationParametersAction\",\n },\n },\n {\n \"name\": \"update_data_docs\",\n \"action\": None,\n },\n {\n \"name\": \"update_data_docs_deluxe_runtime\",\n \"action\": {\n \"class_name\": \"UpdateDataDocsAction\",\n },\n },\n ],\n \"evaluation_parameters\": {\n \"environment\": \"runtime-$GE_ENVIRONMENT\",\n \"tolerance\": 1.0e-2,\n \"aux_param_0\": \"runtime-$MY_PARAM\",\n \"aux_param_1\": \"1 + $MY_PARAM\",\n \"new_runtime_eval_param\": \"bloopy!\",\n },\n \"runtime_configuration\": {\n \"result_format\": \"BASIC\",\n \"partial_unexpected_count\": 999,\n \"new_runtime_config_key\": \"bleepy!\",\n },\n }\n )\n assert (\n substituted_config_template_and_runtime_kwargs.to_json_dict()\n == expected_nested_checkpoint_config_template_and_runtime_template_name.to_json_dict()\n )\n\n monkeypatch.delenv(\"GE_ENVIRONMENT\")\n monkeypatch.delenv(\"VAR\")\n monkeypatch.delenv(\"MY_PARAM\")\n monkeypatch.delenv(\"OLD_PARAM\")\n"
]
| [
[
"pandas.DataFrame"
]
]
|
future-daydayup/XLearning | [
"a4fa2a8c47d13fd86f1e39bd23c1a43ea5d4082c"
]
| [
"examples/tensorflow/dataDeal.py"
]
| [
"import numpy as np\nimport os\n\nclass trainData:\n def __init__(self, fileStr, batch_size):\n self.fileStr = os.listdir(fileStr)\n self.batch_size = batch_size\n self.batch = []\n self.cache = []\n self.count_batch = 0\n self.flag = 0\n self.inc = -1\n self.iter_num = 0\n\n for s in self.fileStr:\n f = open(fileStr+\"/\"+s, \"r\")\n for line in f:\n iter = (line.split(\" \")[0], (np.asarray(line.split(\" \")[1].split(\",\"), dtype=np.float32)))\n if self.iter_num < self.batch_size:\n self.batch.append(iter)\n self.iter_num += 1\n else:\n self.cache.append(self.batch)\n self.count_batch += 1\n self.batch = [iter]\n self.iter_num = 1 \n \n if self.batch:\n supplement_batch = self.cache[0]\n supplement_count = self.batch_size-len(self.batch)\n self.batch.extend(supplement_batch[:supplement_count])\n self.cache.append(self.batch)\n self.count_batch += 1\n\n def nextBatch(self):\n if(self.inc + 1 == self.count_batch):\n self.inc = -1\n self.inc += 1\n return self.cache[self.inc]\n \n def batchCount(self):\n return self.count_batch\n\ndef oneHot(sLabel):\n arr = np.zeros(2,np.float32)\n arr[int(''.join(sLabel))] = 1.0\n return arr\n"
]
| [
[
"numpy.zeros"
]
]
|
sankhaMukherjee/ConvTD | [
"bbe03db50932ca33ae5a0d0e3f1b8d818344a06a"
]
| [
"dataGeneration/multiExp.py"
]
| [
"import numpy as np\nfrom scipy.integrate import odeint\n\ndef dy(y, t):\n\n p = {}\n p['k1'] = 0.005\n p['k2'] = 0.05\n p['k3'] = 0.003\n p['d'] = 0.01\n p['km'] = 2.0\n\n dydt = np.zeros(y.shape)\n\n dydt[0] = - p['k1']*y[0]\n dydt[1] = ( p['k1']*y[0] - p['k2']*y[1] + p['k3']*y[2] \n - p['d']*y[1]/(p['km']+y[1]) )\n dydt[2] = p['k2']*y[1] - p['k3']*y[2]\n\n return dydt\n\ndef yFunc(t, y0):\n yHat = odeint(dy, [y0, 0, 0], t)\n return yHat\n\ndef generateDataOne(y0, t, in_width = 5):\n\n data = yFunc(t, y0)\n \n rs, cs = data.shape\n c = 0\n \n allXc = []\n allyc = []\n for c in range(cs):\n Xc = []\n yc = []\n tempX = np.zeros(in_width)\n for i, v in enumerate(data[:-1, c]):\n tempX[:-1] = tempX[1:]\n tempX[-1] = v\n Xc.append( tempX.copy() )\n yc.append( data[i+1, c] )\n\n Xc = np.array(Xc)\n yc = np.array(yc)\n\n Xc = Xc[in_width-1:]\n yc = yc[in_width-1:]\n\n # time/batch, convolution width, channels\n Xc = Xc.reshape( -1, in_width, 1 )\n yc = yc.reshape( -1, 1 )\n\n allXc.append( Xc )\n allyc.append( yc )\n\n \n allXc = np.concatenate( allXc, 2 )\n allyc = np.concatenate( allyc, 1 )\n \n return allXc, allyc\n\ndef generateData(t, in_width = 5, nPatients=10):\n\n X, y = [], []\n for y0 in np.random.uniform(0.5, 1.5, nPatients):\n allX, ally = generateDataOne(y0, t, in_width)\n X.append( allX.copy() )\n y.append( ally.copy() )\n\n X = np.concatenate(X, 0)\n y = np.concatenate(y, 0)\n\n return X, y\n\ndef main():\n\n in_width = 5\n\n t = np.linspace(0, 10, 17)\n X, y = generateData(t, in_width)\n\n print(X.shape)\n print(y.shape)\n \n return\n\nif __name__ == '__main__':\n main()"
]
| [
[
"numpy.concatenate",
"scipy.integrate.odeint",
"numpy.array",
"numpy.zeros",
"numpy.random.uniform",
"numpy.linspace"
]
]
|
eivan/MegaDepth | [
"d2671bae67f3c45f607da1e4a80a483692f0e8d9"
]
| [
"predict_depth.py"
]
| [
"import torch\nfrom pathlib import Path\nimport sys\nimport math\nfrom torch.autograd import Variable\nimport numpy as np\nfrom options.train_options import TrainOptions\n\nfrom data.data_loader import CreateDataLoader\nfrom models.models import create_model\nfrom skimage import io\nfrom skimage.transform import resize\n\ndef predict_depth(img_path_in):\n \n opt = TrainOptions()\n opt.parser.add_argument('-f', type=str, default='dummy', help='dummy') # needed coz' jupyter\n opt = opt.parse()\n model = create_model(opt)\n \n model.switch_to_eval()\n\n img = np.float32(io.imread(img_path_in))/255.0\n height, width, depth = img.shape\n \n input_width = 512# * np.clip(np.floor(width / 512), 1, 2);\n input_height = 384# * np.clip(np.floor(height / 384), 1, 2);\n \n img = resize(img, (input_height, input_width), order = 1)\n input_img = torch.from_numpy( np.transpose(img, (2,0,1)) ).contiguous().float()\n input_img = input_img.unsqueeze(0)\n\n if torch.cuda.is_available():\n input_images = Variable(input_img.cuda())\n else:\n input_images = Variable(input_img.cpu())\n pred_log_depth = model.netG.forward(input_images) \n pred_log_depth = torch.squeeze(pred_log_depth)\n\n pred_depth = torch.exp(pred_log_depth)\n\n # visualize prediction using inverse depth, so that we don't need sky segmentation (if you want to use RGB map for visualization, \\\n # you have to run semantic segmentation to mask the sky first since the depth of sky is random from CNN)\n pred_inv_depth = 1/pred_depth\n pred_inv_depth = pred_inv_depth.data.cpu().numpy()\n # you might also use percentile for better visualization\n pred_inv_depth = pred_inv_depth/np.amax(pred_inv_depth)\n\n pred_inv_depth = resize(pred_inv_depth, (height, width), order = 1)\n \n return pred_inv_depth\n\n"
]
| [
[
"torch.squeeze",
"torch.cuda.is_available",
"numpy.transpose",
"numpy.amax",
"torch.exp"
]
]
|
Gilbert-Zhu/Stochastic-Simulation | [
"a7e5ea23ae21db61075e35fe2dc42d51abbf8caf"
]
| [
"HW1/HW1Q3.py"
]
| [
"import numpy as np\nnp.random.seed(1) # fix random number seed\nXlist = [] # list to keep samples of # customers\nArealist = [] # list to keep samples of average # customers\n\nfor reps in range(0,30):\n clock = 0 # initialize clock\n X = 0 # initialize X\n T = 100000 # Total time unit\n NextArrival = np.random.exponential(scale=1/0.8, size=1)\n NextDeparture = float('inf')\n Xlast = X\n Tlast = clock\n Area = 0\n while clock <= T: # simulation time\n clock = np.min([NextArrival,NextDeparture])\n \n if NextArrival < NextDeparture: # A customer arrives\n if X == 0: \n NextDeparture = clock + np.random.exponential(scale=1.0)\n X += 1\n NextArrival = clock + np.random.exponential(scale=1/0.8) \n elif NextArrival == NextDeparture: \n # Arrival and departure at the same time\n NextArrival = clock + np.random.exponential(scale=1/0.8)\n NextDeparture = clock + np.random.exponential(scale=1.0) \n else: # A customer leaves\n if X >= 1:\n X -= 1\n NextDeparture = clock + np.random.exponential(scale=1.0)\n else: # empty queue\n NextDeparture = float('inf')\n # update the area udner the sample path\n Area = Area + Xlast * (clock - Tlast)\n # record the current time and state\n Xlast = X\n Tlast = clock\n # add samples to the lists\n Arealist.append(Area/float(clock))\n# print sample averages\nprint(np.mean(Arealist))\n\n \n \n \n \n \n \n \n \n "
]
| [
[
"numpy.random.seed",
"numpy.min",
"numpy.random.exponential",
"numpy.mean"
]
]
|
huseinzol05/malaya-boilerplate | [
"c962cbd5332e9f5c0418edfa54e9e34022cb647c"
]
| [
"malaya_boilerplate/frozen_graph.py"
]
| [
"import os\n\ntry:\n os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'\nexcept BaseException:\n pass\n\nimport logging\nimport numpy as np\nimport tensorflow as tf\nimport struct\nfrom operator import itemgetter\nfrom tensorflow.core.framework import types_pb2, graph_pb2, attr_value_pb2\nfrom .utils import available_gpu, _get_home\n\nlogger = logging.getLogger('frozen_graph')\nUNKNOWN = b'\\xff\\xff\\xff\\xff'\n\n\ndef check_tf_version():\n version = tf.__version__\n return int(version.split('.')[0])\n\n\nif check_tf_version() > 1:\n try:\n from tensorflow_addons.utils.resource_loader import LazySO\n\n _beam_search_so = LazySO('custom_ops/seq2seq/_beam_search_ops.so')\n gather_tree = _beam_search_so.ops.addons_gather_tree\n except BaseException:\n import warnings\n\n warnings.warn(\n 'Cannot import beam_search_ops from Tensorflow Addons, `deep_model` for stemmer will not available to use, make sure Tensorflow Addons version >= 0.12.0'\n )\n\n\nelse:\n try:\n from tensorflow.contrib.seq2seq.python.ops import beam_search_ops\n except BaseException:\n import warnings\n\n warnings.warn(\n 'Cannot import beam_search_ops from Tensorflow 1, `deep_model` for stemmer will not available to use, make sure Tensorflow 1 version >= 1.15'\n )\n\n\ndef nodes_session(graph, inputs, outputs, extra=None, attention=None):\n input_nodes = {i: graph.get_tensor_by_name(f'import/{i}:0') for i in inputs}\n output_nodes = {\n o: graph.get_tensor_by_name(f'import/{o}:0') for o in outputs\n }\n if extra:\n extra = {k: graph.get_tensor_by_name(v) for k, v in extra.items()}\n output_nodes = {**output_nodes, **extra}\n if attention:\n output_nodes = {**output_nodes, **attention}\n return input_nodes, output_nodes\n\n\ndef generate_session(graph, **kwargs):\n \"\"\"\n Load session for a Tensorflow graph.\n\n Parameters\n ----------\n graph: tensorflow.Graph\n gpu_limit: float, optional (default = 0.999)\n limit percentage to use a gpu memory.\n\n Returns\n -------\n result : tensorflow.Session\n \"\"\"\n config = tf.compat.v1.ConfigProto()\n if len(available_gpu()):\n config.allow_soft_placement = True\n try:\n gpu_limit = float(kwargs.get('gpu_limit', 0.999))\n logger.debug(f'gpu_limit: {gpu_limit}')\n except BaseException:\n raise ValueError('gpu_limit must be a float')\n if not 0 < gpu_limit < 1:\n raise ValueError('gpu_limit must 0 < gpu_limit < 1')\n\n config.gpu_options.per_process_gpu_memory_fraction = gpu_limit\n config.gpu_options.allow_growth = True\n\n sess = tf.compat.v1.Session(config=config, graph=graph)\n return sess\n\n\ndef get_device(**kwargs):\n device = kwargs.get('device', 'CPU:0')\n splitted = device.split(':')\n if len(splitted) != 2:\n raise ValueError('`device` must set as `device:{no}`.')\n if not splitted[1].isdigit():\n raise ValueError('`no` from `device:{no}` is not a digit')\n no = int(splitted[1])\n if no < 0:\n raise ValueError('`no` from `device:{no}` must >= 0')\n device_type = splitted[0].upper()\n if device_type not in {'XLA_CPU', 'XLA_CPU_JIT', 'CPU', 'GPU', 'XLA_GPU'}:\n raise ValueError(\n \"`device` from `device:{no}` must one of ['XLA_CPU', 'XLA_CPU_JIT', 'CPU', 'GPU', 'XLA_GPU']\"\n )\n auto_gpu = kwargs.get('auto_gpu', True)\n gpus = available_gpu()\n\n if auto_gpu and len(gpus) and 'GPU' not in device_type:\n gpu = sorted(gpus, key=itemgetter(1), reverse=True)[0]\n device = gpu[0]\n\n if 'GPU' in device:\n if not len(gpus):\n raise ValueError(f'gpu is not available but device is {device}')\n\n if not 0 <= no < len(gpus):\n raise ValueError(f'gpu must 0 <= gpu < {len(gpus)}')\n\n return f'/device:{device}'\n\n\ndef convert_graph_precision(source_graph_def, target_type='FP16'):\n def rewrite_batch_norm_node_v2(node, graph_def, target_type='FP16'):\n \"\"\"\n Rewrite FusedBatchNorm with FusedBatchNormV2 for reserve_space_1 and reserve_space_2 in FusedBatchNorm require float32 for\n gradient calculation (See here: https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/fused-batch-norm)\n \"\"\"\n if target_type == 'BFLOAT16':\n dtype = types_pb2.DT_BFLOAT16\n elif target_type == 'FP16':\n dtype = types_pb2.DT_HALF\n elif target_type == 'FP64':\n dtype = types_pb2.DT_DOUBLE\n else:\n dtype = types_pb2.DT_FLOAT\n new_node = graph_def.node.add()\n new_node.op = 'FusedBatchNormV2'\n new_node.name = node.name\n new_node.input.extend(node.input)\n new_node.attr['U'].CopyFrom(\n attr_value_pb2.AttrValue(type=types_pb2.DT_FLOAT)\n )\n for attr in list(node.attr.keys()):\n if attr == 'T':\n node.attr[attr].type = dtype\n new_node.attr[attr].CopyFrom(node.attr[attr])\n\n if target_type == 'BFLOAT16':\n dtype = types_pb2.DT_BFLOAT16\n elif target_type == 'FP16':\n dtype = types_pb2.DT_HALF\n elif target_type == 'FP64':\n dtype = types_pb2.DT_DOUBLE\n else:\n dtype = types_pb2.DT_FLOAT\n\n for node in source_graph_def.node:\n if node.op == 'FusedBatchNorm':\n rewrite_batch_norm_node_v2(\n node, target_graph_def, target_type=target_type\n )\n continue\n if ('BatchNorm' in node.name) or ('batch_normalization' in node.name):\n continue\n attrs = list(node.attr.keys())\n if node.op == 'convert_gradient_to_tensor_HBc3xYw22Mw':\n node.op = 'Identity'\n node.attr.setdefault('T')\n node.attr['T'].type = dtype\n del node.attr['_disable_call_shape_inference']\n\n for attr in attrs:\n if node.attr[attr].type == types_pb2.DT_FLOAT:\n node.attr[attr].type = dtype\n if attr == 'value':\n tensor = node.attr[attr].tensor\n if tensor.dtype == types_pb2.DT_FLOAT:\n if tensor.float_val:\n float_val = tf.make_ndarray(node.attr[attr].tensor)\n node.attr[attr].tensor.CopyFrom(\n tf.compat.v1.make_tensor_proto(\n float_val, dtype=dtype\n )\n )\n continue\n if tensor.tensor_content:\n tensor_shape = [x.size for x in tensor.tensor_shape.dim]\n tensor_weights = tf.make_ndarray(tensor)\n tensor_weights = np.reshape(\n tensor_weights, tensor_shape\n )\n tensor_proto = tf.compat.v1.make_tensor_proto(\n tensor_weights, dtype=dtype\n )\n node.attr[attr].tensor.CopyFrom(tensor_proto)\n continue\n\n return source_graph_def\n\n\ndef load_graph(package, frozen_graph_filename, **kwargs):\n \"\"\"\n Load frozen graph from a checkpoint.\n\n Parameters\n ----------\n frozen_graph_filename: str\n use_tensorrt: bool, optional (default=False)\n Use TensorRT.\n tensorrt_precision_mode: str, optional (default='FP32')\n TensorRT precision mode, only supported one of ['FP32', 'FP16', 'INT8'].\n if device is not a gpu, `load_graph` will throw an error.\n precision_mode: str, optional (default='FP32')\n change precision frozen graph, only supported one of ['BFLOAT16', 'FP16', 'FP32', 'FP64'].\n auto_gpu: bool, optional (default=True)\n if installed gpu version, will automatically allocate a model to a gpu with the most empty memory.\n t5_graph: bool, optional (default=False)\n if True, will replace static shape to dynamic shape for first element in batch.\n This should do for T5 models only.\n glowtts_graph: bool, optional (default=False)\n if True, will have some extra condition for glowTTS models.\n glowtts_multispeaker_graph: bool, optional (default=False)\n if True, will have some extra condition for glowTTS Multispeaker models.\n device: str, optional (default='CPU:0')\n device to use for specific model, read more at https://www.tensorflow.org/guide/gpu\n\n Returns\n -------\n result : tensorflow.Graph\n \"\"\"\n\n use_tensorrt = kwargs.get('use_tensorrt', False)\n logger.debug(f'use_tensorrt: {use_tensorrt}')\n tensorrt_precision_mode = kwargs.get(\n 'tensorrt_precision_mode', 'FP32'\n ).upper()\n logger.debug(f'tensorrt_precision_mode: {tensorrt_precision_mode}')\n precision_mode = kwargs.get('precision_mode', 'FP32').upper()\n logger.debug(f'precision_mode: {precision_mode}')\n\n t5_graph = kwargs.get('t5_graph', False)\n logger.debug(f't5_graph: {t5_graph}')\n\n glowtts_graph = kwargs.get('glowtts_graph', False)\n logger.debug(f'glowtts_graph: {glowtts_graph}')\n\n glowtts_multispeaker_graph = kwargs.get('glowtts_multispeaker_graph', False)\n logger.debug(f'glowtts_multispeaker_graph: {glowtts_multispeaker_graph}')\n device = get_device(**kwargs)\n\n if tensorrt_precision_mode not in {'FP32', 'FP16', 'INT8'}:\n raise ValueError(\n \"`tensorrt_precision_mode` only support one of ['FP32', 'FP16', 'INT8']\"\n )\n\n if precision_mode not in {'BFLOAT16', 'FP16', 'FP32', 'FP64'}:\n raise ValueError(\n \"`precision_mode` only support one of ['BFLOAT16', 'FP16', 'FP32', 'FP64']\"\n )\n\n if 'GPU' not in device and use_tensorrt:\n raise ValueError(\n 'not able to detect any gpu to use TensorRT, reinstall gpu version and retry.'\n )\n\n if precision_mode != 'FP32' and use_tensorrt:\n raise ValueError(\n '`precision_mode` must `FP32` if use TensorRT, set `tensorrt_precision_mode` instead.'\n )\n\n if package is None:\n path = frozen_graph_filename\n else:\n home, _ = _get_home(package=package)\n path = frozen_graph_filename.replace(home, '')\n path = os.path.sep.join(os.path.normpath(path).split(os.path.sep)[1:-1])\n\n logger.info(f'running {path} using device {device}')\n\n with tf.io.gfile.GFile(frozen_graph_filename, 'rb') as f:\n try:\n graph_def = tf.compat.v1.GraphDef()\n graph_def.ParseFromString(f.read())\n except Exception as e:\n if package is None:\n exception_text = f'{e}, {path} corrupted, clear the cache and try again.'\n else:\n exception_text = f\"{e}, file corrupted due to some reasons, please run `{package.replace('-', '_')}.utils.delete_cache('{path}')` and try again\"\n raise Exception(exception_text)\n\n # https://github.com/onnx/tensorflow-onnx/issues/77#issuecomment-445066091\n # to fix import T5\n for node in graph_def.node:\n if node.op == 'RefSwitch':\n node.op = 'Switch'\n for index in range(len(node.input)):\n if 'moving_' in node.input[index]:\n node.input[index] = node.input[index] + '/read'\n elif node.op == 'AssignSub':\n node.op = 'Sub'\n if 'use_locking' in node.attr:\n del node.attr['use_locking']\n elif node.op == 'AssignAdd':\n node.op = 'Add'\n if 'use_locking' in node.attr:\n del node.attr['use_locking']\n elif node.op in ['Assign', 'AssignVariableOp']:\n if node.op == 'AssignVariableOp':\n node.attr.setdefault('T')\n node.attr['T'].type = node.attr['dtype'].type\n del node.attr['dtype']\n node.op = 'Identity'\n if 'use_locking' in node.attr:\n del node.attr['use_locking']\n if 'validate_shape' in node.attr:\n del node.attr['validate_shape']\n if len(node.input) == 2:\n node.input[0] = node.input[1]\n del node.input[1]\n elif node.op == 'GatherTree':\n if check_tf_version() > 1:\n node.op = 'Addons>GatherTree'\n elif node.op == 'convert_gradient_to_tensor_HBc3xYw22Mw':\n if use_tensorrt:\n node.op = 'Identity'\n node.attr.setdefault('T')\n del node.attr['_disable_call_shape_inference']\n elif (node.op == 'Switch'\n and 'wave_net_block' in node.name\n and 'AssignVariableOp_' in node.name\n and glowtts_graph):\n node.attr['T'].type = 1\n elif (node.op == 'Switch'\n and 'wave_net' in node.name\n and '/weight_normalization_' in node.name\n and 'AssignVariableOp_' in node.name\n and glowtts_multispeaker_graph):\n node.attr['T'].type = 1\n\n if ('Reshape/shape' in node.name or 'Reshape_1/shape' in node.name) and t5_graph:\n b = node.attr['value'].tensor.tensor_content\n arr_int = [int.from_bytes(b[i:i + 4], 'little') for i in range(0, len(b), 4)]\n if len(arr_int):\n arr_byte = [UNKNOWN] + [struct.pack('<i', i) for i in arr_int[1:]]\n arr_byte = b''.join(arr_byte)\n node.attr['value'].tensor.tensor_content = arr_byte\n\n if len(node.attr['value'].tensor.int_val):\n node.attr['value'].tensor.int_val[0] = -1\n\n if use_tensorrt:\n logger.info(\n f'Converting {path} to TensorRT with precision {tensorrt_precision_mode}.'\n )\n try:\n from tensorflow.python.compiler.tensorrt import trt_convert as trt\n\n converter = trt.TrtGraphConverter(\n input_graph_def=graph_def,\n precision_mode=tensorrt_precision_mode,\n )\n graph_def = converter.convert()\n except Exception as e:\n raise Exception(\n f'{e}, not able convert {path} to TensorRT with precision {tensorrt_precision_mode}.'\n )\n\n if precision_mode != 'FP32':\n logger.info(f'Converting {path} to {precision_mode}.')\n try:\n if precision_mode == 'BFLOAT16':\n # some weird error related to range bfloat16\n r = tf.range(0, 10, dtype=tf.bfloat16)\n graph_def = convert_graph_precision(\n graph_def, target_type=precision_mode\n )\n except Exception as e:\n raise Exception(\n f'{e}, not able convert {path} to {precision_mode}.'\n )\n\n with tf.Graph().as_default() as graph:\n with tf.device(device):\n tf.import_graph_def(graph_def)\n return graph\n"
]
| [
[
"tensorflow.io.gfile.GFile",
"tensorflow.range",
"tensorflow.compat.v1.make_tensor_proto",
"numpy.reshape",
"tensorflow.compat.v1.ConfigProto",
"tensorflow.Graph",
"tensorflow.import_graph_def",
"tensorflow.compat.v1.GraphDef",
"tensorflow.compat.v1.Session",
"tensorflow.python.compiler.tensorrt.trt_convert.TrtGraphConverter",
"tensorflow.device",
"tensorflow.core.framework.attr_value_pb2.AttrValue",
"tensorflow.make_ndarray"
]
]
|
DSIP-UPatras/ICASSP2019_TCN | [
"cd28909ccf3696b835446cbec2f15eb60610a2af"
]
| [
"code/script_experiment.py"
]
| [
"\nimport numpy as np\nimport tensorflow as tf\nimport random\n\n# The below is necessary in Python 3.2.3 onwards to\n# have reproducible behavior for certain hash-based operations.\n# See these references for further details:\n# https://docs.python.org/3.4/using/cmdline.html#envvar-PYTHONHASHSEED\n# https://github.com/keras-team/keras/issues/2280#issuecomment-306959926\nimport os\nos.environ['PYTHONHASHSEED'] = '0'\n\n# The below is necessary for starting Numpy generated random numbers\n# in a well-defined initial state.\nnp.random.seed(1234)\n\n# The below is necessary for starting core Python generated random numbers\n# in a well-defined state.\nrandom.seed(12345)\n\n# Force TensorFlow to use single thread.\n# Multiple threads are a potential source of\n# non-reproducible results.\n# For further details, see:\n# https://stackoverflow.com/questions/42022950/which-seeds-have-to-be-set-where-to-realize-100-reproducibility-of-training-res\nsession_conf = tf.ConfigProto(\n intra_op_parallelism_threads=0,\n inter_op_parallelism_threads=0\n)\nsession_conf.gpu_options.allow_growth = True\nfrom keras import backend as K\n\n# The below tf.set_random_seed() will make random number generation\n# in the TensorFlow backend have a well-defined initial state.\n# For further details, see:\n# https://www.tensorflow.org/api_docs/python/tf/set_random_seed\ntf.set_random_seed(1234)\n\nsess = tf.Session(graph=tf.get_default_graph(), config=session_conf)\nK.set_session(sess)\n\n##############################################################################\nimport sys\nimport preprocessing\nimport json\nimport scipy\nimport keras\nimport tensorflow as tf\nfrom keras import optimizers, initializers, regularizers, constraints\nfrom utils import *\nfrom generator import DataGenerator\nfrom models import getNetwork\nfrom sklearn import metrics\n\nprint('Keras:', keras.__version__)\nprint('Tensorflow:', tf.__version__)\n\n# 1. Logging\nif len(sys.argv) == 4:\n CONFIG_FILE = str(sys.argv[1])\n SUBJECT = int(sys.argv[2])\n TIMESTAMP = int(sys.argv[3])\nelse:\n print('Expected different number of arguments. {} were given'.format(len(sys.argv) - 1))\n sys.exit()\n\nwith open(CONFIG_FILE) as json_file:\n config_params = json.load(json_file)\n\nLOGGING_FILE_PREFIX = config_params['logging']['log_file'] + '_' + str(TIMESTAMP)\nif config_params['logging']['enable']:\n LOGGING_FILE = '../results/L_' + LOGGING_FILE_PREFIX + '.log'\n LOGGING_TENSORBOARD_FILE = '../results/tblogs/L_' + LOGGING_FILE_PREFIX\n\nif config_params['model']['save']:\n MODEL_SAVE_FILE = '../results/models/O1_' + LOGGING_FILE_PREFIX + '_{}.json'\n MODEL_WEIGHTS_SAVE_FILE = '../results/models/O2_' + LOGGING_FILE_PREFIX + '_{}.h5'\n\nMETRICS_SAVE_FILE = '../results/metrics/O3_' + LOGGING_FILE_PREFIX + '_{}.mat'\n\n\nif not os.path.exists(os.path.dirname(METRICS_SAVE_FILE)):\n try:\n os.makedirs(os.path.dirname(METRICS_SAVE_FILE))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\nif not os.path.exists(os.path.dirname(MODEL_SAVE_FILE)):\n try:\n os.makedirs(os.path.dirname(MODEL_SAVE_FILE))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n \nif not os.path.exists(os.path.dirname(LOGGING_TENSORBOARD_FILE)):\n try:\n os.makedirs(os.path.dirname(LOGGING_TENSORBOARD_FILE))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n \n\n\nprint('Logging file: {}'.format(LOGGING_FILE))\nprint('Tensorboard file: {}'.format(LOGGING_TENSORBOARD_FILE))\nprint('Model JSON file: {}'.format(MODEL_SAVE_FILE))\nprint('Model H5 file: {}'.format(MODEL_WEIGHTS_SAVE_FILE))\nprint('Metrics file: {}'.format(METRICS_SAVE_FILE))\n\n# 2. Config params generator\nPARAMS_TRAIN_GENERATOR = DEFAULT_GENERATOR_PARAMS.copy()\nparams_gen = config_params['dataset'].get('train_generator', {}).copy()\nfor key in params_gen.keys():\n PARAMS_TRAIN_GENERATOR[key] = params_gen[key]\n\nPARAMS_VALID_GENERATOR = DEFAULT_GENERATOR_PARAMS.copy()\nparams_gen = config_params['dataset'].get('valid_generator', {}).copy()\nfor key in params_gen.keys():\n PARAMS_VALID_GENERATOR[key] = params_gen[key]\n\n# 3. Initialization\nINPUT_DIRECTORY = '../dataset/Ninapro-DB1-Proc'\nPARAMS_TRAIN_GENERATOR['preprocess_function_1'] = [preprocessing.lpf]\nPARAMS_TRAIN_GENERATOR['preprocess_function_1_extra'] = [{'fs': 100}]\nPARAMS_TRAIN_GENERATOR['data_type'] = 'rms'\nPARAMS_TRAIN_GENERATOR['classes'] = [i for i in range(53)]\n\nPARAMS_VALID_GENERATOR['preprocess_function_1'] = [preprocessing.lpf]\nPARAMS_VALID_GENERATOR['preprocess_function_1_extra'] = [{'fs': 100}]\nPARAMS_VALID_GENERATOR['data_type'] = 'rms'\nPARAMS_VALID_GENERATOR['classes'] = [i for i in range(53)]\n\nSUBJECTS = config_params['dataset'].get('subjects', [i for i in range(1, 28)])\nif np.min(SUBJECTS) <= 0 or np.max(SUBJECTS) >= 28:\n raise AssertionError('Subject IDs should be between 1 and 27 inclusive for DB1. Were given {}\\n'.format(SUBJECTS))\n\nPARAMS_TRAIN_GENERATOR.pop('input_directory', '')\nPARAMS_VALID_GENERATOR.pop('input_directory', '')\n\nMODEL = getNetwork(config_params['model']['name'])\n\nmean_train, mean_test, mean_test_3, mean_test_5 = [], [], [], []\nmean_cm = []\nmean_train_loss, mean_test_loss = [], []\n\nif config_params['logging']['enable']:\n if os.path.isfile(LOGGING_FILE) == False:\n with open(LOGGING_FILE, 'w') as f:\n f.write(\n 'TIMESTAMP: {}\\n'\n 'KERAS: {}\\n'\n 'TENSORFLOW: {}\\n'\n 'DATASET: {}\\n'\n 'TRAIN_GENERATOR: {}\\n'\n 'VALID_GENERATOR: {}\\n'\n 'MODEL: {}\\n'\n 'MODEL_PARAMS: {}\\n'\n 'TRAIN_PARAMS: {}\\n'.format(\n TIMESTAMP,\n keras.__version__, tf.__version__,\n config_params['dataset']['name'], PARAMS_TRAIN_GENERATOR,\n PARAMS_VALID_GENERATOR,\n config_params['model']['name'], config_params['model']['extra'],\n config_params['training']\n )\n )\n f.write(\n 'SUBJECT,TRAIN_SHAPE,TEST_SHAPE,TRAIN_LOSS,TRAIN_ACC,TEST_LOSS,TEST_ACC,TEST_TOP_3_ACC,TEST_TOP_5_ACC\\n')\n\nprint('Subject: {}'.format(SUBJECT))\ninput_dir = '{}/subject-{:02d}'.format(INPUT_DIRECTORY, SUBJECT)\n\ntrain_generator = DataGenerator(input_directory=input_dir, **PARAMS_TRAIN_GENERATOR)\nvalid_generator = DataGenerator(input_directory=input_dir, **PARAMS_VALID_GENERATOR)\nX_test, Y_test, test_reps = valid_generator.get_data()\n\n# print('Train generator:')\n# print(train_generator)\n# print('Test generator:')\n# print(valid_generator)\n\nmodel = MODEL(\n input_shape=(None, 10),\n classes=train_generator.n_classes,\n **config_params['model']['extra'])\n#model.summary()\n\nif config_params['training']['optimizer'] == 'adam':\n optimizer = optimizers.Adam(lr=config_params['training']['l_rate'], epsilon=0.001)\nelif config_params['training']['optimizer'] == 'sgd':\n optimizer = optimizers.SGD(lr=config_params['training']['l_rate'], momentum=0.9)\n\nmodel.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy', top_3_accuracy, top_5_accuracy])\n\ntrain_callbacks = []\nif config_params['logging']['enable']:\n tensorboardCallback = MyTensorboard(log_dir=LOGGING_TENSORBOARD_FILE + \"/{}\".format(SUBJECT),\n batch_size=100,\n histogram_freq=10)\n train_callbacks.append(tensorboardCallback)\nlrScheduler = MyLRScheduler(**config_params['training']['l_rate_schedule'])\ntrain_callbacks.append(lrScheduler)\n\nhistory = model.fit_generator(train_generator, epochs=config_params['training']['epochs'],\n validation_data=(X_test,Y_test), callbacks=train_callbacks, verbose=2)\nY_pred = model.predict(X_test)\n\ny_pred = np.argmax(Y_pred, axis=1)\ny_test = np.argmax(Y_test, axis=1)\n\nif config_params['model']['save']:\n # serialize model to JSON\n model_json = model.to_json()\n with open(MODEL_SAVE_FILE.format(SUBJECT), \"w\") as json_file:\n json_file.write(model_json)\n # serialize weights to HDF5\n model.save_weights(MODEL_WEIGHTS_SAVE_FILE.format(SUBJECT))\n print(\"Saved model to disk\")\n\n\n# Confusion Matrix\n# C_{i, j} is equal to the number of observations known to be in group i but predicted to be in group j.\ncnf_matrix_frame = metrics.confusion_matrix(y_test, y_pred)\nif np.array(mean_cm).shape != cnf_matrix_frame.shape:\n mean_cm = cnf_matrix_frame\nelse:\n mean_cm += cnf_matrix_frame\n\nmean_train.append(history.history['acc'][-1])\nmean_test.append(history.history['val_acc'][-1])\nmean_train_loss.append(history.history['loss'][-1])\nmean_test_loss.append(history.history['val_loss'][-1])\nmean_test_3.append(history.history['val_top_3_accuracy'][-1])\nmean_test_5.append(history.history['val_top_5_accuracy'][-1])\n\nif config_params['logging']['enable']:\n with open(LOGGING_FILE, 'a') as f:\n f.write('{},{},{},{},{},{},{},{},{}\\n'.format(SUBJECT, train_generator.__len__() * PARAMS_TRAIN_GENERATOR['batch_size'], valid_generator.__len__(),\n mean_train_loss[-1], mean_train[-1], mean_test_loss[-1], mean_test[-1], mean_test_3[-1], mean_test_5[-1]))\n\n\nmetrics_dict = {\n 'mean_cm': mean_cm,\n 'mean_test': mean_test,\n 'mean_test_3': mean_test_3,\n 'mean_test_5': mean_test_5,\n 'mean_train': mean_train,\n 'mean_train_loss': mean_train_loss,\n 'mean_test_loss': mean_test_loss\n}\nscipy.io.savemat(METRICS_SAVE_FILE.format(SUBJECT), metrics_dict)\n"
]
| [
[
"tensorflow.set_random_seed",
"numpy.max",
"sklearn.metrics.confusion_matrix",
"numpy.array",
"tensorflow.get_default_graph",
"numpy.random.seed",
"numpy.min",
"tensorflow.ConfigProto",
"numpy.argmax"
]
]
|
leizhenyu-lzy/DrowsyDrivingDetect | [
"9416769c4ceb5c5775cb98e7ccb11faa0fd760dd"
]
| [
"KeyPointsDetect/ToolFunction.py"
]
| [
"# 1950083 自动化 刘智宇\nimport torch\nimport os\nimport cv2 as cv\nimport numpy as np\nimport pandas as pd\nfrom Consts import *\n\n\n\"\"\"\nname: count_files\nfunctional: count number of files in a directory(use:os.walk)\ninputs: root_dir\noutputs: number of files in the directory\n\"\"\"\ndef count_files(root_dir):\n num_files = 0\n for root, dirs, files in os.walk(root_dir):\n for file_name in files:\n # print(os.path.join(root, file_name))\n num_files = num_files + 1\n return num_files\n\n\n\"\"\"\nname: unify_img_coords_simple_annotation\nfunctional: unify the coords of the image(s)\ninputs: not_unify_coords : 简化过但是没有同一化的coords annotation\n img_dir : 图片路径。如果是单张图片,使用时也需要放入列表中\noutputs: unified coords\n\"\"\"\ndef unify_img_coords_annotation(not_unify_coords, img_paths):\n # print(separate_bar, \"进行坐标unify\", separate_bar)\n # 判断是单张图片还是多张图片(list)\n num_of_img = len(img_paths)\n if num_of_img == 1: # 如果是单张图片增加一个新维度,提高代码复用\n print(\"Single Image.\")\n not_unify_coords = not_unify_coords[np.newaxis, :]\n else:\n print(\"Multiple Images.\")\n print(\"共有 {} 张图片需要处理\".format(num_of_img))\n\n # 创建一个大小相同的矩阵\n unify_coords = not_unify_coords.copy()\n # print(unify_coords.dtype) # int32\n # unify同一化\n for img_idx in range(num_of_img):\n x_min = not_unify_coords[img_idx][x_min_rect_idx]; x_max = not_unify_coords[img_idx][x_max_rect_idx]\n y_min = not_unify_coords[img_idx][y_min_rect_idx]; y_max = not_unify_coords[img_idx][y_max_rect_idx]\n rect_x = x_max - x_min; rect_y = y_max - y_min\n for point_idx in range(left_eye_start, inner_lip_end * 2 + 2, 2):\n unify_coords[img_idx][point_idx] = (not_unify_coords[img_idx][point_idx]-x_min) * unify_gray_image_size[0] / rect_x\n for point_idx in range(left_eye_start + 1, inner_lip_end * 2 + 2, 2):\n unify_coords[img_idx][point_idx] = (not_unify_coords[img_idx][point_idx]-y_min) * unify_gray_image_size[1] / rect_y\n\n # 输出验证信息,返回结果\n # print(unify_coords, unify_coords.shape, unify_coords.dtype) # (7500, 76) int32\n # print(not_unify_coords, not_unify_coords.shape) # (7500, 76)\n # print(separate_bar, \"坐标unify完成\", separate_bar)\n return unify_coords\n\n\n\"\"\"\nname: show_key_points_and_rect_in_origin_img\nfunctional: use the origin image and unified coords to point the key points\ninputs: unify_coords : 一定是简化的坐标\n img_path : 图片路径\n imread_type : cv.imread(\"img_dir\", flags)中flags参数,仅用于传递参数(default:cv.IMREAD_COLOR)\n wait_time : cv.waitKey(wait_time)时间参数,仅用于传递参数(default:1000(1秒))\noutputs: None\n\"\"\"\ndef show_key_points_and_rect_in_origin_img(not_unify_coords, img_path, imread_type=cv.IMREAD_COLOR, wait_time=0):\n # 如果是不完整的路径(仅有上一级文件夹和图片名)则将其补全(加上文件夹所在位置)\n if not os.path.isabs(img_path):\n img_path = os.path.join(dataset_images_base_dir, img_path)\n\n img_origin = cv.imread(img_path, flags=imread_type)\n x_min = not_unify_coords[x_min_rect_idx]; x_max = not_unify_coords[x_max_rect_idx]\n y_min = not_unify_coords[y_min_rect_idx]; y_max = not_unify_coords[y_max_rect_idx]\n cv.rectangle(img_origin, pt1=(x_min, y_min), pt2=(x_max, y_max), color=bgr_Green, thickness=1)\n for i in range(key_points_numbers):\n cv.circle(img_origin, center=(not_unify_coords[2 * i], not_unify_coords[2 * i + 1]), radius=0, color=bgr_Pink, thickness=3)\n cv.imshow(\"img_origin\", img_origin)\n cv.waitKey(wait_time)\n cv.destroyAllWindows()\n\n\n\"\"\"\nname: show_key_points_in_unify_img\nfunctional: use the origin image (or unify image) and unified coords to point the unified key points\ninputs: unify_coords : 一定是简化的坐标(可以接受的参数类型: <class 'numpy.ndarray'> (76,))\n img_path : 图片路径(可以是完整路径,也可以是不完整的路径(即只有图片文件夹和图片名))\n 不完整的路径(仅有上一级文件夹和图片名)也可也运行 eg : 50--Celebration_Or_Party/50_Celebration_Or_Party_houseparty_50_321.jpg\n unify_img : 使用的是unify的图片还是未经过unify的origin图片(有将数据集图像重新处理并保持的想法,以此简化计算,加快训练,未实现)\n imread_type : cv.imread(\"img_dir\", flags)中flags参数,仅用于传递参数(default:cv.IMREAD_COLOR)\n wait_time : cv.waitKey(wait_time)时间参数,仅用于传递参数(default:1000(1秒))\noutputs: None\n\"\"\"\ndef show_key_points_in_unify_img(unify_coords, img_path, unify_img=False, imread_type=cv.IMREAD_COLOR, wait_time=1500):\n # 从img中取出矩形框选部分是通过row_col\n # 在img上画出rect或者circle是通过x_y\n # 数据集标注采用的是x_y方式标注点\n\n # 如果是不完整的路径(仅有上一级文件夹和图片名)则将其补全(加上文件夹所在位置)\n if not os.path.isabs(img_path):\n img_path = os.path.join(dataset_images_base_dir, img_path)\n\n if not unify_img: # 传入的图片没有经过unify\n img = cv.imread(img_path, flags=imread_type)\n img_unify = img[unify_coords[row_min_rect_idx]:unify_coords[row_max_rect_idx],\n unify_coords[col_min_rect_idx]:unify_coords[col_max_rect_idx]]\n img_unify = cv.resize(img_unify, unify_gray_image_size)\n else: # 传入的图片经过unify,无需resize,也就不需要矩形框\n img_unify = cv.imread(img_path, flags=imread_type)\n # print(img_color_unify.shape)\n\n for i in range(key_points_numbers):\n cv.circle(img_unify, center=(unify_coords[2 * i], unify_coords[2 * i + 1]), radius=0, color=bgr_Pink, thickness=2)\n\n cv.imshow(\"key points\", img_unify)\n cv.waitKey(wait_time)\n cv.destroyAllWindows()\n\n# def show_key_points_in_unify_img(unify_img, unify_coords, wait_time=0):\n# unify_img_copy = unify_img.copy()\n# for i in range(key_points_numbers):\n# cv.circle(unify_img_copy, center=(unify_coords[2 * i], unify_coords[2 * i + 1]), radius=0, color=bgr_Pink, thickness=3)\n# cv.imshow(\"key points\", unify_img_copy)\n# cv.waitKey(wait_time)\n# cv.destroyAllWindows()\n\n\"\"\"\npass\n\"\"\"\ndef show_train_key_points_in_unify_img(Net, Dataset, image_paths, unify_int_coords, show_train_image_idx, unify_img=False, imread_type=cv.IMREAD_COLOR, wait_time=1500):\n Net.eval()\n unify_gray_image, actual_coords = Dataset[show_train_image_idx]\n unify_gray_image = torch.reshape(unify_gray_image, (-1, 1, unify_gray_image_size[0], unify_gray_image_size[1])) # 更改形状(添加维度)\n # unify_gray_image = unify_gray_image.to(device) # 一定要to(device)否则报错:Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same\n train_coords = Net(unify_gray_image)\n train_coords = train_coords.detach().cpu().numpy() # 转换为 <class 'numpy.ndarray'> # 一定要.cpu()否则在GPU上无法正常运行\n train_coords = np.reshape(train_coords, -1) # 拉成一维数组\n # print(train_coords.shape) # 72\n train_coords = np.append(train_coords, unify_int_coords[show_train_image_idx][x_min_rect_idx:y_max_rect_idx+1]) # 加上矩形框大小\n train_coords = train_coords.astype(np.int32) # 一定要数据类型转换\n train_img_path = image_paths[show_train_image_idx]\n print(\"eval_train_coords\")\n print(train_coords)\n show_key_points_in_unify_img(unify_coords=train_coords, img_path=train_img_path, unify_img=False, imread_type=imread_type, wait_time=wait_time)\n return train_coords\n\n\n\"\"\"\n\n\"\"\"\ndef get_train_key_points_in_unify_img_from_camera(Net, unify_color_img, unify_gray_tensor_img):\n Net.eval()\n unify_gray_image = torch.reshape(unify_gray_tensor_img, unify_tensor_image_size) # 更改形状(添加维度)\n unify_gray_image = unify_gray_image.to(device)\n train_coords = Net(unify_gray_image)\n train_coords = train_coords.detach().cpu().numpy() # 转换为 <class 'numpy.ndarray'> # 一定要.cpu()否则在GPU上无法正常运行\n train_coords = np.reshape(train_coords, -1) # 拉成一维数组\n train_coords = train_coords.astype(np.int32) # 一定要数据类型转换\n for i in range(key_points_numbers):\n cv.circle(unify_color_img, center=(train_coords[2 * i], train_coords[2 * i + 1]), radius=0, color=bgr_Pink, thickness=3)\n return train_coords\n\n\n\n\"\"\"\nname: show_key_points_in_incomplete_unify_img\nfunctional: 将不是所有关键点都在矩形框中的图片信息进行展示(仅在测试时使用,训练时并不会调用)\ninputs: unify_coords : key points coordinates after unify step\n not_unify_coords : key points coordinates before unify step(方便展示出问题)\n img_path : 图片路径\noutputs: None\n\"\"\"\ndef show_key_points_in_incomplete_unify_img(unify_coords, not_unify_coords, img_path):\n unify_coords_shape = unify_coords.shape # unify_coords形状\n # 标注不全的图片(人脸有些关键点在图像区域外)\n incomplete_num = 0\n temp_path = \"\"\n \"\"\"\n for img_idx in range(unify_coords_shape[0]):\n for point_idx in range(unify_coords_shape[1]):\n if unify_coords[img_idx, point_idx] < 0: # 有unify_coords数值为负\n incomplete_num += 1\n print(\"img_idx: \", img_idx, \" \", \"path: \", img_path[img_idx])\n # print(unify_coords[img_idx])\n # temp_path = os.path.join(dataset_images_base_dir, img_path[img_idx])\n # show_key_points_in_unify_img(unify_coords[img_idx], temp_path)\n break\n print(\"共有{}张图片关键点在区域外\".format(incomplete_num)) # 共有44张图片关键点在区域外\n \"\"\"\n # 1035 和 2747 所有关键点在区域外\n for img_idx in (1035, 2747):\n print(\"img_idx: \", img_idx, \" \", \"path: \", img_path[img_idx])\n print(not_unify_coords[img_idx])\n temp_path = os.path.join(dataset_images_base_dir, img_path[img_idx])\n show_key_points_and_rect_in_origin_img(not_unify_coords[img_idx], temp_path)\n \"\"\"\n ( 92 , 0 ) value -4 path: 48--Parachutist_Paratrooper/48_Parachutist_Paratrooper_Parachutist_Paratrooper_48_487.jpg\n ( 107 , 0 ) value -3 path: 32--Worker_Laborer/32_Worker_Laborer_Worker_Laborer_32_23.jpg\n ( 274 , 0 ) value -4 path: 13--Interview/13_Interview_Interview_On_Location_13_179.jpg\n ( 409 , 0 ) value -1 path: 28--Sports_Fan/28_Sports_Fan_Sports_Fan_28_462.jpg\n ( 516 , 34 ) value -2 path: 36--Football/36_Football_americanfootball_ball_36_714.jpg\n ( 601 , 0 ) value -1 path: 7--Cheering/7_Cheering_Cheering_7_40.jpg\n ( 1035 , 0 ) value -66 path: 12--Group/12_Group_Group_12_Group_Group_12_839.jpg\n ( 1038 , 3 ) value -2 path: 46--Jockey/46_Jockey_Jockey_46_857.jpg\n ( 1135 , 0 ) value -1 path: 50--Celebration_Or_Party/50_Celebration_Or_Party_houseparty_50_895.jpg\n ( 1367 , 0 ) value -1 path: 4--Dancing/4_Dancing_Dancing_4_983.jpg\n ( 1451 , 1 ) value -12 path: 29--Students_Schoolkids/29_Students_Schoolkids_Students_Schoolkids_29_432.jpg\n ( 1752 , 0 ) value -1 path: 12--Group/12_Group_Group_12_Group_Group_12_122.jpg\n ( 1798 , 0 ) value -1 path: 49--Greeting/49_Greeting_peoplegreeting_49_74.jpg\n ( 1802 , 0 ) value -1 path: 28--Sports_Fan/28_Sports_Fan_Sports_Fan_28_61.jpg\n ( 2199 , 0 ) value -25 path: 2--Demonstration/2_Demonstration_Demonstration_Or_Protest_2_809.jpg\n ( 2701 , 0 ) value -8 path: 32--Worker_Laborer/32_Worker_Laborer_Worker_Laborer_32_478.jpg\n ( 2747 , 0 ) value -68 path: 28--Sports_Fan/28_Sports_Fan_Sports_Fan_28_959.jpg\n ( 2913 , 0 ) value -1 path: 44--Aerobics/44_Aerobics_Aerobics_44_189.jpg\n ( 3085 , 0 ) value -3 path: 0--Parade/0_Parade_Parade_0_592.jpg\n ( 3086 , 32 ) value -1 path: 10--People_Marching/10_People_Marching_People_Marching_2_832.jpg\n ( 3174 , 32 ) value -3 path: 2--Demonstration/2_Demonstration_Political_Rally_2_83.jpg\n ( 3187 , 32 ) value -4 path: 61--Street_Battle/61_Street_Battle_streetfight_61_282.jpg\n ( 3786 , 36 ) value -1 path: 24--Soldier_Firing/24_Soldier_Firing_Soldier_Firing_24_828.jpg\n ( 4221 , 5 ) value -1 path: 28--Sports_Fan/28_Sports_Fan_Sports_Fan_28_227.jpg\n ( 4253 , 0 ) value -10 path: 49--Greeting/49_Greeting_peoplegreeting_49_759.jpg\n ( 4266 , 0 ) value -3 path: 13--Interview/13_Interview_Interview_On_Location_13_623.jpg\n ( 4327 , 0 ) value -3 path: 18--Concerts/18_Concerts_Concerts_18_737.jpg\n ( 4574 , 32 ) value -1 path: 28--Sports_Fan/28_Sports_Fan_Sports_Fan_28_918.jpg\n ( 4852 , 0 ) value -3 path: 12--Group/12_Group_Group_12_Group_Group_12_610.jpg\n ( 4925 , 0 ) value -1 path: 4--Dancing/4_Dancing_Dancing_4_22.jpg\n ( 4994 , 0 ) value -8 path: 2--Demonstration/2_Demonstration_Political_Rally_2_803.jpg\n ( 5551 , 0 ) value -2 path: 13--Interview/13_Interview_Interview_On_Location_13_765.jpg\n ( 5681 , 32 ) value -1 path: 35--Basketball/35_Basketball_playingbasketball_35_476.jpg\n ( 5701 , 32 ) value -7 path: 29--Students_Schoolkids/29_Students_Schoolkids_Students_Schoolkids_29_531.jpg\n ( 5721 , 0 ) value -1 path: 50--Celebration_Or_Party/50_Celebration_Or_Party_houseparty_50_33.jpg\n ( 5926 , 0 ) value -3 path: 2--Demonstration/2_Demonstration_Demonstrators_2_398.jpg\n ( 6007 , 0 ) value -2 path: 12--Group/12_Group_Group_12_Group_Group_12_35.jpg\n ( 6076 , 0 ) value -2 path: 41--Swimming/41_Swimming_Swimmer_41_1039.jpg\n ( 6087 , 0 ) value -7 path: 12--Group/12_Group_Large_Group_12_Group_Large_Group_12_219.jpg\n ( 6360 , 5 ) value -2 path: 47--Matador_Bullfighter/47_Matador_Bullfighter_matadorbullfighting_47_561.jpg\n ( 6554 , 0 ) value -3 path: 7--Cheering/7_Cheering_Cheering_7_805.jpg\n ( 6637 , 0 ) value -12 path: 58--Hockey/58_Hockey_icehockey_puck_58_580.jpg\n ( 6805 , 0 ) value -1 path: 14--Traffic/14_Traffic_Traffic_14_620.jpg\n ( 7120 , 38 ) value -1 path: 50--Celebration_Or_Party/50_Celebration_Or_Party_houseparty_50_853.jpg\n \"\"\"\n\n\n# WFLW数据集路径检查\ndef check_path():\n # print(separate_bar, \"WFLW数据集路径检查开始\", separate_bar)\n if os.path.exists(dataset_images_base_dir):\n print(\"WFLW数据集图像路径: \", dataset_images_base_dir)\n print(\"成功找到WFLW数据集图像路径\")\n else:\n print(\"WFLW数据集图像路径有误,请对Consts.py文件进行修改\")\n return False\n\n if os.path.isfile(train_dataset_annotation_dir):\n print(\"WFLW数据集标注路径: \", train_dataset_annotation_dir)\n print(\"成功找到WFLW数据集标注路径\")\n else:\n print(\"WFLW数据集标注路径有误,请对Consts.py文件进行修改\")\n return False\n # print(separate_bar, \"WFLW数据集路径检查完毕\", separate_bar)\n return True\n\n\n# WFLW数据集信息显示\ndef inform_dataset_basic(_origin_anno_size, _simple_anno_size, DatasetType=\"train\"):\n # print(separate_bar, \"数据集相关信息如下\", separate_bar)\n if DatasetType == \"train\":\n TypePrefix = \"训练\"\n dataset_name = train_dataset_name\n elif DatasetType == \"test\":\n TypePrefix = \"测试\"\n dataset_name = test_dataset_name\n else:\n print(\"Dataset Type can not be matched.\")\n exit(-1)\n\n print(\"数据集名称: \", dataset_name)\n print(\"原始\" + TypePrefix + \"数据标注shape:\", _origin_anno_size)\n print(\"简化\" + TypePrefix + \"数据标注shape:\", _simple_anno_size)\n # print(separate_bar, \"输出数据集信息结束\", separate_bar)\n\n\ndef testGPU():\n # print(separate_bar, \"开始测试GPU\", separate_bar)\n if torch.cuda.is_available():\n print(\"GPU is available. Use GPU.\")\n # print(separate_bar, \"GPU测试结束\", separate_bar)\n return True\n else:\n print(\"Only CPU is available. Use CPU.\")\n # print(separate_bar, \"GPU测试结束\", separate_bar)\n return False\n\n\n\"\"\"\nname: read_annotation\nfunctional: use pandas to read the annotation.txt and get the simplified information\ninputs: root_dir : directory of the annotation file (default : train_dataset_annotation_dir)\noutputs: annotation (<class 'numpy.ndarray'>)\n size of the origin annotation \n size of the simple annotation\n\"\"\"\ndef read_annotation(root_dir=train_dataset_annotation_dir):\n # 使用pandas读取完整的标注进入DataFrame\n origin_annotation = pd.read_csv(filepath_or_buffer=root_dir, sep=' ', header=None, index_col=None)\n origin_annotation = origin_annotation.values # 转化为列表形式\n origin_annotation_shape = origin_annotation.shape\n # print(origin_annotation_shape)\n # 取出关注的关键点,简化标注\n simple_annotation_p1 = origin_annotation[:, left_eye_start_ * 2: inner_lip_end_ * 2 + 2] # 眼睛嘴唇的关键点正好连续\n simple_annotation_p2 = origin_annotation[:, x_min_rect_idx_: y_max_rect_idx_ + 1] # 脸部矩形的两个点\n simple_annotation_p3 = origin_annotation[:, img_relative_root_idx_] # 对应图像路径\n simple_annotation_p3 = simple_annotation_p3[:, np.newaxis] # 添加新维度,否则无法进行concatenate操作\n # print(simple_annotation_p1.shape, type(simple_annotation_p1)) # (7500, 72) <class 'numpy.ndarray'>\n # print(simple_annotation_p2.shape, type(simple_annotation_p2)) # (7500, 4) <class 'numpy.ndarray'>\n # print(simple_annotation_p3.shape, type(simple_annotation_p3)) # (7500, 1) <class 'numpy.ndarray'>\n # 合成简化的标注\n simple_annotation = np.concatenate((simple_annotation_p1, simple_annotation_p2, simple_annotation_p3), axis=1)\n # print(simple_annotation)\n simple_annotation_shape = simple_annotation.shape\n # print(simple_annotation_shape) # (7500, 77)\n return simple_annotation, origin_annotation_shape, simple_annotation_shape\n\n\nif __name__ == \"__main__\":\n pass\n"
]
| [
[
"numpy.concatenate",
"numpy.reshape",
"torch.cuda.is_available",
"numpy.append",
"pandas.read_csv",
"torch.reshape"
]
]
|
jbclements/RacketFrames | [
"07ed04b93fbbc214a72ec28ab4f99f0e36ed3f18"
]
| [
"racketframes/benchmark/Pandas/indexing/multi_index_object.py"
]
| [
"import string\n\nimport numpy as np\nimport pandas.util.testing as tm\nfrom pandas import date_range, MultiIndex\n\nfrom .pandas_vb_common import setup # noqa\n\n\nclass GetLoc(object):\n\n goal_time = 0.2\n\n def setup(self):\n self.mi_large = MultiIndex.from_product(\n [np.arange(1000), np.arange(20), list(string.ascii_letters)],\n names=['one', 'two', 'three'])\n self.mi_med = MultiIndex.from_product(\n [np.arange(1000), np.arange(10), list('A')],\n names=['one', 'two', 'three'])\n self.mi_small = MultiIndex.from_product(\n [np.arange(100), list('A'), list('A')],\n names=['one', 'two', 'three'])\n\n def time_large_get_loc(self):\n self.mi_large.get_loc((999, 19, 'Z'))\n\n def time_large_get_loc_warm(self):\n for _ in range(1000):\n self.mi_large.get_loc((999, 19, 'Z'))\n\n def time_med_get_loc(self):\n self.mi_med.get_loc((999, 9, 'A'))\n\n def time_med_get_loc_warm(self):\n for _ in range(1000):\n self.mi_med.get_loc((999, 9, 'A'))\n\n def time_string_get_loc(self):\n self.mi_small.get_loc((99, 'A', 'A'))\n\n def time_small_get_loc_warm(self):\n for _ in range(1000):\n self.mi_small.get_loc((99, 'A', 'A'))\n\n\nclass Duplicates(object):\n\n goal_time = 0.2\n\n def setup(self):\n size = 65536\n arrays = [np.random.randint(0, 8192, size),\n np.random.randint(0, 1024, size)]\n mask = np.random.rand(size) < 0.1\n self.mi_unused_levels = MultiIndex.from_arrays(arrays)\n self.mi_unused_levels = self.mi_unused_levels[mask]\n\n def time_remove_unused_levels(self):\n self.mi_unused_levels.remove_unused_levels()\n\n\nclass Integer(object):\n\n goal_time = 0.2\n\n def setup(self):\n self.mi_int = MultiIndex.from_product([np.arange(1000),\n np.arange(1000)],\n names=['one', 'two'])\n self.obj_index = np.array([(0, 10), (0, 11), (0, 12),\n (0, 13), (0, 14), (0, 15),\n (0, 16), (0, 17), (0, 18),\n (0, 19)], dtype=object)\n\n def time_get_indexer(self):\n self.mi_int.get_indexer(self.obj_index)\n\n def time_is_monotonic(self):\n self.mi_int.is_monotonic\n\n\nclass Duplicated(object):\n\n goal_time = 0.2\n\n def setup(self):\n n, k = 200, 5000\n levels = [np.arange(n),\n tm.makeStringIndex(n).values,\n 1000 + np.arange(n)]\n labels = [np.random.choice(n, (k * n)) for lev in levels]\n self.mi = MultiIndex(levels=levels, labels=labels)\n\n def time_duplicated(self):\n self.mi.duplicated()\n\n\nclass Sortlevel(object):\n\n goal_time = 0.2\n\n def setup(self):\n n = 1182720\n low, high = -4096, 4096\n arrs = [np.repeat(np.random.randint(low, high, (n // k)), k)\n for k in [11, 7, 5, 3, 1]]\n self.mi_int = MultiIndex.from_arrays(arrs)[np.random.permutation(n)]\n\n a = np.repeat(np.arange(100), 1000)\n b = np.tile(np.arange(1000), 100)\n self.mi = MultiIndex.from_arrays([a, b])\n self.mi = self.mi.take(np.random.permutation(np.arange(100000)))\n\n def time_sortlevel_int64(self):\n self.mi_int.sortlevel()\n\n def time_sortlevel_zero(self):\n self.mi.sortlevel(0)\n\n def time_sortlevel_one(self):\n self.mi.sortlevel(1)\n\n\nclass Values(object):\n\n goal_time = 0.2\n\n def setup_cache(self):\n\n level1 = range(1000)\n level2 = date_range(start='1/1/2012', periods=100)\n mi = MultiIndex.from_product([level1, level2])\n return mi\n\n def time_datetime_level_values_copy(self, mi):\n mi.copy().values\n\n def time_datetime_level_values_sliced(self, mi):\n mi[:10].values"
]
| [
[
"numpy.array",
"numpy.random.rand",
"numpy.random.choice",
"pandas.date_range",
"numpy.random.permutation",
"pandas.MultiIndex.from_arrays",
"numpy.random.randint",
"pandas.MultiIndex.from_product",
"pandas.MultiIndex",
"numpy.arange",
"pandas.util.testing.makeStringIndex"
]
]
|
DEVHEE/ai-robot-hand-with-raspberry-pi | [
"d556706c6f7ae33d893f8411b06d4a5d6ba0625d"
]
| [
"software/mask_recognition/train_mask_recongition.py"
]
| [
"\"\"\"\nai-robot-hand-with-raspberry-pi\nCOPYRIGHT © 2021 KIM DONGHEE. ALL RIGHTS RESERVED.\n\"\"\"\n\n'''\nUsed dataset: https://www.kaggle.com/omkargurav/face-mask-dataset\n'''\n\n# Import modules.\nimport os\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom imutils import paths\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.layers import AveragePooling2D\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.preprocessing.image import load_img\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\n\n# Parse the arguments.\nap = argparse.ArgumentParser()\nap.add_argument(\"-d\", \"--dataset\", type=str, default=\"dataset\",\n help=\"the path of the input dataset\")\nap.add_argument(\"-p\", \"--plot\", type=str, default=\"loss_acc_plot.png\",\n help=\"the path of output loss/accuracy plot\")\nap.add_argument(\"-m\", \"--model\", type=str,\n default=\"mask_recognizer.model\",\n help=\"the path to output the face mask recognizer model\")\nargs = vars(ap.parse_args())\n\n# Set init learning rate, epochs, and batch size.\nINIT_LR = 1e-4\nEPOCHS = 20\nBS = 32\n\n# Get the image list from the dataset directory, and then initialize the data(images) and class image list.\nprint(\"Loading images...\")\nimagePaths = list(paths.list_images(args[\"dataset\"]))\ndata = []\nlabels = []\n\n# Loop over the image paths.\nfor imagePath in imagePaths:\n # Extract class labels from file names.\n label = imagePath.split(os.path.sep)[-2]\n\n # Load the 224x224 input image and preprocess it.\n image = load_img(imagePath, target_size=(224, 224))\n image = img_to_array(image)\n image = preprocess_input(image)\n\n # Update the data and label list, respectively.\n data.append(image)\n labels.append(label)\n\n# Convert data and labels to NumPy array.\ndata = np.array(data, dtype=\"float32\")\nlabels = np.array(labels)\n\n# Perform one-hot encoding on the labels.\nlb = LabelBinarizer()\nlabels = lb.fit_transform(labels)\nlabels = to_categorical(labels)\n\n# Partition the data into training and testing splits using 75% of the data for training and the remaining 25% for testing.\n(trainX, testX, trainY, testY) = train_test_split(data, labels,\n test_size=0.20, stratify=labels, random_state=42)\n\n# Construct the training image generator for data augmentation.\naug = ImageDataGenerator(\n rotation_range=20,\n zoom_range=0.15,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.15,\n horizontal_flip=True,\n fill_mode=\"nearest\")\n\n# Load the MobileNetV2 network to ensure that the head FC layer set is left off.\nbaseModel = MobileNetV2(weights=\"imagenet\", include_top=False,\n input_tensor=Input(shape=(224, 224, 3)))\n\n# Construct the head of the model to be placed on top of the base model.\nheadModel = baseModel.output\nheadModel = AveragePooling2D(pool_size=(7, 7))(headModel)\nheadModel = Flatten(name=\"flatten\")(headModel)\nheadModel = Dense(128, activation=\"relu\")(headModel)\nheadModel = Dropout(0.5)(headModel)\nheadModel = Dense(2, activation=\"softmax\")(headModel)\n\n# Place the head FC model on top of the base model (it will be the actual model we will train).\nmodel = Model(inputs=baseModel.input, outputs=headModel)\n\n# Repeat to all layers of the base model to fix it so that it is not updated during the first training process.\nfor layer in baseModel.layers:\n layer.trainable = False\n\n# Compile our model.\nprint(\"Compiling model...\")\nopt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)\nmodel.compile(loss=\"binary_crossentropy\", optimizer=opt,\n metrics=[\"accuracy\"])\n\n# Train the head of the network.\nprint(\"Training head...\")\nH = model.fit(\n aug.flow(trainX, trainY, batch_size=BS),\n steps_per_epoch=len(trainX) // BS,\n validation_data=(testX, testY),\n validation_steps=len(testX) // BS,\n epochs=EPOCHS)\n\n# Make predictions on the testing set\nprint(\"Evaluating network...\")\npredIdxs = model.predict(testX, batch_size=BS)\n\n# For each image in the testing set we need to find the index of the label with corresponding largest predicted probability.\npredIdxs = np.argmax(predIdxs, axis=1)\n\n# Show a nicely formatted classification report.\nprint(classification_report(testY.argmax(axis=1), predIdxs,\n target_names=lb.classes_))\n\n# Serialize the model to disk.\nprint(\"Saving mask recognizer model...\")\nmodel.save(args[\"model\"], save_format=\"h5\")\n\n# Make a plot the training loss and accuracy.\nN = EPOCHS\nplt.style.use(\"ggplot\")\nplt.figure()\nplt.plot(np.arange(0, N), H.history[\"loss\"], label=\"train_loss\")\nplt.plot(np.arange(0, N), H.history[\"val_loss\"], label=\"val_loss\")\nplt.plot(np.arange(0, N), H.history[\"accuracy\"], label=\"train_acc\")\nplt.plot(np.arange(0, N), H.history[\"val_accuracy\"], label=\"val_acc\")\nplt.title(\"Training Loss and Accuracy on Mask Recognition\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Loss / Accuracy\")\nplt.legend(loc=\"lower left\")\nplt.savefig(args[\"plot\"])"
]
| [
[
"tensorflow.keras.utils.to_categorical",
"tensorflow.keras.preprocessing.image.load_img",
"tensorflow.keras.applications.mobilenet_v2.preprocess_input",
"tensorflow.keras.layers.AveragePooling2D",
"tensorflow.keras.models.Model",
"tensorflow.keras.layers.Dense",
"matplotlib.pyplot.savefig",
"numpy.argmax",
"numpy.arange",
"tensorflow.keras.optimizers.Adam",
"sklearn.preprocessing.LabelBinarizer",
"numpy.array",
"tensorflow.keras.preprocessing.image.ImageDataGenerator",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.preprocessing.image.img_to_array",
"matplotlib.pyplot.style.use",
"sklearn.model_selection.train_test_split",
"tensorflow.keras.layers.Input",
"tensorflow.keras.layers.Flatten",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ylabel"
]
]
|
Nevronas/skeleton | [
"51a1fffdd09d67d8c4806d1375932352ef8a47d1"
]
| [
"small_proj/src/model.py"
]
| [
"import torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\n\n# First define all the layers.\n\nclass conv_bn(torch.nn.Module):\n def __init__(self, inp_ch, outp_ch):\n super(conv_bn, self).__init__()\n self.conv = torch.nn.Sequential(\n torch.nn.Conv2d(inp_ch, outp_ch, 3),\n torch.nn.BatchNorm2d(outp_ch),\n torch.nn.ReLU(inplace=True)\n )\n\n def forward(self, x):\n return self.conv(x)\n\n\n# Then define all the models.\n\nclass Model1(torch.nn.Module):\n def __init__(self, in_ch):\n super(Model1, self).__init__()\n self.conv1 = conv_bn(in_ch, 5)\n self.layer = torch.nn.Linear(50 * 50 * 5, 10)\n\n def forward(self, x):\n x = self.conv1(x)\n return self.layer(x)\n\n# ..."
]
| [
[
"torch.nn.Linear",
"torch.nn.Conv2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
]
|
cali-li/nlp-recipes | [
"558d822be6d50ed0f571f4b96a689e64a8440e2d"
]
| [
"utils_nlp/models/bert/sequence_classification.py"
]
| [
"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\n\nfrom collections import namedtuple\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset\nfrom pytorch_pretrained_bert.modeling import BertForSequenceClassification\nfrom pytorch_pretrained_bert.optimization import BertAdam\nfrom tqdm import tqdm\n\nfrom utils_nlp.models.bert.common import Language\nfrom utils_nlp.common.pytorch_utils import get_device, move_to_device\n\nfrom cached_property import cached_property\n\n\nclass BERTSequenceClassifier:\n \"\"\"BERT-based sequence classifier\"\"\"\n\n def __init__(self, language=Language.ENGLISH, num_labels=2, cache_dir=\".\"):\n \"\"\"Initializes the classifier and the underlying pretrained model.\n\n Args:\n language (Language, optional): The pretrained model's language.\n Defaults to Language.ENGLISH.\n num_labels (int, optional): The number of unique labels in the\n training data. Defaults to 2.\n cache_dir (str, optional): Location of BERT's cache directory.\n Defaults to \".\".\n \"\"\"\n if num_labels < 2:\n raise ValueError(\"Number of labels should be at least 2.\")\n\n self.language = language\n self.num_labels = num_labels\n self.cache_dir = cache_dir\n\n # create classifier\n self.model = BertForSequenceClassification.from_pretrained(\n language, cache_dir=cache_dir, num_labels=num_labels\n )\n self.has_cuda = self.cuda\n\n @cached_property\n def cuda(self):\n \"\"\" cache the output of torch.cuda.is_available() \"\"\"\n\n self.has_cuda = torch.cuda.is_available()\n return self.has_cuda\n\n def fit(\n self,\n token_ids,\n input_mask,\n labels,\n token_type_ids=None,\n num_gpus=None,\n num_epochs=1,\n batch_size=32,\n lr=2e-5,\n warmup_proportion=None,\n verbose=True,\n ):\n \"\"\"Fine-tunes the BERT classifier using the given training data.\n\n Args:\n token_ids (list): List of training token id lists.\n input_mask (list): List of input mask lists.\n labels (list): List of training labels.\n token_type_ids (list, optional): List of lists. Each sublist\n contains segment ids indicating if the token belongs to\n the first sentence(0) or second sentence(1). Only needed\n for two-sentence tasks.\n num_gpus (int, optional): The number of gpus to use.\n If None is specified, all available GPUs\n will be used. Defaults to None.\n num_epochs (int, optional): Number of training epochs.\n Defaults to 1.\n batch_size (int, optional): Training batch size. Defaults to 32.\n lr (float): Learning rate of the Adam optimizer. Defaults to 2e-5.\n warmup_proportion (float, optional): Proportion of training to\n perform linear learning rate warmup for. E.g., 0.1 = 10% of\n training. Defaults to None.\n verbose (bool, optional): If True, shows the training progress and\n loss values. Defaults to True.\n \"\"\"\n\n device, num_gpus = get_device(num_gpus)\n\n self.model = move_to_device(self.model, device, num_gpus)\n\n token_ids_tensor = torch.tensor(token_ids, dtype=torch.long)\n input_mask_tensor = torch.tensor(input_mask, dtype=torch.long)\n labels_tensor = torch.tensor(labels, dtype=torch.long)\n\n if token_type_ids:\n token_type_ids_tensor = torch.tensor(token_type_ids, dtype=torch.long)\n train_dataset = TensorDataset(\n token_ids_tensor, input_mask_tensor, token_type_ids_tensor, labels_tensor\n )\n else:\n train_dataset = TensorDataset(token_ids_tensor, input_mask_tensor, labels_tensor)\n train_sampler = RandomSampler(train_dataset)\n\n train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=batch_size)\n # define optimizer and model parameters\n param_optimizer = list(self.model.named_parameters())\n no_decay = [\"bias\", \"LayerNorm.bias\", \"LayerNorm.weight\"]\n optimizer_grouped_parameters = [\n {\n \"params\": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],\n \"weight_decay\": 0.01,\n },\n {\n \"params\": [p for n, p in param_optimizer if any(nd in n for nd in no_decay)],\n \"weight_decay\": 0.0,\n },\n ]\n\n num_batches = len(train_dataloader)\n num_train_optimization_steps = num_batches * num_epochs\n\n if warmup_proportion is None:\n opt = BertAdam(optimizer_grouped_parameters, lr=lr)\n else:\n opt = BertAdam(\n optimizer_grouped_parameters,\n lr=lr,\n t_total=num_train_optimization_steps,\n warmup=warmup_proportion,\n )\n\n # define loss function\n loss_func = nn.CrossEntropyLoss().to(device)\n\n # train\n self.model.train() # training mode\n\n for epoch in range(num_epochs):\n training_loss = 0\n for i, batch in enumerate(tqdm(train_dataloader, desc=\"Iteration\")):\n if token_type_ids:\n x_batch, mask_batch, token_type_ids_batch, y_batch = tuple(\n t.to(device) for t in batch\n )\n else:\n token_type_ids_batch = None\n x_batch, mask_batch, y_batch = tuple(t.to(device) for t in batch)\n\n opt.zero_grad()\n\n y_h = self.model(\n input_ids=x_batch,\n token_type_ids=token_type_ids_batch,\n attention_mask=mask_batch,\n labels=None,\n )\n loss = loss_func(y_h, y_batch).mean()\n\n training_loss += loss.item()\n\n loss.backward()\n opt.step()\n if verbose:\n if i % ((num_batches // 10) + 1) == 0:\n print(\n \"epoch:{}/{}; batch:{}->{}/{}; average training loss:{:.6f}\".format(\n epoch + 1,\n num_epochs,\n i + 1,\n min(i + 1 + num_batches // 10, num_batches),\n num_batches,\n training_loss / (i + 1),\n )\n )\n # empty cache\n del [x_batch, y_batch, mask_batch, token_type_ids_batch]\n torch.cuda.empty_cache()\n\n def predict(\n self,\n token_ids,\n input_mask,\n token_type_ids=None,\n num_gpus=None,\n batch_size=32,\n probabilities=False,\n ):\n \"\"\"Scores the given dataset and returns the predicted classes.\n\n Args:\n token_ids (list): List of training token lists.\n input_mask (list): List of input mask lists.\n token_type_ids (list, optional): List of lists. Each sublist\n contains segment ids indicating if the token belongs to\n the first sentence(0) or second sentence(1). Only needed\n for two-sentence tasks.\n num_gpus (int, optional): The number of gpus to use.\n If None is specified, all available GPUs\n will be used. Defaults to None.\n batch_size (int, optional): Scoring batch size. Defaults to 32.\n probabilities (bool, optional):\n If True, the predicted probability distribution\n is also returned. Defaults to False.\n Returns:\n 1darray, namedtuple(1darray, ndarray): Predicted classes or\n (classes, probabilities) if probabilities is True.\n \"\"\"\n device, num_gpus = get_device(num_gpus)\n self.model = move_to_device(self.model, device, num_gpus)\n\n # score\n self.model.eval()\n\n token_ids_tensor = torch.tensor(token_ids, dtype=torch.long)\n input_mask_tensor = torch.tensor(input_mask, dtype=torch.long)\n\n if token_type_ids:\n token_type_ids_tensor = torch.tensor(token_type_ids, dtype=torch.long)\n test_dataset = TensorDataset(token_ids_tensor, input_mask_tensor, token_type_ids_tensor)\n else:\n test_dataset = TensorDataset(token_ids_tensor, input_mask_tensor)\n\n test_sampler = SequentialSampler(test_dataset)\n test_dataloader = DataLoader(test_dataset, sampler=test_sampler, batch_size=batch_size)\n\n preds = []\n for i, batch in enumerate(tqdm(test_dataloader, desc=\"Iteration\")):\n if token_type_ids:\n x_batch, mask_batch, token_type_ids_batch = tuple(t.to(device) for t in batch)\n else:\n token_type_ids_batch = None\n x_batch, mask_batch = tuple(t.to(device) for t in batch)\n\n with torch.no_grad():\n p_batch = self.model(\n input_ids=x_batch,\n token_type_ids=token_type_ids_batch,\n attention_mask=mask_batch,\n labels=None,\n )\n preds.append(p_batch.cpu())\n\n preds = np.concatenate(preds)\n\n if probabilities:\n return namedtuple(\"Predictions\", \"classes probabilities\")(\n preds.argmax(axis=1), nn.Softmax(dim=1)(torch.Tensor(preds)).numpy()\n )\n else:\n return preds.argmax(axis=1)\n"
]
| [
[
"numpy.concatenate",
"torch.utils.data.RandomSampler",
"torch.nn.Softmax",
"torch.nn.CrossEntropyLoss",
"torch.utils.data.SequentialSampler",
"torch.no_grad",
"torch.cuda.empty_cache",
"torch.cuda.is_available",
"torch.tensor",
"torch.utils.data.DataLoader",
"torch.Tensor",
"torch.utils.data.TensorDataset"
]
]
|
nagnath001/domain-classification-text | [
"1ef43a009d0999f40ea9f6c8d2b4c93d9b845838"
]
| [
"code.py"
]
| [
"# --------------\nimport pandas as pd\r\nimport os\r\nimport numpy as np\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n\r\n# path_train : location of test file\r\n# Code starts here\r\n\r\n#Loading data\r\ndf = pd.read_csv(path_train)\r\nprint(df.head())\r\n\r\n#Function to create new column\r\ndef label_race (row):\r\n if row['food'] == \"T\":\r\n return 'food'\r\n elif row['recharge'] == \"T\":\r\n return 'recharge'\r\n elif row['support'] == \"T\":\r\n return 'support'\r\n elif row['reminders'] == \"T\":\r\n return 'reminders'\r\n elif row['travel'] == \"T\":\r\n return 'travel'\r\n elif row['nearby'] == \"T\":\r\n return 'nearby'\r\n elif row['movies'] == \"T\":\r\n return 'movies'\r\n elif row['casual'] == \"T\":\r\n return 'casual'\r\n else:\r\n return \"other\"\r\n \r\n# Creating a new column called category which has the column marked as true for that particular message. \r\ndf[\"category\"] = df.apply (lambda row: label_race (row),axis=1)\r\n\r\n# Dropping all other columns except the category column\r\ndrop_col= [\"food\", \"recharge\", \"support\", \"reminders\", \"nearby\", \"movies\", \"casual\", \"other\", \"travel\"]\r\ndf = df.drop(drop_col,1)\r\n\r\n\r\nprint(\"\\nUpdated dataframe:\\n\",df.head())\r\n\r\n#Code ends here\r\n\n\n\n# --------------\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.preprocessing import LabelEncoder\r\n# Sampling only 1000 samples of each category\r\ndf = df.groupby('category').apply(lambda x: x.sample(n=1000, random_state=0))\r\n# Code starts here\r\nall_text=df['message'].str.lower()\r\ntfidf = TfidfVectorizer(stop_words=\"english\")\r\nvector = tfidf.fit_transform(all_text)\r\nX = vector.toarray()\r\nle=LabelEncoder()\r\ndf[\"category\"] = le.fit_transform(df[\"category\"])\r\ny = df[\"category\"]\r\n\n\n\n# --------------\nfrom sklearn.metrics import accuracy_score, classification_report\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.svm import LinearSVC\r\n\r\n# Code starts here\r\nX_train,X_val,y_train,y_val=train_test_split(X,y,test_size=0.3,random_state=42)\r\nlog_reg=LogisticRegression(random_state=0)\r\nlog_reg.fit(X_train,y_train)\r\ny_pred=log_reg.predict(X_val)\r\nlog_accuracy=accuracy_score(y_val,y_pred)\r\nprint(\"log_accuracy=\",log_accuracy)\r\nnb=MultinomialNB()\r\nnb.fit(X_train,y_train)\r\ny_pred1=nb.predict(X_val)\r\nnb_accuracy=accuracy_score(y_val,y_pred1)\r\nprint(\"nb_accuracy=\",nb_accuracy)\r\nlsvm=LinearSVC(random_state=0)\r\nlsvm.fit(X_train,y_train)\r\ny_pred2=lsvm.predict(X_val)\r\nlsvm_accuracy=accuracy_score(y_val,y_pred2)\r\nprint(\"lsvm_accuracy=\",lsvm_accuracy)\r\n\r\n\r\n\r\n\n\n\n# --------------\n\r\n# path_test : Location of test data\r\n\r\n#Loading the dataframe\r\ndf_test = pd.read_csv(path_test)\r\n\r\n#Creating the new column category\r\ndf_test[\"category\"] = df_test.apply (lambda row: label_race (row),axis=1)\r\n\r\n#Dropping the other columns\r\ndrop= [\"food\", \"recharge\", \"support\", \"reminders\", \"nearby\", \"movies\", \"casual\", \"other\", \"travel\"]\r\ndf_test= df_test.drop(drop,1)\r\n\r\n# Code starts here\r\n\r\nall_text = df_test[\"message\"].str.lower()\r\n\r\n# Transforming using the tfidf object - tfidf\r\nX_test = tfidf.transform(all_text).toarray()\r\n\r\n# Transforming using label encoder object - le\r\ny_test = le.transform(df_test[\"category\"])\r\n\r\n# Predicting using the logistic regression model - logreg\r\ny_pred = log_reg.predict(X_test)\r\nlog_accuracy_2 = accuracy_score(y_test,y_pred)\r\nprint (str(log_accuracy_2)+(\" is the accuracy of the logistic regression model\"))\r\n\r\n# Predicting using the naive bayes model - nb\r\ny_pred = nb.predict(X_test)\r\nnb_accuracy_2 = accuracy_score(y_test,y_pred)\r\nprint (str(nb_accuracy_2)+(\" is the accuracy of the Naive Bayes model\"))\r\n\r\n\r\n# Predicting using the linear svm model - lsvm\r\ny_pred = lsvm.predict(X_test)\r\nlsvm_accuracy_2 = accuracy_score(y_test,y_pred)\r\nprint (str(lsvm_accuracy_2)+(\" is the accuracy of the Support Vector model\"))\r\n\n\n\n# --------------\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem.wordnet import WordNetLemmatizer\r\nimport string\r\nimport gensim\r\nfrom gensim.models.lsimodel import LsiModel\r\nfrom gensim import corpora\r\nfrom pprint import pprint\r\n# import nltk\r\n# nltk.download('wordnet')\r\n\r\n# Creating a stopwords list\r\nstop = set(stopwords.words('english'))\r\nexclude = set(string.punctuation)\r\nlemma = WordNetLemmatizer()\r\n# Function to lemmatize and remove the stopwords\r\ndef clean(doc):\r\n stop_free = \" \".join([i for i in doc.lower().split() if i not in stop])\r\n punc_free = \"\".join(ch for ch in stop_free if ch not in exclude)\r\n normalized = \" \".join(lemma.lemmatize(word) for word in punc_free.split())\r\n return normalized\r\n# Creating a list of documents from the complaints column\r\nlist_of_docs = df[\"message\"].tolist()\r\n# Implementing the function for all the complaints of list_of_docs\r\ndoc_clean = [clean(doc).split() for doc in list_of_docs]\r\n# Code starts here\r\n# Creating the dictionary from our cleaned word list doc_clean\r\ndictionary = corpora.Dictionary(doc_clean)\r\n# Creating the corpus\r\ndoc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean]\r\n# Creating the LSi model\r\nlsimodel = LsiModel(corpus=doc_term_matrix, num_topics=5, id2word=dictionary)\r\npprint(lsimodel.print_topics())\r\n\r\n\r\n\r\n\n\n\n# --------------\nfrom gensim.models import LdaModel\r\nfrom gensim.models import CoherenceModel\r\n\r\n# doc_term_matrix - Word matrix created in the last task\r\n# dictionary - Dictionary created in the last task\r\n\r\n# Function to calculate coherence values\r\ndef compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3):\r\n \"\"\"\r\n Compute c_v coherence for various number of topics\r\n\r\n Parameters:\r\n ----------\r\n dictionary : Gensim dictionary\r\n corpus : Gensim corpus\r\n texts : List of input texts\r\n limit : Max num of topics\r\n\r\n Returns:\r\n -------\r\n topic_list : No. of topics chosen\r\n coherence_values : Coherence values corresponding to the LDA model with respective number of topics\r\n \"\"\"\r\n coherence_values = []\r\n topic_list = []\r\n for num_topics in range(start, limit, step):\r\n model = gensim.models.ldamodel.LdaModel(doc_term_matrix, random_state = 0, num_topics=num_topics, id2word = dictionary, iterations=10)\r\n topic_list.append(num_topics)\r\n coherencemodel = CoherenceModel(model=model, texts=texts, dictionary=dictionary, coherence='c_v')\r\n coherence_values.append(coherencemodel.get_coherence())\r\n\r\n return topic_list, coherence_values\r\n# Code starts here\r\ntopic_list,coherence_value_list=compute_coherence_values(dictionary=dictionary,corpus=doc_term_matrix,texts=doc_clean, limit=41, start=1, step=5)\r\nprint(topic_list)\r\n\r\nmax_index=coherence_value_list.index(max(coherence_value_list))\r\nprint(max_index)\r\nopt_topic= topic_list[max_index]\r\nprint(opt_topic)\r\n\r\nlda_model=LdaModel(corpus=doc_term_matrix, num_topics=opt_topic, id2word = dictionary, iterations=10 , passes=30,random_state=0)\r\n# printing the topics\r\npprint(lda_model.print_topics(5))\r\n\r\n\r\n\r\n\n\n\n"
]
| [
[
"sklearn.preprocessing.LabelEncoder",
"sklearn.metrics.accuracy_score",
"sklearn.naive_bayes.MultinomialNB",
"sklearn.linear_model.LogisticRegression",
"sklearn.feature_extraction.text.TfidfVectorizer",
"sklearn.model_selection.train_test_split",
"pandas.read_csv",
"sklearn.svm.LinearSVC"
]
]
|
boisgera/ash | [
"f4a288b45450dc7e421dcbcc97f009538939fc74"
]
| [
"videos/lti-balls.py"
]
| [
"#!/usr/bin/env python\n\n# Python Standard Library\npass\n\n# Third-Party Libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import to_rgb\n\n\n# Local Library\nimport mivp\n\n\n# ------------------------------------------------------------------------------\ngrey_4 = to_rgb(\"#ced4da\")\n\n# ------------------------------------------------------------------------------\n\ndef Q(f, xs, ys):\n X, Y = np.meshgrid(xs, ys)\n v = np.vectorize\n fx = v(lambda x, y: f([x, y])[0])\n fy = v(lambda x, y: f([x, y])[1])\n return X, Y, fx(X, Y), fy(X, Y)\n\n# ------------------------------------------------------------------------------\n\n# Vector field\ndef fun(t, xy):\n x, y = xy\n dx = -2*x + y\n dy = -2*y + x\n return np.array([dx, dy])\n\n\n# Time span & frame rate\nt_span = (0.0, 5.0)\n\ndf = 60.0 # 60.0\ndt = 1.0 / df\nt = np.arange(t_span[0], t_span[1], dt)\nt = np.r_[t, t_span[1]]\n\n# Initial set boundary\ny0 = [0.0, 0.0]\nradius = 0.5\nn = 10\nxc, yc = y0\n\n\ndef vectorize(fun):\n return np.vectorize(fun, signature=\"()->(n)\")\n\nradius = 0.5\n\n@vectorize\ndef boundary1(s):\n theta = 2*np.pi*s\n return np.array([\n -4 + radius * np.cos(theta),\n 1 + radius * np.sin(theta),\n ])\n\n@vectorize\ndef boundary2(s):\n theta = 2*np.pi*s\n return np.array([\n 4 + radius * np.cos(theta),\n -1 + radius * np.sin(theta),\n ])\n\n@vectorize\ndef boundary3(s):\n theta = 2*np.pi*s\n return np.array([\n 1 + radius * np.cos(theta),\n 4 + radius * np.sin(theta),\n ])\n\n@vectorize\ndef boundary4(s):\n theta = 2*np.pi*s\n return np.array([\n -1 + radius * np.cos(theta),\n -4 + radius * np.sin(theta),\n ])\n\n\n# Precision\nrtol = 1e-9 # default: 1e-3\natol = 1e-12 # default: 1e-6\n\n# ------------------------------------------------------------------------------\n\nfig = plt.figure()\nx = y = np.linspace(-5.0, 5.0, 1000)\nplt.streamplot(*Q(lambda xy: fun(0, xy), x, y), color=grey_4, zorder=-100)\nplt.plot([0], [0], lw=3.0, marker=\"o\", ms=10.0, markevery=[-1],\n markeredgecolor=\"white\", color=grey_4)\nplt.axis(\"square\")\nplt.axis(\"off\")\n\ndata = mivp.solve_alt(\n fun=fun,\n t_eval=t,\n boundary=[boundary1, boundary2, boundary3, boundary4],\n boundary_rtol=0.0,\n boundary_atol=0.01,\n rtol=rtol,\n atol=atol,\n method=\"LSODA\",\n)\n\ncircle = None\n\ndef display_radius(i, axes):\n global circle\n if circle:\n circle.remove()\n \n r = 0\n for datum in data:\n x, y = datum[i]\n r = max(r, max(np.sqrt(x*x + y*y)))\n \n \n theta = np.linspace(0, 2*np.pi, 1000)\n circle = axes.plot(\n r*np.cos(theta), r*np.sin(theta), \n linestyle='dashed', color=\"k\", linewidth=1.0,\n )[0]\n\nmivp.generate_movie(data, filename=\"lti-balls.mp4\", axes=fig.axes[0], fps=df, hook=display_radius)\n"
]
| [
[
"numpy.array",
"numpy.sin",
"numpy.vectorize",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.sqrt",
"numpy.cos",
"matplotlib.colors.to_rgb",
"numpy.linspace",
"numpy.meshgrid",
"matplotlib.pyplot.axis"
]
]
|
XingwenZhang/tutorials | [
"514a513f2839106603fea2bba6b8908725f874fc"
]
| [
"beginner_source/deploy_seq2seq_hybrid_frontend_tutorial.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nDeploying a Seq2Seq Model with TorchScript\n==================================================\n**Author:** `Matthew Inkawhich <https://github.com/MatthewInkawhich>`_\n1.2, this tutorial was updated to work with PyTorch 1.2\n\"\"\"\n\n\n######################################################################\n# This tutorial will walk through the process of transitioning a\n# sequence-to-sequence model to TorchScript using the TorchScript\n# API. The model that we will convert is the chatbot model from the\n# `Chatbot tutorial <https://pytorch.org/tutorials/beginner/chatbot_tutorial.html>`__.\n# You can either treat this tutorial as a “Part 2” to the Chatbot tutorial\n# and deploy your own pretrained model, or you can start with this\n# document and use a pretrained model that we host. In the latter case,\n# you can reference the original Chatbot tutorial for details\n# regarding data preprocessing, model theory and definition, and model\n# training.\n#\n# What is TorchScript?\n# ----------------------------\n#\n# During the research and development phase of a deep learning-based\n# project, it is advantageous to interact with an **eager**, imperative\n# interface like PyTorch’s. This gives users the ability to write\n# familiar, idiomatic Python, allowing for the use of Python data\n# structures, control flow operations, print statements, and debugging\n# utilities. Although the eager interface is a beneficial tool for\n# research and experimentation applications, when it comes time to deploy\n# the model in a production environment, having a **graph**-based model\n# representation is very beneficial. A deferred graph representation\n# allows for optimizations such as out-of-order execution, and the ability\n# to target highly optimized hardware architectures. Also, a graph-based\n# representation enables framework-agnostic model exportation. PyTorch\n# provides mechanisms for incrementally converting eager-mode code into\n# TorchScript, a statically analyzable and optimizable subset of Python\n# that Torch uses to represent deep learning programs independently from\n# the Python runtime.\n#\n# The API for converting eager-mode PyTorch programs into TorchScript is\n# found in the torch.jit module. This module has two core modalities for\n# converting an eager-mode model to a TorchScript graph representation:\n# **tracing** and **scripting**. The ``torch.jit.trace`` function takes a\n# module or function and a set of example inputs. It then runs the example\n# input through the function or module while tracing the computational\n# steps that are encountered, and outputs a graph-based function that\n# performs the traced operations. **Tracing** is great for straightforward\n# modules and functions that do not involve data-dependent control flow,\n# such as standard convolutional neural networks. However, if a function\n# with data-dependent if statements and loops is traced, only the\n# operations called along the execution route taken by the example input\n# will be recorded. In other words, the control flow itself is not\n# captured. To convert modules and functions containing data-dependent\n# control flow, a **scripting** mechanism is provided. The\n# ``torch.jit.script`` function/decorator takes a module or function and\n# does not requires example inputs. Scripting then explicitly converts\n# the module or function code to TorchScript, including all control flows.\n# One caveat with using scripting is that it only supports a subset of\n# Python, so you might need to rewrite the code to make it compatible\n# with the TorchScript syntax.\n#\n# For all details relating to the supported features, see the `TorchScript\n# language reference <https://pytorch.org/docs/master/jit.html>`__.\n# To provide the maximum flexibility, you can also mix tracing and scripting\n# modes together to represent your whole program, and these techniques can\n# be applied incrementally.\n#\n# .. figure:: /_static/img/chatbot/pytorch_workflow.png\n# :align: center\n# :alt: workflow\n#\n\n\n\n######################################################################\n# Acknowledgements\n# ----------------\n#\n# This tutorial was inspired by the following sources:\n#\n# 1) Yuan-Kuei Wu’s pytorch-chatbot implementation:\n# https://github.com/ywk991112/pytorch-chatbot\n#\n# 2) Sean Robertson’s practical-pytorch seq2seq-translation example:\n# https://github.com/spro/practical-pytorch/tree/master/seq2seq-translation\n#\n# 3) FloydHub’s Cornell Movie Corpus preprocessing code:\n# https://github.com/floydhub/textutil-preprocess-cornell-movie-corpus\n#\n\n\n######################################################################\n# Prepare Environment\n# -------------------\n#\n# First, we will import the required modules and set some constants. If\n# you are planning on using your own model, be sure that the\n# ``MAX_LENGTH`` constant is set correctly. As a reminder, this constant\n# defines the maximum allowed sentence length during training and the\n# maximum length output that the model is capable of producing.\n#\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport re\nimport os\nimport unicodedata\nimport numpy as np\n\ndevice = torch.device(\"cpu\")\n\n\nMAX_LENGTH = 10 # Maximum sentence length\n\n# Default word tokens\nPAD_token = 0 # Used for padding short sentences\nSOS_token = 1 # Start-of-sentence token\nEOS_token = 2 # End-of-sentence token\n\n\n######################################################################\n# Model Overview\n# --------------\n#\n# As mentioned, the model that we are using is a\n# `sequence-to-sequence <https://arxiv.org/abs/1409.3215>`__ (seq2seq)\n# model. This type of model is used in cases when our input is a\n# variable-length sequence, and our output is also a variable length\n# sequence that is not necessarily a one-to-one mapping of the input. A\n# seq2seq model is comprised of two recurrent neural networks (RNNs) that\n# work cooperatively: an **encoder** and a **decoder**.\n#\n# .. figure:: /_static/img/chatbot/seq2seq_ts.png\n# :align: center\n# :alt: model\n#\n#\n# Image source:\n# https://jeddy92.github.io/JEddy92.github.io/ts_seq2seq_intro/\n#\n# Encoder\n# ~~~~~~~\n#\n# The encoder RNN iterates through the input sentence one token\n# (e.g. word) at a time, at each time step outputting an “output” vector\n# and a “hidden state” vector. The hidden state vector is then passed to\n# the next time step, while the output vector is recorded. The encoder\n# transforms the context it saw at each point in the sequence into a set\n# of points in a high-dimensional space, which the decoder will use to\n# generate a meaningful output for the given task.\n#\n# Decoder\n# ~~~~~~~\n#\n# The decoder RNN generates the response sentence in a token-by-token\n# fashion. It uses the encoder’s context vectors, and internal hidden\n# states to generate the next word in the sequence. It continues\n# generating words until it outputs an *EOS_token*, representing the end\n# of the sentence. We use an `attention\n# mechanism <https://arxiv.org/abs/1409.0473>`__ in our decoder to help it\n# to “pay attention” to certain parts of the input when generating the\n# output. For our model, we implement `Luong et\n# al. <https://arxiv.org/abs/1508.04025>`__\\ ’s “Global attention” module,\n# and use it as a submodule in our decode model.\n#\n\n\n######################################################################\n# Data Handling\n# -------------\n#\n# Although our models conceptually deal with sequences of tokens, in\n# reality, they deal with numbers like all machine learning models do. In\n# this case, every word in the model’s vocabulary, which was established\n# before training, is mapped to an integer index. We use a ``Voc`` object\n# to contain the mappings from word to index, as well as the total number\n# of words in the vocabulary. We will load the object later before we run\n# the model.\n#\n# Also, in order for us to be able to run evaluations, we must provide a\n# tool for processing our string inputs. The ``normalizeString`` function\n# converts all characters in a string to lowercase and removes all\n# non-letter characters. The ``indexesFromSentence`` function takes a\n# sentence of words and returns the corresponding sequence of word\n# indexes.\n#\n\nclass Voc:\n def __init__(self, name):\n self.name = name\n self.trimmed = False\n self.word2index = {}\n self.word2count = {}\n self.index2word = {PAD_token: \"PAD\", SOS_token: \"SOS\", EOS_token: \"EOS\"}\n self.num_words = 3 # Count SOS, EOS, PAD\n\n def addSentence(self, sentence):\n for word in sentence.split(' '):\n self.addWord(word)\n\n def addWord(self, word):\n if word not in self.word2index:\n self.word2index[word] = self.num_words\n self.word2count[word] = 1\n self.index2word[self.num_words] = word\n self.num_words += 1\n else:\n self.word2count[word] += 1\n\n # Remove words below a certain count threshold\n def trim(self, min_count):\n if self.trimmed:\n return\n self.trimmed = True\n keep_words = []\n for k, v in self.word2count.items():\n if v >= min_count:\n keep_words.append(k)\n\n print('keep_words {} / {} = {:.4f}'.format(\n len(keep_words), len(self.word2index), len(keep_words) / len(self.word2index)\n ))\n # Reinitialize dictionaries\n self.word2index = {}\n self.word2count = {}\n self.index2word = {PAD_token: \"PAD\", SOS_token: \"SOS\", EOS_token: \"EOS\"}\n self.num_words = 3 # Count default tokens\n for word in keep_words:\n self.addWord(word)\n\n\n# Lowercase and remove non-letter characters\ndef normalizeString(s):\n s = s.lower()\n s = re.sub(r\"([.!?])\", r\" \\1\", s)\n s = re.sub(r\"[^a-zA-Z.!?]+\", r\" \", s)\n return s\n\n\n# Takes string sentence, returns sentence of word indexes\ndef indexesFromSentence(voc, sentence):\n return [voc.word2index[word] for word in sentence.split(' ')] + [EOS_token]\n\n\n######################################################################\n# Define Encoder\n# --------------\n#\n# We implement our encoder’s RNN with the ``torch.nn.GRU`` module which we\n# feed a batch of sentences (vectors of word embeddings) and it internally\n# iterates through the sentences one token at a time calculating the\n# hidden states. We initialize this module to be bidirectional, meaning\n# that we have two independent GRUs: one that iterates through the\n# sequences in chronological order, and another that iterates in reverse\n# order. We ultimately return the sum of these two GRUs’ outputs. Since\n# our model was trained using batching, our ``EncoderRNN`` model’s\n# ``forward`` function expects a padded input batch. To batch\n# variable-length sentences, we allow a maximum of *MAX_LENGTH* tokens in\n# a sentence, and all sentences in the batch that have less than\n# *MAX_LENGTH* tokens are padded at the end with our dedicated *PAD_token*\n# tokens. To use padded batches with a PyTorch RNN module, we must wrap\n# the forward pass call with ``torch.nn.utils.rnn.pack_padded_sequence``\n# and ``torch.nn.utils.rnn.pad_packed_sequence`` data transformations.\n# Note that the ``forward`` function also takes an ``input_lengths`` list,\n# which contains the length of each sentence in the batch. This input is\n# used by the ``torch.nn.utils.rnn.pack_padded_sequence`` function when\n# padding.\n#\n# TorchScript Notes:\n# ~~~~~~~~~~~~~~~~~~~~~~\n#\n# Since the encoder’s ``forward`` function does not contain any\n# data-dependent control flow, we will use **tracing** to convert it to\n# script mode. When tracing a module, we can leave the module definition\n# as-is. We will initialize all models towards the end of this document\n# before we run evaluations.\n#\n\nclass EncoderRNN(nn.Module):\n def __init__(self, hidden_size, embedding, n_layers=1, dropout=0):\n super(EncoderRNN, self).__init__()\n self.n_layers = n_layers\n self.hidden_size = hidden_size\n self.embedding = embedding\n\n # Initialize GRU; the input_size and hidden_size params are both set to 'hidden_size'\n # because our input size is a word embedding with number of features == hidden_size\n self.gru = nn.GRU(hidden_size, hidden_size, n_layers,\n dropout=(0 if n_layers == 1 else dropout), bidirectional=True)\n\n def forward(self, input_seq, input_lengths, hidden=None):\n # type: (Tensor, Tensor, Optional[Tensor]) -> Tuple[Tensor, Tensor]\n # Convert word indexes to embeddings\n embedded = self.embedding(input_seq)\n # Pack padded batch of sequences for RNN module\n packed = torch.nn.utils.rnn.pack_padded_sequence(embedded, input_lengths)\n # Forward pass through GRU\n outputs, hidden = self.gru(packed, hidden)\n # Unpack padding\n outputs, _ = torch.nn.utils.rnn.pad_packed_sequence(outputs)\n # Sum bidirectional GRU outputs\n outputs = outputs[:, :, :self.hidden_size] + outputs[:, : ,self.hidden_size:]\n # Return output and final hidden state\n return outputs, hidden\n\n\n######################################################################\n# Define Decoder’s Attention Module\n# ---------------------------------\n#\n# Next, we’ll define our attention module (``Attn``). Note that this\n# module will be used as a submodule in our decoder model. Luong et\n# al. consider various “score functions”, which take the current decoder\n# RNN output and the entire encoder output, and return attention\n# “energies”. This attention energies tensor is the same size as the\n# encoder output, and the two are ultimately multiplied, resulting in a\n# weighted tensor whose largest values represent the most important parts\n# of the query sentence at a particular time-step of decoding.\n#\n\n# Luong attention layer\nclass Attn(nn.Module):\n def __init__(self, method, hidden_size):\n super(Attn, self).__init__()\n self.method = method\n if self.method not in ['dot', 'general', 'concat']:\n raise ValueError(self.method, \"is not an appropriate attention method.\")\n self.hidden_size = hidden_size\n if self.method == 'general':\n self.attn = nn.Linear(self.hidden_size, hidden_size)\n elif self.method == 'concat':\n self.attn = nn.Linear(self.hidden_size * 2, hidden_size)\n self.v = nn.Parameter(torch.FloatTensor(hidden_size))\n\n def dot_score(self, hidden, encoder_output):\n return torch.sum(hidden * encoder_output, dim=2)\n\n def general_score(self, hidden, encoder_output):\n energy = self.attn(encoder_output)\n return torch.sum(hidden * energy, dim=2)\n\n def concat_score(self, hidden, encoder_output):\n energy = self.attn(torch.cat((hidden.expand(encoder_output.size(0), -1, -1), encoder_output), 2)).tanh()\n return torch.sum(self.v * energy, dim=2)\n\n def forward(self, hidden, encoder_outputs):\n # Calculate the attention weights (energies) based on the given method\n if self.method == 'general':\n attn_energies = self.general_score(hidden, encoder_outputs)\n elif self.method == 'concat':\n attn_energies = self.concat_score(hidden, encoder_outputs)\n elif self.method == 'dot':\n attn_energies = self.dot_score(hidden, encoder_outputs)\n\n # Transpose max_length and batch_size dimensions\n attn_energies = attn_energies.t()\n\n # Return the softmax normalized probability scores (with added dimension)\n return F.softmax(attn_energies, dim=1).unsqueeze(1)\n\n\n######################################################################\n# Define Decoder\n# --------------\n#\n# Similarly to the ``EncoderRNN``, we use the ``torch.nn.GRU`` module for\n# our decoder’s RNN. This time, however, we use a unidirectional GRU. It\n# is important to note that unlike the encoder, we will feed the decoder\n# RNN one word at a time. We start by getting the embedding of the current\n# word and applying a\n# `dropout <https://pytorch.org/docs/stable/nn.html?highlight=dropout#torch.nn.Dropout>`__.\n# Next, we forward the embedding and the last hidden state to the GRU and\n# obtain a current GRU output and hidden state. We then use our ``Attn``\n# module as a layer to obtain the attention weights, which we multiply by\n# the encoder’s output to obtain our attended encoder output. We use this\n# attended encoder output as our ``context`` tensor, which represents a\n# weighted sum indicating what parts of the encoder’s output to pay\n# attention to. From here, we use a linear layer and softmax normalization\n# to select the next word in the output sequence.\n\n# TorchScript Notes:\n# ~~~~~~~~~~~~~~~~~~~~~~\n#\n# Similarly to the ``EncoderRNN``, this module does not contain any\n# data-dependent control flow. Therefore, we can once again use\n# **tracing** to convert this model to TorchScript after it\n# is initialized and its parameters are loaded.\n#\n\nclass LuongAttnDecoderRNN(nn.Module):\n def __init__(self, attn_model, embedding, hidden_size, output_size, n_layers=1, dropout=0.1):\n super(LuongAttnDecoderRNN, self).__init__()\n\n # Keep for reference\n self.attn_model = attn_model\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.n_layers = n_layers\n self.dropout = dropout\n\n # Define layers\n self.embedding = embedding\n self.embedding_dropout = nn.Dropout(dropout)\n self.gru = nn.GRU(hidden_size, hidden_size, n_layers, dropout=(0 if n_layers == 1 else dropout))\n self.concat = nn.Linear(hidden_size * 2, hidden_size)\n self.out = nn.Linear(hidden_size, output_size)\n\n self.attn = Attn(attn_model, hidden_size)\n\n def forward(self, input_step, last_hidden, encoder_outputs):\n # Note: we run this one step (word) at a time\n # Get embedding of current input word\n embedded = self.embedding(input_step)\n embedded = self.embedding_dropout(embedded)\n # Forward through unidirectional GRU\n rnn_output, hidden = self.gru(embedded, last_hidden)\n # Calculate attention weights from the current GRU output\n attn_weights = self.attn(rnn_output, encoder_outputs)\n # Multiply attention weights to encoder outputs to get new \"weighted sum\" context vector\n context = attn_weights.bmm(encoder_outputs.transpose(0, 1))\n # Concatenate weighted context vector and GRU output using Luong eq. 5\n rnn_output = rnn_output.squeeze(0)\n context = context.squeeze(1)\n concat_input = torch.cat((rnn_output, context), 1)\n concat_output = torch.tanh(self.concat(concat_input))\n # Predict next word using Luong eq. 6\n output = self.out(concat_output)\n output = F.softmax(output, dim=1)\n # Return output and final hidden state\n return output, hidden\n\n\n######################################################################\n# Define Evaluation\n# -----------------\n#\n# Greedy Search Decoder\n# ~~~~~~~~~~~~~~~~~~~~~\n#\n# As in the chatbot tutorial, we use a ``GreedySearchDecoder`` module to\n# facilitate the actual decoding process. This module has the trained\n# encoder and decoder models as attributes, and drives the process of\n# encoding an input sentence (a vector of word indexes), and iteratively\n# decoding an output response sequence one word (word index) at a time.\n#\n# Encoding the input sequence is straightforward: simply forward the\n# entire sequence tensor and its corresponding lengths vector to the\n# ``encoder``. It is important to note that this module only deals with\n# one input sequence at a time, **NOT** batches of sequences. Therefore,\n# when the constant **1** is used for declaring tensor sizes, this\n# corresponds to a batch size of 1. To decode a given decoder output, we\n# must iteratively run forward passes through our decoder model, which\n# outputs softmax scores corresponding to the probability of each word\n# being the correct next word in the decoded sequence. We initialize the\n# ``decoder_input`` to a tensor containing an *SOS_token*. After each pass\n# through the ``decoder``, we *greedily* append the word with the highest\n# softmax probability to the ``decoded_words`` list. We also use this word\n# as the ``decoder_input`` for the next iteration. The decoding process\n# terminates either if the ``decoded_words`` list has reached a length of\n# *MAX_LENGTH* or if the predicted word is the *EOS_token*.\n#\n# TorchScript Notes:\n# ~~~~~~~~~~~~~~~~~~~~~~\n#\n# The ``forward`` method of this module involves iterating over the range\n# of :math:`[0, max\\_length)` when decoding an output sequence one word at\n# a time. Because of this, we should use **scripting** to convert this\n# module to TorchScript. Unlike with our encoder and decoder models,\n# which we can trace, we must make some necessary changes to the\n# ``GreedySearchDecoder`` module in order to initialize an object without\n# error. In other words, we must ensure that our module adheres to the\n# rules of the TorchScript mechanism, and does not utilize any language\n# features outside of the subset of Python that TorchScript includes.\n#\n# To get an idea of some manipulations that may be required, we will go\n# over the diffs between the ``GreedySearchDecoder`` implementation from\n# the chatbot tutorial and the implementation that we use in the cell\n# below. Note that the lines highlighted in red are lines removed from the\n# original implementation and the lines highlighted in green are new.\n#\n# .. figure:: /_static/img/chatbot/diff.png\n# :align: center\n# :alt: diff\n#\n# Changes:\n# ^^^^^^^^\n#\n# - Added ``decoder_n_layers`` to the constructor arguments\n#\n# - This change stems from the fact that the encoder and decoder\n# models that we pass to this module will be a child of\n# ``TracedModule`` (not ``Module``). Therefore, we cannot access the\n# decoder’s number of layers with ``decoder.n_layers``. Instead, we\n# plan for this, and pass this value in during module construction.\n#\n#\n# - Store away new attributes as constants\n#\n# - In the original implementation, we were free to use variables from\n# the surrounding (global) scope in our ``GreedySearchDecoder``\\ ’s\n# ``forward`` method. However, now that we are using scripting, we\n# do not have this freedom, as the assumption with scripting is that\n# we cannot necessarily hold on to Python objects, especially when\n# exporting. An easy solution to this is to store these values from\n# the global scope as attributes to the module in the constructor,\n# and add them to a special list called ``__constants__`` so that\n# they can be used as literal values when constructing the graph in\n# the ``forward`` method. An example of this usage is on NEW line\n# 19, where instead of using the ``device`` and ``SOS_token`` global\n# values, we use our constant attributes ``self._device`` and\n# ``self._SOS_token``.\n#\n#\n# - Enforce types of ``forward`` method arguments\n#\n# - By default, all parameters to a TorchScript function are assumed\n# to be Tensor. If we need to pass an argument of a different type,\n# we can use function type annotations as introduced in `PEP\n# 3107 <https://www.python.org/dev/peps/pep-3107/>`__. In addition,\n# it is possible to declare arguments of different types using\n# MyPy-style type annotations (see\n# `doc <https://pytorch.org/docs/master/jit.html#types>`__).\n#\n#\n# - Change initialization of ``decoder_input``\n#\n# - In the original implementation, we initialized our\n# ``decoder_input`` tensor with ``torch.LongTensor([[SOS_token]])``.\n# When scripting, we are not allowed to initialize tensors in a\n# literal fashion like this. Instead, we can initialize our tensor\n# with an explicit torch function such as ``torch.ones``. In this\n# case, we can easily replicate the scalar ``decoder_input`` tensor\n# by multiplying 1 by our SOS_token value stored in the constant\n# ``self._SOS_token``.\n#\n\nclass GreedySearchDecoder(nn.Module):\n def __init__(self, encoder, decoder, decoder_n_layers):\n super(GreedySearchDecoder, self).__init__()\n self.encoder = encoder\n self.decoder = decoder\n self._device = device\n self._SOS_token = SOS_token\n self._decoder_n_layers = decoder_n_layers\n\n __constants__ = ['_device', '_SOS_token', '_decoder_n_layers']\n\n def forward(self, input_seq : torch.Tensor, input_length : torch.Tensor, max_length : int):\n # Forward input through encoder model\n encoder_outputs, encoder_hidden = self.encoder(input_seq, input_length)\n # Prepare encoder's final hidden layer to be first hidden input to the decoder\n decoder_hidden = encoder_hidden[:self._decoder_n_layers]\n # Initialize decoder input with SOS_token\n decoder_input = torch.ones(1, 1, device=self._device, dtype=torch.long) * self._SOS_token\n # Initialize tensors to append decoded words to\n all_tokens = torch.zeros([0], device=self._device, dtype=torch.long)\n all_scores = torch.zeros([0], device=self._device)\n # Iteratively decode one word token at a time\n for _ in range(max_length):\n # Forward pass through decoder\n decoder_output, decoder_hidden = self.decoder(decoder_input, decoder_hidden, encoder_outputs)\n # Obtain most likely word token and its softmax score\n decoder_scores, decoder_input = torch.max(decoder_output, dim=1)\n # Record token and score\n all_tokens = torch.cat((all_tokens, decoder_input), dim=0)\n all_scores = torch.cat((all_scores, decoder_scores), dim=0)\n # Prepare current token to be next decoder input (add a dimension)\n decoder_input = torch.unsqueeze(decoder_input, 0)\n # Return collections of word tokens and scores\n return all_tokens, all_scores\n\n\n\n######################################################################\n# Evaluating an Input\n# ~~~~~~~~~~~~~~~~~~~\n#\n# Next, we define some functions for evaluating an input. The ``evaluate``\n# function takes a normalized string sentence, processes it to a tensor of\n# its corresponding word indexes (with batch size of 1), and passes this\n# tensor to a ``GreedySearchDecoder`` instance called ``searcher`` to\n# handle the encoding/decoding process. The searcher returns the output\n# word index vector and a scores tensor corresponding to the softmax\n# scores for each decoded word token. The final step is to convert each\n# word index back to its string representation using ``voc.index2word``.\n#\n# We also define two functions for evaluating an input sentence. The\n# ``evaluateInput`` function prompts a user for an input, and evaluates\n# it. It will continue to ask for another input until the user enters ‘q’\n# or ‘quit’.\n#\n# The ``evaluateExample`` function simply takes a string input sentence as\n# an argument, normalizes it, evaluates it, and prints the response.\n#\n\ndef evaluate(searcher, voc, sentence, max_length=MAX_LENGTH):\n ### Format input sentence as a batch\n # words -> indexes\n indexes_batch = [indexesFromSentence(voc, sentence)]\n # Create lengths tensor\n lengths = torch.tensor([len(indexes) for indexes in indexes_batch])\n # Transpose dimensions of batch to match models' expectations\n input_batch = torch.LongTensor(indexes_batch).transpose(0, 1)\n # Use appropriate device\n input_batch = input_batch.to(device)\n lengths = lengths.to(device)\n # Decode sentence with searcher\n tokens, scores = searcher(input_batch, lengths, max_length)\n # indexes -> words\n decoded_words = [voc.index2word[token.item()] for token in tokens]\n return decoded_words\n\n\n# Evaluate inputs from user input (stdin)\ndef evaluateInput(searcher, voc):\n input_sentence = ''\n while(1):\n try:\n # Get input sentence\n input_sentence = input('> ')\n # Check if it is quit case\n if input_sentence == 'q' or input_sentence == 'quit': break\n # Normalize sentence\n input_sentence = normalizeString(input_sentence)\n # Evaluate sentence\n output_words = evaluate(searcher, voc, input_sentence)\n # Format and print response sentence\n output_words[:] = [x for x in output_words if not (x == 'EOS' or x == 'PAD')]\n print('Bot:', ' '.join(output_words))\n\n except KeyError:\n print(\"Error: Encountered unknown word.\")\n\n# Normalize input sentence and call evaluate()\ndef evaluateExample(sentence, searcher, voc):\n print(\"> \" + sentence)\n # Normalize sentence\n input_sentence = normalizeString(sentence)\n # Evaluate sentence\n output_words = evaluate(searcher, voc, input_sentence)\n output_words[:] = [x for x in output_words if not (x == 'EOS' or x == 'PAD')]\n print('Bot:', ' '.join(output_words))\n\n\n######################################################################\n# Load Pretrained Parameters\n# --------------------------\n#\n# Ok, its time to load our model!\n#\n# Use hosted model\n# ~~~~~~~~~~~~~~~~\n#\n# To load the hosted model:\n#\n# 1) Download the model `here <https://download.pytorch.org/models/tutorials/4000_checkpoint.tar>`__.\n#\n# 2) Set the ``loadFilename`` variable to the path to the downloaded\n# checkpoint file.\n#\n# 3) Leave the ``checkpoint = torch.load(loadFilename)`` line uncommented,\n# as the hosted model was trained on CPU.\n#\n# Use your own model\n# ~~~~~~~~~~~~~~~~~~\n#\n# To load your own pre-trained model:\n#\n# 1) Set the ``loadFilename`` variable to the path to the checkpoint file\n# that you wish to load. Note that if you followed the convention for\n# saving the model from the chatbot tutorial, this may involve changing\n# the ``model_name``, ``encoder_n_layers``, ``decoder_n_layers``,\n# ``hidden_size``, and ``checkpoint_iter`` (as these values are used in\n# the model path).\n#\n# 2) If you trained the model on a CPU, make sure that you are opening the\n# checkpoint with the ``checkpoint = torch.load(loadFilename)`` line.\n# If you trained the model on a GPU and are running this tutorial on a\n# CPU, uncomment the\n# ``checkpoint = torch.load(loadFilename, map_location=torch.device('cpu'))``\n# line.\n#\n# TorchScript Notes:\n# ~~~~~~~~~~~~~~~~~~~~~~\n#\n# Notice that we initialize and load parameters into our encoder and\n# decoder models as usual. If you are using tracing mode(`torch.jit.trace`)\n# for some part of your models, you must call .to(device) to set the device\n# options of the models and .eval() to set the dropout layers to test mode\n# **before** tracing the models. `TracedModule` objects do not inherit the\n# ``to`` or ``eval`` methods. Since in this tutorial we are only using\n# scripting instead of tracing, we only need to do this before we do\n# evaluation (which is the same as we normally do in eager mode).\n#\n\nsave_dir = os.path.join(\"data\", \"save\")\ncorpus_name = \"cornell movie-dialogs corpus\"\n\n# Configure models\nmodel_name = 'cb_model'\nattn_model = 'dot'\n#attn_model = 'general'\n#attn_model = 'concat'\nhidden_size = 500\nencoder_n_layers = 2\ndecoder_n_layers = 2\ndropout = 0.1\nbatch_size = 64\n\n# If you're loading your own model\n# Set checkpoint to load from\ncheckpoint_iter = 4000\n# loadFilename = os.path.join(save_dir, model_name, corpus_name,\n# '{}-{}_{}'.format(encoder_n_layers, decoder_n_layers, hidden_size),\n# '{}_checkpoint.tar'.format(checkpoint_iter))\n\n# If you're loading the hosted model\nloadFilename = 'data/4000_checkpoint.tar'\n\n# Load model\n# Force CPU device options (to match tensors in this tutorial)\ncheckpoint = torch.load(loadFilename, map_location=torch.device('cpu'))\nencoder_sd = checkpoint['en']\ndecoder_sd = checkpoint['de']\nencoder_optimizer_sd = checkpoint['en_opt']\ndecoder_optimizer_sd = checkpoint['de_opt']\nembedding_sd = checkpoint['embedding']\nvoc = Voc(corpus_name)\nvoc.__dict__ = checkpoint['voc_dict']\n\n\nprint('Building encoder and decoder ...')\n# Initialize word embeddings\nembedding = nn.Embedding(voc.num_words, hidden_size)\nembedding.load_state_dict(embedding_sd)\n# Initialize encoder & decoder models\nencoder = EncoderRNN(hidden_size, embedding, encoder_n_layers, dropout)\ndecoder = LuongAttnDecoderRNN(attn_model, embedding, hidden_size, voc.num_words, decoder_n_layers, dropout)\n# Load trained model params\nencoder.load_state_dict(encoder_sd)\ndecoder.load_state_dict(decoder_sd)\n# Use appropriate device\nencoder = encoder.to(device)\ndecoder = decoder.to(device)\n# Set dropout layers to eval mode\nencoder.eval()\ndecoder.eval()\nprint('Models built and ready to go!')\n\n\n######################################################################\n# Convert Model to TorchScript\n# -----------------------------\n#\n# Encoder\n# ~~~~~~~\n#\n# As previously mentioned, to convert the encoder model to TorchScript,\n# we use **scripting**. The encoder model takes an input sequence and\n# a corresponding lengths tensor. Therefore, we create an example input\n# sequence tensor ``test_seq``, which is of appropriate size (MAX_LENGTH,\n# 1), contains numbers in the appropriate range\n# :math:`[0, voc.num\\_words)`, and is of the appropriate type (int64). We\n# also create a ``test_seq_length`` scalar which realistically contains\n# the value corresponding to how many words are in the ``test_seq``. The\n# next step is to use the ``torch.jit.trace`` function to trace the model.\n# Notice that the first argument we pass is the module that we want to\n# trace, and the second is a tuple of arguments to the module’s\n# ``forward`` method.\n#\n# Decoder\n# ~~~~~~~\n#\n# We perform the same process for tracing the decoder as we did for the\n# encoder. Notice that we call forward on a set of random inputs to the\n# traced_encoder to get the output that we need for the decoder. This is\n# not required, as we could also simply manufacture a tensor of the\n# correct shape, type, and value range. This method is possible because in\n# our case we do not have any constraints on the values of the tensors\n# because we do not have any operations that could fault on out-of-range\n# inputs.\n#\n# GreedySearchDecoder\n# ~~~~~~~~~~~~~~~~~~~\n#\n# Recall that we scripted our searcher module due to the presence of\n# data-dependent control flow. In the case of scripting, we do necessary\n# language changes to make sure the implementation complies with\n# TorchScript. We initialize the scripted searcher the same way that we\n# would initialize an un-scripted variant.\n#\n\n### Compile the whole greedy search model to TorchScript model\n# Create artificial inputs\ntest_seq = torch.LongTensor(MAX_LENGTH, 1).random_(0, voc.num_words).to(device)\ntest_seq_length = torch.LongTensor([test_seq.size()[0]]).to(device)\n# Trace the model\ntraced_encoder = torch.jit.trace(encoder, (test_seq, test_seq_length))\n\n### Convert decoder model\n# Create and generate artificial inputs\ntest_encoder_outputs, test_encoder_hidden = traced_encoder(test_seq, test_seq_length)\ntest_decoder_hidden = test_encoder_hidden[:decoder.n_layers]\ntest_decoder_input = torch.LongTensor(1, 1).random_(0, voc.num_words)\n# Trace the model\ntraced_decoder = torch.jit.trace(decoder, (test_decoder_input, test_decoder_hidden, test_encoder_outputs))\n\n### Initialize searcher module by wrapping ``torch.jit.script`` call\nscripted_searcher = torch.jit.script(GreedySearchDecoder(traced_encoder, traced_decoder, decoder.n_layers))\n\n\n\n\n######################################################################\n# Print Graphs\n# ------------\n#\n# Now that our models are in TorchScript form, we can print the graphs of\n# each to ensure that we captured the computational graph appropriately.\n# Since TorchScript allow us to recursively compile the whole model\n# hierarchy and inline the ``encoder`` and ``decoder`` graph into a single\n# graph, we just need to print the `scripted_searcher` graph\n\nprint('scripted_searcher graph:\\n', scripted_searcher.graph)\n\n\n######################################################################\n# Run Evaluation\n# --------------\n#\n# Finally, we will run evaluation of the chatbot model using the TorchScript\n# models. If converted correctly, the models will behave exactly as they\n# would in their eager-mode representation.\n#\n# By default, we evaluate a few common query sentences. If you want to\n# chat with the bot yourself, uncomment the ``evaluateInput`` line and\n# give it a spin.\n#\n\n\n# Use appropriate device\nscripted_searcher.to(device)\n# Set dropout layers to eval mode\nscripted_searcher.eval()\n\n# Evaluate examples\nsentences = [\"hello\", \"what's up?\", \"who are you?\", \"where am I?\", \"where are you from?\"]\nfor s in sentences:\n evaluateExample(s, scripted_searcher, voc)\n\n# Evaluate your input\n#evaluateInput(traced_encoder, traced_decoder, scripted_searcher, voc)\n\n\n######################################################################\n# Save Model\n# ----------\n#\n# Now that we have successfully converted our model to TorchScript, we\n# will serialize it for use in a non-Python deployment environment. To do\n# this, we can simply save our ``scripted_searcher`` module, as this is\n# the user-facing interface for running inference against the chatbot\n# model. When saving a Script module, use script_module.save(PATH) instead\n# of torch.save(model, PATH).\n#\n\nscripted_searcher.save(\"scripted_chatbot.pth\")\n"
]
| [
[
"torch.nn.Linear",
"torch.device",
"torch.nn.Dropout",
"torch.cat",
"torch.zeros",
"torch.nn.GRU",
"torch.nn.functional.softmax",
"torch.max",
"torch.FloatTensor",
"torch.ones",
"torch.unsqueeze",
"torch.nn.utils.rnn.pad_packed_sequence",
"torch.LongTensor",
"torch.nn.utils.rnn.pack_padded_sequence",
"torch.jit.trace",
"torch.nn.Embedding",
"torch.sum"
]
]
|
Ghost---Shadow/gpt-neox | [
"1391b197ac79b8d4b88a0e97d1e98371d8b61fef"
]
| [
"megatron/model/transformer.py"
]
| [
"# coding=utf-8\n#\n# Copyright 2021 Biderman et al. This file is based on code by the authors denoted below and has been modified from its original version.\n#\n# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Transformer.\"\"\"\n\nimport math\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\n\nfrom .norms import get_norm\nfrom megatron import mpu\nfrom megatron.model.fused_softmax import FusedScaleMaskSoftmax\nfrom megatron.model.activations import get_activation\nfrom megatron.model.utils import exists, get_fusion_type\nfrom megatron.model.positional_embeddings import (\n RotaryEmbedding,\n apply_rotary_pos_emb,\n apply_rotary_pos_emb_torch,\n AliBi,\n)\nfrom megatron.model.fused_bias_dropout import (\n get_bias_dropout_add,\n bias_dropout_add_fused_train,\n bias_dropout_add_fused_inference,\n)\nfrom megatron.model.utils import configure_sparse_attention\n\n# flags required to enable jit fusion kernels\ntorch._C._jit_set_profiling_mode(False)\ntorch._C._jit_set_profiling_executor(False)\ntorch._C._jit_override_can_fuse_on_cpu(True)\ntorch._C._jit_override_can_fuse_on_gpu(True)\n\n\"\"\" We use the following notation throughout this file:\n h: hidden size\n n: number of attention heads\n p: number of model parallel partitions\n np: n/p\n hp: h/p\n hn: h/n\n b: batch size\n s: sequence length\n l: number of layers\n Transformer takes input of size [s, b, h] and returns a\n tensor of the same size. We use the following arguments:\n hyperparameters: transformer hyperparameters\n attention_mask_func: a function that takes `unmasked-attention-scores`\n with size [b, np, s, s] and an `attention-mask` and will apply\n the masking. The function should return a masked score of the\n same size [b, np, s, s].\n masked-attention-scores = attention_mask_func(\n unmasked-attention-scores, attention-mask)\n\"\"\"\n\n\nclass ParallelMLP(nn.Module):\n \"\"\"MLP.\n\n MLP will take the input with h hidden state, project it to 4*h\n hidden dimension, perform nonlinear transformation, and project the\n state back into h hidden dimension. At the end, dropout is also\n applied.\n \"\"\"\n\n def __init__(\n self, neox_args, init_method, output_layer_init_method, parallel_output=False\n ):\n super().__init__()\n\n self.activation_func = get_activation(neox_args)\n self.activation_type = neox_args.activation\n self.bias_gelu_fusion = neox_args.bias_gelu_fusion\n\n # auto scale so geglu has equal parameters\n ff_mult = 4 * 2 / 3 if self.activation_type == \"geglu\" else 4\n ff_dim = (\n int(ff_mult * neox_args.hidden_size) * 2\n if self.activation_type == \"geglu\"\n else ff_mult * neox_args.hidden_size\n )\n self.dense_h_to_4h = mpu.ColumnParallelLinear(\n neox_args=neox_args,\n input_size=neox_args.hidden_size,\n output_size=ff_dim,\n gather_output=False,\n init_method=init_method,\n skip_bias_add=True,\n )\n ff_dim_in = ff_dim // 2 if self.activation_type == \"geglu\" else ff_dim\n # Project back to h.\n self.dense_4h_to_h = mpu.RowParallelLinear(\n neox_args=neox_args,\n input_size=ff_dim_in,\n output_size=neox_args.hidden_size,\n input_is_parallel=True,\n init_method=output_layer_init_method,\n skip_bias_add=True,\n parallel_output=parallel_output,\n )\n\n def forward(self, hidden_states):\n\n # [s, b, 4hp]\n intermediate_parallel, bias_parallel = self.dense_h_to_4h(hidden_states)\n\n if (\n self.activation_type == \"gelu\" and self.bias_gelu_fusion\n ) or self.activation_type == \"geglu\":\n intermediate_parallel = self.activation_func(\n intermediate_parallel, bias_parallel\n )\n else:\n intermediate_parallel = self.activation_func(\n intermediate_parallel + bias_parallel\n )\n\n # [s, b, h]\n output, output_bias = self.dense_4h_to_h(intermediate_parallel)\n return output, output_bias\n\n\nclass ParallelLinear(nn.Module):\n \"\"\"\n A Parallel Linear Layer transforming the transformer outputs from hidden_size -> vocab_size\n \"\"\"\n\n def __init__(\n self,\n neox_args,\n parallel_output=True,\n inference=False,\n init_method=nn.init.xavier_normal_,\n ):\n super().__init__()\n parallelism = neox_args.output_layer_parallelism\n if parallelism == \"column\":\n self.final_linear = mpu.ColumnParallelLinear(\n neox_args=neox_args,\n input_size=neox_args.hidden_size,\n output_size=neox_args.padded_vocab_size,\n bias=False,\n init_method=init_method,\n gather_output=not parallel_output,\n skip_bias_add=False,\n )\n else:\n self.final_linear = mpu.RowParallelLinear(\n neox_args=neox_args,\n input_size=neox_args.hidden_size,\n output_size=neox_args.padded_vocab_size,\n bias=False,\n input_is_parallel=False,\n init_method=init_method,\n parallel_output=False if inference else parallel_output,\n skip_bias_add=False,\n )\n\n def forward(self, hidden_states):\n return self.final_linear(hidden_states)\n\n\nclass ParallelSelfAttention(nn.Module):\n \"\"\"Parallel self-attention layer abstract class.\n\n Self-attention layer takes input with size [b, s, h]\n and returns output of the same size.\n \"\"\"\n\n def __init__(\n self,\n neox_args,\n attention_mask_func,\n init_method,\n output_layer_init_method,\n layer_number,\n rpe=None,\n rotary=False,\n get_key_value=False,\n parallel_output=False,\n ):\n super().__init__()\n\n self.fp16 = neox_args.precision == \"fp16\"\n self.bf16 = neox_args.precision == \"bfloat16\"\n self.attention_mask_func = attention_mask_func\n self.apply_query_key_layer_scaling = neox_args.apply_query_key_layer_scaling\n self.get_key_value = get_key_value\n self.attention_softmax_in_fp32 = neox_args.attention_softmax_in_fp32\n if self.apply_query_key_layer_scaling:\n self.attention_softmax_in_fp32 = True\n self.layer_number = layer_number\n # Per attention head and per partition values.\n world_size = mpu.get_model_parallel_world_size()\n self.hidden_size_per_partition = mpu.divide(neox_args.hidden_size, world_size)\n self.hidden_size_per_attention_head = mpu.divide(\n neox_args.hidden_size, neox_args.num_attention_heads\n )\n self.num_attention_heads_per_partition = mpu.divide(\n neox_args.num_attention_heads, world_size\n )\n self.pos_emb = neox_args.pos_emb\n\n # Strided linear layer.\n self.query_key_value = mpu.ColumnParallelLinear(\n neox_args=neox_args,\n input_size=neox_args.hidden_size,\n output_size=3 * neox_args.hidden_size,\n gather_output=False,\n init_method=init_method,\n )\n\n coeff = None\n self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)\n if self.apply_query_key_layer_scaling:\n coeff = max(1, self.layer_number)\n self.norm_factor *= coeff\n\n self.rpe = rpe\n\n if self.pos_emb == \"alibi\":\n self.alibi_embed = AliBi(\n neox_args.num_attention_heads,\n neox_args.model_parallel_size,\n mpu.get_model_parallel_rank(),\n )\n\n # TODO: this arg shouldn't need to be passed in - get from neox_args\n if rotary:\n if neox_args.rotary_pct == 1:\n self.rotary_ndims = None\n else:\n assert neox_args.rotary_pct < 1\n self.rotary_ndims = int(\n self.hidden_size_per_attention_head * neox_args.rotary_pct\n )\n dim = (\n self.rotary_ndims\n if self.rotary_ndims is not None\n else self.hidden_size_per_attention_head\n )\n self.rotary_emb = RotaryEmbedding(\n dim, base=neox_args.rotary_emb_base, precision=neox_args.params_dtype\n )\n else:\n self.rotary_emb = None\n\n self.attention_type = neox_args.attention_config[layer_number]\n self.sparse = self.attention_type != \"global\"\n if self.sparse:\n self.sparse_attn = configure_sparse_attention(\n neox_args,\n self.attention_type,\n self.num_attention_heads_per_partition,\n mpu=mpu,\n )\n else:\n self.scale_mask_softmax = FusedScaleMaskSoftmax(\n input_in_fp16=self.fp16,\n input_in_bf16=self.bf16,\n fusion_type=get_fusion_type(neox_args),\n mask_func=self.attention_mask_func,\n softmax_in_fp32=self.attention_softmax_in_fp32,\n scale=coeff,\n )\n\n # Dropout. Note that for a single iteration, this layer will generate\n # different outputs on different number of parallel partitions but\n # on average it should not be partition dependent.\n self.attention_dropout = nn.Dropout(neox_args.attention_dropout)\n\n # Output.\n self.dense = mpu.RowParallelLinear(\n neox_args=neox_args,\n input_size=neox_args.hidden_size,\n output_size=neox_args.hidden_size,\n input_is_parallel=True,\n init_method=output_layer_init_method,\n skip_bias_add=True,\n parallel_output=parallel_output,\n )\n\n def attention(\n self, query_layer, key_layer, value_layer, layer_past, attention_mask\n ):\n # ===================================\n # Raw attention scores. [b, np, s, s]\n # ===================================\n\n # [b, np, sq, sk]\n output_size = (\n query_layer.size(1),\n query_layer.size(2),\n query_layer.size(0),\n key_layer.size(0),\n )\n\n # [sq, b, np, hn] -> [sq, b * np, hn]\n query_layer = query_layer.view(\n output_size[2], output_size[0] * output_size[1], -1\n )\n key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)\n\n # preallocating result tensor: [b * np, sq, sk]\n matmul_result = torch.empty(\n output_size[0] * output_size[1],\n output_size[2],\n output_size[3],\n dtype=query_layer.dtype,\n device=torch.cuda.current_device(),\n )\n\n # Raw attention scores. [b * np, sq, sk]\n matmul_result = torch.baddbmm(\n matmul_result,\n query_layer.transpose(0, 1), # [b * np, sq, hn]\n key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]\n beta=0.0,\n alpha=(1.0 / self.norm_factor),\n )\n\n # change view to [b, np, sq, sk]\n attention_scores = matmul_result.view(*output_size)\n\n # ==================================================\n # Update attention mask for inference. [b, np, sq, sk]\n # ==================================================\n\n if self.get_key_value:\n with torch.no_grad():\n if layer_past is not None and layer_past.numel() > 0:\n attention_mask = attention_mask[\n ..., attention_scores.size(3) - 1, : attention_scores.size(3)\n ].unsqueeze(2)\n else:\n attention_mask = attention_mask[\n ..., : attention_scores.size(3), : attention_scores.size(3)\n ]\n\n # ===========================\n # Attention probs and dropout\n # ===========================\n\n if exists(self.rpe):\n rpe = self.rpe(query_layer.size(0), key_layer.size(0))\n attention_scores += rpe # [1, np, sq, sk]\n\n if self.pos_emb == \"alibi\":\n attention_scores = self.alibi_embed(attention_scores)\n\n # attention scores and attention mask [b, np, sq, sk]\n attention_probs = self.scale_mask_softmax(attention_scores, attention_mask)\n\n # This is actually dropping out entire tokens to attend to, which might\n # seem a bit unusual, but is taken from the original Transformer paper.\n with mpu.get_cuda_rng_tracker().fork():\n attention_probs = self.attention_dropout(attention_probs)\n\n # =========================\n # Context layer. [sq, b, hp]\n # =========================\n\n # value_layer -> context layer.\n # [sk, b, np, hn] --> [b, np, sq, hn]\n\n # context layer shape: [b, np, sq, hn]\n output_size = (\n value_layer.size(1),\n value_layer.size(2),\n query_layer.size(0),\n value_layer.size(3),\n )\n\n # change view [sk, b * np, hn]\n value_layer = value_layer.view(\n value_layer.size(0), output_size[0] * output_size[1], -1\n )\n\n # change view [b * np, sq, sk]\n attention_probs = attention_probs.view(\n output_size[0] * output_size[1], output_size[2], -1\n )\n\n # matmul: [b * np, sq, hn]\n context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))\n\n # change view [b, np, sq, hn]\n context_layer = context_layer.view(*output_size)\n return context_layer\n\n def sparse_attention(self, query_layer, key_layer, value_layer, attention_mask):\n # TODO: sparse attn dropout?\n # TODO: pad to block size\n # shape of q/k/v is [sq, b, np, hn] and needs to be transposed to [b, np, sq, hn]\n query_layer, key_layer, value_layer = map(\n lambda t: t.permute(1, 2, 0, 3).contiguous(),\n (query_layer, key_layer, value_layer),\n )\n # output shape [b, np(heads), sq, hn]\n attn_mask = attention_mask.to(query_layer.dtype) * -10000\n if exists(self.rpe):\n rpe = self.rpe(query_layer.size(0), key_layer.size(0))\n else:\n rpe = None\n return self.sparse_attn(\n query_layer, key_layer, value_layer, attn_mask=attn_mask, rpe=rpe\n )\n\n def forward(self, hidden_states, attention_mask, layer_past=None):\n\n # hidden_states: [sq, b, h]\n\n # =====================\n # Query, Key, and Value\n # =====================\n\n # Attention heads [sq, b, h] --> [sq, b, (np * 3 * hn)]\n mixed_x_layer, _ = self.query_key_value(hidden_states)\n\n # [sq, b, (np * 3 * hn)] --> [sq, b, np, 3 * hn]\n new_tensor_shape = mixed_x_layer.size()[:-1] + (\n self.num_attention_heads_per_partition,\n 3 * self.hidden_size_per_attention_head,\n )\n mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)\n\n # [sq, b, np, 3 * hn] --> 3 [sq, b, np, hn]\n (query_layer, key_layer, value_layer) = mpu.split_tensor_along_last_dim(\n mixed_x_layer, 3\n )\n\n if exists(self.rotary_emb):\n if exists(self.rotary_ndims):\n # partial rotary\n query_rot, query_pass = (\n query_layer[..., : self.rotary_ndims],\n query_layer[..., self.rotary_ndims :],\n )\n key_rot, key_pass = (\n key_layer[..., : self.rotary_ndims],\n key_layer[..., self.rotary_ndims :],\n )\n else:\n # full rotary\n query_rot, key_rot = query_layer, key_layer\n apply_rotary_fn = (\n apply_rotary_pos_emb_torch if self.bf16 else apply_rotary_pos_emb\n )\n\n seq_len = key_layer.shape[0]\n offset = 0\n if exists(layer_past) and layer_past.numel() > 0:\n offset = layer_past[0].shape[0]\n seq_len += offset\n cos, sin = self.rotary_emb(value_layer, seq_len=seq_len)\n query_layer, key_layer = apply_rotary_fn(\n query_rot, key_rot, cos, sin, offset=offset\n )\n\n if exists(self.rotary_ndims):\n query_layer = torch.cat((query_layer, query_pass), dim=-1)\n key_layer = torch.cat((key_layer, key_pass), dim=-1)\n\n # ==================================\n # Cache key and value for inference\n # ==================================\n\n if exists(layer_past) and layer_past.numel() > 0:\n past_key, past_value = layer_past\n key_layer = torch.cat((past_key.type_as(key_layer), key_layer), dim=0)\n value_layer = torch.cat(\n (past_value.type_as(value_layer), value_layer), dim=0\n )\n\n if self.get_key_value:\n present = torch.stack((key_layer, value_layer))\n\n if not self.sparse:\n context_layer = self.attention(\n query_layer, key_layer, value_layer, layer_past, attention_mask\n )\n else:\n context_layer = self.sparse_attention(\n query_layer, key_layer, value_layer, attention_mask\n )\n\n # [b, np, sq, hn] --> [sq, b, np, hn]\n context_layer = context_layer.permute(2, 0, 1, 3).contiguous()\n\n # [sq, b, np, hn] --> [sq, b, hp]\n new_context_layer_shape = context_layer.size()[:-2] + (\n self.hidden_size_per_partition,\n )\n context_layer = context_layer.view(*new_context_layer_shape)\n\n # =================\n # Output. [sq, b, h]\n # =================\n\n output, bias = self.dense(context_layer)\n\n if self.get_key_value:\n output = [output, present]\n\n return output, bias\n\n\nclass ParallelTransformerLayer(nn.Module):\n \"\"\"A single transformer layer.\n\n Transformer layer takes input with size [b, s, h] and returns an\n output of the same size.\n \"\"\"\n\n def __init__(\n self,\n neox_args,\n attention_mask_func,\n init_method,\n output_layer_init_method,\n layer_number,\n rpe=None,\n rotary=False,\n get_key_value=False,\n ):\n\n super().__init__()\n self.layer_number = layer_number\n\n norm, eps = get_norm(neox_args)\n\n # Layernorm on the input data.\n self.input_layernorm = norm(neox_args.hidden_size, eps=eps)\n self.get_key_value = get_key_value\n\n self.hidden_dropout = neox_args.hidden_dropout\n self.bias_dropout_fusion = neox_args.bias_dropout_fusion\n self.gpt_j_residual = neox_args.gpt_j_residual\n\n if self.gpt_j_residual:\n self.reduce = mpu.mappings.reduce_from_model_parallel_region\n\n # Self attention.\n self.attention = ParallelSelfAttention(\n neox_args=neox_args,\n attention_mask_func=attention_mask_func,\n init_method=init_method,\n output_layer_init_method=output_layer_init_method,\n layer_number=layer_number,\n rpe=rpe,\n get_key_value=self.get_key_value,\n rotary=rotary,\n parallel_output=self.gpt_j_residual,\n )\n\n # Layernorm on the output of the attention layer.\n self.post_attention_layernorm = norm(neox_args.hidden_size, eps=eps)\n\n # MLP\n self.mlp = ParallelMLP(\n neox_args=neox_args,\n init_method=init_method,\n output_layer_init_method=output_layer_init_method,\n parallel_output=self.gpt_j_residual,\n )\n\n def _get_bias_dropout(self):\n if self.bias_dropout_fusion:\n fn = (\n bias_dropout_add_fused_train\n if self.training\n else bias_dropout_add_fused_inference\n )\n else:\n fn = get_bias_dropout_add(self.training)\n return fn\n\n def forward(self, x, attention_mask, layer_past=None):\n bias_dropout_fn = self._get_bias_dropout()\n # x: [b, s, h]\n if self.gpt_j_residual:\n # pseudocode:\n # x = x + attn(ln1(x)) + mlp(ln2(x))\n # this means we can avoid doing the allreduce in the attn / mlp outputs\n # to save communication time (we can do a single allreduce after we add mlp / attn outputs).\n \n # attention_output = attn(ln1(x))\n residual = x\n attention_output, attention_bias = self.attention(\n self.input_layernorm(x), attention_mask, layer_past=layer_past\n )\n if self.get_key_value:\n attention_output, presents = attention_output\n\n with torch.enable_grad():\n attention_output = bias_dropout_fn(\n attention_output,\n bias=attention_bias.expand_as(attention_output),\n residual=None,\n prob=self.hidden_dropout,\n )\n\n # output = mlp(ln2(x)) + attention_output\n mlp_output, mlp_bias = self.mlp(self.post_attention_layernorm(x))\n with torch.enable_grad():\n output = bias_dropout_fn(\n mlp_output,\n bias=mlp_bias.expand_as(mlp_output),\n residual=attention_output,\n prob=self.hidden_dropout,\n )\n\n # output = output + residual\n output = residual + self.reduce(output)\n else:\n # pseudocode:\n # x = x + attn(ln1(x))\n # x = x + mlp(ln2(x))\n\n residual = x\n\n # x = x + attn(ln1(x))\n attention_output, attention_bias = self.attention(\n self.input_layernorm(x), attention_mask, layer_past=layer_past\n )\n if self.get_key_value:\n attention_output, presents = attention_output\n with torch.enable_grad():\n attention_output = bias_dropout_fn(\n attention_output,\n bias=attention_bias.expand_as(residual),\n residual=residual,\n prob=self.hidden_dropout,\n )\n\n # output = x + mlp(ln2(x))\n mlp_output, mlp_bias = self.mlp(\n self.post_attention_layernorm(attention_output)\n )\n with torch.enable_grad():\n output = bias_dropout_fn(\n mlp_output,\n bias=mlp_bias.expand_as(attention_output),\n residual=attention_output,\n prob=self.hidden_dropout,\n )\n\n if self.get_key_value:\n output = [output, presents]\n\n return output\n\n\nclass ParallelTransformerLayerPipe(ParallelTransformerLayer):\n \"\"\"Extends ParallelTransformerLayer to forward attention_mask through the pipeline. \"\"\"\n\n def forward(self, args):\n in_inference = len(args) == 4 # length of the args in inference == 4\n in_train = len(args) == 2 # length of the args in training == 2\n if in_train:\n hidden_states, attention_mask = args\n # we are returning just [hidden_states, mask]\n return super().forward(hidden_states, attention_mask), attention_mask\n elif in_inference:\n # we are in inference\n hidden_states, layer_past, presents, attention_mask = args\n past = torch.Tensor()\n if layer_past is not None and layer_past.numel() > 0:\n past = layer_past[self.layer_number]\n outputs = super().forward(hidden_states, attention_mask, layer_past=past)\n\n if self.get_key_value:\n # outputs = [hidden_states, present]\n hidden_states, present = outputs\n if presents.numel() == 0:\n presents = present.unsqueeze(dim=0)\n else:\n presents = torch.cat((presents, present.unsqueeze(dim=0)))\n else:\n hidden_states = outputs\n return hidden_states, layer_past, presents, attention_mask\n else:\n raise ValueError(\n f\"In layer {self.layer_number} - Incorrect number of arguments ({len(args)}) for {self.__class__.__name__}\"\n )\n\n\nclass ParallelLinearPipe(ParallelLinear):\n \"\"\"Another helper class to pass presents through to the output when doing inference with a Pipe Parallel model\"\"\"\n\n def forward(self, args):\n if not isinstance(args, tuple):\n # in training, args = hidden_state (tensor, so we check if object isn't a tuple and pass through here)\n hidden_state = args\n logits, bias = super().forward(hidden_state)\n return logits\n elif len(args) == 2:\n # we are in inference, so input is (hidden_states, presents)\n hidden_state, presents = args\n logits, bias = super().forward(hidden_state)\n return logits, presents\n else:\n raise ValueError(\n f\"Incorrect number of arguments for {self.__class__.__name__}\"\n )\n\n\nclass NormPipe(nn.Module):\n \"\"\"Just a helper class to pass presents through to the output when doing inference with a Pipe Parallel model\"\"\"\n\n def __init__(self, norm_class, hidden_size, eps):\n super().__init__()\n self.norm = norm_class(hidden_size, eps=eps)\n\n def forward(self, args):\n if not isinstance(args, tuple):\n # in training, args = hidden_state (tensor, so we check if object isn't a tuple and pass through here)\n hidden_state = args\n return self.norm(hidden_state)\n elif len(args) == 2:\n # in inference, args will be (hidden_state, presents)\n hidden_state, presents = args\n hidden_state = self.norm(hidden_state)\n return hidden_state, presents\n else:\n raise ValueError(\n f\"Incorrect number of arguments for {self.__class__.__name__}\"\n )\n\n\ndef parallel_lm_logits(input_, word_embeddings_weight, parallel_output, bias=None):\n \"\"\"LM logits using word embedding weights.\"\"\"\n # Parallel logits.\n input_parallel = mpu.copy_to_model_parallel_region(input_)\n\n # Matrix multiply.\n if bias is None:\n logits_parallel = F.linear(input_parallel, word_embeddings_weight)\n else:\n logits_parallel = F.linear(input_parallel, word_embeddings_weight, bias)\n\n # Gather if needed.\n if parallel_output:\n return logits_parallel\n\n return mpu.gather_from_model_parallel_region(logits_parallel)"
]
| [
[
"torch.nn.Dropout",
"torch.cat",
"torch.stack",
"torch._C._jit_set_profiling_executor",
"torch.no_grad",
"torch.enable_grad",
"torch._C._jit_override_can_fuse_on_gpu",
"torch.cuda.current_device",
"torch.nn.functional.linear",
"torch._C._jit_set_profiling_mode",
"torch.Tensor",
"torch._C._jit_override_can_fuse_on_cpu"
]
]
|
krikra/scipy | [
"ab5e425a48646d55c414bcc326607679f30d6bea"
]
| [
"scipy/interpolate/fitpack2.py"
]
| [
"\"\"\"\nfitpack --- curve and surface fitting with splines\n\nfitpack is based on a collection of Fortran routines DIERCKX\nby P. Dierckx (see http://www.netlib.org/dierckx/) transformed\nto double routines by Pearu Peterson.\n\"\"\"\n# Created by Pearu Peterson, June,August 2003\nfrom __future__ import division, print_function, absolute_import\n\n__all__ = [\n 'UnivariateSpline',\n 'InterpolatedUnivariateSpline',\n 'LSQUnivariateSpline',\n 'BivariateSpline',\n 'LSQBivariateSpline',\n 'SmoothBivariateSpline',\n 'LSQSphereBivariateSpline',\n 'SmoothSphereBivariateSpline',\n 'RectBivariateSpline',\n 'RectSphereBivariateSpline']\n\n\nimport warnings\n\nfrom numpy import zeros, concatenate, alltrue, ravel, all, diff, array, ones\nimport numpy as np\n\nfrom . import fitpack\nfrom . import dfitpack\n\n\n################ Univariate spline ####################\n\n_curfit_messages = {1:\"\"\"\nThe required storage space exceeds the available storage space, as\nspecified by the parameter nest: nest too small. If nest is already\nlarge (say nest > m/2), it may also indicate that s is too small.\nThe approximation returned is the weighted least-squares spline\naccording to the knots t[0],t[1],...,t[n-1]. (n=nest) the parameter fp\ngives the corresponding weighted sum of squared residuals (fp>s).\n\"\"\",\n 2:\"\"\"\nA theoretically impossible result was found during the iteration\nprocess for finding a smoothing spline with fp = s: s too small.\nThere is an approximation returned but the corresponding weighted sum\nof squared residuals does not satisfy the condition abs(fp-s)/s < tol.\"\"\",\n 3:\"\"\"\nThe maximal number of iterations maxit (set to 20 by the program)\nallowed for finding a smoothing spline with fp=s has been reached: s\ntoo small.\nThere is an approximation returned but the corresponding weighted sum\nof squared residuals does not satisfy the condition abs(fp-s)/s < tol.\"\"\",\n 10:\"\"\"\nError on entry, no approximation returned. The following conditions\nmust hold:\nxb<=x[0]<x[1]<...<x[m-1]<=xe, w[i]>0, i=0..m-1\nif iopt=-1:\n xb<t[k+1]<t[k+2]<...<t[n-k-2]<xe\"\"\"\n }\n\n\n# UnivariateSpline, ext parameter can be an int or a string\n_extrap_modes = {0: 0, 'extrapolate': 0,\n 1: 1, 'zeros': 1,\n 2: 2, 'raise': 2,\n 3: 3, 'const': 3}\n\n\nclass UnivariateSpline(object):\n \"\"\"\n One-dimensional smoothing spline fit to a given set of data points.\n\n Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data. `s`\n specifies the number of knots by specifying a smoothing condition.\n\n Parameters\n ----------\n x : (N,) array_like\n 1-D array of independent input data. Must be increasing.\n y : (N,) array_like\n 1-D array of dependent input data, of the same length as `x`.\n w : (N,) array_like, optional\n Weights for spline fitting. Must be positive. If None (default),\n weights are all equal.\n bbox : (2,) array_like, optional\n 2-sequence specifying the boundary of the approximation interval. If\n None (default), ``bbox=[x[0], x[-1]]``.\n k : int, optional\n Degree of the smoothing spline. Must be <= 5.\n Default is k=3, a cubic spline.\n s : float or None, optional\n Positive smoothing factor used to choose the number of knots. Number\n of knots will be increased until the smoothing condition is satisfied::\n\n sum((w[i] * (y[i]-spl(x[i])))**2, axis=0) <= s\n\n If None (default), ``s = len(w)`` which should be a good value if\n ``1/w[i]`` is an estimate of the standard deviation of ``y[i]``.\n If 0, spline will interpolate through all data points.\n ext : int or str, optional\n Controls the extrapolation mode for elements\n not in the interval defined by the knot sequence.\n\n * if ext=0 or 'extrapolate', return the extrapolated value.\n * if ext=1 or 'zeros', return 0\n * if ext=2 or 'raise', raise a ValueError\n * if ext=3 of 'const', return the boundary value.\n\n The default value is 0.\n\n check_finite : bool, optional\n Whether to check that the input arrays contain only finite numbers.\n Disabling may give a performance gain, but may result in problems\n (crashes, non-termination or non-sensical results) if the inputs\n do contain infinities or NaNs.\n Default is False.\n\n See Also\n --------\n InterpolatedUnivariateSpline : Subclass with smoothing forced to 0\n LSQUnivariateSpline : Subclass in which knots are user-selected instead of\n being set by smoothing condition\n splrep : An older, non object-oriented wrapping of FITPACK\n splev, sproot, splint, spalde\n BivariateSpline : A similar class for two-dimensional spline interpolation\n\n Notes\n -----\n The number of data points must be larger than the spline degree `k`.\n\n **NaN handling**: If the input arrays contain ``nan`` values, the result\n is not useful, since the underlying spline fitting routines cannot deal\n with ``nan`` . A workaround is to use zero weights for not-a-number\n data points:\n\n >>> from scipy.interpolate import UnivariateSpline\n >>> x, y = np.array([1, 2, 3, 4]), np.array([1, np.nan, 3, 4])\n >>> w = np.isnan(y)\n >>> y[w] = 0.\n >>> spl = UnivariateSpline(x, y, w=~w)\n\n Notice the need to replace a ``nan`` by a numerical value (precise value\n does not matter as long as the corresponding weight is zero.)\n\n Examples\n --------\n >>> import matplotlib.pyplot as plt\n >>> from scipy.interpolate import UnivariateSpline\n >>> x = np.linspace(-3, 3, 50)\n >>> y = np.exp(-x**2) + 0.1 * np.random.randn(50)\n >>> plt.plot(x, y, 'ro', ms=5)\n\n Use the default value for the smoothing parameter:\n\n >>> spl = UnivariateSpline(x, y)\n >>> xs = np.linspace(-3, 3, 1000)\n >>> plt.plot(xs, spl(xs), 'g', lw=3)\n\n Manually change the amount of smoothing:\n\n >>> spl.set_smoothing_factor(0.5)\n >>> plt.plot(xs, spl(xs), 'b', lw=3)\n >>> plt.show()\n\n \"\"\"\n def __init__(self, x, y, w=None, bbox=[None]*2, k=3, s=None,\n ext=0, check_finite=False):\n\n if check_finite:\n w_finite = np.isfinite(w).all() if w is not None else True\n if (not np.isfinite(x).all() or not np.isfinite(y).all() or\n not w_finite):\n raise ValueError(\"x and y array must not contain NaNs or infs.\")\n if not all(diff(x) > 0.0):\n raise ValueError('x must be strictly increasing')\n\n # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier\n try:\n self.ext = _extrap_modes[ext]\n except KeyError:\n raise ValueError(\"Unknown extrapolation mode %s.\" % ext)\n\n data = dfitpack.fpcurf0(x,y,k,w=w,\n xb=bbox[0],xe=bbox[1],s=s)\n if data[-1] == 1:\n # nest too small, setting to maximum bound\n data = self._reset_nest(data)\n self._data = data\n self._reset_class()\n\n @classmethod\n def _from_tck(cls, tck, ext=0):\n \"\"\"Construct a spline object from given tck\"\"\"\n self = cls.__new__(cls)\n t, c, k = tck\n self._eval_args = tck\n #_data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier\n self._data = (None,None,None,None,None,k,None,len(t),t,\n c,None,None,None,None)\n self.ext = ext\n return self\n\n def _reset_class(self):\n data = self._data\n n,t,c,k,ier = data[7],data[8],data[9],data[5],data[-1]\n self._eval_args = t[:n],c[:n],k\n if ier == 0:\n # the spline returned has a residual sum of squares fp\n # such that abs(fp-s)/s <= tol with tol a relative\n # tolerance set to 0.001 by the program\n pass\n elif ier == -1:\n # the spline returned is an interpolating spline\n self._set_class(InterpolatedUnivariateSpline)\n elif ier == -2:\n # the spline returned is the weighted least-squares\n # polynomial of degree k. In this extreme case fp gives\n # the upper bound fp0 for the smoothing factor s.\n self._set_class(LSQUnivariateSpline)\n else:\n # error\n if ier == 1:\n self._set_class(LSQUnivariateSpline)\n message = _curfit_messages.get(ier,'ier=%s' % (ier))\n warnings.warn(message)\n\n def _set_class(self, cls):\n self._spline_class = cls\n if self.__class__ in (UnivariateSpline, InterpolatedUnivariateSpline,\n LSQUnivariateSpline):\n self.__class__ = cls\n else:\n # It's an unknown subclass -- don't change class. cf. #731\n pass\n\n def _reset_nest(self, data, nest=None):\n n = data[10]\n if nest is None:\n k,m = data[5],len(data[0])\n nest = m+k+1 # this is the maximum bound for nest\n else:\n if not n <= nest:\n raise ValueError(\"`nest` can only be increased\")\n t, c, fpint, nrdata = [np.resize(data[j], nest) for j in [8,9,11,12]]\n\n args = data[:8] + (t,c,n,fpint,nrdata,data[13])\n data = dfitpack.fpcurf1(*args)\n return data\n\n def set_smoothing_factor(self, s):\n \"\"\" Continue spline computation with the given smoothing\n factor s and with the knots found at the last call.\n\n This routine modifies the spline in place.\n\n \"\"\"\n data = self._data\n if data[6] == -1:\n warnings.warn('smoothing factor unchanged for'\n 'LSQ spline with fixed knots')\n return\n args = data[:6] + (s,) + data[7:]\n data = dfitpack.fpcurf1(*args)\n if data[-1] == 1:\n # nest too small, setting to maximum bound\n data = self._reset_nest(data)\n self._data = data\n self._reset_class()\n\n def __call__(self, x, nu=0, ext=None):\n \"\"\"\n Evaluate spline (or its nu-th derivative) at positions x.\n\n Parameters\n ----------\n x : array_like\n A 1-D array of points at which to return the value of the smoothed\n spline or its derivatives. Note: x can be unordered but the\n evaluation is more efficient if x is (partially) ordered.\n nu : int\n The order of derivative of the spline to compute.\n ext : int\n Controls the value returned for elements of ``x`` not in the\n interval defined by the knot sequence.\n\n * if ext=0 or 'extrapolate', return the extrapolated value.\n * if ext=1 or 'zeros', return 0\n * if ext=2 or 'raise', raise a ValueError\n * if ext=3 or 'const', return the boundary value.\n\n The default value is 0, passed from the initialization of\n UnivariateSpline.\n\n \"\"\"\n x = np.asarray(x)\n # empty input yields empty output\n if x.size == 0:\n return array([])\n# if nu is None:\n# return dfitpack.splev(*(self._eval_args+(x,)))\n# return dfitpack.splder(nu=nu,*(self._eval_args+(x,)))\n if ext is None:\n ext = self.ext\n else:\n try:\n ext = _extrap_modes[ext]\n except KeyError:\n raise ValueError(\"Unknown extrapolation mode %s.\" % ext)\n return fitpack.splev(x, self._eval_args, der=nu, ext=ext)\n\n def get_knots(self):\n \"\"\" Return positions of interior knots of the spline.\n\n Internally, the knot vector contains ``2*k`` additional boundary knots.\n \"\"\"\n data = self._data\n k,n = data[5],data[7]\n return data[8][k:n-k]\n\n def get_coeffs(self):\n \"\"\"Return spline coefficients.\"\"\"\n data = self._data\n k,n = data[5],data[7]\n return data[9][:n-k-1]\n\n def get_residual(self):\n \"\"\"Return weighted sum of squared residuals of the spline approximation.\n\n This is equivalent to::\n\n sum((w[i] * (y[i]-spl(x[i])))**2, axis=0)\n\n \"\"\"\n return self._data[10]\n\n def integral(self, a, b):\n \"\"\" Return definite integral of the spline between two given points.\n\n Parameters\n ----------\n a : float\n Lower limit of integration.\n b : float\n Upper limit of integration.\n\n Returns\n -------\n integral : float\n The value of the definite integral of the spline between limits.\n\n Examples\n --------\n >>> from scipy.interpolate import UnivariateSpline\n >>> x = np.linspace(0, 3, 11)\n >>> y = x**2\n >>> spl = UnivariateSpline(x, y)\n >>> spl.integral(0, 3)\n 9.0\n\n which agrees with :math:`\\\\int x^2 dx = x^3 / 3` between the limits\n of 0 and 3.\n\n A caveat is that this routine assumes the spline to be zero outside of\n the data limits:\n\n >>> spl.integral(-1, 4)\n 9.0\n >>> spl.integral(-1, 0)\n 0.0\n\n \"\"\"\n return dfitpack.splint(*(self._eval_args+(a,b)))\n\n def derivatives(self, x):\n \"\"\" Return all derivatives of the spline at the point x.\n\n Parameters\n ----------\n x : float\n The point to evaluate the derivatives at.\n\n Returns\n -------\n der : ndarray, shape(k+1,)\n Derivatives of the orders 0 to k.\n\n Examples\n --------\n >>> from scipy.interpolate import UnivariateSpline\n >>> x = np.linspace(0, 3, 11)\n >>> y = x**2\n >>> spl = UnivariateSpline(x, y)\n >>> spl.derivatives(1.5)\n array([2.25, 3.0, 2.0, 0])\n\n \"\"\"\n d,ier = dfitpack.spalde(*(self._eval_args+(x,)))\n if not ier == 0:\n raise ValueError(\"Error code returned by spalde: %s\" % ier)\n return d\n\n def roots(self):\n \"\"\" Return the zeros of the spline.\n\n Restriction: only cubic splines are supported by fitpack.\n \"\"\"\n k = self._data[5]\n if k == 3:\n z,m,ier = dfitpack.sproot(*self._eval_args[:2])\n if not ier == 0:\n raise ValueError(\"Error code returned by spalde: %s\" % ier)\n return z[:m]\n raise NotImplementedError('finding roots unsupported for '\n 'non-cubic splines')\n\n def derivative(self, n=1):\n \"\"\"\n Construct a new spline representing the derivative of this spline.\n\n Parameters\n ----------\n n : int, optional\n Order of derivative to evaluate. Default: 1\n\n Returns\n -------\n spline : UnivariateSpline\n Spline of order k2=k-n representing the derivative of this\n spline.\n\n See Also\n --------\n splder, antiderivative\n\n Notes\n -----\n\n .. versionadded:: 0.13.0\n\n Examples\n --------\n This can be used for finding maxima of a curve:\n\n >>> from scipy.interpolate import UnivariateSpline\n >>> x = np.linspace(0, 10, 70)\n >>> y = np.sin(x)\n >>> spl = UnivariateSpline(x, y, k=4, s=0)\n\n Now, differentiate the spline and find the zeros of the\n derivative. (NB: `sproot` only works for order 3 splines, so we\n fit an order 4 spline):\n\n >>> spl.derivative().roots() / np.pi\n array([ 0.50000001, 1.5 , 2.49999998])\n\n This agrees well with roots :math:`\\\\pi/2 + n\\\\pi` of\n :math:`\\\\cos(x) = \\\\sin'(x)`.\n\n \"\"\"\n tck = fitpack.splder(self._eval_args, n)\n return UnivariateSpline._from_tck(tck, self.ext)\n\n def antiderivative(self, n=1):\n \"\"\"\n Construct a new spline representing the antiderivative of this spline.\n\n Parameters\n ----------\n n : int, optional\n Order of antiderivative to evaluate. Default: 1\n\n Returns\n -------\n spline : UnivariateSpline\n Spline of order k2=k+n representing the antiderivative of this\n spline.\n\n Notes\n -----\n\n .. versionadded:: 0.13.0\n\n See Also\n --------\n splantider, derivative\n\n Examples\n --------\n >>> from scipy.interpolate import UnivariateSpline\n >>> x = np.linspace(0, np.pi/2, 70)\n >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2)\n >>> spl = UnivariateSpline(x, y, s=0)\n\n The derivative is the inverse operation of the antiderivative,\n although some floating point error accumulates:\n\n >>> spl(1.7), spl.antiderivative().derivative()(1.7)\n (array(2.1565429877197317), array(2.1565429877201865))\n\n Antiderivative can be used to evaluate definite integrals:\n\n >>> ispl = spl.antiderivative()\n >>> ispl(np.pi/2) - ispl(0)\n 2.2572053588768486\n\n This is indeed an approximation to the complete elliptic integral\n :math:`K(m) = \\\\int_0^{\\\\pi/2} [1 - m\\\\sin^2 x]^{-1/2} dx`:\n\n >>> from scipy.special import ellipk\n >>> ellipk(0.8)\n 2.2572053268208538\n\n \"\"\"\n tck = fitpack.splantider(self._eval_args, n)\n return UnivariateSpline._from_tck(tck, self.ext)\n\n\nclass InterpolatedUnivariateSpline(UnivariateSpline):\n \"\"\"\n One-dimensional interpolating spline for a given set of data points.\n\n Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data. Spline\n function passes through all provided points. Equivalent to\n `UnivariateSpline` with s=0.\n\n Parameters\n ----------\n x : (N,) array_like\n Input dimension of data points -- must be increasing\n y : (N,) array_like\n input dimension of data points\n w : (N,) array_like, optional\n Weights for spline fitting. Must be positive. If None (default),\n weights are all equal.\n bbox : (2,) array_like, optional\n 2-sequence specifying the boundary of the approximation interval. If\n None (default), ``bbox=[x[0], x[-1]]``.\n k : int, optional\n Degree of the smoothing spline. Must be 1 <= `k` <= 5.\n ext : int or str, optional\n Controls the extrapolation mode for elements\n not in the interval defined by the knot sequence.\n\n * if ext=0 or 'extrapolate', return the extrapolated value.\n * if ext=1 or 'zeros', return 0\n * if ext=2 or 'raise', raise a ValueError\n * if ext=3 of 'const', return the boundary value.\n\n The default value is 0.\n\n check_finite : bool, optional\n Whether to check that the input arrays contain only finite numbers.\n Disabling may give a performance gain, but may result in problems\n (crashes, non-termination or non-sensical results) if the inputs\n do contain infinities or NaNs.\n Default is False.\n\n See Also\n --------\n UnivariateSpline : Superclass -- allows knots to be selected by a\n smoothing condition\n LSQUnivariateSpline : spline for which knots are user-selected\n splrep : An older, non object-oriented wrapping of FITPACK\n splev, sproot, splint, spalde\n BivariateSpline : A similar class for two-dimensional spline interpolation\n\n Notes\n -----\n The number of data points must be larger than the spline degree `k`.\n\n Examples\n --------\n >>> import matplotlib.pyplot as plt\n >>> from scipy.interpolate import InterpolatedUnivariateSpline\n >>> x = np.linspace(-3, 3, 50)\n >>> y = np.exp(-x**2) + 0.1 * np.random.randn(50)\n >>> spl = InterpolatedUnivariateSpline(x, y)\n >>> plt.plot(x, y, 'ro', ms=5)\n >>> xs = np.linspace(-3, 3, 1000)\n >>> plt.plot(xs, spl(xs), 'g', lw=3, alpha=0.7)\n >>> plt.show()\n\n Notice that the ``spl(x)`` interpolates `y`:\n\n >>> spl.get_residual()\n 0.0\n\n \"\"\"\n def __init__(self, x, y, w=None, bbox=[None]*2, k=3,\n ext=0, check_finite=False):\n\n if check_finite:\n w_finite = np.isfinite(w).all() if w is not None else True\n if (not np.isfinite(x).all() or not np.isfinite(y).all() or\n not w_finite):\n raise ValueError(\"Input must not contain NaNs or infs.\")\n if not all(diff(x) > 0.0):\n raise ValueError('x must be strictly increasing')\n\n # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier\n self._data = dfitpack.fpcurf0(x,y,k,w=w,\n xb=bbox[0],xe=bbox[1],s=0)\n self._reset_class()\n\n try:\n self.ext = _extrap_modes[ext]\n except KeyError:\n raise ValueError(\"Unknown extrapolation mode %s.\" % ext)\n\n\n_fpchec_error_string = \"\"\"The input parameters have been rejected by fpchec. \\\nThis means that at least one of the following conditions is violated:\n\n1) k+1 <= n-k-1 <= m\n2) t(1) <= t(2) <= ... <= t(k+1)\n t(n-k) <= t(n-k+1) <= ... <= t(n)\n3) t(k+1) < t(k+2) < ... < t(n-k)\n4) t(k+1) <= x(i) <= t(n-k)\n5) The conditions specified by Schoenberg and Whitney must hold\n for at least one subset of data points, i.e., there must be a\n subset of data points y(j) such that\n t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1\n\"\"\"\n\n\nclass LSQUnivariateSpline(UnivariateSpline):\n \"\"\"\n One-dimensional spline with explicit internal knots.\n\n Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data. `t`\n specifies the internal knots of the spline\n\n Parameters\n ----------\n x : (N,) array_like\n Input dimension of data points -- must be increasing\n y : (N,) array_like\n Input dimension of data points\n t : (M,) array_like\n interior knots of the spline. Must be in ascending order and::\n\n bbox[0] < t[0] < ... < t[-1] < bbox[-1]\n\n w : (N,) array_like, optional\n weights for spline fitting. Must be positive. If None (default),\n weights are all equal.\n bbox : (2,) array_like, optional\n 2-sequence specifying the boundary of the approximation interval. If\n None (default), ``bbox = [x[0], x[-1]]``.\n k : int, optional\n Degree of the smoothing spline. Must be 1 <= `k` <= 5.\n Default is k=3, a cubic spline.\n ext : int or str, optional\n Controls the extrapolation mode for elements\n not in the interval defined by the knot sequence.\n\n * if ext=0 or 'extrapolate', return the extrapolated value.\n * if ext=1 or 'zeros', return 0\n * if ext=2 or 'raise', raise a ValueError\n * if ext=3 of 'const', return the boundary value.\n\n The default value is 0.\n\n check_finite : bool, optional\n Whether to check that the input arrays contain only finite numbers.\n Disabling may give a performance gain, but may result in problems\n (crashes, non-termination or non-sensical results) if the inputs\n do contain infinities or NaNs.\n Default is False.\n\n Raises\n ------\n ValueError\n If the interior knots do not satisfy the Schoenberg-Whitney conditions\n\n See Also\n --------\n UnivariateSpline : Superclass -- knots are specified by setting a\n smoothing condition\n InterpolatedUnivariateSpline : spline passing through all points\n splrep : An older, non object-oriented wrapping of FITPACK\n splev, sproot, splint, spalde\n BivariateSpline : A similar class for two-dimensional spline interpolation\n\n Notes\n -----\n The number of data points must be larger than the spline degree `k`.\n\n Knots `t` must satisfy the Schoenberg-Whitney conditions,\n i.e., there must be a subset of data points ``x[j]`` such that\n ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``.\n\n Examples\n --------\n >>> from scipy.interpolate import LSQUnivariateSpline, UnivariateSpline\n >>> import matplotlib.pyplot as plt\n >>> x = np.linspace(-3, 3, 50)\n >>> y = np.exp(-x**2) + 0.1 * np.random.randn(50)\n\n Fit a smoothing spline with a pre-defined internal knots:\n\n >>> t = [-1, 0, 1]\n >>> spl = LSQUnivariateSpline(x, y, t)\n\n >>> xs = np.linspace(-3, 3, 1000)\n >>> plt.plot(x, y, 'ro', ms=5)\n >>> plt.plot(xs, spl(xs), 'g-', lw=3)\n >>> plt.show()\n\n Check the knot vector:\n\n >>> spl.get_knots()\n array([-3., -1., 0., 1., 3.])\n\n Constructing lsq spline using the knots from another spline:\n\n >>> x = np.arange(10)\n >>> s = UnivariateSpline(x, x, s=0)\n >>> s.get_knots()\n array([ 0., 2., 3., 4., 5., 6., 7., 9.])\n >>> knt = s.get_knots()\n >>> s1 = LSQUnivariateSpline(x, x, knt[1:-1]) # Chop 1st and last knot\n >>> s1.get_knots()\n array([ 0., 2., 3., 4., 5., 6., 7., 9.])\n\n \"\"\"\n\n def __init__(self, x, y, t, w=None, bbox=[None]*2, k=3,\n ext=0, check_finite=False):\n\n if check_finite:\n w_finite = np.isfinite(w).all() if w is not None else True\n if (not np.isfinite(x).all() or not np.isfinite(y).all() or\n not w_finite or not np.isfinite(t).all()):\n raise ValueError(\"Input(s) must not contain NaNs or infs.\")\n if not all(diff(x) > 0.0):\n raise ValueError('x must be strictly increasing')\n\n # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier\n xb = bbox[0]\n xe = bbox[1]\n if xb is None:\n xb = x[0]\n if xe is None:\n xe = x[-1]\n t = concatenate(([xb]*(k+1), t, [xe]*(k+1)))\n n = len(t)\n if not alltrue(t[k+1:n-k]-t[k:n-k-1] > 0, axis=0):\n raise ValueError('Interior knots t must satisfy '\n 'Schoenberg-Whitney conditions')\n if not dfitpack.fpchec(x, t, k) == 0:\n raise ValueError(_fpchec_error_string)\n data = dfitpack.fpcurfm1(x, y, k, t, w=w, xb=xb, xe=xe)\n self._data = data[:-3] + (None, None, data[-1])\n self._reset_class()\n\n try:\n self.ext = _extrap_modes[ext]\n except KeyError:\n raise ValueError(\"Unknown extrapolation mode %s.\" % ext)\n\n\n################ Bivariate spline ####################\n\nclass _BivariateSplineBase(object):\n \"\"\" Base class for Bivariate spline s(x,y) interpolation on the rectangle\n [xb,xe] x [yb, ye] calculated from a given set of data points\n (x,y,z).\n\n See Also\n --------\n bisplrep, bisplev : an older wrapping of FITPACK\n BivariateSpline :\n implementation of bivariate spline interpolation on a plane grid\n SphereBivariateSpline :\n implementation of bivariate spline interpolation on a spherical grid\n \"\"\"\n\n def get_residual(self):\n \"\"\" Return weighted sum of squared residuals of the spline\n approximation: sum ((w[i]*(z[i]-s(x[i],y[i])))**2,axis=0)\n \"\"\"\n return self.fp\n\n def get_knots(self):\n \"\"\" Return a tuple (tx,ty) where tx,ty contain knots positions\n of the spline with respect to x-, y-variable, respectively.\n The position of interior and additional knots are given as\n t[k+1:-k-1] and t[:k+1]=b, t[-k-1:]=e, respectively.\n \"\"\"\n return self.tck[:2]\n\n def get_coeffs(self):\n \"\"\" Return spline coefficients.\"\"\"\n return self.tck[2]\n\n def __call__(self, x, y, mth=None, dx=0, dy=0, grid=True):\n \"\"\"\n Evaluate the spline or its derivatives at given positions.\n\n Parameters\n ----------\n x, y : array_like\n Input coordinates.\n\n If `grid` is False, evaluate the spline at points ``(x[i],\n y[i]), i=0, ..., len(x)-1``. Standard Numpy broadcasting\n is obeyed.\n\n If `grid` is True: evaluate spline at the grid points\n defined by the coordinate arrays x, y. The arrays must be\n sorted to increasing order.\n dx : int\n Order of x-derivative\n\n .. versionadded:: 0.14.0\n dy : int\n Order of y-derivative\n\n .. versionadded:: 0.14.0\n grid : bool\n Whether to evaluate the results on a grid spanned by the\n input arrays, or at points specified by the input arrays.\n\n .. versionadded:: 0.14.0\n\n mth : str\n Deprecated argument. Has no effect.\n\n \"\"\"\n x = np.asarray(x)\n y = np.asarray(y)\n\n if mth is not None:\n warnings.warn(\"The `mth` argument is deprecated and will be removed\",\n FutureWarning)\n\n tx, ty, c = self.tck[:3]\n kx, ky = self.degrees\n if grid:\n if x.size == 0 or y.size == 0:\n return np.zeros((x.size, y.size), dtype=self.tck[2].dtype)\n\n if dx or dy:\n z,ier = dfitpack.parder(tx,ty,c,kx,ky,dx,dy,x,y)\n if not ier == 0:\n raise ValueError(\"Error code returned by parder: %s\" % ier)\n else:\n z,ier = dfitpack.bispev(tx,ty,c,kx,ky,x,y)\n if not ier == 0:\n raise ValueError(\"Error code returned by bispev: %s\" % ier)\n else:\n # standard Numpy broadcasting\n if x.shape != y.shape:\n x, y = np.broadcast_arrays(x, y)\n\n shape = x.shape\n x = x.ravel()\n y = y.ravel()\n\n if x.size == 0 or y.size == 0:\n return np.zeros(shape, dtype=self.tck[2].dtype)\n\n if dx or dy:\n z,ier = dfitpack.pardeu(tx,ty,c,kx,ky,dx,dy,x,y)\n if not ier == 0:\n raise ValueError(\"Error code returned by pardeu: %s\" % ier)\n else:\n z,ier = dfitpack.bispeu(tx,ty,c,kx,ky,x,y)\n if not ier == 0:\n raise ValueError(\"Error code returned by bispeu: %s\" % ier)\n\n z = z.reshape(shape)\n return z\n\n\n_surfit_messages = {1:\"\"\"\nThe required storage space exceeds the available storage space: nxest\nor nyest too small, or s too small.\nThe weighted least-squares spline corresponds to the current set of\nknots.\"\"\",\n 2:\"\"\"\nA theoretically impossible result was found during the iteration\nprocess for finding a smoothing spline with fp = s: s too small or\nbadly chosen eps.\nWeighted sum of squared residuals does not satisfy abs(fp-s)/s < tol.\"\"\",\n 3:\"\"\"\nthe maximal number of iterations maxit (set to 20 by the program)\nallowed for finding a smoothing spline with fp=s has been reached:\ns too small.\nWeighted sum of squared residuals does not satisfy abs(fp-s)/s < tol.\"\"\",\n 4:\"\"\"\nNo more knots can be added because the number of b-spline coefficients\n(nx-kx-1)*(ny-ky-1) already exceeds the number of data points m:\neither s or m too small.\nThe weighted least-squares spline corresponds to the current set of\nknots.\"\"\",\n 5:\"\"\"\nNo more knots can be added because the additional knot would (quasi)\ncoincide with an old one: s too small or too large a weight to an\ninaccurate data point.\nThe weighted least-squares spline corresponds to the current set of\nknots.\"\"\",\n 10:\"\"\"\nError on entry, no approximation returned. The following conditions\nmust hold:\nxb<=x[i]<=xe, yb<=y[i]<=ye, w[i]>0, i=0..m-1\nIf iopt==-1, then\n xb<tx[kx+1]<tx[kx+2]<...<tx[nx-kx-2]<xe\n yb<ty[ky+1]<ty[ky+2]<...<ty[ny-ky-2]<ye\"\"\",\n -3:\"\"\"\nThe coefficients of the spline returned have been computed as the\nminimal norm least-squares solution of a (numerically) rank deficient\nsystem (deficiency=%i). If deficiency is large, the results may be\ninaccurate. Deficiency may strongly depend on the value of eps.\"\"\"\n }\n\n\nclass BivariateSpline(_BivariateSplineBase):\n \"\"\"\n Base class for bivariate splines.\n\n This describes a spline ``s(x, y)`` of degrees ``kx`` and ``ky`` on\n the rectangle ``[xb, xe] * [yb, ye]`` calculated from a given set\n of data points ``(x, y, z)``.\n\n This class is meant to be subclassed, not instantiated directly.\n To construct these splines, call either `SmoothBivariateSpline` or\n `LSQBivariateSpline`.\n\n See Also\n --------\n UnivariateSpline : a similar class for univariate spline interpolation\n SmoothBivariateSpline :\n to create a BivariateSpline through the given points\n LSQBivariateSpline :\n to create a BivariateSpline using weighted least-squares fitting\n SphereBivariateSpline :\n bivariate spline interpolation in spherical cooridinates\n bisplrep : older wrapping of FITPACK\n bisplev : older wrapping of FITPACK\n\n \"\"\"\n\n @classmethod\n def _from_tck(cls, tck):\n \"\"\"Construct a spline object from given tck and degree\"\"\"\n self = cls.__new__(cls)\n if len(tck) != 5:\n raise ValueError(\"tck should be a 5 element tuple of tx, ty, c, kx, ky\")\n self.tck = tck[:3]\n self.degrees = tck[3:]\n return self\n\n def ev(self, xi, yi, dx=0, dy=0):\n \"\"\"\n Evaluate the spline at points\n\n Returns the interpolated value at ``(xi[i], yi[i]),\n i=0,...,len(xi)-1``.\n\n Parameters\n ----------\n xi, yi : array_like\n Input coordinates. Standard Numpy broadcasting is obeyed.\n dx : int, optional\n Order of x-derivative\n\n .. versionadded:: 0.14.0\n dy : int, optional\n Order of y-derivative\n\n .. versionadded:: 0.14.0\n \"\"\"\n return self.__call__(xi, yi, dx=dx, dy=dy, grid=False)\n\n def integral(self, xa, xb, ya, yb):\n \"\"\"\n Evaluate the integral of the spline over area [xa,xb] x [ya,yb].\n\n Parameters\n ----------\n xa, xb : float\n The end-points of the x integration interval.\n ya, yb : float\n The end-points of the y integration interval.\n\n Returns\n -------\n integ : float\n The value of the resulting integral.\n\n \"\"\"\n tx,ty,c = self.tck[:3]\n kx,ky = self.degrees\n return dfitpack.dblint(tx,ty,c,kx,ky,xa,xb,ya,yb)\n\n\nclass SmoothBivariateSpline(BivariateSpline):\n \"\"\"\n Smooth bivariate spline approximation.\n\n Parameters\n ----------\n x, y, z : array_like\n 1-D sequences of data points (order is not important).\n w : array_like, optional\n Positive 1-D sequence of weights, of same length as `x`, `y` and `z`.\n bbox : array_like, optional\n Sequence of length 4 specifying the boundary of the rectangular\n approximation domain. By default,\n ``bbox=[min(x,tx),max(x,tx), min(y,ty),max(y,ty)]``.\n kx, ky : ints, optional\n Degrees of the bivariate spline. Default is 3.\n s : float, optional\n Positive smoothing factor defined for estimation condition:\n ``sum((w[i]*(z[i]-s(x[i], y[i])))**2, axis=0) <= s``\n Default ``s=len(w)`` which should be a good value if ``1/w[i]`` is an\n estimate of the standard deviation of ``z[i]``.\n eps : float, optional\n A threshold for determining the effective rank of an over-determined\n linear system of equations. `eps` should have a value between 0 and 1,\n the default is 1e-16.\n\n See Also\n --------\n bisplrep : an older wrapping of FITPACK\n bisplev : an older wrapping of FITPACK\n UnivariateSpline : a similar class for univariate spline interpolation\n LSQUnivariateSpline : to create a BivariateSpline using weighted\n\n Notes\n -----\n The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``.\n\n \"\"\"\n\n def __init__(self, x, y, z, w=None, bbox=[None] * 4, kx=3, ky=3, s=None,\n eps=None):\n xb,xe,yb,ye = bbox\n nx,tx,ny,ty,c,fp,wrk1,ier = dfitpack.surfit_smth(x,y,z,w,\n xb,xe,yb,ye,\n kx,ky,s=s,\n eps=eps,lwrk2=1)\n if ier > 10: # lwrk2 was to small, re-run\n nx,tx,ny,ty,c,fp,wrk1,ier = dfitpack.surfit_smth(x,y,z,w,\n xb,xe,yb,ye,\n kx,ky,s=s,\n eps=eps,lwrk2=ier)\n if ier in [0,-1,-2]: # normal return\n pass\n else:\n message = _surfit_messages.get(ier,'ier=%s' % (ier))\n warnings.warn(message)\n\n self.fp = fp\n self.tck = tx[:nx],ty[:ny],c[:(nx-kx-1)*(ny-ky-1)]\n self.degrees = kx,ky\n\n\nclass LSQBivariateSpline(BivariateSpline):\n \"\"\"\n Weighted least-squares bivariate spline approximation.\n\n Parameters\n ----------\n x, y, z : array_like\n 1-D sequences of data points (order is not important).\n tx, ty : array_like\n Strictly ordered 1-D sequences of knots coordinates.\n w : array_like, optional\n Positive 1-D array of weights, of the same length as `x`, `y` and `z`.\n bbox : (4,) array_like, optional\n Sequence of length 4 specifying the boundary of the rectangular\n approximation domain. By default,\n ``bbox=[min(x,tx),max(x,tx), min(y,ty),max(y,ty)]``.\n kx, ky : ints, optional\n Degrees of the bivariate spline. Default is 3.\n eps : float, optional\n A threshold for determining the effective rank of an over-determined\n linear system of equations. `eps` should have a value between 0 and 1,\n the default is 1e-16.\n\n See Also\n --------\n bisplrep : an older wrapping of FITPACK\n bisplev : an older wrapping of FITPACK\n UnivariateSpline : a similar class for univariate spline interpolation\n SmoothBivariateSpline : create a smoothing BivariateSpline\n\n Notes\n -----\n The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``.\n\n \"\"\"\n\n def __init__(self, x, y, z, tx, ty, w=None, bbox=[None]*4, kx=3, ky=3,\n eps=None):\n nx = 2*kx+2+len(tx)\n ny = 2*ky+2+len(ty)\n tx1 = zeros((nx,),float)\n ty1 = zeros((ny,),float)\n tx1[kx+1:nx-kx-1] = tx\n ty1[ky+1:ny-ky-1] = ty\n\n xb,xe,yb,ye = bbox\n tx1,ty1,c,fp,ier = dfitpack.surfit_lsq(x,y,z,tx1,ty1,w,\n xb,xe,yb,ye,\n kx,ky,eps,lwrk2=1)\n if ier > 10:\n tx1,ty1,c,fp,ier = dfitpack.surfit_lsq(x,y,z,tx1,ty1,w,\n xb,xe,yb,ye,\n kx,ky,eps,lwrk2=ier)\n if ier in [0,-1,-2]: # normal return\n pass\n else:\n if ier < -2:\n deficiency = (nx-kx-1)*(ny-ky-1)+ier\n message = _surfit_messages.get(-3) % (deficiency)\n else:\n message = _surfit_messages.get(ier, 'ier=%s' % (ier))\n warnings.warn(message)\n self.fp = fp\n self.tck = tx1, ty1, c\n self.degrees = kx, ky\n\n\nclass RectBivariateSpline(BivariateSpline):\n \"\"\"\n Bivariate spline approximation over a rectangular mesh.\n\n Can be used for both smoothing and interpolating data.\n\n Parameters\n ----------\n x,y : array_like\n 1-D arrays of coordinates in strictly ascending order.\n z : array_like\n 2-D array of data with shape (x.size,y.size).\n bbox : array_like, optional\n Sequence of length 4 specifying the boundary of the rectangular\n approximation domain. By default,\n ``bbox=[min(x,tx),max(x,tx), min(y,ty),max(y,ty)]``.\n kx, ky : ints, optional\n Degrees of the bivariate spline. Default is 3.\n s : float, optional\n Positive smoothing factor defined for estimation condition:\n ``sum((w[i]*(z[i]-s(x[i], y[i])))**2, axis=0) <= s``\n Default is ``s=0``, which is for interpolation.\n\n See Also\n --------\n SmoothBivariateSpline : a smoothing bivariate spline for scattered data\n bisplrep : an older wrapping of FITPACK\n bisplev : an older wrapping of FITPACK\n UnivariateSpline : a similar class for univariate spline interpolation\n\n \"\"\"\n\n def __init__(self, x, y, z, bbox=[None] * 4, kx=3, ky=3, s=0):\n x, y = ravel(x), ravel(y)\n if not all(diff(x) > 0.0):\n raise ValueError('x must be strictly increasing')\n if not all(diff(y) > 0.0):\n raise ValueError('y must be strictly increasing')\n if not ((x.min() == x[0]) and (x.max() == x[-1])):\n raise ValueError('x must be strictly ascending')\n if not ((y.min() == y[0]) and (y.max() == y[-1])):\n raise ValueError('y must be strictly ascending')\n if not x.size == z.shape[0]:\n raise ValueError('x dimension of z must have same number of '\n 'elements as x')\n if not y.size == z.shape[1]:\n raise ValueError('y dimension of z must have same number of '\n 'elements as y')\n z = ravel(z)\n xb, xe, yb, ye = bbox\n nx, tx, ny, ty, c, fp, ier = dfitpack.regrid_smth(x, y, z, xb, xe, yb,\n ye, kx, ky, s)\n\n if ier not in [0, -1, -2]:\n msg = _surfit_messages.get(ier, 'ier=%s' % (ier))\n raise ValueError(msg)\n\n self.fp = fp\n self.tck = tx[:nx], ty[:ny], c[:(nx - kx - 1) * (ny - ky - 1)]\n self.degrees = kx, ky\n\n\n_spherefit_messages = _surfit_messages.copy()\n_spherefit_messages[10] = \"\"\"\nERROR. On entry, the input data are controlled on validity. The following\n restrictions must be satisfied:\n -1<=iopt<=1, m>=2, ntest>=8 ,npest >=8, 0<eps<1,\n 0<=teta(i)<=pi, 0<=phi(i)<=2*pi, w(i)>0, i=1,...,m\n lwrk1 >= 185+52*v+10*u+14*u*v+8*(u-1)*v**2+8*m\n kwrk >= m+(ntest-7)*(npest-7)\n if iopt=-1: 8<=nt<=ntest , 9<=np<=npest\n 0<tt(5)<tt(6)<...<tt(nt-4)<pi\n 0<tp(5)<tp(6)<...<tp(np-4)<2*pi\n if iopt>=0: s>=0\n if one of these conditions is found to be violated,control\n is immediately repassed to the calling program. in that\n case there is no approximation returned.\"\"\"\n_spherefit_messages[-3] = \"\"\"\nWARNING. The coefficients of the spline returned have been computed as the\n minimal norm least-squares solution of a (numerically) rank\n deficient system (deficiency=%i, rank=%i). Especially if the rank\n deficiency, which is computed by 6+(nt-8)*(np-7)+ier, is large,\n the results may be inaccurate. They could also seriously depend on\n the value of eps.\"\"\"\n\n\nclass SphereBivariateSpline(_BivariateSplineBase):\n \"\"\"\n Bivariate spline s(x,y) of degrees 3 on a sphere, calculated from a\n given set of data points (theta,phi,r).\n\n .. versionadded:: 0.11.0\n\n See Also\n --------\n bisplrep, bisplev : an older wrapping of FITPACK\n UnivariateSpline : a similar class for univariate spline interpolation\n SmoothUnivariateSpline :\n to create a BivariateSpline through the given points\n LSQUnivariateSpline :\n to create a BivariateSpline using weighted least-squares fitting\n \"\"\"\n\n def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):\n \"\"\"\n Evaluate the spline or its derivatives at given positions.\n\n Parameters\n ----------\n theta, phi : array_like\n Input coordinates.\n\n If `grid` is False, evaluate the spline at points\n ``(theta[i], phi[i]), i=0, ..., len(x)-1``. Standard\n Numpy broadcasting is obeyed.\n\n If `grid` is True: evaluate spline at the grid points\n defined by the coordinate arrays theta, phi. The arrays\n must be sorted to increasing order.\n dtheta : int, optional\n Order of theta-derivative\n\n .. versionadded:: 0.14.0\n dphi : int\n Order of phi-derivative\n\n .. versionadded:: 0.14.0\n grid : bool\n Whether to evaluate the results on a grid spanned by the\n input arrays, or at points specified by the input arrays.\n\n .. versionadded:: 0.14.0\n\n \"\"\"\n theta = np.asarray(theta)\n phi = np.asarray(phi)\n\n if theta.size > 0 and (theta.min() < 0. or theta.max() > np.pi):\n raise ValueError(\"requested theta out of bounds.\")\n if phi.size > 0 and (phi.min() < 0. or phi.max() > 2. * np.pi):\n raise ValueError(\"requested phi out of bounds.\")\n\n return _BivariateSplineBase.__call__(self, theta, phi,\n dx=dtheta, dy=dphi, grid=grid)\n\n def ev(self, theta, phi, dtheta=0, dphi=0):\n \"\"\"\n Evaluate the spline at points\n\n Returns the interpolated value at ``(theta[i], phi[i]),\n i=0,...,len(theta)-1``.\n\n Parameters\n ----------\n theta, phi : array_like\n Input coordinates. Standard Numpy broadcasting is obeyed.\n dtheta : int, optional\n Order of theta-derivative\n\n .. versionadded:: 0.14.0\n dphi : int, optional\n Order of phi-derivative\n\n .. versionadded:: 0.14.0\n \"\"\"\n return self.__call__(theta, phi, dtheta=dtheta, dphi=dphi, grid=False)\n\n\nclass SmoothSphereBivariateSpline(SphereBivariateSpline):\n \"\"\"\n Smooth bivariate spline approximation in spherical coordinates.\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n theta, phi, r : array_like\n 1-D sequences of data points (order is not important). Coordinates\n must be given in radians. Theta must lie within the interval (0, pi),\n and phi must lie within the interval (0, 2pi).\n w : array_like, optional\n Positive 1-D sequence of weights.\n s : float, optional\n Positive smoothing factor defined for estimation condition:\n ``sum((w(i)*(r(i) - s(theta(i), phi(i))))**2, axis=0) <= s``\n Default ``s=len(w)`` which should be a good value if 1/w[i] is an\n estimate of the standard deviation of r[i].\n eps : float, optional\n A threshold for determining the effective rank of an over-determined\n linear system of equations. `eps` should have a value between 0 and 1,\n the default is 1e-16.\n\n Notes\n -----\n For more information, see the FITPACK_ site about this function.\n\n .. _FITPACK: http://www.netlib.org/dierckx/sphere.f\n\n Examples\n --------\n Suppose we have global data on a coarse grid (the input data does not\n have to be on a grid):\n\n >>> theta = np.linspace(0., np.pi, 7)\n >>> phi = np.linspace(0., 2*np.pi, 9)\n >>> data = np.empty((theta.shape[0], phi.shape[0]))\n >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0.\n >>> data[1:-1,1], data[1:-1,-1] = 1., 1.\n >>> data[1,1:-1], data[-2,1:-1] = 1., 1.\n >>> data[2:-2,2], data[2:-2,-2] = 2., 2.\n >>> data[2,2:-2], data[-3,2:-2] = 2., 2.\n >>> data[3,3:-2] = 3.\n >>> data = np.roll(data, 4, 1)\n\n We need to set up the interpolator object\n\n >>> lats, lons = np.meshgrid(theta, phi)\n >>> from scipy.interpolate import SmoothSphereBivariateSpline\n >>> lut = SmoothSphereBivariateSpline(lats.ravel(), lons.ravel(),\n ... data.T.ravel(), s=3.5)\n\n As a first test, we'll see what the algorithm returns when run on the\n input coordinates\n\n >>> data_orig = lut(theta, phi)\n\n Finally we interpolate the data to a finer grid\n\n >>> fine_lats = np.linspace(0., np.pi, 70)\n >>> fine_lons = np.linspace(0., 2 * np.pi, 90)\n\n >>> data_smth = lut(fine_lats, fine_lons)\n\n >>> import matplotlib.pyplot as plt\n >>> fig = plt.figure()\n >>> ax1 = fig.add_subplot(131)\n >>> ax1.imshow(data, interpolation='nearest')\n >>> ax2 = fig.add_subplot(132)\n >>> ax2.imshow(data_orig, interpolation='nearest')\n >>> ax3 = fig.add_subplot(133)\n >>> ax3.imshow(data_smth, interpolation='nearest')\n >>> plt.show()\n\n \"\"\"\n\n def __init__(self, theta, phi, r, w=None, s=0., eps=1E-16):\n if np.issubclass_(w, float):\n w = ones(len(theta)) * w\n nt_, tt_, np_, tp_, c, fp, ier = dfitpack.spherfit_smth(theta, phi,\n r, w=w, s=s,\n eps=eps)\n if ier not in [0, -1, -2]:\n message = _spherefit_messages.get(ier, 'ier=%s' % (ier))\n raise ValueError(message)\n\n self.fp = fp\n self.tck = tt_[:nt_], tp_[:np_], c[:(nt_ - 4) * (np_ - 4)]\n self.degrees = (3, 3)\n\n\nclass LSQSphereBivariateSpline(SphereBivariateSpline):\n \"\"\"\n Weighted least-squares bivariate spline approximation in spherical\n coordinates.\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n theta, phi, r : array_like\n 1-D sequences of data points (order is not important). Coordinates\n must be given in radians. Theta must lie within the interval (0, pi),\n and phi must lie within the interval (0, 2pi).\n tt, tp : array_like\n Strictly ordered 1-D sequences of knots coordinates.\n Coordinates must satisfy ``0 < tt[i] < pi``, ``0 < tp[i] < 2*pi``.\n w : array_like, optional\n Positive 1-D sequence of weights, of the same length as `theta`, `phi`\n and `r`.\n eps : float, optional\n A threshold for determining the effective rank of an over-determined\n linear system of equations. `eps` should have a value between 0 and 1,\n the default is 1e-16.\n\n Notes\n -----\n For more information, see the FITPACK_ site about this function.\n\n .. _FITPACK: http://www.netlib.org/dierckx/sphere.f\n\n Examples\n --------\n Suppose we have global data on a coarse grid (the input data does not\n have to be on a grid):\n\n >>> theta = np.linspace(0., np.pi, 7)\n >>> phi = np.linspace(0., 2*np.pi, 9)\n >>> data = np.empty((theta.shape[0], phi.shape[0]))\n >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0.\n >>> data[1:-1,1], data[1:-1,-1] = 1., 1.\n >>> data[1,1:-1], data[-2,1:-1] = 1., 1.\n >>> data[2:-2,2], data[2:-2,-2] = 2., 2.\n >>> data[2,2:-2], data[-3,2:-2] = 2., 2.\n >>> data[3,3:-2] = 3.\n >>> data = np.roll(data, 4, 1)\n\n We need to set up the interpolator object. Here, we must also specify the\n coordinates of the knots to use.\n\n >>> lats, lons = np.meshgrid(theta, phi)\n >>> knotst, knotsp = theta.copy(), phi.copy()\n >>> knotst[0] += .0001\n >>> knotst[-1] -= .0001\n >>> knotsp[0] += .0001\n >>> knotsp[-1] -= .0001\n >>> from scipy.interpolate import LSQSphereBivariateSpline\n >>> lut = LSQSphereBivariateSpline(lats.ravel(), lons.ravel(),\n ... data.T.ravel(), knotst, knotsp)\n\n As a first test, we'll see what the algorithm returns when run on the\n input coordinates\n\n >>> data_orig = lut(theta, phi)\n\n Finally we interpolate the data to a finer grid\n\n >>> fine_lats = np.linspace(0., np.pi, 70)\n >>> fine_lons = np.linspace(0., 2*np.pi, 90)\n\n >>> data_lsq = lut(fine_lats, fine_lons)\n\n >>> import matplotlib.pyplot as plt\n >>> fig = plt.figure()\n >>> ax1 = fig.add_subplot(131)\n >>> ax1.imshow(data, interpolation='nearest')\n >>> ax2 = fig.add_subplot(132)\n >>> ax2.imshow(data_orig, interpolation='nearest')\n >>> ax3 = fig.add_subplot(133)\n >>> ax3.imshow(data_lsq, interpolation='nearest')\n >>> plt.show()\n\n \"\"\"\n\n def __init__(self, theta, phi, r, tt, tp, w=None, eps=1E-16):\n if np.issubclass_(w, float):\n w = ones(len(theta)) * w\n nt_, np_ = 8 + len(tt), 8 + len(tp)\n tt_, tp_ = zeros((nt_,), float), zeros((np_,), float)\n tt_[4:-4], tp_[4:-4] = tt, tp\n tt_[-4:], tp_[-4:] = np.pi, 2. * np.pi\n tt_, tp_, c, fp, ier = dfitpack.spherfit_lsq(theta, phi, r, tt_, tp_,\n w=w, eps=eps)\n if ier < -2:\n deficiency = 6 + (nt_ - 8) * (np_ - 7) + ier\n message = _spherefit_messages.get(-3) % (deficiency, -ier)\n warnings.warn(message)\n elif ier not in [0, -1, -2]:\n message = _spherefit_messages.get(ier, 'ier=%s' % (ier))\n raise ValueError(message)\n\n self.fp = fp\n self.tck = tt_, tp_, c\n self.degrees = (3, 3)\n\n\n_spfit_messages = _surfit_messages.copy()\n_spfit_messages[10] = \"\"\"\nERROR: on entry, the input data are controlled on validity\n the following restrictions must be satisfied.\n -1<=iopt(1)<=1, 0<=iopt(2)<=1, 0<=iopt(3)<=1,\n -1<=ider(1)<=1, 0<=ider(2)<=1, ider(2)=0 if iopt(2)=0.\n -1<=ider(3)<=1, 0<=ider(4)<=1, ider(4)=0 if iopt(3)=0.\n mu >= mumin (see above), mv >= 4, nuest >=8, nvest >= 8,\n kwrk>=5+mu+mv+nuest+nvest,\n lwrk >= 12+nuest*(mv+nvest+3)+nvest*24+4*mu+8*mv+max(nuest,mv+nvest)\n 0< u(i-1)<u(i)< pi,i=2,..,mu,\n -pi<=v(1)< pi, v(1)<v(i-1)<v(i)<v(1)+2*pi, i=3,...,mv\n if iopt(1)=-1: 8<=nu<=min(nuest,mu+6+iopt(2)+iopt(3))\n 0<tu(5)<tu(6)<...<tu(nu-4)< pi\n 8<=nv<=min(nvest,mv+7)\n v(1)<tv(5)<tv(6)<...<tv(nv-4)<v(1)+2*pi\n the schoenberg-whitney conditions, i.e. there must be\n subset of grid co-ordinates uu(p) and vv(q) such that\n tu(p) < uu(p) < tu(p+4) ,p=1,...,nu-4\n (iopt(2)=1 and iopt(3)=1 also count for a uu-value\n tv(q) < vv(q) < tv(q+4) ,q=1,...,nv-4\n (vv(q) is either a value v(j) or v(j)+2*pi)\n if iopt(1)>=0: s>=0\n if s=0: nuest>=mu+6+iopt(2)+iopt(3), nvest>=mv+7\n if one of these conditions is found to be violated,control is\n immediately repassed to the calling program. in that case there is no\n approximation returned.\"\"\"\n\n\nclass RectSphereBivariateSpline(SphereBivariateSpline):\n \"\"\"\n Bivariate spline approximation over a rectangular mesh on a sphere.\n\n Can be used for smoothing data.\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n u : array_like\n 1-D array of latitude coordinates in strictly ascending order.\n Coordinates must be given in radians and lie within the interval\n (0, pi).\n v : array_like\n 1-D array of longitude coordinates in strictly ascending order.\n Coordinates must be given in radians. First element (v[0]) must lie\n within the interval [-pi, pi). Last element (v[-1]) must satisfy\n v[-1] <= v[0] + 2*pi.\n r : array_like\n 2-D array of data with shape ``(u.size, v.size)``.\n s : float, optional\n Positive smoothing factor defined for estimation condition\n (``s=0`` is for interpolation).\n pole_continuity : bool or (bool, bool), optional\n Order of continuity at the poles ``u=0`` (``pole_continuity[0]``) and\n ``u=pi`` (``pole_continuity[1]``). The order of continuity at the pole\n will be 1 or 0 when this is True or False, respectively.\n Defaults to False.\n pole_values : float or (float, float), optional\n Data values at the poles ``u=0`` and ``u=pi``. Either the whole\n parameter or each individual element can be None. Defaults to None.\n pole_exact : bool or (bool, bool), optional\n Data value exactness at the poles ``u=0`` and ``u=pi``. If True, the\n value is considered to be the right function value, and it will be\n fitted exactly. If False, the value will be considered to be a data\n value just like the other data values. Defaults to False.\n pole_flat : bool or (bool, bool), optional\n For the poles at ``u=0`` and ``u=pi``, specify whether or not the\n approximation has vanishing derivatives. Defaults to False.\n\n See Also\n --------\n RectBivariateSpline : bivariate spline approximation over a rectangular\n mesh\n\n Notes\n -----\n Currently, only the smoothing spline approximation (``iopt[0] = 0`` and\n ``iopt[0] = 1`` in the FITPACK routine) is supported. The exact\n least-squares spline approximation is not implemented yet.\n\n When actually performing the interpolation, the requested `v` values must\n lie within the same length 2pi interval that the original `v` values were\n chosen from.\n\n For more information, see the FITPACK_ site about this function.\n\n .. _FITPACK: http://www.netlib.org/dierckx/spgrid.f\n\n Examples\n --------\n Suppose we have global data on a coarse grid\n\n >>> lats = np.linspace(10, 170, 9) * np.pi / 180.\n >>> lons = np.linspace(0, 350, 18) * np.pi / 180.\n >>> data = np.dot(np.atleast_2d(90. - np.linspace(-80., 80., 18)).T,\n ... np.atleast_2d(180. - np.abs(np.linspace(0., 350., 9)))).T\n\n We want to interpolate it to a global one-degree grid\n\n >>> new_lats = np.linspace(1, 180, 180) * np.pi / 180\n >>> new_lons = np.linspace(1, 360, 360) * np.pi / 180\n >>> new_lats, new_lons = np.meshgrid(new_lats, new_lons)\n\n We need to set up the interpolator object\n\n >>> from scipy.interpolate import RectSphereBivariateSpline\n >>> lut = RectSphereBivariateSpline(lats, lons, data)\n\n Finally we interpolate the data. The `RectSphereBivariateSpline` object\n only takes 1-D arrays as input, therefore we need to do some reshaping.\n\n >>> data_interp = lut.ev(new_lats.ravel(),\n ... new_lons.ravel()).reshape((360, 180)).T\n\n Looking at the original and the interpolated data, one can see that the\n interpolant reproduces the original data very well:\n\n >>> import matplotlib.pyplot as plt\n >>> fig = plt.figure()\n >>> ax1 = fig.add_subplot(211)\n >>> ax1.imshow(data, interpolation='nearest')\n >>> ax2 = fig.add_subplot(212)\n >>> ax2.imshow(data_interp, interpolation='nearest')\n >>> plt.show()\n\n Chosing the optimal value of ``s`` can be a delicate task. Recommended\n values for ``s`` depend on the accuracy of the data values. If the user\n has an idea of the statistical errors on the data, she can also find a\n proper estimate for ``s``. By assuming that, if she specifies the\n right ``s``, the interpolator will use a spline ``f(u,v)`` which exactly\n reproduces the function underlying the data, she can evaluate\n ``sum((r(i,j)-s(u(i),v(j)))**2)`` to find a good estimate for this ``s``.\n For example, if she knows that the statistical errors on her\n ``r(i,j)``-values are not greater than 0.1, she may expect that a good\n ``s`` should have a value not larger than ``u.size * v.size * (0.1)**2``.\n\n If nothing is known about the statistical error in ``r(i,j)``, ``s`` must\n be determined by trial and error. The best is then to start with a very\n large value of ``s`` (to determine the least-squares polynomial and the\n corresponding upper bound ``fp0`` for ``s``) and then to progressively\n decrease the value of ``s`` (say by a factor 10 in the beginning, i.e.\n ``s = fp0 / 10, fp0 / 100, ...`` and more carefully as the approximation\n shows more detail) to obtain closer fits.\n\n The interpolation results for different values of ``s`` give some insight\n into this process:\n\n >>> fig2 = plt.figure()\n >>> s = [3e9, 2e9, 1e9, 1e8]\n >>> for ii in xrange(len(s)):\n ... lut = RectSphereBivariateSpline(lats, lons, data, s=s[ii])\n ... data_interp = lut.ev(new_lats.ravel(),\n ... new_lons.ravel()).reshape((360, 180)).T\n ... ax = fig2.add_subplot(2, 2, ii+1)\n ... ax.imshow(data_interp, interpolation='nearest')\n ... ax.set_title(\"s = %g\" % s[ii])\n >>> plt.show()\n\n \"\"\"\n\n def __init__(self, u, v, r, s=0., pole_continuity=False, pole_values=None,\n pole_exact=False, pole_flat=False):\n iopt = np.array([0, 0, 0], dtype=int)\n ider = np.array([-1, 0, -1, 0], dtype=int)\n if pole_values is None:\n pole_values = (None, None)\n elif isinstance(pole_values, (float, np.float32, np.float64)):\n pole_values = (pole_values, pole_values)\n if isinstance(pole_continuity, bool):\n pole_continuity = (pole_continuity, pole_continuity)\n if isinstance(pole_exact, bool):\n pole_exact = (pole_exact, pole_exact)\n if isinstance(pole_flat, bool):\n pole_flat = (pole_flat, pole_flat)\n\n r0, r1 = pole_values\n iopt[1:] = pole_continuity\n if r0 is None:\n ider[0] = -1\n else:\n ider[0] = pole_exact[0]\n\n if r1 is None:\n ider[2] = -1\n else:\n ider[2] = pole_exact[1]\n\n ider[1], ider[3] = pole_flat\n\n u, v = np.ravel(u), np.ravel(v)\n if not np.all(np.diff(u) > 0.0):\n raise ValueError('u must be strictly increasing')\n if not np.all(np.diff(v) > 0.0):\n raise ValueError('v must be strictly increasing')\n\n if not u.size == r.shape[0]:\n raise ValueError('u dimension of r must have same number of '\n 'elements as u')\n if not v.size == r.shape[1]:\n raise ValueError('v dimension of r must have same number of '\n 'elements as v')\n\n if pole_continuity[1] is False and pole_flat[1] is True:\n raise ValueError('if pole_continuity is False, so must be '\n 'pole_flat')\n if pole_continuity[0] is False and pole_flat[0] is True:\n raise ValueError('if pole_continuity is False, so must be '\n 'pole_flat')\n\n r = np.ravel(r)\n nu, tu, nv, tv, c, fp, ier = dfitpack.regrid_smth_spher(iopt, ider,\n u.copy(), v.copy(), r.copy(), r0, r1, s)\n\n if ier not in [0, -1, -2]:\n msg = _spfit_messages.get(ier, 'ier=%s' % (ier))\n raise ValueError(msg)\n\n self.fp = fp\n self.tck = tu[:nu], tv[:nv], c[:(nu - 4) * (nv-4)]\n self.degrees = (3, 3)\n"
]
| [
[
"numpy.concatenate",
"numpy.array",
"numpy.asarray",
"numpy.zeros",
"numpy.broadcast_arrays",
"numpy.diff",
"numpy.resize",
"numpy.ravel",
"numpy.alltrue",
"numpy.isfinite",
"numpy.issubclass_"
]
]
|
naykun/MusicResearch | [
"97bd64f23710c9f45634da0fd4674172746cfaf5"
]
| [
"Polyphony_Dataset_Convertor/old/polyphony_lib.py"
]
| [
"# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Utility functions for working with polyphonic sequences.\"\"\"\n\nfrom __future__ import division\n\nimport collections\nimport copy\n\n# internal imports\n\nfrom six.moves import range # pylint: disable=redefined-builtin\nimport tensorflow as tf\n\nfrom magenta.music import constants\nfrom magenta.music import events_lib\nfrom magenta.music import sequences_lib\nfrom magenta.pipelines import statistics\nfrom magenta.protobuf import music_pb2\n\nDEFAULT_STEPS_PER_QUARTER = constants.DEFAULT_STEPS_PER_QUARTER\nMAX_MIDI_PITCH = constants.MAX_MIDI_PITCH\nMIN_MIDI_PITCH = constants.MIN_MIDI_PITCH\nSTANDARD_PPQ = constants.STANDARD_PPQ\n\n\nclass PolyphonicEvent(object):\n \"\"\"Class for storing events in a polyphonic sequence.\"\"\"\n\n # Beginning of the sequence.\n START = 0\n # End of the sequence.\n END = 1\n # End of a step within the sequence.\n STEP_END = 2\n # Start of a new note.\n NEW_NOTE = 3\n # Continuation of a note.\n CONTINUED_NOTE = 4\n\n def __init__(self, event_type, pitch):\n if not (PolyphonicEvent.START <= event_type <=\n PolyphonicEvent.CONTINUED_NOTE):\n raise ValueError('Invalid event type: %s' % event_type)\n if not (pitch is None or MIN_MIDI_PITCH <= pitch <= MAX_MIDI_PITCH):\n raise ValueError('Invalid pitch: %s' % pitch)\n\n self.event_type = event_type\n self.pitch = pitch\n\n def __repr__(self):\n return 'PolyphonicEvent(%r, %r)' % (self.event_type, self.pitch)\n\n def __eq__(self, other):\n if not isinstance(other, PolyphonicEvent):\n return False\n return (self.event_type == other.event_type and\n self.pitch == other.pitch)\n\n\nclass PolyphonicSequence(events_lib.EventSequence):\n \"\"\"Stores a polyphonic sequence as a stream of single-note events.\n\n Events are PolyphonicEvent tuples that encode event type and pitch.\n \"\"\"\n\n def __init__(self, quantized_sequence=None, steps_per_quarter=None,\n start_step=0):\n \"\"\"Construct a PolyphonicSequence.\n\n Either quantized_sequence or steps_per_quarter should be supplied.\n\n Args:\n quantized_sequence: a quantized NoteSequence proto.\n steps_per_quarter: how many steps a quarter note represents.\n start_step: The offset of this sequence relative to the\n beginning of the source sequence. If a quantized sequence is used as\n input, only notes starting after this step will be considered.\n \"\"\"\n assert (quantized_sequence, steps_per_quarter).count(None) == 1\n\n if quantized_sequence:\n sequences_lib.assert_is_relative_quantized_sequence(quantized_sequence)\n self._events = self._from_quantized_sequence(quantized_sequence,\n start_step)\n self._steps_per_quarter = (\n quantized_sequence.quantization_info.steps_per_quarter)\n else:\n self._events = [\n PolyphonicEvent(event_type=PolyphonicEvent.START, pitch=None)]\n self._steps_per_quarter = steps_per_quarter\n\n self._start_step = start_step\n\n @property\n def start_step(self):\n return self._start_step\n\n @property\n def steps_per_quarter(self):\n return self._steps_per_quarter\n\n def trim_trailing_end_events(self):\n \"\"\"Removes the trailing END event if present.\n\n Should be called before using a sequence to prime generation.\n \"\"\"\n while self._events[-1].event_type == PolyphonicEvent.END:\n del self._events[-1]\n\n def _append_silence_steps(self, num_steps):\n \"\"\"Adds steps of silence to the end of the sequence.\"\"\"\n for _ in range(num_steps):\n self._events.append(\n PolyphonicEvent(event_type=PolyphonicEvent.STEP_END, pitch=None))\n\n def _trim_steps(self, num_steps):\n \"\"\"Trims a given number of steps from the end of the sequence.\"\"\"\n steps_trimmed = 0\n for i in reversed(range(len(self._events))):\n if self._events[i].event_type == PolyphonicEvent.STEP_END:\n if steps_trimmed == num_steps:\n del self._events[i + 1:]\n break\n steps_trimmed += 1\n elif i == 0:\n self._events = [\n PolyphonicEvent(event_type=PolyphonicEvent.START, pitch=None)]\n break\n\n def set_length(self, steps, from_left=False):\n \"\"\"Sets the length of the sequence to the specified number of steps.\n\n If the event sequence is not long enough, pads with silence to make the\n sequence the specified length. If it is too long, it will be truncated to\n the requested length.\n\n Note that this will append a STEP_END event to the end of the sequence if\n there is an unfinished step.\n\n Args:\n steps: How many quantized steps long the event sequence should be.\n from_left: Whether to add/remove from the left instead of right.\n \"\"\"\n if from_left:\n raise NotImplementedError('from_left is not supported')\n\n # First remove any trailing end events.\n self.trim_trailing_end_events()\n # Then add an end step event, to close out any incomplete steps.\n self._events.append(\n PolyphonicEvent(event_type=PolyphonicEvent.STEP_END, pitch=None))\n # Then trim or pad as needed.\n if self.num_steps < steps:\n self._append_silence_steps(steps - self.num_steps)\n elif self.num_steps > steps:\n self._trim_steps(self.num_steps - steps)\n # Then add a trailing end event.\n self._events.append(\n PolyphonicEvent(event_type=PolyphonicEvent.END, pitch=None))\n assert self.num_steps == steps\n\n def append(self, event):\n \"\"\"Appends the event to the end of the sequence.\n\n Args:\n event: The polyphonic event to append to the end.\n Raises:\n ValueError: If `event` is not a valid polyphonic event.\n \"\"\"\n if not isinstance(event, PolyphonicEvent):\n raise ValueError('Invalid polyphonic event: %s' % event)\n self._events.append(event)\n\n def __len__(self):\n \"\"\"How many events are in this sequence.\n\n Returns:\n Number of events as an integer.\n \"\"\"\n return len(self._events)\n\n def __getitem__(self, i):\n \"\"\"Returns the event at the given index.\"\"\"\n return self._events[i]\n\n def __iter__(self):\n \"\"\"Return an iterator over the events in this sequence.\"\"\"\n return iter(self._events)\n\n def __str__(self):\n strs = []\n for event in self:\n if event.event_type == PolyphonicEvent.START:\n strs.append('START')\n elif event.event_type == PolyphonicEvent.END:\n strs.append('END')\n elif event.event_type == PolyphonicEvent.STEP_END:\n strs.append('|||')\n elif event.event_type == PolyphonicEvent.NEW_NOTE:\n strs.append('(%s, NEW)' % event.pitch)\n elif event.event_type == PolyphonicEvent.CONTINUED_NOTE:\n strs.append('(%s, CONTINUED)' % event.pitch)\n else:\n raise ValueError('Unknown event type: %s' % event.event_type)\n return '\\n'.join(strs)\n\n @property\n def end_step(self):\n return self.start_step + self.num_steps\n\n @property\n def num_steps(self):\n \"\"\"Returns how many steps long this sequence is.\n\n Does not count incomplete steps (i.e., steps that do not have a terminating\n STEP_END event).\n\n Returns:\n Length of the sequence in quantized steps.\n \"\"\"\n steps = 0\n for event in self:\n if event.event_type == PolyphonicEvent.STEP_END:\n steps += 1\n return steps\n\n @property\n def steps(self):\n \"\"\"Return a Python list of the time step at each event in this sequence.\"\"\"\n step = self.start_step\n result = []\n for event in self:\n result.append(step)\n if event.event_type == PolyphonicEvent.STEP_END:\n step += 1\n return result\n\n @staticmethod\n def _from_quantized_sequence(quantized_sequence, start_step=0):\n \"\"\"Populate self with events from the given quantized NoteSequence object.\n\n Sequences start with START.\n\n Within a step, new pitches are started with NEW_NOTE and existing\n pitches are continued with CONTINUED_NOTE. A step is ended with\n STEP_END. If an active pitch is not continued, it is considered to\n have ended.\n\n Sequences end with END.\n\n Args:\n quantized_sequence: A quantized NoteSequence instance.\n start_step: Start converting the sequence at this time step.\n Assumed to be the beginning of a bar.\n\n Returns:\n A list of events.\n \"\"\"\n pitch_start_steps = collections.defaultdict(list)\n pitch_end_steps = collections.defaultdict(list)\n\n for note in quantized_sequence.notes:\n if note.quantized_start_step < start_step:\n continue\n pitch_start_steps[note.quantized_start_step].append(note.pitch)\n pitch_end_steps[note.quantized_end_step].append(note.pitch)\n\n events = [PolyphonicEvent(event_type=PolyphonicEvent.START, pitch=None)]\n\n # Use a list rather than a set because one pitch may be active multiple\n # times.\n active_pitches = []\n for step in range(start_step,\n quantized_sequence.total_quantized_steps):\n step_events = []\n\n for pitch in pitch_end_steps[step]:\n active_pitches.remove(pitch)\n\n for pitch in active_pitches:\n step_events.append(\n PolyphonicEvent(event_type=PolyphonicEvent.CONTINUED_NOTE,\n pitch=pitch))\n\n for pitch in pitch_start_steps[step]:\n active_pitches.append(pitch)\n step_events.append(PolyphonicEvent(event_type=PolyphonicEvent.NEW_NOTE,\n pitch=pitch))\n\n events.extend(sorted(step_events, key=lambda e: e.pitch, reverse=True))\n events.append(\n PolyphonicEvent(event_type=PolyphonicEvent.STEP_END, pitch=None))\n events.append(PolyphonicEvent(event_type=PolyphonicEvent.END, pitch=None))\n\n return events\n\n def to_sequence(self,\n velocity=100,\n instrument=0,\n program=0,\n qpm=constants.DEFAULT_QUARTERS_PER_MINUTE,\n base_note_sequence=None):\n \"\"\"Converts the PolyphonicSequence to NoteSequence proto.\n\n Assumes that the sequences ends with a STEP_END followed by an END event. To\n ensure this is true, call set_length before calling this method.\n\n Args:\n velocity: Midi velocity to give each note. Between 1 and 127 (inclusive).\n instrument: Midi instrument to give each note.\n program: Midi program to give each note.\n qpm: Quarter notes per minute (float).\n base_note_sequence: A NoteSequence to use a starting point. Must match the\n specified qpm.\n\n Raises:\n ValueError: if an unknown event is encountered.\n\n Returns:\n A NoteSequence proto.\n \"\"\"\n seconds_per_step = 60.0 / qpm / self._steps_per_quarter\n\n sequence_start_time = self.start_step * seconds_per_step\n\n if base_note_sequence:\n sequence = copy.deepcopy(base_note_sequence)\n if sequence.tempos[0].qpm != qpm:\n raise ValueError(\n 'Supplied QPM (%d) does not match QPM of base_note_sequence (%d)'\n % (qpm, sequence.tempos[0].qpm))\n else:\n sequence = music_pb2.NoteSequence()\n sequence.tempos.add().qpm = qpm\n sequence.ticks_per_quarter = STANDARD_PPQ\n\n step = 0\n # Use lists rather than sets because one pitch may be active multiple times.\n pitch_start_steps = []\n pitches_to_end = []\n for i, event in enumerate(self):\n if event.event_type == PolyphonicEvent.START:\n if i != 0:\n tf.logging.debug(\n 'Ignoring START marker not at beginning of sequence at position '\n '%d' % i)\n elif event.event_type == PolyphonicEvent.END and i < len(self) - 1:\n tf.logging.debug(\n 'Ignoring END maker before end of sequence at position %d' % i)\n elif event.event_type == PolyphonicEvent.NEW_NOTE:\n pitch_start_steps.append((event.pitch, step))\n elif event.event_type == PolyphonicEvent.CONTINUED_NOTE:\n try:\n pitches_to_end.remove(event.pitch)\n except ValueError:\n tf.logging.debug(\n 'Attempted to continue pitch %s at step %s, but pitch was not '\n 'active. Ignoring.' % (event.pitch, step))\n elif (event.event_type == PolyphonicEvent.STEP_END or\n event.event_type == PolyphonicEvent.END):\n # Find active pitches that should end. Create notes for them, based on\n # when they started.\n # Make a copy of pitch_start_steps so we can remove things from it while\n # iterating.\n for pitch_start_step in list(pitch_start_steps):\n if pitch_start_step[0] in pitches_to_end:\n pitches_to_end.remove(pitch_start_step[0])\n pitch_start_steps.remove(pitch_start_step)\n\n note = sequence.notes.add()\n note.start_time = (pitch_start_step[1] * seconds_per_step +\n sequence_start_time)\n note.end_time = step * seconds_per_step + sequence_start_time\n note.pitch = pitch_start_step[0]\n note.velocity = velocity\n note.instrument = instrument\n note.program = program\n\n assert not pitches_to_end\n\n # Increment the step counter.\n step += 1\n\n # All active pitches are eligible for ending unless continued.\n pitches_to_end = [ps[0] for ps in pitch_start_steps]\n else:\n raise ValueError('Unknown event type: %s' % event.event_type)\n \n \n # Modified by Someday\n '''\n \n if pitch_start_steps:\n raise ValueError(\n 'Sequence ended, but not all pitches were ended. This likely means '\n 'the sequence was missing a STEP_END event before the end of the '\n 'sequence. To ensure a well-formed sequence, call set_length first.')\n \n '''\n\n sequence.total_time = seconds_per_step * (step - 1) + sequence_start_time\n if sequence.notes:\n assert sequence.total_time >= sequence.notes[-1].end_time\n\n return sequence\n\n\ndef extract_polyphonic_sequences(\n quantized_sequence, start_step=0, min_steps_discard=None,\n max_steps_discard=None):\n \"\"\"Extracts a polyphonic track from the given quantized NoteSequence.\n\n Currently, this extracts only one polyphonic sequence from a given track.\n\n Args:\n quantized_sequence: A quantized NoteSequence.\n start_step: Start extracting a sequence at this time step. Assumed\n to be the beginning of a bar.\n min_steps_discard: Minimum length of tracks in steps. Shorter tracks are\n discarded.\n max_steps_discard: Maximum length of tracks in steps. Longer tracks are\n discarded.\n\n Returns:\n poly_seqs: A python list of PolyphonicSequence instances.\n stats: A dictionary mapping string names to `statistics.Statistic` objects.\n \"\"\"\n sequences_lib.assert_is_relative_quantized_sequence(quantized_sequence)\n\n stats = dict([(stat_name, statistics.Counter(stat_name)) for stat_name in\n ['polyphonic_tracks_discarded_too_short',\n 'polyphonic_tracks_discarded_too_long',\n 'polyphonic_tracks_discarded_more_than_1_program']])\n\n steps_per_bar = sequences_lib.steps_per_bar_in_quantized_sequence(\n quantized_sequence)\n\n # Create a histogram measuring lengths (in bars not steps).\n stats['polyphonic_track_lengths_in_bars'] = statistics.Histogram(\n 'polyphonic_track_lengths_in_bars',\n [0, 1, 10, 20, 30, 40, 50, 100, 200, 500, 1000])\n\n # Allow only 1 program.\n programs = set()\n for note in quantized_sequence.notes:\n programs.add(note.program)\n if len(programs) > 1:\n stats['polyphonic_tracks_discarded_more_than_1_program'].increment()\n return [], stats.values()\n\n # Translate the quantized sequence into a PolyphonicSequence.\n poly_seq = PolyphonicSequence(quantized_sequence,\n start_step=start_step)\n\n poly_seqs = []\n num_steps = poly_seq.num_steps\n\n if min_steps_discard is not None and num_steps < min_steps_discard:\n stats['polyphonic_tracks_discarded_too_short'].increment()\n elif max_steps_discard is not None and num_steps > max_steps_discard:\n stats['polyphonic_tracks_discarded_too_long'].increment()\n else:\n poly_seqs.append(poly_seq)\n stats['polyphonic_track_lengths_in_bars'].increment(\n num_steps // steps_per_bar)\n\n return poly_seqs, stats.values()\n"
]
| [
[
"tensorflow.logging.debug"
]
]
|
openvisual/TensorFlow-2.x-YOLOv3 | [
"f0b8b74dc557c1ba79154373c904f865ae60bbc4"
]
| [
"yolov3/utils.py"
]
| [
"#================================================================\n#\n# File name : utils.py\n# Author : PyLessons\n# Created date: 2020-09-27\n# Website : https://pylessons.com/\n# GitHub : https://github.com/pythonlessons/TensorFlow-2.x-YOLOv3\n# Description : additional yolov3 and yolov4 functions\n#\n#================================================================\nfrom multiprocessing import Process, Queue, Pipe\nimport cv2\nimport time\nimport random\nimport colorsys\nimport numpy as np\nimport tensorflow as tf\nfrom yolov3.configs import *\nfrom yolov3.yolov4 import *\nfrom tensorflow.python.saved_model import tag_constants\n\ndef load_yolo_weights(model, weights_file):\n tf.keras.backend.clear_session() # used to reset layer names\n # load Darknet original weights to TensorFlow model\n if YOLO_TYPE == \"yolov3\":\n range1 = 75 if not TRAIN_YOLO_TINY else 13\n range2 = [58, 66, 74] if not TRAIN_YOLO_TINY else [9, 12]\n if YOLO_TYPE == \"yolov4\":\n range1 = 110 if not TRAIN_YOLO_TINY else 21\n range2 = [93, 101, 109] if not TRAIN_YOLO_TINY else [17, 20]\n \n with open(weights_file, 'rb') as wf:\n major, minor, revision, seen, _ = np.fromfile(wf, dtype=np.int32, count=5)\n\n j = 0\n for i in range(range1):\n if i > 0:\n conv_layer_name = 'conv2d_%d' %i\n else:\n conv_layer_name = 'conv2d'\n \n if j > 0:\n bn_layer_name = 'batch_normalization_%d' %j\n else:\n bn_layer_name = 'batch_normalization'\n \n conv_layer = model.get_layer(conv_layer_name)\n filters = conv_layer.filters\n k_size = conv_layer.kernel_size[0]\n in_dim = conv_layer.input_shape[-1]\n\n if i not in range2:\n # darknet weights: [beta, gamma, mean, variance]\n bn_weights = np.fromfile(wf, dtype=np.float32, count=4 * filters)\n # tf weights: [gamma, beta, mean, variance]\n bn_weights = bn_weights.reshape((4, filters))[[1, 0, 2, 3]]\n bn_layer = model.get_layer(bn_layer_name)\n j += 1\n else:\n conv_bias = np.fromfile(wf, dtype=np.float32, count=filters)\n\n # darknet shape (out_dim, in_dim, height, width)\n conv_shape = (filters, in_dim, k_size, k_size)\n conv_weights = np.fromfile(wf, dtype=np.float32, count=np.product(conv_shape))\n # tf shape (height, width, in_dim, out_dim)\n conv_weights = conv_weights.reshape(conv_shape).transpose([2, 3, 1, 0])\n\n if i not in range2:\n conv_layer.set_weights([conv_weights])\n bn_layer.set_weights(bn_weights)\n else:\n conv_layer.set_weights([conv_weights, conv_bias])\n\n assert len(wf.read()) == 0, 'failed to read all data'\n\ndef Load_Yolo_model():\n gpus = tf.config.experimental.list_physical_devices('GPU')\n if len(gpus) > 0:\n print(f'GPUs {gpus}')\n try: tf.config.experimental.set_memory_growth(gpus[0], True)\n except RuntimeError: pass\n pass\n \n if YOLO_FRAMEWORK == \"tf\": # TensorFlow detection\n if YOLO_TYPE == \"yolov4\":\n Darknet_weights = YOLO_V4_TINY_WEIGHTS if TRAIN_YOLO_TINY else YOLO_V4_WEIGHTS\n elif YOLO_TYPE == \"yolov3\":\n Darknet_weights = YOLO_V3_TINY_WEIGHTS if TRAIN_YOLO_TINY else YOLO_V3_WEIGHTS\n pass\n \n if YOLO_CUSTOM_WEIGHTS == False:\n yolo = Create_Yolo(input_size=YOLO_INPUT_SIZE, CLASSES=YOLO_COCO_CLASSES)\n load_yolo_weights(yolo, Darknet_weights) # use Darknet weights\n else:\n yolo = Create_Yolo(input_size=YOLO_INPUT_SIZE, CLASSES=TRAIN_CLASSES)\n yolo.load_weights(f\"./checkpoints/{TRAIN_MODEL_NAME}\") # use custom weights\n pass\n elif YOLO_FRAMEWORK == \"trt\": # TensorRT detection\n saved_model_loaded = tf.saved_model.load(YOLO_CUSTOM_WEIGHTS, tags=[tag_constants.SERVING])\n signature_keys = list(saved_model_loaded.signatures.keys())\n yolo = saved_model_loaded.signatures['serving_default']\n pass\n\n return yolo\npass\n\ndef image_preprocess(image, target_size, gt_boxes=None):\n ih, iw = target_size\n h, w, _ = image.shape\n\n scale = min(iw/w, ih/h)\n nw, nh = int(scale * w), int(scale * h)\n image_resized = cv2.resize(image, (nw, nh))\n\n image_paded = np.full(shape=[ih, iw, 3], fill_value=128.0)\n dw, dh = (iw - nw) // 2, (ih-nh) // 2\n image_paded[dh:nh+dh, dw:nw+dw, :] = image_resized\n image_paded = image_paded / 255.\n\n if gt_boxes is None:\n return image_paded\n\n else:\n gt_boxes[:, [0, 2]] = gt_boxes[:, [0, 2]] * scale + dw\n gt_boxes[:, [1, 3]] = gt_boxes[:, [1, 3]] * scale + dh\n return image_paded, gt_boxes\n\n\ndef draw_bbox(image, bboxes, CLASSES=YOLO_COCO_CLASSES, show_label=True, show_confidence = True, Text_colors=(255,255,0), rectangle_colors='', tracking=False): \n NUM_CLASS = read_class_names(CLASSES)\n num_classes = len(NUM_CLASS)\n image_h, image_w, _ = image.shape\n hsv_tuples = [(1.0 * x / num_classes, 1., 1.) for x in range(num_classes)]\n #print(\"hsv_tuples\", hsv_tuples)\n colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\n colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors))\n\n random.seed(0)\n random.shuffle(colors)\n random.seed(None)\n\n for i, bbox in enumerate(bboxes):\n coor = np.array(bbox[:4], dtype=np.int32)\n score = bbox[4]\n class_ind = int(bbox[5])\n bbox_color = rectangle_colors if rectangle_colors != '' else colors[class_ind]\n bbox_thick = int(0.6 * (image_h + image_w) / 1000)\n if bbox_thick < 1: bbox_thick = 1\n fontScale = 0.75 * bbox_thick\n (x1, y1), (x2, y2) = (coor[0], coor[1]), (coor[2], coor[3])\n\n # put object rectangle\n cv2.rectangle(image, (x1, y1), (x2, y2), bbox_color, bbox_thick*2)\n\n if show_label:\n # get text label\n score_str = \" {:.2f}\".format(score) if show_confidence else \"\"\n\n if tracking: score_str = \" \"+str(score)\n\n label = \"{}\".format(NUM_CLASS[class_ind]) + score_str\n\n # get text size\n (text_width, text_height), baseline = cv2.getTextSize(label, cv2.FONT_HERSHEY_COMPLEX_SMALL,\n fontScale, thickness=bbox_thick)\n # put filled text rectangle\n cv2.rectangle(image, (x1, y1), (x1 + text_width, y1 - text_height - baseline), bbox_color, thickness=cv2.FILLED)\n\n # put text above rectangle\n cv2.putText(image, label, (x1, y1-4), cv2.FONT_HERSHEY_COMPLEX_SMALL,\n fontScale, Text_colors, bbox_thick, lineType=cv2.LINE_AA)\n\n return image\n\n\ndef bboxes_iou(boxes1, boxes2):\n boxes1 = np.array(boxes1)\n boxes2 = np.array(boxes2)\n\n boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1])\n boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) * (boxes2[..., 3] - boxes2[..., 1])\n\n left_up = np.maximum(boxes1[..., :2], boxes2[..., :2])\n right_down = np.minimum(boxes1[..., 2:], boxes2[..., 2:])\n\n inter_section = np.maximum(right_down - left_up, 0.0)\n inter_area = inter_section[..., 0] * inter_section[..., 1]\n union_area = boxes1_area + boxes2_area - inter_area\n ious = np.maximum(1.0 * inter_area / union_area, np.finfo(np.float32).eps)\n\n return ious\n\n\ndef nms(bboxes, iou_threshold, sigma=0.3, method='nms'):\n \"\"\"\n :param bboxes: (xmin, ymin, xmax, ymax, score, class)\n\n Note: soft-nms, https://arxiv.org/pdf/1704.04503.pdf\n https://github.com/bharatsingh430/soft-nms\n \"\"\"\n classes_in_img = list(set(bboxes[:, 5]))\n best_bboxes = []\n\n for cls in classes_in_img:\n cls_mask = (bboxes[:, 5] == cls)\n cls_bboxes = bboxes[cls_mask]\n # Process 1: Determine whether the number of bounding boxes is greater than 0 \n while len(cls_bboxes) > 0:\n # Process 2: Select the bounding box with the highest score according to socre order A\n max_ind = np.argmax(cls_bboxes[:, 4])\n best_bbox = cls_bboxes[max_ind]\n best_bboxes.append(best_bbox)\n cls_bboxes = np.concatenate([cls_bboxes[: max_ind], cls_bboxes[max_ind + 1:]])\n # Process 3: Calculate this bounding box A and\n # Remain all iou of the bounding box and remove those bounding boxes whose iou value is higher than the threshold \n iou = bboxes_iou(best_bbox[np.newaxis, :4], cls_bboxes[:, :4])\n weight = np.ones((len(iou),), dtype=np.float32)\n\n assert method in ['nms', 'soft-nms']\n\n if method == 'nms':\n iou_mask = iou > iou_threshold\n weight[iou_mask] = 0.0\n\n if method == 'soft-nms':\n weight = np.exp(-(1.0 * iou ** 2 / sigma))\n\n cls_bboxes[:, 4] = cls_bboxes[:, 4] * weight\n score_mask = cls_bboxes[:, 4] > 0.\n cls_bboxes = cls_bboxes[score_mask]\n\n return best_bboxes\n\n\ndef postprocess_boxes(pred_bbox, original_image, input_size, score_threshold):\n valid_scale=[0, np.inf]\n pred_bbox = np.array(pred_bbox)\n\n pred_xywh = pred_bbox[:, 0:4]\n pred_conf = pred_bbox[:, 4]\n pred_prob = pred_bbox[:, 5:]\n\n # 1. (x, y, w, h) --> (xmin, ymin, xmax, ymax)\n pred_coor = np.concatenate([pred_xywh[:, :2] - pred_xywh[:, 2:] * 0.5,\n pred_xywh[:, :2] + pred_xywh[:, 2:] * 0.5], axis=-1)\n # 2. (xmin, ymin, xmax, ymax) -> (xmin_org, ymin_org, xmax_org, ymax_org)\n org_h, org_w = original_image.shape[:2]\n resize_ratio = min(input_size / org_w, input_size / org_h)\n\n dw = (input_size - resize_ratio * org_w) / 2\n dh = (input_size - resize_ratio * org_h) / 2\n\n pred_coor[:, 0::2] = 1.0 * (pred_coor[:, 0::2] - dw) / resize_ratio\n pred_coor[:, 1::2] = 1.0 * (pred_coor[:, 1::2] - dh) / resize_ratio\n\n # 3. clip some boxes those are out of range\n pred_coor = np.concatenate([np.maximum(pred_coor[:, :2], [0, 0]),\n np.minimum(pred_coor[:, 2:], [org_w - 1, org_h - 1])], axis=-1)\n invalid_mask = np.logical_or((pred_coor[:, 0] > pred_coor[:, 2]), (pred_coor[:, 1] > pred_coor[:, 3]))\n pred_coor[invalid_mask] = 0\n\n # 4. discard some invalid boxes\n bboxes_scale = np.sqrt(np.multiply.reduce(pred_coor[:, 2:4] - pred_coor[:, 0:2], axis=-1))\n scale_mask = np.logical_and((valid_scale[0] < bboxes_scale), (bboxes_scale < valid_scale[1]))\n\n # 5. discard boxes with low scores\n classes = np.argmax(pred_prob, axis=-1)\n scores = pred_conf * pred_prob[np.arange(len(pred_coor)), classes]\n score_mask = scores > score_threshold\n mask = np.logical_and(scale_mask, score_mask)\n coors, scores, classes = pred_coor[mask], scores[mask], classes[mask]\n\n return np.concatenate([coors, scores[:, np.newaxis], classes[:, np.newaxis]], axis=-1)\n\n\ndef detect_image(Yolo, image_path, output_path, input_size=416, show=False, CLASSES=YOLO_COCO_CLASSES, score_threshold=0.3, iou_threshold=0.45, rectangle_colors=''):\n original_image = cv2.imread(image_path)\n original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)\n original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)\n\n image_data = image_preprocess(np.copy(original_image), [input_size, input_size])\n image_data = image_data[np.newaxis, ...].astype(np.float32)\n\n if YOLO_FRAMEWORK == \"tf\":\n pred_bbox = Yolo.predict(image_data)\n elif YOLO_FRAMEWORK == \"trt\":\n batched_input = tf.constant(image_data)\n result = Yolo(batched_input)\n pred_bbox = []\n for key, value in result.items():\n value = value.numpy()\n pred_bbox.append(value)\n \n pred_bbox = [tf.reshape(x, (-1, tf.shape(x)[-1])) for x in pred_bbox]\n pred_bbox = tf.concat(pred_bbox, axis=0)\n \n bboxes = postprocess_boxes(pred_bbox, original_image, input_size, score_threshold)\n bboxes = nms(bboxes, iou_threshold, method='nms')\n\n image = draw_bbox(original_image, bboxes, CLASSES=CLASSES, rectangle_colors=rectangle_colors)\n # CreateXMLfile(\"XML_Detections\", str(int(time.time())), original_image, bboxes, read_class_names(CLASSES))\n\n if output_path != '': cv2.imwrite(output_path, image)\n if show:\n # Show the image\n cv2.imshow(\"predicted image\", image)\n # Load and hold the image\n cv2.waitKey(0)\n # To close the window after the required kill value was provided\n cv2.destroyAllWindows()\n \n return image\n\ndef Predict_bbox_mp(Frames_data, Predicted_data, Processing_times):\n gpus = tf.config.experimental.list_physical_devices('GPU')\n if len(gpus) > 0:\n try: tf.config.experimental.set_memory_growth(gpus[0], True)\n except RuntimeError: print(\"RuntimeError in tf.config.experimental.list_physical_devices('GPU')\")\n Yolo = Load_Yolo_model()\n times = []\n while True:\n if Frames_data.qsize()>0:\n image_data = Frames_data.get()\n t1 = time.time()\n Processing_times.put(time.time())\n \n if YOLO_FRAMEWORK == \"tf\":\n pred_bbox = Yolo.predict(image_data)\n elif YOLO_FRAMEWORK == \"trt\":\n batched_input = tf.constant(image_data)\n result = Yolo(batched_input)\n pred_bbox = []\n for key, value in result.items():\n value = value.numpy()\n pred_bbox.append(value)\n\n pred_bbox = [tf.reshape(x, (-1, tf.shape(x)[-1])) for x in pred_bbox]\n pred_bbox = tf.concat(pred_bbox, axis=0)\n \n Predicted_data.put(pred_bbox)\n\n\ndef postprocess_mp(Predicted_data, original_frames, Processed_frames, Processing_times, input_size, CLASSES, score_threshold, iou_threshold, rectangle_colors, realtime):\n times = []\n while True:\n if Predicted_data.qsize()>0:\n pred_bbox = Predicted_data.get()\n if realtime:\n while original_frames.qsize() > 1:\n original_image = original_frames.get()\n else:\n original_image = original_frames.get()\n \n bboxes = postprocess_boxes(pred_bbox, original_image, input_size, score_threshold)\n bboxes = nms(bboxes, iou_threshold, method='nms')\n image = draw_bbox(original_image, bboxes, CLASSES=CLASSES, rectangle_colors=rectangle_colors)\n times.append(time.time()-Processing_times.get())\n times = times[-20:]\n \n ms = sum(times)/len(times)*1000\n fps = 1000 / ms\n image = cv2.putText(image, \"Time: {:.1f}FPS\".format(fps), (0, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2)\n #print(\"Time: {:.2f}ms, Final FPS: {:.1f}\".format(ms, fps))\n \n Processed_frames.put(image)\n\ndef Show_Image_mp(Processed_frames, show, Final_frames):\n while True:\n if Processed_frames.qsize()>0:\n image = Processed_frames.get()\n Final_frames.put(image)\n if show:\n cv2.imshow('output', image)\n if cv2.waitKey(25) & 0xFF == ord(\"q\"):\n cv2.destroyAllWindows()\n break\n\n# detect from webcam\ndef detect_video_realtime_mp(video_path, output_path, input_size=416, show=False, CLASSES=YOLO_COCO_CLASSES, score_threshold=0.3, iou_threshold=0.45, rectangle_colors='', realtime=False):\n if realtime:\n vid = cv2.VideoCapture(0)\n else:\n vid = cv2.VideoCapture(video_path)\n\n # by default VideoCapture returns float instead of int\n width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fps = int(vid.get(cv2.CAP_PROP_FPS))\n codec = cv2.VideoWriter_fourcc(*'XVID')\n out = cv2.VideoWriter(output_path, codec, fps, (width, height)) # output_path must be .mp4\n no_of_frames = int(vid.get(cv2.CAP_PROP_FRAME_COUNT))\n\n original_frames = Queue()\n Frames_data = Queue()\n Predicted_data = Queue()\n Processed_frames = Queue()\n Processing_times = Queue()\n Final_frames = Queue()\n \n p1 = Process(target=Predict_bbox_mp, args=(Frames_data, Predicted_data, Processing_times))\n p2 = Process(target=postprocess_mp, args=(Predicted_data, original_frames, Processed_frames, Processing_times, input_size, CLASSES, score_threshold, iou_threshold, rectangle_colors, realtime))\n p3 = Process(target=Show_Image_mp, args=(Processed_frames, show, Final_frames))\n p1.start()\n p2.start()\n p3.start()\n \n while True:\n ret, img = vid.read()\n if not ret:\n break\n\n original_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)\n original_frames.put(original_image)\n\n image_data = image_preprocess(np.copy(original_image), [input_size, input_size])\n image_data = image_data[np.newaxis, ...].astype(np.float32)\n Frames_data.put(image_data)\n \n while True:\n if original_frames.qsize() == 0 and Frames_data.qsize() == 0 and Predicted_data.qsize() == 0 and Processed_frames.qsize() == 0 and Processing_times.qsize() == 0 and Final_frames.qsize() == 0:\n p1.terminate()\n p2.terminate()\n p3.terminate()\n break\n elif Final_frames.qsize()>0:\n image = Final_frames.get()\n if output_path != '': out.write(image)\n\n cv2.destroyAllWindows()\n\ndef detect_video(Yolo, video_path, output_path, input_size=416, show=False, CLASSES=YOLO_COCO_CLASSES, score_threshold=0.3, iou_threshold=0.45, rectangle_colors=''):\n times, times_2 = [], []\n vid = cv2.VideoCapture(video_path)\n\n # by default VideoCapture returns float instead of int\n width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fps = int(vid.get(cv2.CAP_PROP_FPS))\n codec = cv2.VideoWriter_fourcc(*'XVID')\n out = cv2.VideoWriter(output_path, codec, fps, (width, height)) # output_path must be .mp4\n\n while True:\n _, img = vid.read()\n\n try:\n original_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)\n except:\n break\n\n image_data = image_preprocess(np.copy(original_image), [input_size, input_size])\n image_data = image_data[np.newaxis, ...].astype(np.float32)\n\n t1 = time.time()\n if YOLO_FRAMEWORK == \"tf\":\n pred_bbox = Yolo.predict(image_data)\n elif YOLO_FRAMEWORK == \"trt\":\n batched_input = tf.constant(image_data)\n result = Yolo(batched_input)\n pred_bbox = []\n for key, value in result.items():\n value = value.numpy()\n pred_bbox.append(value)\n \n t2 = time.time()\n \n pred_bbox = [tf.reshape(x, (-1, tf.shape(x)[-1])) for x in pred_bbox]\n pred_bbox = tf.concat(pred_bbox, axis=0)\n\n bboxes = postprocess_boxes(pred_bbox, original_image, input_size, score_threshold)\n bboxes = nms(bboxes, iou_threshold, method='nms')\n \n image = draw_bbox(original_image, bboxes, CLASSES=CLASSES, rectangle_colors=rectangle_colors)\n\n t3 = time.time()\n times.append(t2-t1)\n times_2.append(t3-t1)\n \n times = times[-20:]\n times_2 = times_2[-20:]\n\n ms = sum(times)/len(times)*1000\n fps = 1000 / ms\n fps2 = 1000 / (sum(times_2)/len(times_2)*1000)\n \n image = cv2.putText(image, \"Time: {:.1f}FPS\".format(fps), (0, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2)\n # CreateXMLfile(\"XML_Detections\", str(int(time.time())), original_image, bboxes, read_class_names(CLASSES))\n \n print(\"Time: {:.2f}ms, Detection FPS: {:.1f}, total FPS: {:.1f}\".format(ms, fps, fps2))\n if output_path != '': out.write(image)\n if show:\n cv2.imshow('output', image)\n if cv2.waitKey(25) & 0xFF == ord(\"q\"):\n cv2.destroyAllWindows()\n break\n\n cv2.destroyAllWindows()\n\n# detect from webcam\ndef detect_realtime(Yolo, output_path, input_size=416, show=False, CLASSES=YOLO_COCO_CLASSES, score_threshold=0.3, iou_threshold=0.45, rectangle_colors=''):\n times = []\n vid = cv2.VideoCapture(0)\n\n # by default VideoCapture returns float instead of int\n width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fps = int(vid.get(cv2.CAP_PROP_FPS))\n codec = cv2.VideoWriter_fourcc(*'XVID')\n out = cv2.VideoWriter(output_path, codec, fps, (width, height)) # output_path must be .mp4\n\n while True:\n _, frame = vid.read()\n\n try:\n original_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n original_frame = cv2.cvtColor(original_frame, cv2.COLOR_BGR2RGB)\n except:\n break\n image_data = image_preprocess(np.copy(original_frame), [input_size, input_size])\n image_data = image_data[np.newaxis, ...].astype(np.float32)\n\n t1 = time.time()\n if YOLO_FRAMEWORK == \"tf\":\n pred_bbox = Yolo.predict(image_data)\n elif YOLO_FRAMEWORK == \"trt\":\n batched_input = tf.constant(image_data)\n result = Yolo(batched_input)\n pred_bbox = []\n for key, value in result.items():\n value = value.numpy()\n pred_bbox.append(value)\n \n t2 = time.time()\n \n pred_bbox = [tf.reshape(x, (-1, tf.shape(x)[-1])) for x in pred_bbox]\n pred_bbox = tf.concat(pred_bbox, axis=0)\n\n bboxes = postprocess_boxes(pred_bbox, original_frame, input_size, score_threshold)\n bboxes = nms(bboxes, iou_threshold, method='nms')\n \n times.append(t2-t1)\n times = times[-20:]\n \n ms = sum(times)/len(times)*1000\n fps = 1000 / ms\n \n print(\"Time: {:.2f}ms, {:.1f} FPS\".format(ms, fps))\n\n frame = draw_bbox(original_frame, bboxes, CLASSES=CLASSES, rectangle_colors=rectangle_colors)\n # CreateXMLfile(\"XML_Detections\", str(int(time.time())), original_frame, bboxes, read_class_names(CLASSES))\n image = cv2.putText(frame, \"Time: {:.1f}FPS\".format(fps), (0, 30),\n cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2)\n\n if output_path != '': out.write(frame)\n if show:\n cv2.imshow('output', frame)\n if cv2.waitKey(25) & 0xFF == ord(\"q\"):\n cv2.destroyAllWindows()\n break\n\n cv2.destroyAllWindows()\n"
]
| [
[
"numpy.product",
"numpy.minimum",
"numpy.copy",
"numpy.exp",
"numpy.finfo",
"numpy.concatenate",
"numpy.full",
"tensorflow.shape",
"tensorflow.concat",
"numpy.logical_and",
"tensorflow.constant",
"numpy.argmax",
"numpy.logical_or",
"numpy.array",
"tensorflow.config.experimental.set_memory_growth",
"numpy.fromfile",
"tensorflow.saved_model.load",
"tensorflow.keras.backend.clear_session",
"tensorflow.config.experimental.list_physical_devices",
"numpy.multiply.reduce",
"numpy.maximum"
]
]
|
samlaf/python-control | [
"c49b55b1f8dfe8e74c562d6a83bf5359343cdccb"
]
| [
"control/tests/ctrlutil_test.py"
]
| [
"import unittest\nimport numpy as np\nfrom control.ctrlutil import *\n\nclass TestUtils(unittest.TestCase):\n def setUp(self):\n self.mag = np.array([1, 10, 100, 2, 0.1, 0.01])\n self.db = np.array([0, 20, 40, 6.0205999, -20, -40])\n\n def check_unwrap_array(self, angle, period=None):\n if period is None:\n angle_mod = angle % (2 * np.pi)\n angle_unwrap = unwrap(angle_mod)\n else:\n angle_mod = angle % period\n angle_unwrap = unwrap(angle_mod, period)\n np.testing.assert_array_almost_equal(angle_unwrap, angle)\n\n def test_unwrap_increasing(self):\n angle = np.linspace(0, 20, 50)\n self.check_unwrap_array(angle)\n\n def test_unwrap_decreasing(self):\n angle = np.linspace(0, -20, 50)\n self.check_unwrap_array(angle)\n\n def test_unwrap_inc_degrees(self):\n angle = np.linspace(0, 720, 50)\n self.check_unwrap_array(angle, 360)\n\n def test_unwrap_dec_degrees(self):\n angle = np.linspace(0, -720, 50)\n self.check_unwrap_array(angle, 360)\n\n def test_unwrap_large_skips(self):\n angle = np.array([0., 4 * np.pi, -2 * np.pi])\n np.testing.assert_array_almost_equal(unwrap(angle), [0., 0., 0.])\n\n def test_unwrap_list(self):\n angle = [0, 2.2, 5.4, -0.4]\n angle_unwrapped = [0, 0.2, 0.4, 0.6]\n np.testing.assert_array_almost_equal(unwrap(angle, 1.0), angle_unwrapped)\n\n def test_db2mag(self):\n for mag, db in zip(self.mag, self.db):\n np.testing.assert_almost_equal(mag, db2mag(db))\n\n def test_db2mag_array(self):\n mag_array = db2mag(self.db)\n np.testing.assert_array_almost_equal(mag_array, self.mag)\n\n def test_mag2db(self):\n for db, mag in zip(self.db, self.mag):\n np.testing.assert_almost_equal(db, mag2db(mag))\n\n def test_mag2db_array(self):\n db_array = mag2db(self.mag)\n np.testing.assert_array_almost_equal(db_array, self.db)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
]
| [
[
"numpy.testing.assert_array_almost_equal",
"numpy.array",
"numpy.linspace"
]
]
|
wookayin/tensorflow-plot | [
"70dbe9100b6e438f961a8efe8ccec0a77ffd1aec"
]
| [
"tfplot/contrib_test.py"
]
| [
"'''Unit Test for tfplot.contrib'''\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport unittest\nimport os\nimport scipy.misc\n\nimport numpy as np\nimport tensorflow as tf\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # filter out INFO and WARN logs\n\nimport matplotlib\nmatplotlib.rcParams['figure.figsize'] = (2.5, 2.5)\n\nfrom termcolor import cprint\nfrom imgcat import imgcat\n\nimport tfplot.contrib\nimport tfplot.test_util as test_util\n\ntest_util.configure_tf_verbosity()\n\n\nclass TestContrib(test_util.TestcaseBase):\n '''\n Tests tfplot.contrib module.\n '''\n def test_contrib_module(self):\n print(\"\")\n for name in tfplot.contrib.__all__:\n fn = tfplot.contrib.__dict__[name]\n print(\" - contrib: {fn} -> module={module}\".format(\n fn=fn, module=fn.__module__))\n self.assertTrue(fn.__module__.startswith('tfplot.contrib'),\n msg=str(fn.__module__))\n self.assertTrue(fn.__doc__, '__doc__ is empty')\n\n def test_probmap(self):\n image_tensor = tf.constant(scipy.misc.face())\n attention_tensor = np.eye(5)\n op = tfplot.contrib.probmap(attention_tensor, figsize=(4, 3))\n self._execute_plot_op(op, print_image=True)\n\n\nif __name__ == '__main__':\n unittest.main()\n"
]
| [
[
"numpy.eye"
]
]
|
lperezmo/epistasis | [
"4f751d9e2d9ca632a7b688cf32bd950ad7c2a754"
]
| [
"epistasis/models/nonlinear/spline.py"
]
| [
"import numpy as np\n\nfrom .minimizer import Minimizer\nfrom .ordinary import EpistasisNonlinearRegression\nfrom epistasis.models import EpistasisLinearRegression\nfrom epistasis.models.utils import (arghandler, FittingError)\nfrom scipy.interpolate import UnivariateSpline\nfrom lmfit import Parameter, Parameters\n\n\n# -------------------- Minimizer object ------------------------\n\nclass SplineMinizer(Minimizer):\n \"\"\"Spline Fitter.\n \"\"\"\n def __init__(self, k=3, s=None):\n self.k = k\n self.s = s\n # Set initalize parameters to zero.\n self.parameters = Parameters()\n for i in range(self.k+1):\n self.parameters.add(name='c{}'.format(i), value=0)\n\n def _sorter(self, x, y=None, tol=1e-5):\n \"\"\"sort x (and y) according to x values\n\n The spline call requires that x must be increasing. This function\n sorts x. If there are non-unique values, it adds a small numerical\n difference using tol.\n \"\"\"\n # Copy x to leave it unchanged.\n x_ = np.copy(x)\n\n # Get non-unique terms\n idx = np.arange(len(x_))\n u, u_idx = np.unique(x, return_index=True)\n idx = np.delete(idx, u_idx)\n\n # Add noise to non-unique\n x_[idx] = x_[idx] + np.random.uniform(1,9.9, size=len(idx))*tol\n\n # Now sort x\n idx = np.argsort(x_)\n\n if y is None:\n return x_[idx]\n else:\n return x_[idx], y[idx]\n\n def function(self, x, *coefs):\n # Order of polynomial\n k = self.k\n\n # Number of coefficients\n n = k + 1\n\n # Knot positions\n t_arr = np.zeros(n*2, dtype=float)\n t_arr[:n] = min(x)\n t_arr[n:] = max(x)\n\n # Coefficients\n c_arr = np.zeros(n*2, dtype=float)\n c_arr[:n] = coefs\n\n # Build Spline function\n tck = [t_arr, c_arr, k]\n model = UnivariateSpline._from_tck(tck)\n\n # Return predicted function\n return model(x)\n\n def predict(self, x):\n return self._spline(x)\n\n def transform(self, x, y):\n ymodel = self.predict(x)\n return (y - ymodel) + x\n\n def fit(self, x, y):\n # Sort values for fit\n x_, y_ = self._sorter(x, y)\n\n # Fit spline.\n self._spline = UnivariateSpline(\n x=x_,\n y=y_,\n k=self.k,\n s=self.s\n )\n \n for i, coef in enumerate(self._spline.get_coeffs()):\n if 'c{}'.format(i) in self.parameters:\n self.parameters['c{}'.format(i)].value = coef\n else:\n raise FittingError('scipy.interpolate.UnivariateSpline '\n 'fitting returned more parameters than\\nexpected, likely'\n ' due to knots being added to closer fit the data.\\nTry '\n 'raising the value of `s` when initializing the spline '\n 'model to prevent this.')\n# -------------------- Minimizer object ------------------------\n\nclass EpistasisSpline(EpistasisNonlinearRegression):\n \"\"\"Estimate nonlinearity in a genotype-phenotype map using a spline.\n\n Parameters\n ----------\n k : int\n order of spline.\n\n s : float, optional\n smoothness factor.\n \"\"\"\n def __init__(self, k=3, s=None, model_type=\"global\"):\n # Set atributes\n self.k = k\n self.s = s\n\n # Set up the function for fitting.\n self.minimizer = SplineMinizer(k=self.k, s=self.s)\n self.order = 1\n self.Xbuilt = {}\n\n # Construct parameters object\n self.set_params(model_type=model_type)\n\n # Store model specs.\n self.model_specs = dict(model_type=self.model_type)\n\n # Set up additive and high-order linear model\n self.Additive = EpistasisLinearRegression(\n order=1, model_type=self.model_type)\n"
]
| [
[
"numpy.delete",
"numpy.zeros",
"scipy.interpolate.UnivariateSpline",
"numpy.copy",
"scipy.interpolate.UnivariateSpline._from_tck",
"numpy.argsort",
"numpy.unique"
]
]
|
Real-Silverywing/pytorch_classification | [
"4aabb1777c29a239d8175bbdcde9989e54b8c71c"
]
| [
"train.py"
]
| [
"# -*- coding:utf-8 -*-\n# @time :2020.02.09\n# @IDE : pycharm\n# @author :lxztju\n# @github : https://github.com/lxztju\n\nimport argparse\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport math\n\nfrom data import train_dataloader,train_datasets,val_dataloader,val_datasets\nimport cfg\nfrom utils import adjust_learning_rate_cosine, adjust_learning_rate_step\nimport matplotlib.pyplot as plt\n\n##创建训练模型参数保存的文件夹\nsave_folder = cfg.SAVE_FOLDER + cfg.model_name\nos.makedirs(save_folder, exist_ok=True)\nLoss_list = []\nAccuracy_list = []\nLoss_Epoch = []\nAcc_Epoch = []\nLoss_temp=[]\nAcc_temp=[]\n\ndef load_checkpoint(filepath):\n checkpoint = torch.load(filepath)\n model = checkpoint['model'] # 提取网络结构\n model.load_state_dict(checkpoint['model_state_dict']) # 加载网络权重参数\n return model\n\n#####build the network model\nif not cfg.RESUME_EPOCH:\n print('****** Training {} ****** '.format(cfg.model_name))\n print('****** loading the Imagenet pretrained weights ****** ')\n if not cfg.model_name.startswith('efficientnet'):\n model = cfg.MODEL_NAMES[cfg.model_name](num_classes=cfg.NUM_CLASSES)\n # #冻结前边一部分层不训练\n ct = 0\n for child in model.children():\n ct += 1\n # print(child)\n if ct < 8:\n print(child)\n for param in child.parameters():\n param.requires_grad = False\n else:\n model = cfg.MODEL_NAMES[cfg.model_name](cfg.model_name,num_classes=cfg.NUM_CLASSES)\n # print(model)\n c = 0\n for name, p in model.named_parameters():\n c += 1\n # print(name)\n if c >=700:\n break\n p.requires_grad = False\n\n # print(model)\nif cfg.RESUME_EPOCH:\n print(' ******* Resume training from {} epoch {} *********'.format(cfg.model_name, cfg.RESUME_EPOCH))\n model = load_checkpoint(os.path.join(save_folder, 'epoch_{}.pth'.format(cfg.RESUME_EPOCH)))\n\n\n\n##进行多gpu的并行计算\nif cfg.GPUS>1:\n print('****** using multiple gpus to training ********')\n model = nn.DataParallel(model,device_ids=list(range(cfg.GPUS)))\nelse:\n print('****** using single gpu to training ********')\nprint(\"...... Initialize the network done!!! .......\")\n\n###模型放置在gpu上进行计算\nif torch.cuda.is_available():\n model.cuda()\n print(\"Using GPU\")\n\n\n##定义优化器与损失函数\n# optimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=cfg.LR)\n# optimizer = optim.Adam(model.parameters(), lr=cfg.LR)\noptimizer = optim.SGD(model.parameters(), lr=cfg.LR,momentum=cfg.MOMENTUM, weight_decay=cfg.WEIGHT_DECAY)\n\ncriterion = nn.CrossEntropyLoss()\n# criterion = nn.BCEWithLogitsLoss()\n# criterion = LabelSmoothSoftmaxCE()\n# criterion = LabelSmoothingCrossEntropy()\n\nlr = cfg.LR\n\nbatch_size = cfg.BATCH_SIZE\n\n#每一个epoch含有多少个batch\nmax_batch = len(train_datasets)//batch_size\nprint(len(train_datasets))\n\nepoch_size = len(train_datasets) // batch_size\n## 训练max_epoch个epoch\nmax_iter = cfg.MAX_EPOCH * epoch_size\nmax_iter_end=math.floor(max_iter/10)*10\nstart_iter = cfg.RESUME_EPOCH * epoch_size\n\nepoch = cfg.RESUME_EPOCH\n\n# cosine学习率调整\nwarmup_epoch=5\nwarmup_steps = warmup_epoch * epoch_size\nglobal_step = 0\n\n# step 学习率调整参数\nstepvalues = (10 * epoch_size, 20 * epoch_size, 30 * epoch_size)\nstep_index = 0\n\nmodel.train()\nfor iteration in range(start_iter, max_iter):\n global_step += 1\n\n ##更新迭代器\n if iteration % epoch_size == 0:\n\n if epoch > 1:\n Loss_average = sum(Loss_temp) / len(Loss_temp)\n Acc_average = sum(Acc_temp) / len(Acc_temp)\n Loss_Epoch.append(Loss_average)\n Acc_Epoch.append(Acc_average)\n Loss_temp = []\n Acc_temp = []\n # create batch iterator\n batch_iterator = iter(train_dataloader)\n val_batch_iterator = iter(val_dataloader)\n loss = 0\n epoch += 1\n ###保存模型\n if epoch % 5 == 0 and epoch > 0:\n if cfg.GPUS > 1:\n checkpoint = {'model': model.module,\n 'model_state_dict': model.module.state_dict(),\n # 'optimizer_state_dict': optimizer.state_dict(),\n 'epoch': epoch}\n torch.save(checkpoint, os.path.join(save_folder, 'epoch_{}.pth'.format(epoch)))\n else:\n checkpoint = {'model': model,\n 'model_state_dict': model.state_dict(),\n # 'optimizer_state_dict': optimizer.state_dict(),\n 'epoch': epoch}\n torch.save(checkpoint, os.path.join(save_folder, 'epoch_{}.pth'.format(epoch)))\n\n\n if iteration in stepvalues:\n step_index += 1\n lr = adjust_learning_rate_step(optimizer, cfg.LR, 0.1, epoch, step_index, iteration, epoch_size)\n\n ## 调整学习率\n # lr = adjust_learning_rate_cosine(optimizer, global_step=global_step,\n # learning_rate_base=cfg.LR,\n # total_steps=max_iter,\n # warmup_steps=warmup_steps)\n\n\n ## 获取image 和 label\n # try:\n images, labels = next(batch_iterator)\n # except:\n # continue\n\n ##在pytorch0.4之后将Variable 与tensor进行合并,所以这里不需要进行Variable封装\n if torch.cuda.is_available():\n images, labels = images.cuda(), labels.cuda()\n\n out = model(images)\n loss = criterion(out, labels.long())\n\n optimizer.zero_grad() # 清空梯度信息,否则在每次进行反向传播时都会累加\n loss.backward() # loss反向传播\n optimizer.step() ##梯度更新\n\n prediction = torch.max(out, 1)[1]\n train_correct = (prediction == labels).sum()\n # 这里得到的train_correct是一个longtensor型,需要转换为float\n # print(train_correct.type())\n train_acc = (train_correct.float()) / batch_size\n\n if iteration % 10 == 0:\n # val_images, val_labels = next(val_batch_iterator)\n # val_out = model(val_images)\n # val_loss = criterion(val_out, val_labels.long())\n\n\n Loss_list.append(loss.item())\n Accuracy_list.append(train_acc * 100)\n Loss_temp.append(loss.item())\n Acc_temp.append(train_acc * 100)\n print('Epoch:' + repr(epoch) + ' || epochiter: ' + repr(iteration % epoch_size) + '/' + repr(epoch_size)\n + '|| Totel iter ' + repr(iteration) + ' || Loss: %.6f||' % (loss.item()) + 'ACC: %.3f ||' %(train_acc * 100) + 'LR: %.8f' % (lr))\n\n if iteration==max_iter_end-1:\n x1 = range(len(Accuracy_list))\n x2 = range(len(Loss_list))\n x3 = range(len(Acc_Epoch))\n x4 = range(len(Loss_Epoch))\n y1 = Accuracy_list\n y2 = Loss_list\n y3 = Acc_Epoch\n y4 = Loss_Epoch\n\n plt.subplot(2, 2, 1)\n plt.plot(x1, y1, 'o-')\n plt.xlabel('Test accuracy vs. iteration')\n plt.ylabel('Test accuracy')\n\n plt.subplot(2, 2, 2)\n plt.plot(x2, y2, '.-')\n plt.xlabel('Test loss vs. iteration')\n plt.ylabel('Test loss')\n\n\n plt.subplot(2, 2, 3)\n plt.plot(x3, y3, '.-')\n plt.xlabel('Test accuracy vs. epoch')\n plt.ylabel('Test Acc')\n\n\n plt.subplot(2, 2, 4)\n plt.plot(x4, y4, '.-')\n plt.xlabel('Test loss vs. epoches')\n plt.ylabel('Test loss')\n plt.show()\n\n plt.savefig(\"accuracy_loss.jpg\")\n\n\n"
]
| [
[
"torch.max",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"torch.cuda.is_available",
"torch.load",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.show",
"torch.nn.CrossEntropyLoss",
"matplotlib.pyplot.subplot"
]
]
|
roeymarinov/TNE | [
"bbe431bd8c0fdea9978cfec4a97bb0bcdb02b58c"
]
| [
"tne/modeling/models/tne_coupled_tuples.py"
]
| [
"import logging\nfrom typing import Any, Dict, List\n\nimport numpy as np\nimport torch\nfrom allennlp.data import TextFieldTensors, Vocabulary\nfrom allennlp.models.model import Model\nfrom allennlp.modules import FeedForward\nfrom allennlp.modules import Seq2SeqEncoder, TimeDistributed, TextFieldEmbedder\nfrom allennlp.modules.span_extractors import EndpointSpanExtractor\nfrom allennlp.nn import util, InitializerApplicator\nfrom allennlp.training.metrics import CategoricalAccuracy\nfrom allennlp.training.metrics.f1_measure import F1Measure\nfrom allennlp.training.metrics.fbeta_measure import FBetaMeasure\nfrom overrides import overrides\n\nfrom tne.modeling.metrics.mcf1_measure import MCF1Measure\nfrom tne.modeling.span_extractors.yake_span_extractor import YakeSpanExtractor\n\nlogger = logging.getLogger(__name__)\n\n\[email protected](\"tne_coupled_tuples_model\")\nclass TNECoupledTuplesModel(Model):\n \"\"\"\n Details\n\n # Parameters\n\n vocab : `Vocabulary`\n text_field_embedder : `TextFieldEmbedder`\n Used to embed the `text` `TextField` we get as input to the model.\n context_layer : `Seq2SeqEncoder`\n This layer incorporates contextual information for each word in the document.\n anchor_feedforward : `FeedForward`\n This feedforward network is applied to the span representations which is then scored\n by a linear layer.\n complement_feedforward : `FeedForward`\n This feedforward network is applied to pairs of span representation, along with any\n pairwise features, which is then scored by a linear layer.\n max_span_width : `int`\n The maximum width of candidate spans.\n coarse_to_fine: `bool`, optional (default = `False`)\n Whether or not to apply the coarse-to-fine filtering.\n inference_order: `int`, optional (default = `1`)\n The number of inference orders. When greater than 1, the span representations are\n updated and coreference scores re-computed.\n lexical_dropout : `int`\n The probability of dropping out dimensions of the embedded text.\n initializer : `InitializerApplicator`, optional (default=`InitializerApplicator()`)\n Used to initialize the model parameters.\n \"\"\"\n\n def __init__(\n self,\n vocab: Vocabulary,\n text_field_embedder: TextFieldEmbedder,\n context_layer: Seq2SeqEncoder,\n anchor_feedforward: FeedForward,\n complement_feedforward: FeedForward,\n preposition_predictor: FeedForward,\n prepositions: List[str],\n span_extractor: YakeSpanExtractor,\n lexical_dropout: float = 0.2,\n initializer: InitializerApplicator = InitializerApplicator(),\n freeze: bool = False,\n num_words: int = 3,\n **kwargs\n ) -> None:\n super().__init__(vocab, **kwargs)\n\n self._num_words = num_words\n\n self._prepositions = prepositions\n self._freeze = freeze\n\n self._text_field_embedder = text_field_embedder\n self._context_layer = context_layer\n self._anchor_feedforward = TimeDistributed(anchor_feedforward)\n self._complement_feedforward = TimeDistributed(complement_feedforward)\n\n self._preposition_scorer = TimeDistributed(preposition_predictor)\n\n self._yake_span_extractor = span_extractor\n\n # self._endpoint_span_extractor = EndpointSpanExtractor(\n # context_layer.get_output_dim(),\n # combination=\"x,y\",\n # num_width_embeddings=None,\n # span_width_embedding_dim=None,\n # bucket_widths=False,\n # )\n\n if lexical_dropout > 0:\n self._lexical_dropout = torch.nn.Dropout(p=lexical_dropout)\n else:\n self._lexical_dropout = lambda x: x\n initializer(self)\n\n self.preposition_loss = torch.nn.CrossEntropyLoss()\n\n self.link_f1 = F1Measure(positive_label=1)\n self.micro_f1 = FBetaMeasure(beta=1.0, average='micro', labels=list(range(len(prepositions))))\n self.overall_f1 = MCF1Measure()\n self.prep_acc = CategoricalAccuracy()\n self.identified_gold_prep_acc = CategoricalAccuracy()\n self.non_identified_gold_prep_acc = CategoricalAccuracy()\n\n @overrides\n def forward(\n self, # type: ignore\n text: TextFieldTensors,\n spans: torch.IntTensor,\n metadata: List[Dict[str, Any]] = None,\n link_labels: torch.IntTensor = None,\n preposition_labels: torch.IntTensor = None,\n ) -> Dict[str, torch.Tensor]:\n\n \"\"\"\n # Parameters\n\n text : `TextFieldTensors`, required.\n The output of a `TextField` representing the text of\n the document.\n spans : `torch.IntTensor`, required.\n A tensor of shape (batch_size, num_spans, 2), representing the inclusive start and end\n indices of candidate spans for mentions. Comes from a `ListField[SpanField]` of\n indices into the text of the document.\n span_labels : `torch.IntTensor`, optional (default = `None`).\n A tensor of shape (batch_size, num_spans), representing the cluster ids\n of each span, or -1 for those which do not appear in any clusters.\n metadata : `List[Dict[str, Any]]`, optional (default = `None`).\n A metadata dictionary for each instance in the batch. We use the \"original_text\" and \"clusters\" keys\n from this dictionary, which respectively have the original text and the annotated gold coreference\n clusters for that instance.\n\n # Returns\n\n An output dictionary consisting of:\n\n loss : `torch.FloatTensor`, optional\n A scalar loss to be optimised.\n \"\"\"\n spans_tuples = self.k_tuple_spans(text, spans, self._num_words).to(preposition_labels.device)\n\n if self._freeze:\n with torch.no_grad():\n span_embeddings = self.get_span_embeddings(text, spans_tuples, metadata).to(preposition_labels.device)\n else:\n span_embeddings = self.get_span_embeddings(text, spans_tuples, metadata).to(preposition_labels.device)\n\n anchor_reps = self._anchor_feedforward(span_embeddings)\n complement_reps = self._complement_feedforward(span_embeddings)\n\n\n # Creating a large matrix that concatenates all permutations of spans with one another, between the\n # representation obtained from the anchor representations and the antecedent representations\n # The reshape corresponds to the number of entities to the power of two,\n # and the the representation size of the antecedent + the anchor\n mat = torch.cat([anchor_reps.squeeze(0).unsqueeze(1).repeat(1, anchor_reps.shape[1], 1),\n complement_reps.squeeze(0).repeat(anchor_reps.shape[1], 1, 1)], -1) \\\n .reshape(anchor_reps.shape[1] ** 2, anchor_reps.shape[-1] * 2)\n\n preposition_scores_temp = self._preposition_scorer(mat.unsqueeze(0)).squeeze(0)\n\n\n preposition_scores = self.k_tuple_scores(text, spans, preposition_scores_temp).to(preposition_labels.device)\n\n\n preposition_hat = torch.argmax(preposition_scores, dim=1).unsqueeze(0)\n\n output_dict = {\n \"predicted_prepositions\": preposition_hat,\n }\n if preposition_labels is not None:\n preposition_labels = preposition_labels.reshape(-1)\n preposition_loss = self.preposition_loss(preposition_scores, preposition_labels)\n\n output_dict[\"loss\"] = preposition_loss\n\n extended_prepositions = [x['extended_prepositions'] for x in metadata][0]\n adapted_preposition_labels = self.adapt_prep_labels_to_predictions(preposition_labels,\n extended_prepositions, preposition_hat)\n\n lowest_val = preposition_scores.detach().cpu().min().numpy().tolist() - 1\n lowest_vec = torch.ones_like(preposition_labels) * lowest_val\n preposition_adapted_scores = preposition_scores.clone().detach()\n preposition_adapted_scores[:, 0] = lowest_vec\n output_dict['best_prepositions'] = torch.argmax(preposition_adapted_scores, dim=1).unsqueeze(0)\n\n self.prep_acc(preposition_adapted_scores.unsqueeze(0),\n adapted_preposition_labels.unsqueeze(0),\n (link_labels != -1) &\n (adapted_preposition_labels != 0).unsqueeze(0))\n\n self.identified_gold_prep_acc(preposition_scores.unsqueeze(0),\n adapted_preposition_labels.unsqueeze(0),\n ((link_labels != -1) &\n (adapted_preposition_labels != 0).unsqueeze(0) & (preposition_hat != 0)))\n\n self.non_identified_gold_prep_acc(preposition_adapted_scores.unsqueeze(0),\n adapted_preposition_labels.unsqueeze(0),\n (link_labels != -1) &\n ((adapted_preposition_labels != 0).unsqueeze(0) & (preposition_hat == 0)))\n\n self.measure_overal_f1(preposition_scores, adapted_preposition_labels, link_labels)\n\n is_relation_preds = torch.cat([(preposition_hat == 0).int(), (preposition_hat != 0).int()], dim=0).T\n self.link_f1(is_relation_preds, link_labels.squeeze(0),\n (link_labels != -1).squeeze(0))\n\n self.overall_f1(preposition_hat,\n adapted_preposition_labels,\n (link_labels != -1))\n\n if metadata is not None:\n output_dict[\"document\"] = [x[\"original_text\"] for x in metadata]\n output_dict[\"tokenized_entities\"] = [x[\"tokenized_entities\"] for x in metadata]\n output_dict[\"tokens\"] = [x[\"tokens\"] for x in metadata]\n return output_dict\n\n def get_span_embeddings(self, text, spans, metadata):\n # Shape: (batch_size, document_length, embedding_size)\n text_embeddings = self._lexical_dropout(self._text_field_embedder(text))\n\n # Shape: (batch_size, document_length)\n text_mask = util.get_text_field_mask(text)\n\n # Shape: (batch_size, document_length, encoding_dim)\n contextualized_embeddings = self._context_layer(text_embeddings, text_mask)\n # Shape: (batch_size, num_spans, 2 * encoding_dim)\n\n span_embeddings = self._yake_span_extractor(contextualized_embeddings, spans, metadata)\n\n return span_embeddings\n\n def measure_overal_f1(self, prep_scores, prep_labels, link_labels):\n # tuples that the model predicted there is a link\n link_exist = prep_scores.detach().argmax(dim=1) != 0\n\n self.micro_f1(prep_scores.unsqueeze(0),\n prep_labels.unsqueeze(0),\n # in cases where both the model predicted no-link, and gold label indicate no-link, masking,\n # to not count these points\n # also masking self-link\n (((link_labels == 1) | link_exist) & (link_labels != -1)))\n\n @overrides\n def get_metrics(self, reset: bool = False) -> Dict[str, float]:\n f1 = self.link_f1.get_metric(reset)\n prep_acc = self.prep_acc.get_metric(reset)\n identified_prep_acc = self.identified_gold_prep_acc.get_metric(reset)\n non_identified_prep_acc = self.non_identified_gold_prep_acc.get_metric(reset)\n micro_f1 = self.micro_f1.get_metric(reset)\n overall_f1 = self.overall_f1.get_metric(reset)\n\n return {\n \"links_p\": f1['precision'],\n \"links_r\": f1['recall'],\n \"links_f1\": f1['f1'],\n \"preposition_acc\": prep_acc,\n \"identified_prep_acc\": identified_prep_acc,\n \"non_identified_prep_acc\": non_identified_prep_acc,\n 'overall_micro_f1': micro_f1['fscore'],\n 'overall_p': overall_f1['precision'],\n 'overall_r': overall_f1['recall'],\n 'overall_f1': overall_f1['fscore'],\n # The precision and recall are the same as the f1 due to the micro averaging, so not logging them\n }\n\n @staticmethod\n def adapt_prep_labels_to_predictions(preposition_labels, extended_prepositions_labels, preposition_predictions):\n updated_labels = []\n for prep_l, prep_p, prep_extend in zip(preposition_labels, preposition_predictions.squeeze(0),\n extended_prepositions_labels):\n if prep_l == prep_p:\n updated_labels.append(prep_p)\n elif prep_p in prep_extend:\n updated_labels.append(prep_p)\n else:\n updated_labels.append(prep_l)\n return torch.tensor(updated_labels).to(preposition_labels.device)\n\n @overrides\n def make_output_human_readable(\n self, output_dict: Dict[str, torch.Tensor]\n ) -> Dict[str, torch.Tensor]:\n \"\"\"\n Takes the result of `forward` and makes it human readable.\n\n This method `modifies` the input dictionary, and returns a human interpretable version, where all the non-links\n predictions are removed, and added with the relevant preposition\n\n \"\"\"\n # links = output_dict['predicted_links'][0]\n preps = output_dict['predicted_prepositions'][0]\n entities = output_dict['tokenized_entities'][0]\n nps_list = list(entities.keys())\n n = int(np.sqrt(len(preps)))\n predictions = {}\n for i in range(n):\n for j in range(n):\n if i == j: continue\n if int(preps[i * n + j]) != 0:\n predictions[(nps_list[i], nps_list[j])] = self._prepositions[int(preps[i * n + j])]\n\n tokens = output_dict['tokens'][0]\n\n human_links = []\n full_links = []\n for (from_entity, to_entity), prep in predictions.items():\n from_start = entities[from_entity]['first_token']\n from_end = entities[from_entity]['last_token']\n from_str = tokens[from_start: from_end + 1]\n\n to_start = entities[to_entity]['first_token']\n to_end = entities[to_entity]['last_token']\n to_str = tokens[to_start: to_end + 1]\n\n human_links.append(' '.join(from_str + ['*' + prep + '*'] + to_str))\n\n full_links.append({\n 'from_first': from_start,\n 'from_last': from_end,\n 'to_first': to_start,\n 'to_last': to_end,\n 'preposition': prep,\n })\n\n entities_str = []\n for ind, ent in entities.items():\n start = ent['first_token']\n end = ent['last_token']\n ent_str = ' '.join(tokens[start: end + 1])\n entities_str.append(ent_str)\n\n human_output = {'document': output_dict['document'],\n 'entities': [entities_str],\n 'predicted_links': [human_links],\n 'full_links': [full_links],\n 'predicted_prepositions': [preps],\n }\n\n return human_output\n\n # given the original spans, generates a list of spans including every consecutive\n # k-tuple of words in the array, along with the appropriate labels\n def k_tuple_spans(self, text_org, spans_org, k):\n spans = spans_org[0]\n text_length = len(text_org['tokens']['mask'][0])\n\n new_spans = torch.zeros(text_length, 2)\n for i in range(text_length):\n if i <= text_length - k - 1:\n new_spans[i][0] = i # fills with all k-tuples in the text\n new_spans[i][1] = i + k\n else:\n new_spans[i][0] = i # adds the rest as tuples\n new_spans[i][1] = text_length\n\n return torch.unsqueeze(new_spans, 0).to(torch.int32)\n\n # given the preposition scores from a k-tuple spans and the original spans\n # and the scores to scores for the original span\n def k_tuple_scores(self, text_org, spans_org, scores_org):\n spans = spans_org[0]\n scores = torch.FloatTensor(len(spans) * len(spans), 25)\n span_starts = [span[0].item() for span in spans]\n text = text_org['tokens']['mask'][0]\n\n for i in range(len(spans)):\n for j in range(len(spans)):\n scores[i * len(spans) + j] = scores_org[span_starts[i] * (len(text)-1) + span_starts[j]]\n\n return scores\n\n\n"
]
| [
[
"torch.zeros",
"torch.nn.Dropout",
"torch.nn.CrossEntropyLoss",
"torch.no_grad",
"torch.unsqueeze",
"torch.tensor",
"torch.ones_like",
"torch.argmax"
]
]
|
ferrocactus/cellar | [
"d1733d4643b3a4c960529806d4904ab3b3c54666"
]
| [
"src/utils/tools.py"
]
| [
"import itertools\nimport json\nimport re\nimport os\n\n\nfrom typing import Optional, Union\nfrom anndata import AnnData\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.neighbors import kneighbors_graph\n\nfrom ast import literal_eval\nfrom functools import reduce\n\nimport anndata\nimport numpy as np\nfrom bidict import bidict\n\nfrom .exceptions import InvalidArgument\nfrom .exceptions import InappropriateArgument\nfrom .validation import _validate_cluster_list\n\n\nthis_dir = os.path.dirname(__file__)\n\n\ndef join_root(path):\n return os.path.abspath(os.path.join(this_dir, path))\n\n\ndef parse(x):\n if x.size == 0:\n return x\n parsed_x = np.char.split(x.flatten(), sep='.', maxsplit=1)\n parsed_x = np.array([i[0] for i in parsed_x])\n parsed_x = np.char.replace(parsed_x, '-', '')\n parsed_x = np.char.replace(parsed_x, ' ', '')\n # Remove everything that goes inside brackets\n parsed_x = [re.sub(r\" ?\\([^)]+\\)\", \"\", item) for item in parsed_x]\n parsed_x = np.char.upper(parsed_x)\n parsed_x = parsed_x.reshape(x.shape)\n return parsed_x\n\n\ndef _emb_exists_in_adata(adata, method, n_components):\n if 'x_emb' not in adata.obsm:\n if 'X_pca' in adata.obsm: # Scanpy compatibility\n adata.obsm['x_emb'] = adata.obsm.pop('X_pca')\n else:\n return None\n\n if 'dim_reduction_info' in adata.uns:\n if adata.uns['dim_reduction_info']['method'] != method:\n return None\n elif adata.obsm['x_emb'].shape[1] == n_components:\n return adata.obsm['x_emb']\n elif adata.uns['dim_reduction_info']['n_components_used'] == 'Automatic' and n_components == 'knee':\n return adata.obsm['x_emb']\n\n if method != 'PCA':\n return None\n\n if isinstance(n_components, str): # knee\n n_components = 10\n if n_components <= adata.obsm['x_emb'].shape[1]:\n return adata.obsm['x_emb'][:, :n_components]\n\n return None\n\n\ndef _labels_exist_in_adata(adata, method, n_clusters):\n if 'labels' not in adata.obs:\n return False\n # Manually labelled file, used for debugging\n # if adata.uns['cluster_info']['method'] == 'F':\n # return True\n if method != adata.uns['cluster_info']['method']:\n return False\n if np.array_equal(n_clusters, adata.uns['cluster_info']['n_clusters_used']):\n return True\n return False\n\n\ndef _2d_emb_exists_in_adata(adata, method, dim, use_emb):\n if f'x_emb_{dim}d' not in adata.obsm:\n return False\n if adata.uns[f'visualization_info_{dim}d']['method'] != method:\n return False\n if adata.uns[f'visualization_info_{dim}d']['used_emb'] != use_emb:\n return False\n return True\n\n\ndef merge_cluster_names(adata, ref):\n # Currently used for alignment only\n if 'cluster_names' not in ref.uns:\n raise InvalidArgument('Cluster Names not found.')\n\n unq_labels = np.unique(adata.obs['labels'])\n adata.uns['cluster_names'] = bidict({i: str(i) for i in unq_labels})\n\n # In case the loaded keys are strings\n temp_dict = bidict({})\n for i in ref.uns['cluster_names']:\n temp_dict[int(i)] = ref.uns['cluster_names'][i]\n ref.uns['cluster_names'] = temp_dict\n\n for i in adata.uns['cluster_names']:\n if i in ref.uns['cluster_names']:\n adata.uns['cluster_names'][i] = ref.uns['cluster_names'][i]\n\n\ndef store_subset(adata, name, indices, from_r=False):\n # ARRAYS START FROM 0\n if from_r:\n indices = np.array(indices).astype(int) - 1\n if 'subsets' not in adata.uns:\n adata.uns['subsets'] = {}\n adata.uns['subsets'][name] = indices\n\n\ndef store_labels(adata, labels, method):\n adata.obs['labels'] = np.array(labels).astype(int)\n # Update entries\n adata.uns['cluster_info'] = {}\n unq_labels = np.unique(adata.obs['labels'])\n adata.uns['cluster_info']['unique_labels'] = unq_labels\n adata.uns['cluster_info']['n_clusters'] = len(unq_labels)\n adata.uns['cluster_info']['method'] = method\n adata.uns['cluster_names'] = bidict(\n {int(i): str(i) for i in unq_labels})\n populate_subsets(adata)\n\n\ndef store_empty_labels(adata):\n adata.obs['labels'] = np.zeros(adata.shape[0]).astype(int)\n adata.uns['cluster_info'] = {}\n adata.uns['cluster_info']['unique_labels'] = np.array([0])\n adata.uns['cluster_info']['n_clusters'] = 1\n adata.uns['cluster_info']['method'] = 'N/A'\n adata.uns['cluster_names'] = bidict({0: '0'})\n populate_subsets(adata)\n\n\ndef match_labels(adata, ids, labels, maps=None):\n ids = np.array(ids).astype(str)\n labels = np.array(labels).astype(str)\n\n if ids.shape[0] != labels.shape[0]:\n raise InvalidArgument(\"Found IDs and labels of different length.\")\n\n # indices allow to reconstruct the original array given unq_labels\n if maps is None:\n unq_labels, indices = np.unique(labels, return_inverse=True)\n else:\n maps = maps.copy()\n unq_labels = np.unique(labels)\n indices = np.zeros((len(labels)))\n for i in maps:\n indices[labels==str(maps[i])] = int(i)\n\n # Get common cell ids and their indices for each array\n common_ids, adata_ind, ids_ind = np.intersect1d(\n adata.obs_names.to_numpy().astype(str), ids, return_indices=True)\n\n # Subtract 1 (will be used as indicator of cells which had no matching id)\n new_labels = np.zeros((adata.shape[0])) - 1\n\n # Fill adata matched indices with correct label\n new_labels[adata_ind] = indices[ids_ind]\n\n # Fill the next cluster with unknown cells\n free_cluster = np.max(indices) + 1\n new_labels[new_labels == -1] = free_cluster\n\n new_labels = new_labels.astype(int)\n\n # Replace labels\n adata.obs['labels'] = new_labels\n\n unq = np.unique(new_labels)\n\n b = bidict({})\n if maps is None:\n # Construct label - cell type dict\n for i in unq:\n if i != free_cluster:\n b[int(i)] = str(unq_labels[i])\n else:\n b[int(i)] = \"No matching ID\"\n else:\n for i in unq:\n if i in maps:\n b[int(i)] = str(maps[i])\n else:\n b[int(i)] = \"No matching ID\"\n\n # Update entries\n adata.uns['cluster_info'] = {}\n unq_labels = unq\n adata.uns['cluster_info']['unique_labels'] = unq\n adata.uns['cluster_info']['n_clusters'] = len(unq)\n adata.uns['cluster_info']['method'] = 'Uploaded Labels'\n adata.uns['cluster_names'] = b\n populate_subsets(adata)\n\n\ndef store_x_emb(adata, x_emb, method):\n adata.obsm['x_emb'] = np.array(x_emb).astype(float)\n adata.uns['dim_reduction_info'] = {}\n adata.uns['dim_reduction_info']['method'] = method\n adata.uns['dim_reduction_info']['n_components'] = x_emb.shape[1]\n adata.uns['dim_reduction_info']['n_components_used'] = x_emb.shape[1]\n adata.uns['dim_reduction_info']['kwargs'] = {}\n\n\ndef store_x_emb_d(adata, x_emb_d, method):\n dim = x_emb_d.shape[1]\n adata.obsm[f'x_emb_{dim}d'] = np.array(x_emb_d).astype(float)\n adata.uns[f'visualization_info_{dim}d'] = {}\n adata.uns[f'visualization_info_{dim}d']['method'] = method\n adata.uns[f'visualization_info_{dim}d']['used_emb'] = \"NA\"\n adata.uns[f'visualization_info_{dim}d']['kwargs'] = \"NA\"\n\n\ndef update_subset_label(adata, subset_name, name):\n \"\"\"\n Parameters:\n subset_name: existing subset name to change\n\n name: new cell type to assign to subset\n \"\"\"\n subset_name = str(subset_name)\n name = str(name)\n\n if subset_name not in adata.uns['subsets']:\n raise InvalidArgument(f\"Subset {subset_name} not found in adata.\")\n\n indices = adata.uns['subsets'][subset_name]\n\n # If cell type exists in dictionary\n if name in list(adata.uns['cluster_names'].values()):\n # Get the cluster ID the cell type is assigned to\n label = int(adata.uns['cluster_names'].inverse[name])\n else:\n # Determine if an entire cluster is being updated\n if len(np.unique(adata.obs['labels'][indices])) == 1:\n label = int(adata.obs['labels'][indices][0])\n # In case this label is elsewhere\n if label in np.delete(adata.obs['labels'].to_numpy(), indices):\n label = np.max(adata.obs['labels']) + 1\n else:\n label = np.max(adata.obs['labels']) + 1\n\n\n adata.uns['cluster_names'][label] = name\n\n # Assign that cluster ID to current cells\n temp_labels = adata.obs['labels'].copy()\n temp_labels[indices] = label\n adata.obs['labels'] = temp_labels.copy()\n\n # Correct dictionary\n unq_new_labels = np.unique(adata.obs['labels'])\n\n for old_label in list(adata.uns['cluster_names'].keys()):\n if old_label not in unq_new_labels:\n adata.uns['cluster_names'].pop(old_label, None)\n\n # Update entries\n adata.uns['cluster_info'] = {}\n unq_labels = np.unique(adata.obs['labels'])\n adata.uns['cluster_info']['unique_labels'] = unq_labels\n adata.uns['cluster_info']['n_clusters'] = len(unq_labels)\n adata.uns['cluster_info']['method'] = \"Modified\"\n populate_subsets(adata)\n\n\ndef populate_subsets(adata):\n # Populate subsets with the found clusters and\n # any don't remove user defined subsets\n if 'subsets' not in adata.uns:\n adata.uns['subsets'] = {}\n\n # Remove old clusters\n for subset in list(adata.uns['subsets'].keys()):\n if subset[:7] == 'Cluster':\n adata.uns['subsets'].pop(subset, None)\n # Update with new clusters\n unq_labels = np.unique(adata.obs['labels'])\n for label in unq_labels:\n adata.uns['subsets'][f'Cluster_{label}'] = \\\n np.reshape(np.where(adata.obs['labels'] == label), (-1))\n\n\ndef merge_clusters(adata, clusters):\n # Merge all clusters to the first one\n clusters = _validate_cluster_list(adata.obs['labels'], clusters)\n if len(clusters) < 2:\n raise InvalidArgument(\"Not enough clusters found to merge\")\n\n c0 = clusters[0]\n c0_name = adata.uns['cluster_names'][c0]\n\n for cluster in clusters[1:]:\n update_subset_label(adata, f'Cluster_{cluster}', c0_name)\n\n\ndef _clear_x_emb_dependents(adata):\n # Clear labels that used old x_emb\n if 'labels' in adata.obs:\n adata.obs.pop('labels')\n print('Clearing labels...')\n # Clear visualization if it used previous embeddings\n for dim in [2, 3]:\n if f'x_emb_{dim}d' in adata.obsm:\n if adata.uns[f'visualization_info_{dim}d']['used_emb'] == True:\n print('Clearing 2d embeddings...')\n adata.obsm.pop(f'x_emb_{dim}d', None)\n adata.uns.pop(f'visualization_info_{dim}d', None)\n\n\ndef get_dic():\n f = open(join_root(\"../markers/cl-simple.json\"), \"rb\")\n onto_data = json.load(f)\n cells = onto_data['graphs'][0]['nodes'] # dictionary of length 2632\n tissue = []\n cell_type = []\n tissues = ['kidney', 'thymus', 'spleen', \"liver\", 'lymph', 'stomach', 'heart',\n 'small intestine', 'large intestine', 'blood', \"brain\", \"thyroid\",\n 'placenta', 'eye', 'other', \"embryo\", \"muscle\"]\n\n identifiers = [['kidney'], ['thymocyte'], ['splenic'], [\"hepat\", \"liver\"],\n ['T', 'B'], ['stomach', 'gastric'], ['heart', 'cardiac'],\n ['small intestine'], ['large intestine'], [\n 'blood'], [\"brain\"], [\"thyroid\"],\n ['placenta'], ['eye', 'retina'], ['other'], [\"embryo\"], [\"muscle\", 'myo']]\n\n for i in cells:\n f = 0\n if ('lbl' in i.keys()):\n for j in range(len(identifiers)):\n for k in identifiers[j]:\n if ((k in i['lbl']) and f == 0):\n tissue.append(tissues[j])\n f = 1\n if (f == 0):\n tissue.append('other')\n cell_type.append(i['id'].split('/')[-1]+': '+i['lbl'])\n else:\n tissue.append('other')\n cell_type.append(i['id'].split('/')[-1])\n dic = {}\n for i in tissue:\n dic[i] = []\n for i in range(len(cell_type)):\n dic[tissue[i]].append(cell_type[i])\n return dic\n\n\ndef get_neighbors(\n x: Union[AnnData, np.ndarray, list],\n n_neighbors: int = 5,\n metric: str = 'euclidean',\n inplace: Optional[bool] = True,\n **kwargs):\n \"\"\"\n Calculate the neighbors based on the dimension reduced data\n\n Parameters\n __________\n x: AnnData object containing the data.\n\n metric: The kind of metric used to calculate neighbors\n\n n_neighbors: the number of closest points as neighbors\n\n inplace: If set to true will update x.obs['uncertainty'], otherwise,\n return a new AnnData object.\n\n **kwargs: Additional parameters that will get passed to the\n clustering object as specified in method. For a full list\n see the documentation of the corresponding method.\n\n Returns\n _______\n If x is an AnnData object, will either return an AnnData object\n or None depending on the value of inplace.\n \"\"\"\n # Validations\n is_AnnData = isinstance(x, AnnData)\n if not is_AnnData:\n raise InvalidArgument(\"x is not in AnnData format.\")\n adata = x.copy() if not inplace else x\n\n n_graph = kneighbors_graph(adata.obsm['x_emb'], n_neighbors=n_neighbors,\n include_self=False, metric=metric,\n mode='distance').toarray()\n\n nn = n_graph.nonzero()\n indices = nn[1].reshape(-1, n_neighbors)\n\n n_labels=[]\n for i in indices:\n n_labels.append(adata.obs['labels'][i])\n adata.obsm['neighbor_labels'] = np.array(n_labels)\n\n\n distances = [n_graph[nn[0][i], nn[1][i]]\n for i in range(len(x)*n_neighbors)]\n distances = np.array(distances).reshape(-1, n_neighbors)\n adata.obsm['neighbor_dist'] = distances\n\n if not inplace:\n return adata\n\n\ndef uncertainty(\n x: Union[AnnData, np.ndarray, list],\n method: str = 'conformal',\n n_neighbors: int = 5,\n inplace: Optional[bool] = True,\n **kwargs):\n \"\"\"\n Calculate the uncertainty for each point\n\n Parameters\n __________\n x: AnnData object containing the data.\n\n method: The method used to calculate uncertainty\n\n n_neighbor: the number of closest points as neighbors\n\n inplace: If set to true will update x.obs['uncertainty'], otherwise,\n return a new AnnData object.\n\n **kwargs: Additional parameters that will get passed to the\n clustering object as specified in method. For a full list\n see the documentation of the corresponding method.\n\n Returns\n _______\n If x is an AnnData object, will either return an AnnData object\n or None depending on the value of inplace.\n \"\"\"\n\n # Validations\n is_AnnData = isinstance(x, AnnData)\n if not is_AnnData:\n raise InvalidArgument(\"x is not in AnnData format.\")\n\n adata = x.copy() if not inplace else x\n\n if 'labels' not in x.obs:\n raise InvalidArgument(\n \"Cannot calculate uncertainty for dataset without labels\")\n\n if 'neighbor_labels' not in x.obsm:\n get_neighbors(x, n_neighbors=n_neighbors)\n\n # uncertainty calculation:\n uncertainty = []\n\n if (method == \"conformal\"):\n threshold = 1 # make sure 'b' is larger than 0\n # x.obsm['neighbor_dist'].sort()\n dist = x.obsm['neighbor_dist']\n n_labels = x.obsm['neighbor_labels']\n labels = np.array(x.obs['labels'])\n nonconformity = []\n for i in range(len(np.unique(labels))):\n # same_label=(n_labels.transpose()==labels.transpose()).transpose()\n same_label = (n_labels == i)\n diff_label = (n_labels != i)\n a = (dist*same_label).sum(axis=1)\n b = (dist*diff_label).sum(axis=1)\n nonconformity.append(a/(b+threshold))\n nonconformity = np.array(nonconformity).transpose()\n # argsort twice to get the ranking\n order = nonconformity.argsort(axis=1)\n # the reversed ranking of nonconformity score\n ranking = order.argsort(axis=1)\n p = ranking/(len(np.unique(labels))+1) # p_value for each label\n sp = p\n sp = sp[range(len(sp)), labels] # selected p\n uncertainty = 1-sp\n uncertainty = np.around(uncertainty, 3)\n # calculate possible labels\n mask = (np.ones((len(labels), len(np.unique(labels)))) == 1)\n mask[range(len(labels)), labels] = False\n p = p*mask # p value expect the selected ones\n\n p = p*(p > (np.average(p, axis=1)+np.std(p, axis=1)\n ).reshape(len(p), -1)) # only leave entry>ave+std\n p = p/(p.sum(axis=1).reshape(len(p), -1)) # normalization\n order = p.argsort(axis=1)\n rank = order.argsort(axis=1)\n rank = rank[:, ::-1]\n p.sort(axis=1)\n p = p[:, ::-1]\n p = np.around(p, 3)\n # adata.uns['pos_labels']=rank\n # adata.uns['label_prob']=p\n\n elif (method == 'confidence'):\n for i in range(len(adata.obs.labels)):\n u, indices = np.unique(adata.obsm['neighbor_labels'][i],\n return_inverse=True)\n knn_label_freq = np.bincount(indices).max()\n confidence = knn_label_freq / n_neighbors\n uncertain_score = (1 - confidence) * 100\n uncertainty.append(uncertain_score)\n else:\n raise InvalidArgument(\"Invalid uncertainty method\")\n\n adata.obs['uncertainty'] = uncertainty\n\n # make different labels for certain and uncertain points\n # threshhold for defining uncertain points\n t = np.average(uncertainty)+np.std(uncertainty)\n uncertain_matrix = (uncertainty > t)\n certainty = []\n t = np.average(uncertainty)+np.std(uncertainty)\n for i in range(len(labels)):\n if (uncertainty[i] > t):\n pos_label = \"\"\n for j in range(len(np.unique(labels))):\n prob = p[i, j]\n if (prob > 0):\n lb = str(rank[i, j])\n pos_label = pos_label+lb+\": \"+str(prob)+\"\\n\"\n certainty.append(\n \"Other possible label(s):\\n\"+str(pos_label))\n adata.uns['uncertainty_text'] = certainty\n\n # adata.obs['uncertain_matrix']=uncertain_matrix\n labels = np.array(adata.obs['labels'])\n uncertain_labels = labels*2+uncertain_matrix # certain labels are even numbers,\n # uncertain labels are odd numbers\n # origin labels = uncertain labels -1 / 2\n # = certain labels / 2\n # adata.obs['uncertain_labels']=uncertain_labels\n\n # make different subsets for certain and uncertain points\n clusters = list(adata.uns['subsets'].keys())\n uncertain_clusters = {}\n for i in clusters:\n uncertain_clusters[i+'_certain'] = np.array([], dtype='int64')\n uncertain_clusters[i+'_uncertain'] = np.array([], dtype='int64')\n for i in range(len(labels)): # put points into certain/uncertain clusters\n if uncertain_labels[i] % 2 == 0: # even, certain points\n cluster = list(adata.uns['subsets'].keys())[\n int(uncertain_labels[i]/2)] # the cluster it belongs to\n uncertain_clusters[cluster+'_certain'] = np.append(\n uncertain_clusters[cluster+'_certain'], i)\n else: # odd, uncertain points\n cluster = list(adata.uns['subsets'].keys())[\n int((uncertain_labels[i]-1)/2)] # the cluster it belongs to\n uncertain_clusters[cluster+'_uncertain'] = np.append(\n uncertain_clusters[cluster+'_uncertain'], i)\n\n adata.uns['uncertain_subsets'] = uncertain_clusters\n\n if not inplace:\n return adata\n\ndef re_id(\n adata:AnnData,\n expr: str = r'\\w*',\n **kwargs\n ):\n # use re to select subsets\n\n p = re.compile(expr)\n keys=[]\n for i in range(len(adata.obs.index)):\n cell_id=adata.obs.index[i]\n m = p.match(cell_id)\n if m:\n if m.end() == len(cell_id):\n keys.append(i)\n\n return keys\n"
]
| [
[
"numpy.max",
"numpy.append",
"numpy.array",
"numpy.bincount",
"numpy.array_equal",
"numpy.zeros",
"numpy.char.upper",
"numpy.std",
"numpy.where",
"numpy.char.replace",
"sklearn.neighbors.kneighbors_graph",
"numpy.average",
"numpy.around",
"numpy.unique"
]
]
|
Manny810/seesaw | [
"b722f1f67760d4831987910891fc5c3537f7ff42"
]
| [
"seesaw/search_loop_models.py"
]
| [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nfrom torch.utils.data import Subset\nfrom tqdm.auto import tqdm\nimport pyroaring as pr\nimport sys\nfrom torch.utils.data import TensorDataset\nfrom torch.utils.data import Subset\nfrom torch.utils.data import DataLoader\n\nimport pandas as pd\nimport numpy as np\n\nimport os\nimport pytorch_lightning as pl\nfrom .pairwise_rank_loss import compute_inversions\n\n\nclass CustomInterrupt(pl.callbacks.Callback):\n def on_keyboard_interrupt(self, trainer, pl_module):\n raise InterruptedError(\"custom\")\n\n\nclass CustomTqdm(pl.callbacks.progress.ProgressBar):\n def init_train_tqdm(self):\n \"\"\"Override this to customize the tqdm bar for training.\"\"\"\n bar = tqdm(\n desc=\"Training\",\n initial=self.train_batch_idx,\n position=(2 * self.process_position),\n disable=self.is_disabled,\n leave=False,\n dynamic_ncols=True,\n file=sys.stdout,\n smoothing=0,\n miniters=40,\n )\n return bar\n\n\nclass PTLogisiticRegression(pl.LightningModule):\n def __init__(\n self,\n input_dim: int,\n bias: bool = True,\n learning_rate: float = 5e-3,\n optimizer: torch.optim.Optimizer = torch.optim.Adam,\n C: float = 0.0,\n positive_weight: float = 1.0,\n **kwargs\n ):\n \"\"\"\n Args:\n input_dim: number of dimensions of the input (at least 1)\n num_classes: number of class labels (binary: 2, multi-class: >2)\n bias: specifies if a constant or intercept should be fitted (equivalent to fit_intercept in sklearn)\n learning_rate: learning_rate for the optimizer\n optimizer: the optimizer to use (default='Adam')\n l1_strength: L1 regularization strength (default=None)\n l2_strength: L2 regularization strength (default=None)\n \"\"\"\n super().__init__()\n self.save_hyperparameters()\n self.optimizer = optimizer\n self.linear = nn.Linear(\n in_features=self.hparams.input_dim, out_features=1, bias=bias\n )\n\n self.loss = nn.BCEWithLogitsLoss(\n pos_weight=torch.tensor([self.hparams.positive_weight]).float(),\n reduction=\"none\",\n )\n self.average_precision = pl.metrics.AveragePrecision(\n num_classes=2, pos_label=1, compute_on_step=False\n )\n\n def forward(self, qvec):\n qvec = self.linear(qvec)\n return qvec\n\n def _batch_step(self, batch, batch_idx):\n X, y = batch\n logits = self(X)\n loss = self.loss(logits, y.view(-1, 1)).reshape(-1).mean()\n\n # L2 regularizer\n if self.hparams.C > 0:\n l2_reg = self.linear.weight.pow(2).sum()\n loss = self.hparams.C * loss + l2_reg\n\n loss /= y.size(0)\n return {\"loss\": loss, \"logits\": logits, \"y\": y}\n\n def training_step(self, batch, batch_idx):\n d = self._batch_step(batch, batch_idx)\n loss = d[\"loss\"]\n self.log(\n \"loss/train\", loss, prog_bar=True, logger=True, on_step=True, on_epoch=False\n )\n return {\"loss\": loss}\n\n def validation_step(self, batch, batch_idx):\n d = self._batch_step(batch, batch_idx)\n loss = d[\"loss\"]\n logits = torch.clone(d[\"logits\"]).view(-1)\n\n self.average_precision(logits, d[\"y\"].view(-1).long())\n self.log(\n \"loss/val\", loss, prog_bar=True, logger=True, on_step=False, on_epoch=True\n )\n return {\"logits\": logits, \"y\": d[\"y\"]}\n\n def validation_epoch_end(self, validation_step_outputs):\n apval = self.average_precision.compute()\n self.log(\n \"AP/val\", apval, prog_bar=True, logger=True, on_epoch=True, on_step=False\n )\n self.average_precision.reset()\n\n def configure_optimizers(self):\n return self.optimizer(self.parameters(), lr=self.hparams.learning_rate)\n\n\ndef fit_reg(\n *,\n mod,\n X,\n y,\n batch_size,\n valX=None,\n valy=None,\n logger=None,\n max_epochs=4,\n gpus=0,\n precision=32\n):\n if not torch.is_tensor(X):\n X = torch.from_numpy(X)\n\n train_ds = TensorDataset(X, torch.from_numpy(y))\n train_loader = DataLoader(\n train_ds, batch_size=batch_size, shuffle=True, num_workers=0\n )\n\n if valX is not None:\n if not torch.is_tensor(valX):\n valX = torch.from_numpy(valX)\n val_ds = TensorDataset(valX, torch.from_numpy(valy))\n es = [\n pl.callbacks.early_stopping.EarlyStopping(\n monitor=\"AP/val\", mode=\"max\", patience=3\n )\n ]\n val_loader = DataLoader(val_ds, batch_size=2000, shuffle=False, num_workers=0)\n else:\n val_loader = None\n es = []\n\n trainer = pl.Trainer(\n logger=None,\n gpus=gpus,\n precision=precision,\n max_epochs=max_epochs,\n callbacks=[CustomInterrupt()],\n checkpoint_callback=False,\n weights_save_path=\"/tmp/\",\n progress_bar_refresh_rate=0, # =10\n )\n trainer.fit(mod, train_loader, val_loader)\n\n\nclass LookupVec(pl.LightningModule):\n def __init__(\n self,\n input_dim: int,\n margin: float = 0.1,\n init_vec: torch.tensor = None,\n learning_rate: float = 5e-3,\n positive_weight: float = 1.0,\n optimizer: torch.optim.Optimizer = torch.optim.Adam,\n **kwargs\n ):\n \"\"\"\n Args:\n input_dim: number of dimensions of the input (at least 1)\n \"\"\"\n super().__init__()\n self.save_hyperparameters()\n self.optimizer = optimizer\n\n if init_vec is not None:\n self.vec = nn.Parameter(init_vec.reshape(1, -1))\n else:\n t = torch.randn(1, input_dim)\n self.vec = nn.Parameter(t / t.norm())\n\n # self.loss = nn.CosineEmbeddingLoss(margin,reduction='none')\n self.rank_loss = nn.MarginRankingLoss(margin=margin, reduction=\"none\")\n\n def forward(self, qvec):\n vec = F.normalize(self.vec.reshape(-1), dim=-1)\n return qvec @ vec.reshape(-1) # qvecs are already normalized\n # return F.cosine_similarity(self.vec, qvec)\n\n def _batch_step(self, batch, batch_idx):\n X1, X2, y = batch\n sim1 = self(X1)\n sim2 = self(X2)\n\n losses = self.rank_loss(sim1, sim2, y.view(-1)).reshape(-1)\n return {\"loss\": losses.mean(), \"y\": y}\n\n def training_step(self, batch, batch_idx):\n d = self._batch_step(batch, batch_idx)\n loss = d[\"loss\"]\n # self.log(\"loss/train\", loss, prog_bar=True, logger=True, on_step=True, on_epoch=False)\n return {\"loss\": loss}\n\n def validation_step(self, batch, batch_idx):\n d = self._batch_step(batch, batch_idx)\n loss = d[\"loss\"]\n\n # self.log('loss/val', loss, prog_bar=True, logger=True, on_step=False, on_epoch=True)\n return {\"y\": d[\"y\"]}\n\n def validation_epoch_end(self, validation_step_outputs):\n apval = self.average_precision.compute()\n self.log(\n \"AP/val\", apval, prog_bar=True, logger=True, on_epoch=True, on_step=False\n )\n self.average_precision.reset()\n\n def configure_optimizers(self):\n return self.optimizer(self.parameters(), lr=self.hparams.learning_rate)\n\n\ndef make_hard_neg_ds(X, y, max_size, curr_vec):\n neg_flag = y < 1.0\n pos_flag = y > 0.0\n positions = torch.arange(y.shape[0])\n scores = X @ curr_vec.reshape(-1, 1)\n\n neg_idx = positions[neg_flag]\n neg_scores = scores[neg_flag]\n hard_neg = torch.argsort(neg_scores.reshape(-1), descending=True)[:max_size]\n hard_neg_idx = neg_idx[hard_neg]\n\n pos_idx = positions[pos_flag] # torch.arange(y.shape[0])[pos_flag]\n pos_scores = scores[pos_flag]\n hard_pos = torch.argsort(pos_scores.reshape(-1), descending=False)[:max_size]\n hard_pos_idx = pos_idx[hard_pos]\n\n assert (y[hard_pos_idx] > 0.0).all()\n assert (y[hard_neg_idx] < 1.0).all()\n\n if hard_neg_idx.shape[0] >= 2:\n assert scores[hard_neg_idx[0]] >= scores[hard_neg_idx[1]]\n\n if hard_pos_idx.shape[0] >= 2:\n assert scores[hard_pos_idx[0]] <= scores[hard_pos_idx[0]]\n\n root = int(math.ceil(math.sqrt(max_size)))\n\n if hard_pos_idx.shape[0] * hard_neg_idx.shape[0] > max_size:\n pos_bound = root\n neg_bound = root\n if hard_pos_idx.shape[0] < root:\n neg_bound = int(math.ceil(max_size / hard_pos_idx.shape[0]))\n\n if hard_neg_idx.shape[0] < root:\n pos_bound = int(math.ceil(max_size / hard_neg_idx.shape[0]))\n\n hard_pos_idx = hard_pos_idx[:pos_bound]\n hard_neg_idx = hard_neg_idx[:neg_bound]\n assert hard_pos_idx.shape[0] * hard_neg_idx.shape[0] >= max_size\n assert (hard_pos_idx.shape[0] - 1) * (hard_neg_idx.shape[0] - 1) < max_size\n\n X1ls = []\n X2ls = []\n for pi in hard_pos_idx:\n for nj in hard_neg_idx:\n X1ls.append(X[pi])\n X2ls.append(X[nj])\n # print(hard_pos_idx.shape, hard_neg_idx.shape)\n\n X1 = torch.stack(X1ls)\n X2 = torch.stack(X2ls)\n train_ds = TensorDataset(X1, X2, torch.ones(X1.shape[0]))\n\n return train_ds\n\n\ndef make_tuple_ds(X, y, max_size):\n X1ls = []\n X2ls = []\n for i in range(X.shape[0]):\n for j in range(X.shape[0]):\n if y[i] > y[j]:\n X1ls.append(X[i])\n X2ls.append(X[j])\n\n X1 = torch.stack(X1ls)\n X2 = torch.stack(X2ls)\n train_ds = TensorDataset(X1, X2, torch.ones(X1.shape[0]))\n if len(train_ds) > max_size:\n ## random sample... # should prefer some more\n randsel = torch.randperm(len(train_ds))[:max_size]\n train_ds = Subset(train_ds, randsel)\n return train_ds\n\n\ndef fit_rank2(\n *,\n mod,\n X,\n y,\n batch_size,\n max_examples,\n valX=None,\n valy=None,\n logger=None,\n margin=0.0,\n max_epochs=4,\n gpus=0,\n precision=32\n):\n\n ## for running on spc.\n if os.environ.get(\"SLURM_NTASKS\", \"\") != \"\":\n del os.environ[\"SLURM_NTASKS\"]\n if os.environ.get(\"SLURM_JOB_NAME\", \"\") != \"\":\n del os.environ[\"SLURM_JOB_NAME\"]\n\n if not torch.is_tensor(X):\n X = torch.from_numpy(X)\n\n assert (y >= 0).all()\n assert (y <= 1).all()\n\n # train_ds = make_hard_neg_ds(X, y, max_size=max_examples, curr_vec=mod.vec.detach())\n # ridx,iis,jjs = hard_neg_tuples(mod.vec.detach().numpy(), X.numpy(), y, max_tups=max_examples)\n # train_ds = TensorDataset(X[ridx][iis],X[ridx][jjs], torch.ones(X[ridx][iis].shape[0]))\n train_ds = hard_neg_tuples_faster(\n mod.vec.detach().numpy(), X.numpy(), y, max_tups=max_examples, margin=margin\n )\n ## want a tensor with pos, neg, 1. ideally the highest scored negatives and lowest scored positives.\n\n train_loader = DataLoader(\n train_ds, batch_size=batch_size, shuffle=True, num_workers=0\n )\n\n if valX is not None:\n if not torch.is_tensor(valX):\n valX = torch.from_numpy(valX)\n val_ds = TensorDataset(valX, torch.from_numpy(valy))\n es = [\n pl.callbacks.early_stopping.EarlyStopping(\n monitor=\"AP/val\", mode=\"max\", patience=3\n )\n ]\n val_loader = DataLoader(val_ds, batch_size=2000, shuffle=False, num_workers=0)\n else:\n val_loader = None\n es = []\n\n trainer = pl.Trainer(\n logger=None,\n gpus=gpus,\n precision=precision,\n max_epochs=max_epochs,\n # callbacks =[],\n callbacks=[CustomInterrupt()],\n # CustomTqdm()# ],\n checkpoint_callback=False,\n weights_save_path=\"/tmp/\",\n progress_bar_refresh_rate=0, # =10\n )\n trainer.fit(mod, train_loader, val_loader)\n\n\ndef adjust_vec(vec, Xt, yt, learning_rate, loss_margin, max_examples, minibatch_size):\n ## cosine sim in produce\n vec = torch.from_numpy(vec).type(torch.float32)\n mod = LookupVec(\n Xt.shape[1],\n margin=loss_margin,\n optimizer=torch.optim.SGD,\n learning_rate=learning_rate,\n init_vec=vec,\n )\n fit_rank2(\n mod=mod,\n X=Xt.astype(\"float32\"),\n y=yt.astype(\"float\"),\n max_examples=max_examples,\n batch_size=minibatch_size,\n max_epochs=1,\n margin=loss_margin,\n )\n newvec = mod.vec.detach().numpy().reshape(1, -1)\n return newvec\n\n\ndef max_inversions_given_max_tups(labs, inversions, max_tups):\n orig_df = pd.DataFrame({\"labs\": labs, \"inversions\": inversions})\n ddf = orig_df.sort_values(\"inversions\", ascending=False)\n\n pdf = ddf[ddf.labs]\n ndf = ddf[~ddf.labs]\n\n ncutoff = pdf.shape[0]\n pcutoff = ndf.shape[0]\n\n def total_inversions(ncutoff, pcutoff):\n if ncutoff <= pcutoff:\n tot = np.minimum(ndf.inversions.values[:ncutoff], pcutoff).sum()\n else:\n tot = np.minimum(pdf.inversions.values[:pcutoff], ncutoff).sum()\n\n return tot\n\n curr_inv = total_inversions(ncutoff, pcutoff)\n\n while (ncutoff * pcutoff > max_tups) and (ncutoff > 1 or pcutoff > 1):\n tot1 = total_inversions(max(1, ncutoff - 1), pcutoff)\n tot2 = total_inversions(ncutoff, max(1, pcutoff - 1))\n if tot2 >= tot1:\n pcutoff -= 1\n else:\n ncutoff -= 1\n\n ncutoff = max(1, ncutoff)\n pcutoff = max(1, pcutoff)\n\n tot_inv = total_inversions(ncutoff, pcutoff)\n tot_tup = ncutoff * pcutoff\n\n pidx = pdf.index.values[:pcutoff]\n nidx = ndf.index.values[:ncutoff]\n return pidx, nidx, tot_inv, tot_tup\n\n\ndef hard_neg_tuples_faster(v, Xt, yt, max_tups, margin):\n \"\"\"returns indices for the 'hardest' ntups\"\"\"\n ### compute reversals for each vector\n ### keep reversals about equal?\n labs = yt == 1.0 # make boolean\n scores = (Xt @ v.reshape(-1, 1)).reshape(-1)\n scores[labs] -= margin\n inversions = compute_inversions(labs, scores)\n pidx, nidx, _, _ = max_inversions_given_max_tups(labs, inversions, max_tups)\n pidx, nidx = np.meshgrid(pidx, nidx)\n pidx = pidx.reshape(-1)\n nidx = nidx.reshape(-1)\n assert labs[pidx].all()\n assert ~labs[nidx].any()\n\n dummy = torch.ones(size=(pidx.shape[0], 1))\n return TensorDataset(torch.from_numpy(Xt[pidx]), torch.from_numpy(Xt[nidx]), dummy)\n\n\ndef hard_neg_tuples(v, Xt, yt, max_tups):\n \"\"\"returns indices for the 'hardest' ntups\"\"\"\n p = np.where(yt > 0)[0]\n n = np.where(yt < 1)[0]\n assert p.shape[0] > 0\n assert n.shape[0] > 0\n\n scores = Xt @ v.reshape(-1, 1)\n score_diffs = scores[p].reshape(-1, 1) - scores[n].reshape(1, -1)\n iis, jjs = np.meshgrid(np.arange(p.shape[0]), np.arange(n.shape[0]), indexing=\"ij\")\n diff_order = np.argsort(score_diffs, axis=None)[:max_tups]\n # score_diffs.flatten()[diff_order]\n pps = p[iis.flatten()[diff_order]]\n nns = n[jjs.flatten()[diff_order]]\n\n ridx = np.array(pr.BitMap(pps).union(pr.BitMap(nns)))\n lookup_tab = np.zeros(Xt.shape[0], dtype=\"int\") - 1\n lookup_tab[ridx] = np.arange(ridx.shape[0], dtype=\"int\")\n piis = lookup_tab[pps]\n pjjs = lookup_tab[nns]\n # then X[ridx][piis] and X[ridx][jjs]\n # rdix o piis == iis <=> piis = iis\n assert (ridx[piis] == pps).all()\n return ridx, piis, pjjs\n\n\n# import cvxpy as cp\ndef adjust_vec2(v, Xt, yt, *, max_examples, loss_margin=0.1, C=0.1, solver=\"SCS\"):\n import cvxpy as cp\n\n # y = evbin.query_ground_truth[cat][dbidxs].values\n # X = hdb.embedded[dbidxs]\n margin = loss_margin\n nump = (yt > 0).sum()\n numn = (yt < 1).sum()\n\n ridx, piis, pjjs = hard_neg_tuples(v, Xt, yt, max_tups=max_examples)\n # hnds = make_hard_neg_ds(torch.from_numpy(Xt),torch.from_numpy(yt).float(),max_size=max_examples,curr_vec=v)\n def rank_loss(s1, s2, margin):\n loss = cp.sum(cp.pos(-(s1 - s2 - margin)))\n return loss\n\n wstr = (v / np.linalg.norm(v)).reshape(-1)\n w = cp.Variable(shape=wstr.shape, name=\"w\")\n w.value = wstr\n nweight = (nump + numn) / (\n nump * numn\n ) # increase with n but also account for tuple blowup wrt n\n X = Xt[ridx] # reduce problem size here\n\n scores = X @ w\n obj = rank_loss(scores[piis], scores[pjjs], loss_margin) * nweight + C * (\n 1.0 - (w @ wstr)\n )\n prob = cp.Problem(cp.Minimize(obj), constraints=[cp.norm2(w) <= 1.0])\n prob.solve(warm_start=True, solver=solver)\n return w.value.copy().reshape(1, -1)\n"
]
| [
[
"torch.nn.Linear",
"torch.stack",
"numpy.minimum",
"torch.ones",
"numpy.where",
"torch.nn.MarginRankingLoss",
"numpy.linalg.norm",
"torch.is_tensor",
"pandas.DataFrame",
"numpy.arange",
"torch.utils.data.DataLoader",
"torch.tensor",
"numpy.zeros",
"numpy.argsort",
"torch.arange",
"torch.from_numpy",
"torch.utils.data.Subset",
"torch.clone",
"numpy.meshgrid",
"torch.randn"
]
]
|
mayhallgroup/PsiEmbed | [
"6a82ac5e762d07aa645a2eb59956fb430ed1d04b"
]
| [
"src/embedding_methods.py"
]
| [
"import numpy as np\nimport psi4\nimport scipy.linalg\nimport sys\nfrom pyscf import gto, dft, scf, lib, mp, cc\n#import os\n\nclass Embed:\n \"\"\" Class with package-independent embedding methods.\"\"\"\n\n def __init__(self, keywords):\n \"\"\"\n Initialize the Embed class.\n\n Parameters\n ----------\n keywords (dict): dictionary with embedding options.\n \"\"\"\n self.keywords = keywords\n self.correlation_energy_shell = []\n self.shell_size = 0\n self.outfile = open(keywords['embedding_output'], 'w')\n return None\n\n @staticmethod\n def dot(A, B):\n \"\"\"\n (Deprecated) Computes the trace (dot or Hadamard product) \n of matrices A and B.\n This has now been replaced by a lambda function in \n embedding_module.py.\n\n Parameters\n ----------\n A : numpy.array\n B : numpy.array\n\n Returns\n -------\n The trace (dot product) of A * B\n\n \"\"\"\n return np.einsum('ij, ij', A, B)\n\n def orbital_rotation(self, orbitals, n_active_aos, ao_overlap = None):\n \"\"\"\n SVD orbitals projected onto active AOs to rotate orbitals.\n\n If ao_overlap is not provided, C is assumed to be in an\n orthogonal basis.\n \n Parameters\n ----------\n orbitals : numpy.array\n MO coefficient matrix.\n n_active_aos : int\n Number of atomic orbitals in the active atoms.\n ao_overlap : numpy.array (None)\n AO overlap matrix.\n\n Returns\n -------\n rotation_matrix : numpy.array\n Matrix to rotate orbitals.\n singular_values : numpy.array\n Singular values.\n \"\"\"\n if ao_overlap is None:\n orthogonal_orbitals = orbitals[:n_active_aos, :]\n else:\n s_half = scipy.linalg.fractional_matrix_power(ao_overlap, 0.5)\n orthogonal_orbitals = (s_half @ orbitals)[:n_active_aos, :]\n\n u, s, v = np.linalg.svd(orthogonal_orbitals, full_matrices=True)\n rotation_matrix = v\n singular_values = s\n return rotation_matrix, singular_values\n\n def orbital_partition(self, sigma, beta_sigma = None):\n \"\"\"\n Partition the orbital space by SPADE or all AOs in the\n projection basis. Beta variables are only used for open shells.\n\n Parameters\n ----------\n sigma : numpy.array\n Singular values.\n beta_sigma : numpy.array (None)\n Beta singular values.\n\n Returns\n -------\n self.n_act_mos : int\n (alpha) number of active MOs.\n self.n_env_mos : int\n (alpha) number of environment MOs.\n self.beta_n_act_mos : int\n Beta number of active MOs.\n self.beta_n_env_mos : int\n Beta number of environment MOs.\n \"\"\"\n if self.keywords['partition_method'] == 'spade':\n delta_s = [-(sigma[i+1] - sigma[i]) for i in range(len(sigma) - 1)]\n self.n_act_mos = np.argpartition(delta_s, -1)[-1] + 1\n self.n_env_mos = len(sigma) - self.n_act_mos\n else:\n assert isinstance(self.keywords['occupied_projection_basis'], str),\\\n '\\n Define a projection basis'\n self.n_act_mos = self.n_active_aos\n self.n_env_mos = len(sigma) - self.n_act_mos\n\n if self.keywords['low_level_reference'] == 'rhf':\n return self.n_act_mos, self.n_env_mos\n else:\n assert beta_sigma is not None, 'Provide beta singular values'\n if self.keywords['partition_method'] == 'spade':\n beta_delta_s = [-(beta_sigma[i+1] - beta_sigma[i]) \\\n for i in range(len(beta_sigma) - 1)]\n self.beta_n_act_mos = np.argpartition(beta_delta_s, -1)[-1] + 1\n self.beta_n_env_mos = len(beta_sigma) - self.beta_n_act_mos\n else:\n assert isinstance(self.keywords['occupied_projection_basis'], str),\\\n '\\n Define a projection basis'\n self.beta_n_act_mos = self.beta_n_active_aos\n self.beta_n_env_mos = len(beta_sigma) - self.beta_n_act_mos\n return (self.n_act_mos, self.n_env_mos, self.beta_n_act_mos,\n self.beta_n_env_mos)\n\n def header(self):\n \"\"\"Prints the header in the output file.\"\"\"\n self.outfile.write('\\n')\n self.outfile.write(' ' + 75*'-' + '\\n')\n self.outfile.write(' PsiEmbed\\n\\n')\n self.outfile.write(' Python Stack for Improved\\n')\n self.outfile.write(' and Efficient Methods and Benchmarking in'\n + ' Embedding Development\\n\\n')\n self.outfile.write(' Daniel Claudino\\n')\n self.outfile.write(' September 2019\\n')\n self.outfile.write(' ' + 75*'-' + '\\n')\n self.outfile.write('\\n')\n self.outfile.write(' Main references: \\n\\n')\n self.outfile.write(' Projection-based embedding:\\n')\n self.outfile.write(' F.R. Manby, M. Stella, J.D. Goodpaster,'\n + ' T.F. Miller. III,\\n')\n self.outfile.write(' J. Chem. Theory Comput. 2012, 8, 2564.\\n\\n')\n\n if self.keywords['partition_method'] == 'spade':\n self.outfile.write(' SPADE partition:\\n')\n self.outfile.write(' D. Claudino, N.J. Mayhall,\\n')\n self.outfile.write(' J. Chem. Theory Comput. 2019, 15, 1053.\\n\\n')\n\n if 'n_cl_shell' in self.keywords.keys():\n self.outfile.write(' Concentric localization (CL):\\n')\n self.outfile.write(' D. Claudino, N.J. Mayhall,\\n')\n self.outfile.write(' J. Chem. Theory Comput. 2019, 15, 6085.\\n\\n')\n\n if self.keywords['package'].lower() == 'psi4':\n self.outfile.write(' Psi4:\\n')\n self.outfile.write(' R. M. Parrish, L. A. Burns, D. G. A. Smith'\n + ', A. C. Simmonett, \\n')\n self.outfile.write(' A. E. DePrince III, E. G. Hohenstein'\n + ', U. Bozkaya, A. Yu. Sokolov,\\n')\n self.outfile.write(' R. Di Remigio, R. M. Richard, J. F. Gonthier'\n + ', A. M. James,\\n') \n self.outfile.write(' H. R. McAlexander, A. Kumar, M. Saitow'\n + ', X. Wang, B. P. Pritchard,\\n')\n self.outfile.write(' P. Verma, H. F. Schaefer III'\n + ', K. Patkowski, R. A. King, E. F. Valeev,\\n')\n self.outfile.write(' F. A. Evangelista, J. M. Turney,'\n + 'T. D. Crawford, and C. D. Sherrill,\\n')\n self.outfile.write(' J. Chem. Theory Comput. 2017, 13, 3185.')\n\n if self.keywords['package'].lower() == 'pyscf':\n self.outfile.write(' PySCF:\\n')\n self.outfile.write(' Q. Sun, T. C. Berkelbach, N. S. Blunt'\n + ', G. H. Booth, S. Guo, Z. Li,\\n')\n self.outfile.write(' J. Liu, J. D. McClain, E. R. Sayfutyarova'\n + ', S. Sharma, S. Wouters,\\n')\n self.outfile.write(' and G. K.‐L. Chan,\\n')\n self.outfile.write(' WIREs Comput. Mol. Sci. 2018, 8, e1340.')\n self.outfile.write('\\n\\n')\n self.outfile.write(' ' + 75*'-' + '\\n')\n return None\n\n def print_scf(self, e_act, e_env, two_e_cross, e_act_emb, correction):\n \"\"\"\n Prints mean-field info from before and after embedding.\n\n Parameters\n ----------\n e_act : float\n Energy of the active subsystem.\n e_env : float\n Energy of the environment subsystem.\n two_e_cross : float\n Intersystem interaction energy.\n e_act_emb : float\n Energy of the embedded active subsystem.\n correction : float\n Correction from the embedded density.\n \"\"\"\n self.outfile.write('\\n\\n Energy values in atomic units\\n')\n self.outfile.write(' Embedded calculation: '\n + self.keywords['high_level'].upper()\n + '-in-' + self.keywords['low_level'].upper() + '\\n\\n')\n if self.keywords['partition_method'] == 'spade':\n if 'occupied_projection_basis' not in self.keywords:\n self.outfile.write(' Orbital partition method: SPADE\\n')\n else:\n self.outfile.write((' Orbital partition method: SPADE with ',\n 'occupied space projected onto '\n + self.keywords['occupied_projection_basis'].upper() + '\\n'))\n else:\n self.outfile.write(' Orbital partition method: All AOs in '\n + self.keywords['occupied_projection_basis'].upper()\n + ' from atoms in A\\n')\n\n self.outfile.write('\\n')\n if hasattr(self, 'beta_n_act_mos') == False:\n self.outfile.write(' Number of orbitals in active subsystem: %s\\n'\n % self.n_act_mos)\n self.outfile.write(' Number of orbitals in environment: %s\\n'\n % self.n_env_mos)\n else:\n self.outfile.write(' Number of alpha orbitals in active subsystem:'\n + ' %s\\n' % self.n_act_mos)\n self.outfile.write(' Number of beta orbitals in active subsystem:'\n + ' %s\\n' % self.beta_n_act_mos)\n self.outfile.write(' Number of alpha orbitals in environment:'\n + ' %s\\n' % self.n_env_mos)\n self.outfile.write(' Number of beta orbitals in environment:'\n + ' %s\\n' % self.beta_n_env_mos)\n self.outfile.write('\\n')\n self.outfile.write(' --- Before embedding --- \\n')\n self.outfile.write(' {:<7} {:<6} \\t\\t = {:>16.10f}\\n'.format('('\n + self.keywords['low_level'].upper() +')', 'E[A]', e_act))\n self.outfile.write(' {:<7} {:<6} \\t\\t = {:>16.10f}\\n'.format('('\n + self.keywords['low_level'].upper() +')', 'E[B]', e_env))\n self.outfile.write(' Intersystem interaction G \\t = {:>16.10f}\\n'.\n format(two_e_cross))\n self.outfile.write(' Nuclear repulsion energy \\t = {:>16.10f}\\n'.\n format(self.nre))\n self.outfile.write(' {:<7} {:<6} \\t\\t = {:>16.10f}\\n'.format('('\n + self.keywords['low_level'].upper() + ')', 'E[A+B]',\n e_act + e_env + two_e_cross + self.nre))\n self.outfile.write('\\n')\n self.outfile.write(' --- After embedding --- \\n')\n self.outfile.write(' Embedded SCF E[A] \\t\\t = {:>16.10f}\\n'.\n format(e_act_emb))\n self.outfile.write(' Embedded density correction \\t = {:>16.10f}\\n'.\n format(correction))\n self.outfile.write(' Embedded HF-in-{:<5} E[A] \\t = {:>16.10f}\\n'.\n format(self.keywords['low_level'].upper(),\n e_act_emb + e_env + two_e_cross + self.nre + correction))\n self.outfile.write(' <SD_before|SD_after> \\t\\t = {:>16.10f}\\n'.format(\n abs(self.determinant_overlap)))\n self.outfile.write('\\n')\n return None\n\n def print_summary(self, e_mf_emb):\n \"\"\"\n Prints summary of CL shells.\n\n Parameters\n ----------\n e_mf_emb : float\n Mean-field embedded energy.\n \"\"\"\n self.outfile.write('\\n Summary of virtual shell energy convergence\\n\\n')\n self.outfile.write('{:^8} \\t {:^8} \\t {:^12} \\t {:^16}\\n'.format(\n 'Shell #', '# active', ' Correlation', 'Total'))\n self.outfile.write('{:^8} \\t {:^8} \\t {:^12} \\t {:^16}\\n'.format(\n 8*'', 'virtuals', 'energy', 'energy'))\n self.outfile.write('{:^8} \\t {:^8} \\t {:^12} \\t {:^16}\\n'.format(\n 7*'-', 8*'-', 13*'-', 16*'-'))\n\n for ishell in range(self.n_cl_shell+1):\n self.outfile.write('{:^8d} \\t {:^8} \\t {:^12.10f} \\t {:^12.10f}\\n'\\\n .format(ishell, self.shell_size*(ishell+1),\n self.correlation_energy_shell[ishell],\n e_mf_emb + self.correlation_energy_shell[ishell]))\n\n if (ishell == self.max_shell and\n self.keywords['n_cl_shell'] > self.max_shell):\n n_virtuals = self._n_basis_functions - self.n_act_mos\n n_effective_virtuals = (self._n_basis_functions - self.n_act_mos\n - self.n_env_mos)\n self.outfile.write('{:^8} \\t {:^8} \\t {:^12.10f} \\t {:^12.10f}\\n'.\n format('Eff.', n_effective_virtuals,\n self.correlation_energy_shell[-1],\n e_mf_emb + self.correlation_energy_shell[-1]))\n self.outfile.write('{:^8} \\t {:^8} \\t {:^12.10f} \\t {:^12.10f}\\n'.\n format('Full', n_virtuals, self.correlation_energy_shell[-1],\n e_mf_emb + self.correlation_energy_shell[-1]))\n self.outfile.write('\\n')\n return None\n \n def print_sigma(self, sigma, ishell):\n \"\"\"\n Formats the printing of singular values from the CL shells.\n\n Parameters\n ----------\n sigma : numpy.array or list\n Singular values.\n ishell :int\n CL shell index.\n \"\"\"\n self.outfile.write('\\n{:>10} {:>2d}\\n'.format('Shell #', ishell))\n self.outfile.write(' ------------\\n')\n self.outfile.write('{:^5} \\t {:^14}\\n'.format('#','Singular value'))\n for i in range(len(sigma)):\n self.outfile.write('{:^5d} \\t {:>12.10f}\\n'.format(i, sigma[i]))\n self.outfile.write('\\n')\n return None\n\n def determinant_overlap(self, orbitals, beta_orbitals = None):\n \"\"\"\n Compute the overlap between determinants formed from the\n provided orbitals and the embedded orbitals\n\n Parameters\n ----------\n orbitals : numpy.array\n Orbitals to compute the overlap with embedded orbitals.\n beta_orbitals : numpy.array (None)\n Beta orbitals, if running with references other than RHF.\n \"\"\"\n if self.keywords['high_level_reference'] == 'rhf' and beta_orbitals == None:\n overlap = self.occupied_orbitals.T @ self.ao_overlap @ orbitals\n u, s, vh = np.linalg.svd(overlap)\n self.determinant_overlap = (\n np.linalg.det(u)*np.linalg.det(vh)*np.prod(s))\n else:\n assert beta_orbitals is not None, '\\nProvide beta orbitals.'\n alpha_overlap = (self.alpha_occupied_orbitals.T @ self.ao_overlap\n @ beta_orbitals)\n u, s, vh = np.linalg.svd(alpha_overlap)\n self.determinant_overlap = 0.5*(\n np.linalg.det(u)*np.linalg.det(vh)*np.prod(s))\n beta_overlap = (self.beta_occupied_orbitals.T @ self.ao_overlap\n @ beta_orbitals)\n u, s, vh = np.linalg.svd(beta_overlap)\n self.determinant_overlap += 0.5*(\n np.linalg.det(u)*np.linalg.det(vh)*np.prod(s))\n return None\n\n def count_shells(self):\n \"\"\"\n Guarantees the correct number of shells are computed.\n\n Returns\n -------\n max_shell : int\n Maximum number of virtual shells.\n self.n_cl_shell : int\n Number of virtual shells.\n \"\"\"\n effective_dimension = (self._n_basis_functions - self.n_act_mos\n - self.n_env_mos)\n self.max_shell = int(effective_dimension/self.shell_size)-1\n if (self.keywords['n_cl_shell']\n > int(effective_dimension/self.shell_size)):\n self.n_cl_shell = self.max_shell\n elif effective_dimension % self.shell_size == 0:\n self.n_cl_shell = self.max_shell - 1\n else:\n self.n_cl_shell = self.keywords['n_cl_shell']\n return self.max_shell, self.n_cl_shell\n\n\nclass PySCFEmbed(Embed):\n \"\"\"Class with embedding methods using PySCF.\"\"\"\n \n def run_mean_field(self, v_emb = None):\n \"\"\"\n Runs mean-field calculation with PySCF.\n If 'level' is not provided, it runs the a calculation at the level\n given by the 'low_level' key in self.keywords. HF otherwise.\n\n Parameters\n ----------\n v_emb : numpy.array or list of numpy.array (None)\n Embedding potential.\n \"\"\"\n self._mol = gto.mole.Mole()\n self._mol.verbose = self.keywords['print_level']\n #self._mol.output = self.keywords['driver_output']\n self._mol.atom = self.keywords['geometry']\n self._mol.max_memory = self.keywords['memory']\n self._mol.basis = self.keywords['basis']\n if v_emb is None: # low-level/environment calculation\n self._mol.output = self.keywords['driver_output']\n if self.keywords['low_level'] == 'hf':\n if self.keywords['low_level_reference'].lower() == 'rhf':\n self._mean_field = scf.RHF(self._mol)\n if self.keywords['low_level_reference'].lower() == 'uhf':\n self._mean_field = scf.UHF(self._mol)\n if self.keywords['low_level_reference'].lower() == 'rohf':\n self._mean_field = scf.ROHF(self._mol)\n self.e_xc = 0.0\n else:\n if self.keywords['low_level_reference'].lower() == 'rhf':\n self._mean_field = dft.RKS(self._mol)\n if self.keywords['low_level_reference'].lower() == 'uhf':\n self._mean_field = dft.UKS(self._mol)\n if self.keywords['low_level_reference'].lower() == 'rohf':\n self._mean_field = dft.ROKS(self._mol)\n self._mean_field.conv_tol = self.keywords['e_convergence']\n self._mean_field.xc = self.keywords['low_level']\n self._mean_field.kernel()\n self.v_xc_total = self._mean_field.get_veff()\n self.e_xc_total = self._mean_field.get_veff().exc\n else:\n if self.keywords['high_level_reference'].lower() == 'rhf':\n self._mean_field = scf.RHF(self._mol)\n if self.keywords['high_level_reference'].lower() == 'uhf':\n self._mean_field = scf.UHF(self._mol)\n if self.keywords['high_level_reference'].lower() == 'rohf':\n self._mean_field = scf.ROHF(self._mol)\n if self.keywords['low_level_reference'].lower() == 'rhf':\n self._mol.nelectron = 2*self.n_act_mos\n self._mean_field.get_hcore = lambda *args: v_emb + self.h_core\n if (self.keywords['low_level_reference'].lower() == 'rohf'\n or self.keywords['low_level_reference'].lower() == 'uhf'):\n self._mol.nelectron = self.n_act_mos + self.beta_n_act_mos\n self._mean_field.get_vemb = lambda *args: v_emb\n #self._mean_field.get_fock = self.get_fock()\n self._mean_field.conv_tol = self.keywords['e_convergence']\n self._mean_field.kernel()\n\n if self.keywords['low_level_reference'] == 'rhf':\n docc = (self._mean_field.mo_occ == 2).sum()\n self.occupied_orbitals = self._mean_field.mo_coeff[:, :docc]\n self.j, self.k = self._mean_field.get_jk() \n self.v_xc_total = self._mean_field.get_veff() - self.j\n else:\n n_alpha = (self._mean_field.mo_occ[0] == 1).sum()\n n_beta = (self._mean_field.mo_occ[1] == 1).sum()\n # TODO: make the distinction for UHF and ROHF orbitals\n if (self.keywords['low_level_reference'] == 'uhf' and v_emb is None\n or self.keywords['high_level_reference'] == 'uhf'\n and v_emb is not None):\n self.alpha_occupied_orbitals = self._mean_field.mo_coeff[\n 0, :, :n_alpha]\n self.beta_occupied_orbitals = self._mean_field.mo_coeff[\n 1, :, :n_beta]\n if (self.keywords['low_level_reference'] == 'rohf' and v_emb is None\n or self.keywords['high_level_reference'] == 'rohf'\n and v_emb is not None):\n self.alpha_occupied_orbitals = self._mean_field.mo_coeff[:, :n_alpha]\n self.beta_occupied_orbitals = self._mean_field.mo_coeff[:, :n_beta]\n j, k = self._mean_field.get_jk() \n self.alpha_j = j[0] \n self.beta_j = j[1]\n self.alpha_k = k[0]\n self.beta_k = k[1]\n self.alpha_v_xc_total = self._mean_field.get_veff()[0] - j[0] - j[1]\n self.beta_v_xc_total = self._mean_field.get_veff()[1] - j[0] - j[1]\n\n self.alpha = 0.0\n self._n_basis_functions = self._mol.nao\n self.nre = self._mol.energy_nuc()\n self.ao_overlap = self._mean_field.get_ovlp(self._mol)\n self.h_core = self._mean_field.get_hcore(self._mol)\n return None\n\n def count_active_aos(self, basis = None):\n \"\"\"\n Computes the number of AOs from active atoms.\n\n Parameters\n ----------\n basis : str\n Name of basis set from which to count active AOs.\n \n Returns\n -------\n self.n_active_aos : int\n Number of AOs in the active atoms.\n \"\"\"\n if basis is None:\n self.n_active_aos = self._mol.aoslice_nr_by_atom()[\n self.keywords['n_active_atoms']-1][3]\n else:\n self._projected_mol = gto.mole.Mole()\n self._projected_mol.atom = self.keywords['geometry']\n self._projected_mol.basis = basis \n self._projected_mf = scf.RHF(self._projected_mol)\n self.n_active_aos = self._projected_mol.aoslice_nr_by_atom()[\n self.keywords['n_active_atoms']-1][3]\n return self.n_active_aos\n \n def basis_projection(self, orbitals, projection_basis):\n \"\"\"\n Defines a projection of orbitals in one basis onto another.\n \n Parameters\n ----------\n orbitals : numpy.array\n MO coefficients to be projected.\n projection_basis : str\n Name of basis set onto which orbitals are to be projected.\n\n Returns\n -------\n projected_orbitals : numpy.array\n MO coefficients of orbitals projected onto projection_basis.\n \"\"\"\n self.projected_overlap = (self._projected_mf.get_ovlp(self._mol)\n [:self.n_active_aos, :self.n_active_aos])\n self.overlap_two_basis = gto.intor_cross('int1e_ovlp_sph', \n self._mol, self._projected_mol)[:self.n_active_aos, :]\n projected_orbitals = (np.linalg.inv(self.projected_overlap)\n @ self.overlap_two_basis @ orbitals)\n return projected_orbitals\n\n def closed_shell_subsystem(self, orbitals):\n \"\"\"\n Computes the potential matrices J, K, and V and subsystem energies.\n\n Parameters\n ----------\n orbitals : numpy.array\n MO coefficients of subsystem.\n\n Returns\n -------\n e : float\n Total energy of subsystem.\n e_xc : float\n DFT Exchange-correlation energy of subsystem.\n j : numpy.array\n Coulomb matrix of subsystem.\n k : numpy.array\n Exchange matrix of subsystem.\n v_xc : numpy.array\n Kohn-Sham potential matrix of subsystem.\n \"\"\"\n density = 2.0*orbitals @ orbitals.T\n #It seems that PySCF lumps J and K in the J array \n j = self._mean_field.get_j(dm = density)\n k = np.zeros([self._n_basis_functions, self._n_basis_functions])\n two_e_term = self._mean_field.get_veff(self._mol, density)\n e_xc = two_e_term.exc\n v_xc = two_e_term - j \n\n # Energy\n e = self.dot(density, self.h_core + j/2) + e_xc\n return e, e_xc, j, k, v_xc\n\n def open_shell_subsystem(self, alpha_orbitals, beta_orbitals):\n \"\"\"\n Computes the potential matrices J, K, and V and subsystem\n energies for open shell cases.\n\n Parameters\n ----------\n alpha_orbitals : numpy.array\n Alpha MO coefficients.\n beta_orbitals : numpy.array\n Beta MO coefficients.\n\n Returns\n -------\n e : float\n Total energy of subsystem.\n e_xc : float\n Exchange-correlation energy of subsystem.\n alpha_j : numpy.array\n Alpha Coulomb matrix of subsystem.\n beta_j : numpy.array\n Beta Coulomb matrix of subsystem.\n alpha_k : numpy.array\n Alpha Exchange matrix of subsystem.\n beta_k : numpy.array\n Beta Exchange matrix of subsystem.\n alpha_v_xc : numpy.array\n Alpha Kohn-Sham potential matrix of subsystem.\n beta_v_xc : numpy.array\n Beta Kohn-Sham potential matrix of subsystem.\n \"\"\"\n alpha_density = alpha_orbitals @ alpha_orbitals.T\n beta_density = beta_orbitals @ beta_orbitals.T\n\n # J and K\n j = self._mean_field.get_j(dm = [alpha_density, beta_density])\n alpha_j = j[0]\n beta_j = j[1]\n alpha_k = np.zeros([self._n_basis_functions, self._n_basis_functions])\n beta_k = np.zeros([self._n_basis_functions, self._n_basis_functions])\n two_e_term = self._mean_field.get_veff(self._mol, [alpha_density,\n beta_density])\n e_xc = two_e_term.exc\n alpha_v_xc = two_e_term[0] - (j[0] + j[1])\n beta_v_xc = two_e_term[1] - (j[0]+j[1])\n\n # Energy\n e = (self.dot(self.h_core, alpha_density + beta_density)\n + 0.5*(self.dot(alpha_j + beta_j, alpha_density + beta_density))\n + e_xc)\n\n return e, e_xc, alpha_j, beta_j, alpha_k, beta_k, alpha_v_xc, beta_v_xc\n \n def correlation_energy(self, span_orbitals = None, kernel_orbitals = None,\n span_orbital_energies = None, kernel_orbital_energies = None):\n \"\"\"\n Computes the correlation energy for the current set of active\n virtual orbitals.\n \n Parameters\n ----------\n span_orbitals : numpy.array\n Orbitals transformed by the span of the previous shell.\n kernel_orbitals : numpy.array\n Orbitals transformed by the kernel of the previous shell.\n span_orbital_energies : numpy.array\n Orbitals energies of the span orbitals.\n kernel_orbital_energies : numpy.array\n Orbitals energies of the kernel orbitals.\n\n Returns\n -------\n correlation_energy : float\n Correlation energy of the span_orbitals.\n \"\"\"\n\n shift = self._n_basis_functions - self.n_env_mos\n if span_orbitals is None:\n # If not using CL orbitals, just freeze the level-shifted MOs\n frozen_orbitals = [i for i in range(shift, self._n_basis_functions)]\n else:\n # Preparing orbitals and energies for CL shell\n effective_orbitals = np.hstack((span_orbitals, kernel_orbitals))\n orbital_energies = np.concatenate((span_orbital_energies,\n kernel_orbital_energies))\n frozen_orbitals = [i for i in range(self.n_act_mos\n + span_orbitals.shape[1], self._n_basis_functions)]\n orbitals = np.hstack((self.occupied_orbitals,\n effective_orbitals, self._mean_field.mo_coeff[:, shift:]))\n orbital_energies = (\n np.concatenate((self._mean_field.mo_energy[:self.n_act_mos],\n orbital_energies, self._mean_field.mo_energy[shift:])))\n # Replace orbitals in the mean_field obj by the CL orbitals\n # and compute correlation energy\n self._mean_field.mo_energy = orbital_energies\n self._mean_field.mo_coeff = orbitals\n\n if self.keywords['high_level'].lower() == 'mp2':\n #embedded_wf = mp.MP2(self._mean_field).run()\n embedded_wf = mp.MP2(self._mean_field).set(frozen = frozen_orbitals).run()\n correlation_energy = embedded_wf.e_corr\n if (self.keywords['high_level'].lower() == 'ccsd' or \n self.keywords['high_level'].lower() == 'ccsd(t)'):\n embedded_wf = cc.CCSD(self._mean_field).set(frozen = frozen_orbitals).run()\n correlation_energy = embedded_wf.e_corr\n if self.keywords['high_level'].lower() == 'ccsd(t)':\n t_correction = embedded_wf.ccsd_t().T\n correlation_energy += t_correction\n # if span_orbitals provided, store correlation energy of shells\n if span_orbitals is not None:\n self.correlation_energy_shell.append(correlation_energy)\n return correlation_energy\n\n def effective_virtuals(self):\n \"\"\"\n Slices the effective virtuals from the entire virtual space.\n\n Returns\n -------\n effective_orbitals : numpy.array\n Virtual orbitals without the level-shifted orbitals\n from the environment.\n \"\"\"\n shift = self._n_basis_functions - self.n_env_mos\n effective_orbitals = self._mean_field.mo_coeff[:, self.n_act_mos:shift]\n return effective_orbitals\n\n def pseudocanonical(self, orbitals):\n \"\"\"\n Returns pseudocanonical orbitals and the corresponding\n orbital energies.\n \n Parameters\n ----------\n orbitals : numpy.array\n MO coefficients of orbitals to be pseudocanonicalized.\n\n Returns\n -------\n e_orbital_pseudo : numpy.array\n diagonal elements of the Fock matrix in the\n pseudocanonical basis.\n pseudo_orbitals : numpy.array\n pseudocanonical orbitals.\n \"\"\"\n fock_matrix = self._mean_field.get_fock()\n mo_fock = orbitals.T @ fock_matrix @ orbitals\n e_orbital_pseudo, pseudo_transformation = np.linalg.eigh(mo_fock)\n pseudo_orbitals = orbitals @ pseudo_transformation\n return e_orbital_pseudo, pseudo_orbitals\n\n def ao_operator(self):\n \"\"\"\n Returns the matrix representation of the operator chosen to\n construct the shells.\n\n Returns\n -------\n\n K : numpy.array\n Exchange.\n V : numpy.array\n Electron-nuclei potential.\n T : numpy.array\n Kinetic energy.\n H : numpy.array\n Core (one-particle) Hamiltonian.\n S : numpy.array\n Overlap matrix.\n F : numpy.array\n Fock matrix.\n K_orb : numpy.array\n K orbitals (see Feller and Davidson, JCP, 74, 3977 (1981)).\n \"\"\"\n if (self.keywords['operator'] == 'K' or\n self.keywords['operator'] == 'K_orb'):\n self.operator = self._mean_field.get_k()\n if self.keywords['operator'] == 'K_orb':\n self.operator = 0.06*self._mean_field.get_fock() - self.operator\n elif self.keywords['operator'] == 'V':\n self.operator = self._mol.intor_symmetric('int1e_nuc')\n elif self.keywords['operator'] == 'T':\n self.operator = self._mol.intor_symmetric('int1e_kin')\n elif self.keywords['operator'] == 'H':\n self.operator = self._mean_field.get_hcore()\n elif self.keywords['operator'] == 'S':\n self.operator = self._mean_field.get_ovlp()\n elif self.keywords['operator'] == 'F':\n self.operator = self._mean_field.get_fock()\n return None\n\nclass Psi4Embed(Embed):\n \"\"\"Class with embedding methods using Psi4.\"\"\"\n\n\n def run_mean_field(self, v_emb = None):\n \"\"\"\n Runs Psi4 (PySCF is coming soon).\n If 'level' is not provided, it runs the a calculation at the level\n given by the 'low_level' key in self.keywords.\n\n Parameters\n ----------\n v_emb : numpy.array or list of numpy.array (None)\n Embedding potential.\n \"\"\"\n if v_emb is None:\n self.outfile = open(self.keywords['embedding_output'], 'w')\n # Preparing molecule string with C1 symmetry\n add_c1 = self.keywords['geometry'].splitlines()\n add_c1.append('symmetry c1')\n self.keywords['geometry'] = '\\n'.join(add_c1)\n\n # Running psi4 for the env (low level)\n psi4.set_memory(str(self.keywords['memory']) + ' MB')\n psi4.core.set_num_threads(self.keywords['num_threads'])\n self._mol = psi4.geometry(self.keywords['geometry'])\n self._mol.set_molecular_charge(self.keywords['charge'])\n self._mol.set_multiplicity(self.keywords['multiplicity'])\n\n psi4.core.be_quiet()\n psi4.core.set_output_file(self.keywords['driver_output'], True)\n psi4.set_options({'save_jk': 'true',\n 'basis': self.keywords['basis'],\n 'reference': self.keywords['low_level_reference'],\n 'ints_tolerance': self.keywords['ints_tolerance'],\n 'e_convergence': self.keywords['e_convergence'],\n 'd_convergence': self.keywords['d_convergence'],\n 'scf_type': self.keywords['eri'],\n 'print': self.keywords['print_level'],\n 'damping_percentage':\n self.keywords['low_level_damping_percentage'],\n 'soscf': self.keywords['low_level_soscf']\n })\n\n self.e, self._wfn = psi4.energy(self.keywords['low_level'],\n molecule = self._mol, return_wfn=True)\n self._n_basis_functions = self._wfn.basisset().nbf()\n if self.keywords['low_level'] != 'HF' :\n self.e_xc_total = psi4.core.VBase.quadrature_values\\\n (self._wfn.V_potential())[\"FUNCTIONAL\"]\n if self.keywords['low_level_reference'] == 'rhf':\n self.v_xc_total = self._wfn.Va().clone().np\n else:\n self.alpha_v_xc_total = self._wfn.Va().clone().np\n self.beta_v_xc_total = self._wfn.Vb().clone().np\n else:\n if self.keywords['low_level_reference'] == 'rhf':\n #self.v_xc_total = np.zeros([self._n_basis_functions,\n #self._n_basis_functions])\n self.v_xc_total = 0.0\n else:\n #self.alpha_v_xc_total = np.zeros([self._n_basis_functions,\n #self._n_basis_functions])\n #self.beta_v_xc_total = np.zeros([self._n_basis_functions,\n #self._n_basis_functions])\n self.alpha_v_xc_total = 0.0 \n self.beta_v_xc_total = 0.0 \n self.e_xc_total = 0.0\n else:\n psi4.set_options({'docc': [self.n_act_mos],\n 'reference': self.keywords['high_level_reference']})\n if self.keywords['high_level_reference'] == 'rhf':\n f = open('newH.dat', 'w')\n for i in range(self.h_core.shape[0]):\n for j in range(self.h_core.shape[1]):\n f.write(\"%s\\n\" % (self.h_core + v_emb)[i, j])\n f.close()\n else:\n psi4.set_options({'socc': [self.n_act_mos - self.beta_n_act_mos]})\n fa = open('Va_emb.dat', 'w')\n fb = open('Vb_emb.dat', 'w')\n for i in range(self.h_core.shape[0]):\n for j in range(self.h_core.shape[1]):\n fa.write(\"%s\\n\" % v_emb[0][i, j])\n fb.write(\"%s\\n\" % v_emb[1][i, j])\n fa.close()\n fb.close()\n\n if (self.keywords['high_level'][:2] == 'cc' and\n self.keywords['cc_type'] == 'df'):\n psi4.set_options({'cc_type': self.keywords['cc_type'],\n 'df_ints_io': 'save' })\n self.e, self._wfn = psi4.energy('hf',\n molecule = self._mol, return_wfn=True)\n\n if self.keywords['low_level_reference'] == 'rhf':\n self.occupied_orbitals = self._wfn.Ca_subset('AO', 'OCC').np\n self.j = self._wfn.jk().J()[0].np\n self.k = self._wfn.jk().K()[0].np\n else:\n self.alpha_occupied_orbitals = self._wfn.Ca_subset('AO', 'OCC').np\n self.beta_occupied_orbitals = self._wfn.Ca_subset('AO', 'OCC').np\n self.alpha_j = self._wfn.jk().J()[0].np\n self.beta_j = self._wfn.jk().J()[1].np\n self.alpha_k = self._wfn.jk().K()[0].np\n self.beta_k = self._wfn.jk().K()[1].np\n\n self.nre = self._mol.nuclear_repulsion_energy()\n self.ao_overlap = self._wfn.S().np\n self.h_core = self._wfn.H().np\n self.alpha = self._wfn.functional().x_alpha()\n return None\n\n def count_active_aos(self, basis = None):\n \"\"\"\n Computes the number of AOs from active atoms.\n\n Parameters\n ----------\n basis : str\n Name of basis set from which to count active AOs.\n \n Returns\n -------\n self.n_active_aos : int\n Number of AOs in the active atoms.\n \"\"\"\n if basis is None:\n basis = self._wfn.basisset()\n n_basis_functions = basis.nbf()\n else:\n projected_wfn = psi4.core.Wavefunction.build(self._mol, basis)\n basis = projected_wfn.basisset()\n n_basis_functions = basis.nbf()\n \n self.n_active_aos = 0\n active_atoms = list(range(self.keywords['n_active_atoms']))\n for ao in range(n_basis_functions):\n for atom in active_atoms:\n if basis.function_to_center(ao) == atom:\n self.n_active_aos += 1\n return self.n_active_aos\n \n def basis_projection(self, orbitals, projection_basis):\n \"\"\"\n Defines a projection of orbitals in one basis onto another.\n \n Parameters\n ----------\n orbitals : numpy.array\n MO coefficients to be projected.\n projection_basis : str\n Name of basis set onto which orbitals are to be projected.\n\n Returns\n -------\n projected_orbitals : numpy.array\n MO coefficients of orbitals projected onto projection_basis.\n \"\"\"\n projected_wfn = psi4.core.Wavefunction.build(self._mol,\n projection_basis)\n mints = psi4.core.MintsHelper(projected_wfn.basisset())\n self.projected_overlap = (\n mints.ao_overlap().np[:self.n_active_aos, :self.n_active_aos])\n self.overlap_two_basis = (mints.ao_overlap(projected_wfn.basisset(),\n self._wfn.basisset()).np[:self.n_active_aos, :])\n projected_orbitals = (np.linalg.inv(self.projected_overlap)\n @ self.overlap_two_basis @ orbitals)\n return projected_orbitals\n\n def closed_shell_subsystem(self, orbitals):\n \"\"\"\n Computes the potential matrices J, K, and V and subsystem energies.\n\n Parameters\n ----------\n orbitals : numpy.array\n MO coefficients of subsystem.\n\n Returns\n -------\n e : float\n Total energy of subsystem.\n e_xc : float\n DFT Exchange-correlation energy of subsystem.\n j : numpy.array\n Coulomb matrix of subsystem.\n k : numpy.array\n Exchange matrix of subsystem.\n v_xc : numpy.array\n Kohn-Sham potential matrix of subsystem.\n \"\"\"\n\n density = orbitals @ orbitals.T\n psi4_orbitals = psi4.core.Matrix.from_array(orbitals)\n\n if hasattr(self._wfn, 'get_basisset'):\n jk = psi4.core.JK.build(self._wfn.basisset(),\n self._wfn.get_basisset('DF_BASIS_SCF'), 'DF')\n else:\n jk = psi4.core.JK.build(self._wfn.basisset())\n jk.set_memory(int(1.25e9))\n jk.initialize()\n jk.C_left_add(psi4_orbitals)\n jk.compute()\n jk.C_clear()\n jk.finalize()\n\n j = jk.J()[0].np\n k = jk.K()[0].np\n\n if(self._wfn.functional().name() != 'HF'):\n self._wfn.Da().copy(psi4.core.Matrix.from_array(density))\n self._wfn.form_V()\n v_xc = self._wfn.Va().clone().np\n e_xc = psi4.core.VBase.quadrature_values(\n self._wfn.V_potential())[\"FUNCTIONAL\"]\n\n else:\n basis = self._wfn.basisset()\n n_basis_functions = basis.nbf()\n v_xc = 0.0\n e_xc = 0.0\n\n # Energy\n e = self.dot(density, 2.0*(self.h_core + j) - self.alpha*k) + e_xc\n return e, e_xc, 2.0 * j, k, v_xc\n\n def pseudocanonical(self, orbitals):\n \"\"\"\n Returns pseudocanonical orbitals and the corresponding\n orbital energies.\n \n Parameters\n ----------\n orbitals : numpy.array\n MO coefficients of orbitals to be pseudocanonicalized.\n\n Returns\n -------\n e_orbital_pseudo : numpy.array\n diagonal elements of the Fock matrix in the\n pseudocanonical basis.\n pseudo_orbitals : numpy.array\n pseudocanonical orbitals.\n \"\"\"\n mo_fock = orbitals.T @ self._wfn.Fa().np @ orbitals\n e_orbital_pseudo, pseudo_transformation = np.linalg.eigh(mo_fock)\n pseudo_orbitals = orbitals @ pseudo_transformation\n return e_orbital_pseudo, pseudo_orbitals\n\n def ao_operator(self):\n \"\"\"\n Returns the matrix representation of the operator chosen to\n construct the shells.\n\n Returns\n -------\n\n K : numpy.array\n Exchange.\n V : numpy.array\n Electron-nuclei potential.\n T : numpy.array\n Kinetic energy.\n H : numpy.array\n Core (one-particle) Hamiltonian.\n S : numpy.array\n Overlap matrix.\n F : numpy.array\n Fock matrix.\n K_orb : numpy.array\n K orbitals (see Feller and Davidson, JCP, 74, 3977 (1981)).\n \"\"\"\n if (self.keywords['operator'] == 'K' or\n self.keywords['operator'] == 'K_orb'):\n jk = psi4.core.JK.build(self._wfn.basisset(),\n self._wfn.get_basisset('DF_BASIS_SCF'),'DF')\n jk.set_memory(int(1.25e9))\n jk.initialize()\n jk.print_header()\n jk.C_left_add(self._wfn.Ca())\n jk.compute()\n jk.C_clear()\n jk.finalize()\n self.operator = jk.K()[0].np\n if self.keywords['operator'] == 'K_orb':\n self.operator = 0.06*self._wfn.Fa().np - self.K\n elif self.keywords['operator'] == 'V':\n mints = psi4.core.MintsHelper(self._wfn.basisset())\n self.operator = mints.ao_potential().np\n elif self.keywords['operator'] == 'T':\n mints = psi4.core.MintsHelper(self._wfn.basisset())\n self.operator = mints.ao_kinetic().np\n elif self.keywords['operator'] == 'H':\n self.operator = self._wfn.H().np\n elif self.keywords['operator'] == 'S':\n self.operator = self._wfn.S().np\n elif self.keywords['operator'] == 'F':\n self.operator = self._wfn.Fa().np\n\n def open_shell_subsystem(self, alpha_orbitals, beta_orbitals):\n \"\"\"\n Computes the potential matrices J, K, and V and subsystem\n energies for open shell cases.\n\n Parameters\n ----------\n alpha_orbitals : numpy.array\n Alpha MO coefficients.\n beta_orbitals : numpy.array\n Beta MO coefficients.\n\n Returns\n -------\n e : float\n Total energy of subsystem.\n e_xc : float\n Exchange-correlation energy of subsystem.\n alpha_j : numpy.array\n Alpha Coulomb matrix of subsystem.\n beta_j : numpy.array\n Beta Coulomb matrix of subsystem.\n alpha_k : numpy.array\n Alpha Exchange matrix of subsystem.\n beta_k : numpy.array\n Beta Exchange matrix of subsystem.\n alpha_v_xc : numpy.array\n Alpha Kohn-Sham potential matrix of subsystem.\n beta_v_xc : numpy.array\n Beta Kohn-Sham potential matrix of subsystem.\n \"\"\"\n alpha_density = alpha_orbitals @ alpha_orbitals.T\n beta_density = beta_orbitals @ beta_orbitals.T\n\n # J and K\n jk = psi4.core.JK.build(self._wfn.basisset(),\n self._wfn.get_basisset('DF_BASIS_SCF'), 'DF')\n jk.set_memory(int(1.25e9))\n jk.initialize()\n jk.C_left_add(psi4.core.Matrix.from_array(alpha_orbitals))\n jk.C_left_add(psi4.core.Matrix.from_array(beta_orbitals))\n jk.compute()\n jk.C_clear()\n jk.finalize()\n alpha_j = jk.J()[0].np\n beta_j = jk.J()[1].np\n alpha_k = jk.K()[0].np\n beta_k = jk.K()[1].np\n \n if(self._wfn.functional().name() != 'HF'):\n self._wfn.Da().copy(psi4.core.Matrix.from_array(alpha_density))\n self._wfn.Db().copy(psi4.core.Matrix.from_array(beta_density))\n self._wfn.form_V()\n alpha_v_xc = self._wfn.Va().clone().np\n beta_v_xc = self._wfn.Vb().clone().np\n e_xc = psi4.core.VBase.quadrature_values(\n self._wfn.V_potential())['FUNCTIONAL']\n else:\n #alpha_v_xc = np.zeros([self._n_basis_functions,\n #self._n_basis_functions])\n #beta_v_xc = np.zeros([self._n_basis_functions,\n #self._n_basis_functions])\n alpha_v_xc = 0.0\n beta_v_xc = 0.0\n e_xc = 0.0\n\n e = (self.dot(self.h_core, alpha_density + beta_density)\n + 0.5*(self.dot(alpha_j + beta_j, alpha_density + beta_density)\n - self.alpha*self.dot(alpha_k, alpha_density)\n - self.alpha*self.dot(beta_k, beta_density)) + e_xc)\n\n return e, e_xc, alpha_j, beta_j, alpha_k, beta_k, alpha_v_xc, beta_v_xc\n\n def orthonormalize(self, S, C, n_non_zero):\n \"\"\"\n (Deprecated) Orthonormalizes a set of orbitals (vectors).\n\n Parameters\n ----------\n S : numpy.array\n Overlap matrix in AO basis.\n C : numpy.array\n MO coefficient matrix, vectors to be orthonormalized.\n n_non_zero : int\n Number of orbitals that have non-zero norm.\n\n Returns\n -------\n C_orthonormal : numpy.array\n Set of n_non_zero orthonormal orbitals.\n \"\"\"\n\n overlap = C.T @ S @ C\n v, w = np.linalg.eigh(overlap)\n idx = v.argsort()[::-1]\n v = v[idx]\n w = w[:,idx]\n C_orthonormal = C @ w\n for i in range(n_non_zero):\n C_orthonormal[:,i] = C_orthonormal[:,i]/np.sqrt(v[i])\n return C_orthonormal[:,:n_non_zero]\n\n def molden(self, shell_orbitals, shell):\n \"\"\"\n Creates molden file from orbitals at the shell.\n\n Parameters\n ----------\n span_orbitals : numpy.array\n Span orbitals.\n shell : int\n Shell index.\n \"\"\"\n self._wfn.Ca().copy(psi4.core.Matrix.from_array(shell_orbitals))\n psi4.driver.molden(self._wfn, str(shell) + '.molden')\n return None\n\n def heatmap(self, span_orbitals, kernel_orbitals, shell):\n \"\"\"\n Creates heatmap file from orbitals at the i-th shell.\n\n Parameters\n ----------\n span_orbitals : numpy.array\n Span orbitals.\n kernel_orbitals : numpy.array\n Kernel orbitals.\n shell : int\n Shell index.\n \"\"\"\n orbitals = np.hstack((span_orbitals, kernel_orbitals))\n mo_operator = orbitals.T @ self.operator @ orbitals\n np.savetxt('heatmap_'+str(shell)+'.dat', mo_operator)\n return None\n\n def correlation_energy(self, span_orbitals = None, kernel_orbitals = None,\n span_orbital_energies = None, kernel_orbital_energies = None):\n \"\"\"\n Computes the correlation energy for the current set of active\n virtual orbitals.\n \n Parameters\n ----------\n span_orbitals : numpy.array\n Orbitals transformed by the span of the previous shell.\n kernel_orbitals : numpy.array\n Orbitals transformed by the kernel of the previous shell.\n span_orbital_energies : numpy.array\n Orbitals energies of the span orbitals.\n kernel_orbital_energies : numpy.array\n Orbitals energies of the kernel orbitals.\n\n Returns\n -------\n correlation_energy : float\n Correlation energy of the span_orbitals.\n \"\"\"\n shift = self._n_basis_functions - self.n_env_mos\n if span_orbitals is None:\n nfrz = self.n_env_mos\n else:\n effective_orbitals = np.hstack((span_orbitals,\n kernel_orbitals))\n orbital_energies = np.concatenate((span_orbital_energies,\n kernel_orbital_energies))\n nfrz = (self._n_basis_functions - self.n_act_mos\n - span_orbitals.shape[1])\n orbitals = np.hstack((self.occupied_orbitals,\n effective_orbitals, self._wfn.Ca().np[:, shift:]))\n orbital_energies = (\n np.concatenate((self._wfn.epsilon_a().np[:self.n_act_mos],\n orbital_energies, self._wfn.epsilon_a().np[shift:])))\n self._wfn.Ca().copy(psi4.core.Matrix.from_array(orbitals))\n self._wfn.epsilon_a().np[:] = orbital_energies[:]\n\n # Update the number of frozen orbitals and compute energy\n frzvpi = psi4.core.Dimension.from_list([nfrz])\n self._wfn.new_frzvpi(frzvpi)\n #wf_eng, wf_wfn = psi4.energy(self.keywords['high_level'],\n #ref_wfn = self._wfn, return_wfn = True)\n psi4.energy(self.keywords['high_level'], ref_wfn = self._wfn)\n correlation_energy = psi4.core.get_variable(\n self.keywords['high_level'].upper() + \" CORRELATION ENERGY\")\n self.correlation_energy_shell.append(correlation_energy)\n return correlation_energy\n\n def effective_virtuals(self):\n \"\"\"\n Slices the effective virtuals from the entire virtual space.\n\n Returns\n -------\n effective_orbitals : numpy.array\n Virtual orbitals without the level-shifted orbitals\n from the environment.\n \"\"\"\n shift = self._n_basis_functions - self.n_env_mos\n effective_orbitals = self._wfn.Ca().np[:, self.n_act_mos:shift]\n return effective_orbitals\n\n"
]
| [
[
"numpy.concatenate",
"numpy.zeros",
"numpy.linalg.eigh",
"numpy.linalg.det",
"numpy.prod",
"numpy.einsum",
"numpy.linalg.svd",
"numpy.sqrt",
"numpy.argpartition",
"numpy.hstack",
"numpy.linalg.inv"
]
]
|
paul-shannon/slexil2 | [
"53f53482ea9d92510b17595f6275cedcfefde2e8"
]
| [
"slexil/ijalLine.py"
]
| [
"\n'''\n******************************************************************\nSLEXIL—Software Linking Elan XML to Illuminated Language\nCopyright (C) 2019 Paul Shannon and David Beck\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nThe full version of the GNU General Public License is found at\n<https://www.gnu.org/licenses/>.\n\nInformation about the software can be obtained by contacting\ndavid.beck at ualberta.ca.\n******************************************************************\n'''\n\nimport pandas as pd\nfrom xml.etree import ElementTree as etree\nfrom morphemeGloss import *\nfrom pprint import pprint\nfrom yattag import *\nimport pdb\nimport formatting\nfrom translationLine import *\n# from errors import *\nimport logging\nfrom LineDataFrame import DataFrame as ldf\nimport identifyLines\n\n# ------------------------------------------------------------------------------------------------------------------------\n# -*- coding: utf-8 -*-\n# ------------------------------------------------------------------------------------------------------------------------\nclass IjalLine:\n tierInfo = []\n spokenTextID = \"\"\n rootElement = None\n rootID = None\n tierElements = []\n doc = None\n lineNumber = None\n soundFile = None\n grammaticalTerms = None\n\n def __init__(self, doc, lineNumber, tierGuide, grammaticalTerms=[]):\n self.doc = doc\n self.lineNumber = lineNumber\n self.tierGuide = tierGuide\n self.rootID = lineNumber + 1\n self.grammaticalTerms = grammaticalTerms\n self.speechTierList = identifyLines.getList(self.doc, self.tierGuide)\n self.rootElement = self.speechTierList[lineNumber]\n self.allElements = findChildren(self.doc, self.rootElement)\n dataFrame = ldf(doc, self.allElements)\n self.tblRaw = dataFrame.getTbl()\n self.tierCount = self.tblRaw.shape[0]\n\n def parse(self):\n self.tbl = standardizeTable(self.tblRaw, self.tierGuide)\n # print(self.tbl)\n # print(self.lineNumber)\n self.tbl.index = range(len(self.tbl.index))\n self.categories = categories = self.tbl[\"category\"].tolist()\n # print(self.lineNumber,self.categories.index(\"speech\"))\n if 'speech' in self.categories:\n self.speechRow = self.categories.index(\"speech\")\n else:\n logging.warning(\"EAF error: Line %s has nothing in the transcription line.\" % (int(self.lineNumber) + 1))\n self.speechRow = None\n if 'translation' in self.categories:\n self.translationRow = self.categories.index(\"translation\")\n else:\n self.translationRow = None\n tierCount = self.tbl.shape[0]\n # pdb.set_trace()\n self.morphemeRows = [i for i in range(tierCount) if self.categories[i] == \"morpheme\"]\n self.morphemeGlossRows = [i for i in range(tierCount) if self.categories[i] == \"morphemeGloss\"]\n # handle the case of a secondary translation\n if 'translation2' in self.categories:\n self.translation2Row = self.categories.index(\"translation2\")\n else:\n self.translation2Row = None\n # handle the case of a second transcription line\n if 'transcription2' in self.categories:\n self.transcription2Row = self.categories.index(\"transcription2\")\n else:\n self.transcription2Row = None\n self.morphemes = self.extractMorphemes()\n self.morphemeGlosses = self.extractMorphemeGlosses()\n self.calculateMorphemeSpacing()\n\n def getTierCount(self):\n return (self.getTable().shape[0])\n\n def getTable(self):\n return (self.tbl)\n\n '''the next three methods handle a use case where there is a missing or \n empty transcription (line) tier but assume that there is a valid time-\n aligned translation tier (not sure we can save a file that has neither)'''\n\n def getStartTime(self):\n col = self.tbl.columns.values.tolist().index(\"START\")\n if self.speechRow != None:\n return (self.tbl.iloc[self.speechRow][self.tbl.columns.values.tolist().index(\"START\")])\n else:\n return (self.tbl.iloc[self.translationRow][self.tbl.columns.values.tolist().index(\"START\")])\n\n\n def getEndTime(self):\n if self.speechRow != None:\n return (self.tbl.iloc[self.speechRow][self.tbl.columns.values.tolist().index(\"END\")])\n else:\n return (self.tbl.iloc[self.translationRow][self.tbl.columns.values.tolist().index(\"END\")])\n\n def getAnnotationID(self):\n if self.speechRow != None:\n return (self.tbl.iloc[self.speechRow][self.tbl.columns.values.tolist().index(\"ANNOTATION_ID\")])\n else:\n return (self.tbl.iloc[self.translationRow][self.tbl.columns.values.tolist().index(\"ANNOTATION_ID\")])\n\n # ----------------------------------------------------------------------------------------------------\n def show(self):\n\n pprint(vars(self))\n\n # ----------------------------------------------------------------------------------------------------\n def getSpokenText(self):\n\n # categories = self.tbl[\"category\"].tolist()\n # row = categories.index(\"speech\")\n if self.speechRow == None:\n return '<div class=\"missing_annotation\">⚠️ Missing transcription line ⚠️</div>'\n else:\n return (self.tbl.iloc[self.speechRow, self.tbl.columns.values.tolist().index(\"TEXT\")])\n\n # ----------------------------------------------------------------------------------------------------\n def getTranslation(self):\n\n # categories = self.tbl[\"category\"].tolist()\n # row = categories.index(\"translation\")\n # pdb.set_trace()\n if self.translationRow == None:\n logging.warning(\"missing translation at line %d\" % (int(self.lineNumber) + 1))\n return (None)\n translation = self.tbl.iloc[self.translationRow, self.tbl.columns.values.tolist().index(\"TEXT\")]\n translationLine = TranslationLine(translation)\n return (translationLine.getStandardized())\n\n # ----------------------------------------------------------------------------------------------------\n def getTranslation2(self):\n if self.translation2Row != None:\n translation2 = self.tbl.iloc[self.translation2Row, self.tbl.columns.values.tolist().index(\"TEXT\")]\n translationLine2 = TranslationLine(translation2)\n return (translationLine2.getStandardized())\n else:\n return (None)\n\n # ----------------------------------------------------------------------------------------------------\n def getTranscription2(self):\n if self.transcription2Row != None:\n transcription2 = self.tbl.iloc[self.transcription2Row, self.tbl.columns.values.tolist().index(\"TEXT\")]\n return (transcription2)\n else:\n return (None)\n\n # ----------------------------------------------------------------------------------------------------\n def extractMorphemes(self):\n\n if (self.morphemeRows == []):\n return ([])\n\n rawMorphemeList = self.tbl[\"TEXT\"].iloc[self.morphemeRows].tolist()\n rawMorphemes = ''.join(rawMorphemeList)\n if \"\\t\" in rawMorphemes:\n rawMorphemeText = self.tbl[\"TEXT\"].iloc[self.morphemeRows].tolist()[0]\n rawMorphemeList = rawMorphemeText.split('\\t')\n\n morphemes = replaceHyphensWithNDashes(rawMorphemeList)\n return (morphemes)\n\n # ----------------------------------------------------------------------------------------------------\n def extractMorphemeGlosses(self):\n\n if (self.morphemeGlossRows == []):\n return ([])\n\n rawMorphemeGlossList = self.tbl[\"TEXT\"].iloc[self.morphemeGlossRows].tolist()\n rawMorphemeGlosses = ''.join(rawMorphemeGlossList)\n if \"\\t\" in rawMorphemeGlosses:\n rawMorphemeGlossText = self.tbl[\"TEXT\"].iloc[self.morphemeGlossRows].tolist()[0]\n rawMorphemeGlossList = rawMorphemeGlossText.split('\\t')\n\n morphemeGlosses = replaceHyphensWithNDashes(rawMorphemeGlossList)\n return (morphemeGlosses)\n\n # ----------------------------------------------------------------------------------------------------\n def getMorphemes(self):\n\n return (self.morphemes)\n\n # ----------------------------------------------------------------------------------------------------\n def getGrammaticalTerms(self, terms):\n try:\n if terms[-1] == '':\n terms = terms[:-1]\n return newTerms\n except IndexError:\n return\n\n # ----------------------------------------------------------------------------------------------------\n def getMorphemeGlosses(self):\n\n return (self.morphemeGlosses)\n\n # ----------------------------------------------------------------------------------------------------\n def calculateMorphemeSpacing(self):\n\n \"\"\"\n the spacing is used to create a styleString, specifying grid cell widths which\n accomodate the widest of each morpheme/gloss pair, so that they each member of\n each pair is vertically aligned:\n m1 m2 ----m3-----\n g1 ---g2--- g3\n \"\"\"\n morphemes = self.getMorphemes()\n glosses = self.getMorphemeGlosses()\n\n if (len(morphemes) > len(glosses)):\n logging.warning(\"EAF error: There are more morphs (%d) than glosses (%d) in line %s.\" % (\n len(morphemes), len(glosses), int(self.lineNumber) + 1))\n theDifference = len(morphemes) - len(glosses)\n for i in range(0, theDifference):\n glosses.append(\"⚠️\")\n elif (len(morphemes) < len(glosses)):\n logging.warning(\"EAF error: There are more glosses (%d) than morphs (%d) in line %s.\" % (\n len(glosses), len(morphemes), int(self.lineNumber) + 1))\n theDifference = len(glosses) - len(morphemes)\n for i in range(0, theDifference):\n morphemes.append(\"⚠️\")\n\n self.morphemeSpacing = []\n\n for i in range(len(morphemes)):\n if \"<su\" in morphemes[i]:\n newmorph = morphemes[i].replace(\"<sub>\", \"\")\n newmorph = newmorph.replace(\"</sub>\", \"\")\n newmorph = newmorph.replace(\"<sup>\", \"\")\n newmorph = newmorph.replace(\"</sup>\", \"\")\n morphemeSize = len(newmorph)\n else:\n morphemeSize = len(morphemes[i])\n if \"<su\" in glosses[i]:\n newGloss = glosses[i].replace(\"<sub>\", \"\")\n newGloss = newGloss.replace(\"</sub>\", \"\")\n newGloss = newGloss.replace(\"<sup>\", \"\")\n newGloss = newGloss.replace(\"</sup>\", \"\")\n glossSize = len(newGloss)\n else:\n glossSize = len(glosses[i])\n self.morphemeSpacing.append(max(morphemeSize, glossSize) + 1)\n\n # ----------------------------------------------------------------------------------------------------\n def getMorphemeSpacing(self):\n\n return (self.morphemeSpacing)\n\n # ----------------------------------------------------------------------------------------------------\n def htmlLeadIn(self, htmlDoc, audioDirectory, audioFileType):\n\n text = \"%d)\" % (self.lineNumber + 1)\n htmlDoc.text(text)\n lineID = self.rootID\n audioTag = '<audio id=\"%s\"><source src=\"%s/%s.%s\"/></audio>' % (\n self.getAnnotationID(), audioDirectory, self.getAnnotationID(),audioFileType)\n htmlDoc.asis(audioTag)\n onError = \"this.style.display=\\'none\\'\"\n buttonTag = '<button onclick=\"playSample(\\'%s\\')\">🔈</button>' % self.getAnnotationID()\n htmlDoc.asis(buttonTag)\n\n # ----------------------------------------------------------------------------------------------------\n def toHTML(self, htmlDoc):\n\n with htmlDoc.tag(\"div\", klass=\"line-content\"):\n with htmlDoc.tag(\"div\", klass=\"line\"):\n styleString = \"grid-template-columns: %s;\" % ''.join([\"%dch \" % p for p in self.morphemeSpacing])\n with htmlDoc.tag(\"div\", klass=\"speech-tier\"):\n htmlDoc.asis(self.getSpokenText())\n\n transcription2 = self.getTranscription2()\n if transcription2 != None:\n with htmlDoc.tag(\"div\", klass=\"secondTranscription-tier\"):\n htmlDoc.asis(self.getTranscription2())\n\n morphemes = self.getMorphemes()\n if (len(morphemes) > 0):\n with htmlDoc.tag(\"div\", klass=\"morpheme-tier\", style=styleString):\n for morpheme in morphemes:\n with htmlDoc.tag(\"div\", klass=\"morpheme-cell\"):\n htmlDoc.asis(morpheme)\n\n morphemeGlosses = self.getMorphemeGlosses()\n if (len(morphemeGlosses) > 0):\n with htmlDoc.tag(\"div\", klass=\"morpheme-tier\", style=styleString):\n for morphemeGloss in self.getMorphemeGlosses():\n with htmlDoc.tag(\"div\", klass=\"morpheme-cell\"):\n mg = MorphemeGloss(morphemeGloss, self.grammaticalTerms)\n mg.parse()\n mg.toHTML(htmlDoc)\n\n translation = self.getTranslation()\n if translation:\n with htmlDoc.tag(\"div\", klass=\"freeTranslation-tier\"):\n htmlDoc.asis(self.getTranslation())\n\n translation2 = self.getTranslation2()\n if translation2 != None:\n with htmlDoc.tag(\"div\", klass=\"freeTranslation-tier\"):\n htmlDoc.text(translation2)\n # add a div to hold annotations\n with htmlDoc.tag(\"div\", klass=\"annotationDiv\"):\n pass#;\n\n\n# ------------------------------------------------------------------------------------------------------------------------\ndef findChildren(doc, rootElement):\n elementsToDo = [rootElement]\n elementsCompleted = []\n\n while (len(elementsToDo) > 0):\n currentElement = elementsToDo[0]\n parentRef = currentElement.attrib[\"ANNOTATION_ID\"]\n pattern = \"TIER/ANNOTATION/REF_ANNOTATION[@ANNOTATION_REF='%s']\" % parentRef\n childElements = doc.findall(pattern)\n elementsToDo.remove(currentElement)\n elementsCompleted.append(currentElement)\n if (len(childElements) > 0):\n elementsToDo.extend(childElements)\n\n return (elementsCompleted)\n\n\n# ------------------------------------------------------------------------------------------------------------------------\ndef buildTable(doc, lineElements):\n tbl_elements = pd.DataFrame(e.attrib for e in lineElements)\n # print(tbl_elements)\n\n startTimeSlotID = tbl_elements.iloc[0, tbl_elements.columns.values.tolist().index('TIME_SLOT_REF1')]\n pattern = \"TIME_ORDER/TIME_SLOT[@TIME_SLOT_ID='%s']\" % startTimeSlotID\n startTime = int(doc.find(pattern).attrib[\"TIME_VALUE\"])\n startTimes = [startTime]\n rowCount = tbl_elements.shape[0]\n for i in range(1, rowCount):\n startTimes.append(float('NaN'))\n\n endTimeSlotID = tbl_elements.iloc[0, tbl_elements.columns.values.tolist().index('TIME_SLOT_REF2')]\n pattern = \"TIME_ORDER/TIME_SLOT[@TIME_SLOT_ID='%s']\" % endTimeSlotID\n endTime = int(doc.find(pattern).attrib[\"TIME_VALUE\"])\n endTimes = [endTime]\n for i in range(1, rowCount):\n endTimes.append(float('NaN'))\n tbl_times = pd.DataFrame({\"START\": startTimes, \"END\": endTimes})\n # print(tbl_times)\n\n ids = [e.attrib[\"ANNOTATION_ID\"] for e in lineElements]\n tierInfo = []\n text = []\n\n for id in ids:\n parentPattern = \"*/*/*/[@ANNOTATION_ID='%s']/../..\" % id\n tierAttributes = doc.find(parentPattern).attrib\n tierInfo.append(tierAttributes)\n childPattern = \"*/*/*/[@ANNOTATION_ID='%s']/ANNOTATION_VALUE\" % id\n elementText = doc.find(childPattern).text\n if (elementText is None):\n elementText = \"\"\n # print(\"elementText: %s\" % elementText)\n text.append(elementText.strip())\n\n tbl_tierInfo = pd.DataFrame(tierInfo)\n\n tbl_text = pd.DataFrame({\"TEXT\": text})\n\n # print(\"---- tbl_elements\")\n # print(tbl_elements)\n #\n # print(\"---- tbl_tierInfo\")\n # print(tbl_tierInfo)\n #\n # print(\"---- tbl_times\")\n # print(tbl_times)\n #\n # print(\"---- tbl_text\")\n # print(tbl_text)\n\n tbl = pd.concat([tbl_elements, tbl_tierInfo, tbl_times, tbl_text], axis=1)\n preferredColumnOrder = [\"ANNOTATION_ID\", \"LINGUISTIC_TYPE_REF\", \"START\", \"END\", \"TEXT\", \"ANNOTATION_REF\",\n \"TIME_SLOT_REF1\", \"TIME_SLOT_REF2\",\n \"PARENT_REF\", \"TIER_ID\"]\n try:\n tbl = tbl[preferredColumnOrder]\n except KeyError:\n preferredColumnOrder = [\"ANNOTATION_ID\", \"LINGUISTIC_TYPE_REF\", \"START\", \"END\", \"TEXT\",\n \"TIME_SLOT_REF1\", \"TIME_SLOT_REF2\", \"TIER_ID\"]\n tbl = tbl[preferredColumnOrder]\n textLengths = [len(t) for t in tbl[\"TEXT\"].tolist()]\n tbl[\"TEXT_LENGTH\"] = textLengths\n hasTabs = [\"\\t\" in t for t in tbl[\"TEXT\"].tolist()]\n tbl[\"HAS_TABS\"] = hasTabs\n hasSpaces = [\" \" in t for t in tbl[\"TEXT\"].tolist()]\n tbl[\"HAS_SPACES\"] = hasSpaces\n # eliminate rows with no text\n # leave it in for now, take the tiers at face value, handle empty lines in toHTML\n tbl = tbl.query(\"TEXT != ''\").reset_index(drop=True)\n return (tbl)\n\n\n# ------------------------------------------------------------------------------------------------------------------------\ndef standardizeTable(tbl, tierGuide):\n tierNames = tbl[\"TIER_ID\"].tolist()\n permittedNames = [tierGuide[k] for k in tierGuide]\n shared = set(tierNames).intersection(permittedNames)\n\n tbl_trimmed = tbl.loc[tbl['TIER_ID'].isin(shared)]\n\n tierNames = tbl_trimmed[\"TIER_ID\"].tolist()\n\n # reverse the guide so we can map from user-supplied and often idiosyncratic\n # TIER_ID values, to the IJAL standard types: speech, translation, morpheme, morphemeGloss\n\n revGuide = {v: k for k, v in tierGuide.items()}\n ids = tbl_trimmed[\"TIER_ID\"]\n standardIDs = [revGuide[key] for key in ids]\n\n # add a new column to the table. we will use this later to assemble the html\n tbl_final = tbl_trimmed.assign(category=standardIDs)\n\n return (tbl_final)\n\n\n# ------------------------------------------------------------------------------------------------------------------------\ndef replaceHyphensWithNDashes(list):\n ''' replace hyphens with n-dashes\n '''\n newList = []\n for text in list:\n text = text.replace('-', '–')\n newList.append(text)\n return (newList)\n"
]
| [
[
"pandas.DataFrame",
"pandas.concat"
]
]
|
asmerdov/CS_GO_Sensors_Data_Analysis | [
"82669ae925258e2d6f29e8c55dfe682c0c1558e2"
]
| [
"ResultsAnalysis.py"
]
| [
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nimport joblib\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.optim import Adam, SGD\nimport tqdm\nimport itertools\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import roc_auc_score, accuracy_score, f1_score\nfrom sklearn.model_selection import cross_val_score, cross_val_predict, KFold, StratifiedKFold\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator\n\nplt.interactive(True)\npd.options.display.max_columns = 15\npic_folder = 'pic/'\n\n# version = 'hidden_size'\n# version = 'test_11'\n# version = 'window_size_0'\n# version = 'time_step_0'\nversions_list = [\n # 'window_size_0',\n # 'window_size_1',\n # 'hidden_size_2',\n # 'hidden_size_3',\n # 'normalization_0',\n # 'time_step_0',\n # 'time_step_1',\n # 'time_step_2',\n # # 'time_step_1_60',\n # 'february_27',\n 'march_1',\n]\nclassic_versions_list = [\n # 'window_size_0',\n # 'time_step_1',\n # 'time_step_2',\n # 'time_step_1_60',\n]\n\n\nattention_names_dict = {\n 0: 'RNN',\n 1: 'RNN + Input Attention, Softmax',\n 2: 'RNN + Input Attention, Sigmoid',\n 4: 'RNN + Input Attention, [0, 1] clamp',\n}\n\ndf_results = pd.DataFrame()\n\nfor version in versions_list:\n df_results_new = pd.read_csv(f'data/df_results_{version}.csv')\n df_results_new = df_results_new.loc[df_results_new['score_val'] != -1, :]\n df_results_new.set_index(['time_step', 'window_size', 'batch_size', 'attention', 'hidden_size', 'normalization', 'n_repeat'], inplace=True)\n # df_results_new = df_results_new[['score_test', 'score_val']]\n df_results_new = df_results_new[['score_test', 'dumb_score_test', 'score_val', 'dumb_score_val']]\n df_results = pd.concat([df_results, df_results_new])\n\nfor version in classic_versions_list:\n df_results_classic = pd.read_csv(f'data/df_results_classic_{version}.csv')\n df_results_classic = df_results_classic.loc[df_results_classic['alg_name'] != 'Random Forest 1']\n df_results_classic = df_results_classic.loc[df_results_classic['time_step'] != 60]\n df_results_classic = df_results_classic.loc[df_results_classic['window_size'] != 600]\n df_results_classic['batch_size'] = -1\n df_results_classic['hidden_size'] = -1\n df_results_classic['normalization'] = -1\n df_results_classic.rename(columns={'alg_name': 'attention'}, inplace=True)\n df_results_classic.set_index(['time_step', 'window_size', 'batch_size', 'attention', 'hidden_size', 'normalization', 'n_repeat'], inplace=True)\n df_results_classic.rename(columns={'score_val': 'score_test'}, inplace=True)\n df_results_classic.rename(index={'Random Forest 0': 'Random Forest'}, inplace=True)\n # df_results_classic.rename(index={'Logistic Regression': 'Random Forest'})\n\n df_results = pd.concat([df_results, df_results_classic])\n# df_results = df_results.join(df_results_classic)\n\ndef plot_dependency(df_results, labels, colors, labels_col='attention', dependency_col='hidden_size', label2text_dict=None,\n xlabel='', suffix='v0', plot_errors=True):\n df_grouped = df_results.groupby([labels_col, dependency_col])['score_test']\n df_agg_mean = df_grouped.mean().reset_index()\n df_agg_std = df_grouped.std().reset_index()\n print(df_agg_mean)\n print(df_agg_std)\n # labels = np.unique(df_agg_mean[labels_col])\n\n plt.figure(figsize=(13.5, 9))\n # plt.figure(figsize=(20, 15))\n\n for label, color in zip(labels, colors):\n mask_label = df_agg_mean[labels_col] == label\n dependency_values = df_agg_mean.loc[mask_label, dependency_col]\n means4label = df_agg_mean.loc[mask_label, 'score_test'].values.ravel()\n stds4label = df_agg_std.loc[mask_label, 'score_test'].values.ravel()\n print(means4label)\n print(stds4label)\n\n if label2text_dict is not None:\n if label in label2text_dict:\n label_text = label2text_dict[label]\n else:\n label_text = label\n else:\n label_text = label\n\n lower = means4label - stds4label\n upper = means4label + stds4label\n\n plt.plot(dependency_values, means4label, label=label_text, color=color, lw=5)\n plt.scatter(dependency_values, means4label, marker='o', s=140, color=color)\n if plot_errors:\n plt.fill_between(dependency_values, lower, upper, alpha=0.1, color=color)\n\n plt.tick_params(axis='both', which='major', labelsize=25, size=20)\n plt.xticks()\n # plt.xlabel('Window Size, s', fontsize=35)\n plt.xlabel(xlabel, fontsize=35)\n plt.ylabel('ROC AUC', fontsize=35)\n plt.legend(fontsize=20) # 16 if not enough space # , loc='lower right')\n # plt.xlim(97, 610) # UPDATE IF 60 IS ADDED!!!\n plt.tight_layout()\n plt.savefig(f'pic/{labels_col}_{dependency_col}_{suffix}.png')\n plt.close()\n\ndef plot_dependency_time_step(df_results, labels, colors, labels_col='attention', dependency_col='hidden_size', label2text_dict=None,\n xlabel='', suffix='v0', plot_errors=True):\n df_grouped = df_results.groupby([labels_col, dependency_col])['score_test']\n df_agg_mean = df_grouped.mean().reset_index()\n df_agg_std = df_grouped.std().reset_index()\n print(df_agg_mean)\n print(df_agg_std)\n # labels = np.unique(df_agg_mean[labels_col])\n\n # plt.figure(figsize=(13.5, 9))\n fig, ax = plt.subplots(figsize=(13.5, 9))\n # plt.figure(figsize=(20, 15))\n\n for label, color in zip(labels, colors):\n mask_label = df_agg_mean[labels_col] == label\n dependency_values = df_agg_mean.loc[mask_label, dependency_col]\n means4label = df_agg_mean.loc[mask_label, 'score_test'].values.ravel()\n stds4label = df_agg_std.loc[mask_label, 'score_test'].values.ravel()\n print(means4label)\n print(stds4label)\n\n if label2text_dict is not None:\n if label in label2text_dict:\n label_text = label2text_dict[label]\n else:\n label_text = label\n else:\n label_text = label\n\n lower = means4label - stds4label\n upper = means4label + stds4label\n\n mask_part_1 = dependency_values < 40\n mask_part_2 = dependency_values >= 30\n\n dependency_values_part_1 = dependency_values[mask_part_1]\n means4label_part_1 = means4label[mask_part_1]\n plt.plot(dependency_values_part_1, means4label_part_1, label=label_text, color=color, lw=5)\n\n dependency_values_part_2 = dependency_values[mask_part_2]\n means4label_part_2 = means4label[mask_part_2]\n plt.plot(dependency_values_part_2, means4label_part_2, color=color, lw=5, linestyle='--')\n\n plt.scatter(dependency_values, means4label, marker='o', s=140, color=color)\n if plot_errors:\n plt.fill_between(dependency_values, lower, upper, alpha=0.1, color=color)\n\n ax.yaxis.set_major_locator(MultipleLocator(0.05))\n ax.xaxis.set_major_locator(MultipleLocator(10))\n plt.tick_params(axis='both', which='major', labelsize=25, size=20)\n plt.xticks()\n # plt.xlabel('Window Size, s', fontsize=35)\n plt.xlabel(xlabel, fontsize=35)\n plt.ylabel('ROC AUC', fontsize=35)\n plt.legend(fontsize=15) # 16 if not enough space # , loc='lower right')\n # plt.xlim(97, 610) # UPDATE IF 60 IS ADDED!!!\n plt.tight_layout()\n plt.savefig(f'pic/{labels_col}_{dependency_col}_{suffix}.png')\n plt.close()\n\n\nif version == 'time_step':\n xlabel = 'Time Step, s'\nelif version == 'hidden_size':\n xlabel = 'Hidden Size'\nelif version == 'window_size':\n xlabel = 'Window Size, s'\nelif version == 'window_size':\n xlabel = 'Window Size, s'\nelse:\n xlabel = version\n\ncolors = ['blue', 'orange', 'green', 'red', 'cyan', 'gold', 'black']\nlabels = [0, 1, 2, 4] + ['Logistic Regression', 'Random Forest', 'SVM']\n\n\n\n### hidden_size\nplot_dependency(df_results, labels, colors, 'attention', dependency_col='hidden_size',\n label2text_dict=attention_names_dict, xlabel='Hidden Size', plot_errors=False)\n\n\n### window_size\n# plot_dependency(df_results, labels, colors, 'attention', dependency_col='window_size',\n# label2text_dict=attention_names_dict, xlabel='Window Size, s', plot_errors=False)\n\n\n### time_step\nmask_not_five = [df_results.index[i][0] != 5 for i in range(len(df_results))]\nplot_dependency_time_step(df_results.iloc[mask_not_five], labels, colors, 'attention', dependency_col='time_step',\n label2text_dict=attention_names_dict, xlabel='Time Step, s', plot_errors=False)\n\n\n\n### normalization\nplot_dependency(df_results, labels, colors, 'attention', dependency_col='normalization',\n label2text_dict=attention_names_dict, xlabel='normalization', plot_errors=False)\n\n# df_att_norm_mean = df_results.groupby(['attention', 'normalization']).mean()\n# df_att_norm_std = df_results.groupby(['attention', 'normalization']).std()\n# df_att_norm_mean.rename(columns={'score_test': 'score_test_mean'}, inplace=True)\n# df_att_norm_mean['score_test_std'] = df_att_norm_std['score_test']\n#\n# df_att_norm_mean.to_csv('data_best/df_att_norm.csv')\n#\n\n\n\n\n\n\nfor alg_name, color in zip(alg_names_list, colors):\n mask_alg = results_no_index['alg_name'] == alg_name\n mean4alg = results_mean.iloc[mask_alg.nonzero()].values.ravel()\n std4alg = results_std.iloc[mask_alg.nonzero()].values.ravel()\n\n lower = mean4alg - std4alg\n upper = mean4alg + std4alg\n\n plt.plot(window_size_list, mean4alg, label=alg_name, linewidth=5, color=color)\n plt.scatter(window_size_list, mean4alg, marker='o', s=140, color=color)\n plt.fill_between(window_size_list, lower, upper, alpha=0.3, color=color)\n\nplt.tick_params(axis='both', which='major', labelsize=30)\nplt.xticks()\n# plt.xlabel('Window Size, s', fontsize=35)\nplt.xlabel('Window Size, s', fontsize=35)\nplt.ylabel('ROC AUC', fontsize=35)\nplt.legend(fontsize=32)\n# plt.xlim(97, 610) # UPDATE IF 60 IS ADDED!!!\nplt.tight_layout()\nplt.savefig('pic/classical_ml_window_size_v0.png')\n\n\n\n\ndf_results.groupby('time_step').mean()\ndf_results.groupby('window_size').mean()\ndf_results.groupby('batch_size').mean()\ndf_results.groupby('hidden_size').mean()\ndf_results.groupby('attention').mean() # For RNN 4 is better than 0!!!\ndf_results.groupby('normalization').mean() # For RNN 4 is better than 0!!!\n\ndf_results.groupby(['time_step', 'window_size']).mean()\ndf_results.groupby(['time_step', 'batch_size']).mean()\ndf_results.groupby(['time_step', 'hidden_size']).mean()\ndf_results.groupby(['window_size', 'batch_size']).mean()\ndf_results.groupby(['window_size', 'hidden_size']).mean()\ndf_results.groupby(['batch_size', 'hidden_size']).mean()\ndf_results.groupby(['attention', 'time_step']).mean()\ndf_results.groupby(['attention', 'window_size']).mean()\ndf_results.groupby(['attention', 'hidden_size']).mean()\ndf_results.groupby(['attention', 'hidden_size', 'window_size', 'time_step']).mean()\n\ndf_results.groupby(['time_step', 'window_size', 'hidden_size']).mean()\n\n\n\"\"\"\nInference after v2:\n1. time_step 20 is probably better\n2. window_size 300 should be used. Larger values have better scores, but the system is not so flexible\n3. batch_size can be any from 8 to 256. Let's set it to 64\n4. hidden size 32 is the best. 64 is slightly worse, 16 is worse\n\n\n\"\"\"\n\n\n\n\"\"\"\nInference after v1 or v0:\n1. Anyway, timestep 30 looks too much. Timestep 5 actually looks fine, but it requires a lot of training. \n2. window_size 120 is too short and noisy. 600 has the best score, but the target become too trivial.\n3. batch_size 2 isn't a good idea. 16 and 128 aren't very distinguishable, the optimal can be from 8 to inf.\n4. The best hidden size is 32, the worst is 2, 8 is ok. More is better till some limit. Maybe to check 16, 64, 128(too much?), ...\n\n5. time_step 10 and window_size 300 is ok.\n6. Shorter time_step requires higher batch_size\n7. Probably higher time_step require lesser hidden_size\n\n\"\"\"\n\n\n\n\n\n\ntime_step_list = [10, 20] # 10 is already tested\nwindow_size_list = [120, 180, 300, 600]\n\nalg_names_list = ['Logistic Regression', 'Random Forest', 'SVM']\nversion = 'v0'\ndf_results = pd.read_csv(f'data/df_results_classic_{version}.csv')\ndf_results.set_index(['window_size', 'alg_name', 'n_repeat'], inplace=True)\n\n\ndef mean_std(x):\n # return pd.Series([x.mean(), x.std()], index=['mean', 'std']).T\n return pd.DataFrame({\n 'mean': x.mean(),\n 'std': x.std(),\n })\n\n# df_results.groupby(['window_size', 'alg_name']).apply(lambda x: mean_std(x))\nresults_mean = df_results.groupby(['window_size', 'alg_name']).apply(lambda x: x.mean())\nresults_std = df_results.groupby(['window_size', 'alg_name']).apply(lambda x: x.std())\n\nresults_no_index = results_std.reset_index().drop(columns='score_val')\n\ncolors = ['blue', 'orange', 'green']\n\nplt.interactive(True)\nplt.close()\n\nplt.figure(figsize=(12, 9))\nfor alg_name, color in zip(alg_names_list, colors):\n mask_alg = results_no_index['alg_name'] == alg_name\n mean4alg = results_mean.iloc[mask_alg.nonzero()].values.ravel()\n std4alg = results_std.iloc[mask_alg.nonzero()].values.ravel()\n\n lower = mean4alg - std4alg\n upper = mean4alg + std4alg\n\n plt.plot(window_size_list, mean4alg, label=alg_name, linewidth=5, color=color)\n plt.scatter(window_size_list, mean4alg, marker='o', s=140, color=color)\n plt.fill_between(window_size_list, lower, upper, alpha=0.3, color=color)\n\nplt.tick_params(axis='both', which='major', labelsize=30)\nplt.xticks()\n# plt.xlabel('Window Size, s', fontsize=35)\nplt.xlabel('Window Size, s', fontsize=35)\nplt.ylabel('ROC AUC', fontsize=35)\nplt.legend(fontsize=32)\n# plt.xlim(97, 610) # UPDATE IF 60 IS ADDED!!!\nplt.tight_layout()\nplt.savefig('pic/classical_ml_window_size_v0.png')\n\n\n\n##### Loading from separate series files\n# filenames = os.listdir('data')\n# def check_relevance(filename):\n# cond_1 = filename[-4:] == '.csv'\n# cond_2 = filename[:7] == 'series_'\n# cond_3 = filename[-6:-4] == version\n# return cond_1 and cond_2 and cond_3\n#\n# relevant_series = [filename for filename in filenames if check_relevance(filename)]\n#\n# df_results = pd.DataFrame()\n#\n# for series_path in relevant_series:\n# series2append = pd.read_csv(f'data/{series_path}')\n# index_names = ['time_step', 'window_size', 'batch_size', 'hidden_size']\n# series2append.columns = index_names + list(series2append.columns[4:])\n# series2append.set_index(index_names, inplace=True)\n# df_results = df_results.append(series2append)\n\n#\n# df_agg_mean = df_results.groupby(['attention', 'hidden_size'])['score_test'].mean().reset_index()\n# df_agg_std = df_results.groupby(['attention', 'hidden_size'])['score_test'].std().reset_index()\n# attention_list = [0, 1, 2]\n# hidden_size_list = [8, 32, 64]\n#\n# plt.close()\n# for attention in attention_list:\n# mask = df_agg_mean['attention'] == attention\n# hidden_sizes = df_agg_mean.loc[mask, 'hidden_size']\n# means = df_agg_mean.loc[mask, 'score_test']\n# stds = df_agg_std.loc[mask, 'score_test']\n# plt.plot(hidden_sizes, means, label=attention_names_dict[attention])\n#\n#\n# plt.legend()\n# plt.tight_layout()"
]
| [
[
"matplotlib.ticker.MultipleLocator",
"pandas.DataFrame",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.interactive",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.tick_params",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.fill_between",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.ylabel",
"pandas.concat",
"matplotlib.pyplot.scatter",
"pandas.read_csv",
"matplotlib.pyplot.xticks"
]
]
|
ZackWolf614/BlackBird | [
"1575127c611be0f9aa606a25f898b58b5f1afd9d"
]
| [
"src/Blackbird.py"
]
| [
"from DynamicMCTS import DynamicMCTS as MCTS\nfrom RandomMCTS import RandomMCTS\nfrom FixedMCTS import FixedMCTS\nfrom Network import Network\nfrom NetworkFactory import NetworkFactory\nfrom DataManager import Connection\nfrom proto.state_pb2 import State\nfrom collections import defaultdict\n\nimport functools\nimport random\nimport yaml\nimport numpy as np\n\nnp.seterr(divide='ignore', invalid='ignore')\nnp.set_printoptions(precision=2)\n\n\nclass ExampleState(object):\n \"\"\" Class which centralizes the data structure of a game state.\n\n `GameState` objects have many properties, but only a few of them are\n relevant to training. `ExampleState` provides an interface on top of\n protocol buffers for reading and storing game state data.\n\n Attributes:\n `MctsPolicy`: A numpy array which holds the policy generated from\n applying MCTS.\n `MctsEval`: A float between -1 and 1 representing the evaluation\n that the MCTS computed.\n `Board`: A numpy array which holds the input state for a board\n state. In general, this is the game state, as well as layers for\n historical positions, current turn, current player, etc.\n `Player`: An optional integer, representing the current player.\n \"\"\"\n def __init__(self, evaluation, policy, board, player=None):\n self.MctsPolicy = policy\n self.MctsEval = evaluation\n self.Board = board\n self.Player = player\n\n @classmethod\n def FromSerialized(cls, serialState):\n \"\"\" Transforms a protobuf bytecode string to an `ExampleState` object.\n\n Args:\n serialState: A protobuf bytecode string holding `GameState`\n info.\n\n Returns:\n An `ExampleState` object holding the relevant deserialized data.\n \"\"\"\n state = State()\n state.ParseFromString(serialState)\n boardDims = np.frombuffer(state.boardDims, dtype=np.int8)\n policyDims = np.frombuffer(state.policyDims, dtype=np.int8)\n\n mctsEval = state.mctsEval,\n mctsPolicy = np.frombuffer(state.mctsPolicy,\n dtype=np.float).reshape(policyDims)\n board = np.frombuffer(state.boardEncoding,\n dtype=np.int8).reshape(boardDims)\n\n return cls(mctsEval, mctsPolicy, board)\n\n def SerializeState(self):\n \"\"\" Returns the protobuf bytecode serialization of the `ExampleState`.\n \"\"\"\n serialized = State()\n\n serialized.mctsEval = self.MctsEval\n serialized.mctsPolicy = self.MctsPolicy.tobytes()\n serialized.boardEncoding = self.Board.tobytes()\n serialized.boardDims = np.array(self.Board.shape,\n dtype=np.int8).tobytes()\n serialized.policyDims = np.array(self.MctsPolicy.shape,\n dtype=np.int8).tobytes()\n\n return serialized.SerializeToString()\n\n\ndef TestRandom(model, temp, numTests):\n \"\"\" Plays the current BlackBird instance against an opponent making\n random moves.\n\n Game statistics are logged in the local `data/blackbird.db` database.\n\n Args:\n `temp`: A float between 0 and 1 determining the exploitation\n temp for MCTS. Usually this should be close to 0.1 to ensure\n optimal move selection.\n `numTests`: An int determining the number of games to play.\n\n Returns:\n A dictionary holding:\n - `wins`: The number of wins `model` had.\n - `draws`: The number of draws `model` had.\n - `losses`: The number of losses `model` had.\n \"\"\"\n resultMap = {1:'wins', 0:'draws', -1:'losses'}\n stats = defaultdict(int)\n\n for _ in range(numTests):\n result = TestModels(model, RandomMCTS(), temp, numTests=1)\n stats[resultMap.get(result, 'indeterminant')] += 1\n model.Conn.PutTrainingStatistic(result, model.Name,\n model.Version, 'RANDOM')\n\n return stats\n\n\ndef TestPrevious(model, temp, numTests):\n \"\"\" Plays the current BlackBird instance against the previous version of\n BlackBird's neural network.\n\n Game statistics are logged in the local `data/blackbird.db` database.\n\n Args:\n `model`: The Blackbird model to test\n `temp`: A float between 0 and 1 determining the exploitation\n temp for MCTS. Usually this should be close to 0.1 to ensure\n optimal move selection.\n `numTests`: An int determining the number of games to play.\n\n Returns:\n A dictionary holding:\n - `wins`: The number of wins `model` had.\n - `draws`: The number of draws `model` had.\n - `losses`: The number of losses `model` had.\n \"\"\"\n oldModel = model.LastVersion()\n resultMap = {1:'wins', 0:'draws', -1:'losses'}\n stats = defaultdict(int)\n\n for _ in range(numTests):\n result = TestModels(model, oldModel, temp, numTests=1)\n stats[resultMap.get(result, 'indeterminant')] += 1\n model.Conn.PutTrainingStatistic(result, model.Name, model.Version,\n oldModel.Name, oldModel.Version)\n\n return stats\n\n\ndef TestGood(model, temp, numTests):\n \"\"\" Plays the current BlackBird instance against a standard MCTS player.\n\n Game statistics are logged in the local `data/blackbird.db` database.\n\n Args:\n `model`: The Blackbird model to test\n `temp`: A float between 0 and 1 determining the exploitation\n temp for MCTS. Usually this should be close to 0.1 to ensure\n optimal move selection.\n `numTests`: An int determining the number of games to play.\n\n Returns:\n A dictionary holding:\n - `wins`: The number of wins `model` had.\n - `draws`: The number of draws `model` had.\n - `losses`: The number of losses `model` had.\n \"\"\"\n good = FixedMCTS(maxDepth=10, explorationRate=0.85, timeLimit=1)\n resultMap = {1:'wins', 0:'draws', -1:'losses'}\n stats = defaultdict(int)\n \n for _ in range(numTests):\n result = TestModels(model, good, temp, numTests=1)\n stats[resultMap.get(result, 'indeterminant')] += 1\n model.Conn.PutTrainingStatistic(result, model.Name, model.Version,\n 'MCTS')\n\n return stats\n\n\ndef TestModels(model1, model2, temp, numTests):\n \"\"\" Base function for playing a BlackBird instance against another model.\n\n Args:\n `model1`: The Blackbird model to test.\n `model2`: The model to play against.\n `temp`: A float between 0 and 1 determining the exploitation\n temp for MCTS. Usually this should be close to 0.1 to ensure\n optimal move selection.\n `numTests`: An int determining the number of games to play.\n\n Returns:\n An integer representing a win (1), draw (0), or loss (-1)\n \"\"\"\n for _ in range(numTests):\n model1ToMove = random.choice([True, False])\n model1Player = 1 if model1ToMove else 2\n winner = None\n model1.DropRoot()\n model2.DropRoot()\n state = model1.Game()\n\n while winner is None:\n if model1ToMove:\n (nextState, *_) = model1.FindMove(state, temp)\n else:\n (nextState, *_) = model2.FindMove(state, temp)\n state = nextState\n model1.MoveRoot(state)\n model2.MoveRoot(state)\n\n model1ToMove = not model1ToMove\n winner = state.Winner()\n\n if winner == model1Player:\n return 1\n elif winner == 0:\n return 0\n else:\n return -1\n\n\ndef GenerateTrainingSamples(model, nGames, temp):\n \"\"\" Generates self-play games to learn from.\n\n This method generates `nGames` self-play games, and stores the game\n states in a local sqlite3 database.\n\n Args:\n `model`: The Blackbird model to use to generate games\n `nGames`: An int determining the number of games to generate.\n `temp`: A float between 0 and 1 determining the exploration temp\n for MCTS. Usually this should be close to 1 to ensure\n high move exploration rate.\n\n Raises:\n ValueError: nGames was not a positive integer.\n \"\"\"\n if nGames <= 0:\n raise ValueError('Use a positive integer for number of games.')\n\n for _ in range(nGames):\n gameHistory = []\n state = model.Game()\n lastAction = None\n winner = None\n model.DropRoot()\n while winner is None:\n (nextState, v, currentProbabilties) = model.FindMove(state, temp)\n example = ExampleState(1 - v, currentProbabilties,\n state.AsInputArray(), player=state.Player)\n state = nextState\n model.MoveRoot(state)\n\n winner = state.Winner(lastAction)\n gameHistory.append(example)\n\n example = ExampleState(None, np.zeros([len(currentProbabilties)]),\n state.AsInputArray(), player=state.Player)\n gameHistory.append(example)\n\n for example in gameHistory:\n if winner == 0:\n example.MctsEval = 0\n else:\n example.MctsEval = 1 if example.Player == winner else -1\n\n serialized = [example.SerializeState() for example in gameHistory]\n model.Conn.PutGames(model.Name, model.Version, state.GameType,\n serialized)\n\n\ndef TrainWithExamples(model, batchSize, learningRate, teacher=None):\n \"\"\" Trains the neural network on provided example positions.\n\n Provided a list of example positions, this method will train\n BlackBird's neural network to play better. If `teacher` is provided,\n the neural network will include a cross-entropy term in the loss\n calculation so that the other network's policy is incorporated into\n the learning.\n\n Args:\n `model`: The Blackbird model to train\n `examples`: A list of `TrainingExample` objects which the\n neural network will learn from.\n `teacher`: An optional `BlackBird` object whose policy the\n current network will include in its loss calculation.\n \"\"\"\n model.SampleValue.cache_clear()\n model.GetPriors.cache_clear()\n\n games = model.Conn.GetGames(model.Name, model.Version)\n examples = [ExampleState.FromSerialized(game) for game in games]\n\n examples = np.random.choice(examples,\n len(examples) -\n (len(examples) % batchSize),\n replace=False)\n\n for i in range(len(examples) // batchSize):\n start = i * batchSize\n batch = examples[start: start + batchSize]\n model.train(\n np.vstack([b.Board for b in batch]),\n np.hstack([b.MctsEval for b in batch]),\n np.vstack([b.MctsPolicy for b in batch]),\n learningRate,\n teacher\n )\n\n model.Version += 1\n model.Conn.PutModel(model.Game.GameType, model.Name, model.Version)\n\n\nclass Model(MCTS, Network):\n \"\"\" Class which encapsulates MCTS powered by a neural network.\n\n The BlackBird class is designed to learn how to win at a board game, by\n using Monte Carlo Tree Search (MCTS) with the tree search powered by a\n neural network.\n Args:\n `game`: A GameState object which holds the rules of the game\n BlackBird is intended to learn.\n `name`: The name of the model.\n `mctsConfig` : JSON config for MCTS runtime evaluation\n `networkConfig` : JSON config for creating a new network from NetworkFactory\n `tensorflowConfig` : Configuaration for tensorflow initialization\n \"\"\"\n\n def __init__(self, game, name, mctsConfig, networkConfig={}, tensorflowConfig={}):\n self.Conn = Connection()\n self.Game = game\n self.Name = name\n self.Version = self.Conn.GetLastVersion(self.Game.GameType, self.Name)\n self._saveName = self.Name + '_' + str(self.Version)\n\n self.MCTSConfig = mctsConfig\n self.NetworkConfig = networkConfig\n self.TensorflowConfig = tensorflowConfig\n MCTS.__init__(self, **mctsConfig)\n\n if networkConfig != {}:\n Network.__init__(self, self._saveName, NetworkFactory(networkConfig, game.LegalMoves), tensorflowConfig)\n else:\n Network.__init__(self, self._saveName, tensorflowConfig=tensorflowConfig)\n\n def LastVersion(self):\n return Model(self.Game, self.Name, self.MCTSConfig, self.NetworkConfig, self.TensorflowConfig)\n\n @functools.lru_cache(maxsize=4096)\n def SampleValue(self, state, player):\n \"\"\" Returns BlackBird's evaluation of a supplied position.\n\n BlackBird's network will evaluate a supplied position, from the\n perspective of `player`.\n\n Args:\n `state`: A GameState object which should be evaluated.\n `player`: An int representing the current player.\n\n Returns:\n `value`: A float between 0 and 1 holding the evaluation of the\n position. 0 is the worst possible evaluation, 1 is the best.\n \"\"\"\n value = self.getEvaluation(state.AsInputArray())\n value = (value + 1) * 0.5 # [-1, 1] -> [0, 1]\n if state.Player != player:\n value = 1 - value\n assert value >= 0, 'Value: {}'.format(value)\n return value\n\n @functools.lru_cache(maxsize=4096)\n def GetPriors(self, state):\n \"\"\" Returns BlackBird's policy of a supplied position.\n\n BlackBird's network will evaluate the policy of a supplied position.\n\n Args:\n `state`: A GameState object which should be evaluated.\n\n Returns:\n `policy`: A list of floats of size `len(state.LegalActions())` \n which sums to 1, representing the probabilities of selecting \n each legal action.\n \"\"\"\n policy = self.getPolicy(state.AsInputArray()) * state.LegalActions()\n policy /= np.sum(policy)\n\n return policy\n"
]
| [
[
"numpy.array",
"numpy.set_printoptions",
"numpy.sum",
"numpy.seterr",
"numpy.frombuffer",
"numpy.hstack",
"numpy.vstack"
]
]
|
fangqyi/sandbox-society | [
"c9510890576fad1037474340194d0b5342a9b45f"
]
| [
"neural_mmo/forge/ethyr/torch/policy/embed.py"
]
| [
"from pdb import set_trace as T\nimport numpy as np\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom neural_mmo.forge.blade.io import node\n\nclass Embedding(nn.Module):\n def __init__(self, var, dim):\n '''Pytorch embedding wrapper that subtracts the min'''\n super().__init__()\n self.embed = torch.nn.Embedding(var.range, dim)\n self.min = var.min\n\n def forward(self, x):\n return self.embed(x - self.min)\n\nclass Input(nn.Module):\n def __init__(self, cls, config):\n '''Embedding wrapper around discrete and continuous vals'''\n super().__init__()\n self.cls = cls\n if isinstance(cls, node.Discrete):\n self.embed = Embedding(cls, config.EMBED)\n elif isinstance(cls, node.Continuous):\n self.embed = torch.nn.Linear(1, config.EMBED)\n\n def forward(self, x):\n if isinstance(self.cls, node.Discrete):\n x = x.long()\n elif isinstance(self.cls, node.Continuous):\n x = x.float().unsqueeze(-1)\n x = self.embed(x)\n return x\n\nclass BiasedInput(nn.Module):\n def __init__(self, cls, config):\n '''Adds a bias to nn.Embedding\n This is useful for attentional models\n to learn a sort of positional embedding'''\n super().__init__()\n self.bias = torch.nn.Embedding(1, config.HIDDEN)\n self.embed = Input(cls, config)\n\n def forward(self, x):\n return self.embed(x) + self.bias.weight\n\nclass MixedDTypeInput(nn.Module):\n def __init__(self, continuous, discrete, config):\n super().__init__()\n\n self.continuous = torch.nn.ModuleList([\n torch.nn.Linear(1, config.EMBED) for _ in range(continuous)])\n self.discrete = torch.nn.Embedding(discrete, config.EMBED)\n\n def forward(self, x):\n continuous = x['Continuous'].split(1, dim=-1)\n continuous = [net(e) for net, e in zip(self.continuous, continuous)]\n continuous = torch.stack(continuous, dim=-2)\n discrete = self.discrete(x['Discrete'].long())\n\n return torch.cat((continuous, discrete), dim=-2)\n"
]
| [
[
"torch.nn.Linear",
"torch.cat",
"torch.stack",
"torch.nn.Embedding"
]
]
|
spectralDNS/shenfun | [
"2164596ccf906242779d9ec361168246ee6214d8"
]
| [
"shenfun/utilities/lagrangian_particles.py"
]
| [
"import numpy as np\nfrom mpi4py import MPI\n\ncomm = MPI.COMM_WORLD\n\n__all__ = ['LagrangianParticles']\n\nclass LagrangianParticles:\n \"\"\"Class for tracking Lagrangian particles\n\n Parameters\n ----------\n points : array\n Initial location of particles. (D, N) array, with N particles in D dimensions\n dt : float\n Time step\n u_hat : :class:`.Function`\n Spectral Galerkin :class:`.Function` for the Eulerian velocity\n\n \"\"\"\n\n def __init__(self, points, dt, u_hat):\n self.x = points\n self.u_hat = u_hat\n self.dt = dt\n self.up = np.zeros(self.x.shape)\n\n def step(self):\n up = self.rhs()\n self.x[:] = self.x + self.dt*up\n\n def rhs(self):\n return self.u_hat.eval(self.x, output_array=self.up)\n\nif __name__ == '__main__':\n from shenfun import *\n import sympy as sp\n import matplotlib.pyplot as plt\n import h5py\n\n N = (40, 40)\n # Should work for any of these bases\n #F0 = FunctionSpace(N[0], 'F', dtype='D', domain=(0., 1.))\n #F1 = FunctionSpace(N[1], 'F', dtype='d', domain=(0., 1.))\n F0 = FunctionSpace(N[0], 'C', bc=(0, 0), domain=(0., 1.))\n F1 = FunctionSpace(N[1], 'C', bc=(0, 0), domain=(0., 1.))\n #F0 = FunctionSpace(N[0], 'C', domain=(0., 1.))\n #F1 = FunctionSpace(N[1], 'C', domain=(0., 1.))\n\n T = TensorProductSpace(comm, (F0, F1))\n TV = VectorSpace(T)\n\n x, y = sp.symbols(\"x,y\")\n psi = 1./np.pi*sp.sin(np.pi*x)**2*sp.sin(np.pi*y)**2 # Streamfunction\n ux = -psi.diff(y, 1)\n uy = psi.diff(x, 1)\n\n uxl = sp.lambdify((x, y), ux, 'numpy')\n uyl = sp.lambdify((x, y), uy, 'numpy')\n X = T.local_mesh(True)\n u = Array(T, buffer=uxl(X[0], X[1]))\n v = Array(T, buffer=uyl(X[0], X[1]))\n uv = Function(TV)\n uv[0] = T.forward(u, uv[0])\n uv[1] = T.forward(v, uv[1])\n\n # Arrange particles in a circle around (0.5, 0.75) with radius 0.15\n t0 = np.linspace(0, 2*np.pi, 100)[:-1]\n points = np.array([0.5+0.15*np.cos(t0), 0.75+0.15*np.sin(t0)])\n\n # Create LagrangianParticles instance with given points\n dt = 0.001\n lp = LagrangianParticles(points, dt, uv)\n\n # Store velocity vectors for later plotting on rank 0\n u.write('velocity.h5', name='u', domain=T.mesh())\n v.write('velocity.h5', name='v', domain=T.mesh())\n if comm.Get_rank() == 0:\n f = h5py.File('velocity.h5', 'r+')\n f.create_group('points')\n\n # Run simulation from time = 0 to 1 forwards, and then integrate back to 0\n end_time = 2.0\n t = 0\n lg = ['Velocity field']\n b = 'Fwd'\n nsteps = int(end_time/dt)+1\n count = 0\n for i in range(nsteps):\n if np.any(np.round(t, 4) in (0, 0.5, 1.0)):\n if comm.Get_rank() == 0:\n f['points'].create_dataset(str(count), shape=points.shape, dtype=float)\n f['points/'+str(count)][:] = lp.x\n print('Storing points at time %2.1f'%t)\n lg.append('%s at %2.1f' %(b, t))\n count += 1\n if i == (nsteps-1)//2:\n lp.dt *= -1\n b = 'Bwd'\n print('Integrate backwards')\n t += lp.dt\n lp.step()\n\n if comm.Get_rank() == 0:\n plt.quiver(f['u/mesh/x0'], f['u/mesh/x1'], f['u/2D/0'].__array__().T, f['v/2D/0'].__array__().T)\n steps = list(f['points'].keys())\n for step in steps:\n plt.scatter(f['points/'+str(step)][0], f['points/'+str(step)][1])\n plt.title('Particles integrated forwards and backwards')\n plt.legend(lg)\n plt.show()\n"
]
| [
[
"numpy.sin",
"numpy.zeros",
"numpy.round",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend",
"numpy.cos",
"matplotlib.pyplot.show",
"numpy.linspace"
]
]
|
ExObsSim/ExoRad2-public | [
"d00f95343fa86eae093abbf3ce9b3e579f9fb826"
]
| [
"exorad/tasks/loadSource.py"
]
| [
"import numpy as np\nfrom astropy import units as u\n\nfrom exorad.models.source import Star, CustomSed\nfrom exorad.tasks.task import Task\nimport os\n\nclass LoadSource(Task):\n \"\"\"\n Updates target with its source and return the source Sed\n\n Parameters\n ----------\n target: Target Class\n target class\n source: dict\n source spectrum description\n wl_range: couple\n wavelength range to investigate: (wl_min, wl_max)\n\n\n Returns\n -------\n Target:\n Target class with star.sed updated\n Sed:\n source Sed\n\n Examples\n --------\n >>> loadSource = LoadSource()\n >>> target, source = loadSource(target= target, source={'sourceSpectrum': {'value':'Planck'}})\n\n Raises\n ------\n AttributeError:\n if some target information are missing\n \"\"\"\n\n def __init__(self):\n self.addTaskParam('target', 'target class object')\n self.addTaskParam('source', 'source spectrum description')\n self.addTaskParam('wl_range', 'wavelength range to investigate')\n\n def execute(self):\n target = self.get_task_param('target')\n source = self.get_task_param('source')\n\n if isinstance(source, str):\n source = {'value': source}\n self.warning('source should be dict, not string.')\n\n if source['value'].lower() == 'custom':\n # if custom source, only R and D are needed for the solid angle\n for attr in ['D', 'R']:\n if not hasattr(target.star.__getattribute__(attr), 'value'):\n self.error('target information incomplete')\n raise AttributeError('target information incomplete')\n star = CustomSed(source['CustomSed']['value'],\n target.star.R,\n target.star.D)\n self.debug('custom sed used {}'.format(source['CustomSed']['value']))\n\n else:\n # check if star information are complete\n for attr in ['D', 'Teff', 'M', 'R']:\n if not hasattr(target.star.__getattribute__(attr), 'value'):\n self.error('target information incomplete')\n raise AttributeError('target information incomplete')\n\n self.debug('source spectrum : {}'.format(source['value'].lower()))\n if source['value'].lower() == 'planck':\n self.debug('Plack sed selected')\n star = Star('.',\n target.star.D,\n target.star.Teff,\n target.star.calc_logg(target.star.M, target.star.R),\n 0.0,\n target.star.R,\n use_planck_spectrum=True)\n\n elif source['value'].lower() == 'phoenix':\n try:\n star_sed_path = source['StellarModels']['value']\n except KeyError:\n if os.environ.get('PHOENIX_PATH', None) is not None:\n star_sed_path = os.environ.get('PHOENIX_PATH', None)\n else:\n raise IOError('No phoenix path specificed')\n\n if not os.path.exists(star_sed_path):\n raise IOError('Phoenix path does not exist: {}'.format(star_sed_path))\n \n star = Star(star_sed_path,\n target.star.D,\n target.star.Teff,\n target.star.calc_logg(target.star.M, target.star.R),\n 0.0,\n target.star.R,\n use_planck_spectrum=False)\n self.debug('stellar sed used {}'.format(star.filename))\n else:\n star = Star('.',\n target.star.D,\n target.star.Teff,\n target.star.calc_logg(target.star.M, target.star.R),\n 0.0,\n target.star.R,\n use_planck_spectrum=True)\n self.info('invalid source spectrum description. Planck spectrum is used')\n\n wl_min, wl_max = self.get_task_param('wl_range')\n if wl_min > wl_max: wl_min, wl_max = wl_max, wl_min\n if not hasattr(wl_min, 'unit'):\n self.debug('wavelength unit not found: micron assumed')\n wl_min *= u.um\n wl_max *= u.um\n\n wl_grid = np.logspace(np.log10(wl_min.value),\n np.log10(wl_max.value), 6000) * \\\n wl_max.unit\n star.sed.spectral_rebin(wl_grid)\n\n target.update_target(star)\n if hasattr(target, 'table'):\n target.table = self._add_star_metadata(target.star, target.table)\n self.set_output([target, star.sed])\n\n def _add_star_metadata(self, star, table):\n metadata = {}\n\n metadata['starName'] = star.name\n metadata['starM'] = star.M\n metadata['starTeff'] = star.Teff\n metadata['starR'] = star.R\n metadata['starDistance'] = star.D\n metadata['starL'] = star.luminosity\n metadata['starModel'] = star.model\n if hasattr(star, 'magk'):\n metadata['starMagK'] = star.magk\n\n table.meta.update(metadata)\n return table\n"
]
| [
[
"numpy.log10"
]
]
|
Kanaricc/M3TR | [
"c341ec1ebac598a1cf0c0c9085c98f4ebf4c2780"
]
| [
"models/vit_utils/efficient.py"
]
| [
"import torch\r\nfrom torch import nn\r\nfrom einops import rearrange, repeat\r\nfrom einops.layers.torch import Rearrange\r\n\r\nclass ViT(nn.Module):\r\n def __init__(self, *, image_size, patch_size, num_classes, dim, transformer, pool = 'cls', channels = 3):\r\n super().__init__()\r\n assert image_size % patch_size == 0, 'image dimensions must be divisible by the patch size'\r\n assert pool in {'cls', 'mean'}, 'pool type must be either cls (cls token) or mean (mean pooling)'\r\n num_patches = (image_size // patch_size) ** 2\r\n patch_dim = channels * patch_size ** 2\r\n\r\n self.to_patch_embedding = nn.Sequential(\r\n Rearrange('b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1 = patch_size, p2 = patch_size),\r\n nn.Linear(patch_dim, dim),\r\n )\r\n\r\n self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim))\r\n self.cls_token = nn.Parameter(torch.randn(1, 1, dim))\r\n self.transformer = transformer\r\n\r\n self.pool = pool\r\n self.to_latent = nn.Identity()\r\n\r\n self.mlp_head = nn.Sequential(\r\n nn.LayerNorm(dim),\r\n nn.Linear(dim, num_classes)\r\n )\r\n\r\n def forward(self, img):\r\n x = self.to_patch_embedding(img)\r\n b, n, _ = x.shape\r\n\r\n cls_tokens = repeat(self.cls_token, '() n d -> b n d', b = b)\r\n x = torch.cat((cls_tokens, x), dim=1)\r\n x += self.pos_embedding[:, :(n + 1)]\r\n x = self.transformer(x)\r\n\r\n x = x.mean(dim = 1) if self.pool == 'mean' else x[:, 0]\r\n\r\n x = self.to_latent(x)\r\n return self.mlp_head(x)\r\n"
]
| [
[
"torch.nn.Linear",
"torch.nn.Identity",
"torch.cat",
"torch.nn.LayerNorm",
"torch.randn"
]
]
|
tinhangchui/robo-gym | [
"6053c60d1a118f6872fce8c7c09a2130f6b51eff"
]
| [
"meta_ifo/robo-gym/train_beosim.py"
]
| [
"import os\nimport glob\nimport time\nfrom datetime import datetime\nimport torch\nimport numpy as np\nimport gym\nfrom IPython import embed\nimport robo_gym\nfrom robo_gym.wrappers.exception_handling import ExceptionHandling\nfrom PPO import PPO\nimport numpy as np\nfrom robo_gym.wrappers.taskEnv import MoveObjectToTargetTask\n\n# target_machine_add = '127.0.0.1'\n# env = gym.make('EndEffectorPositioningURSim-v0', ur_model='ur10', ip=target_machine_add)\n# env = ExceptionHandling(env)\n\ndef train():\n\n print(\"============================================================================================\")\n\n\n ####### initialize environment hyperparameters ######\n\n target_machine_add = '127.0.0.1'\n startingPosition = [0, 0.3, 1]\n targetPosition = np.array([-0.24, 0.17, 0])\n env = gym.make('BeoarmTestBlock-v0', ip=target_machine_add, gui=True)\n env = MoveObjectToTargetTask(env, 'wood_cube_10cm', targetPosition, distanceThreshold=0.1)\n env = ExceptionHandling(env)\n\n env_name = \"beosim\"\n has_continuous_action_space = True # continuous action space; else discrete\n\n max_ep_len = 500 # max timesteps in one episode\n max_training_timesteps = int(1e6) # break training loop if timeteps > max_training_timesteps\n\n print_freq = max_ep_len * 8 # print avg reward in the interval (in num timesteps)\n log_freq = max_ep_len * 4 # log avg reward in the interval (in num timesteps)\n save_model_freq = int(1e3) # save model frequency (in num timesteps)\n\n action_std = 0.6 # starting std for action distribution (Multivariate Normal)\n action_std_decay_rate = 0.05 # linearly decay action_std (action_std = action_std - action_std_decay_rate)\n min_action_std = 0.1 # minimum action_std (stop decay after action_std <= min_action_std)\n action_std_decay_freq = int(2.5e5) # action_std decay frequency (in num timesteps)\n\n #####################################################\n\n\n ## Note : print/log frequencies should be > than max_ep_len\n\n\n ################ PPO hyperparameters ################\n\n update_timestep = max_ep_len * 4 # update policy every n timesteps\n K_epochs = 80 # update policy for K epochs in one PPO update\n\n eps_clip = 0.2 # clip parameter for PPO\n gamma = 0.99 # discount factor\n\n lr_actor = 0.0003 # learning rate for actor network\n lr_critic = 0.001 # learning rate for critic network\n\n random_seed = 0 # set random seed if required (0 = no random seed)\n\n #####################################################\n\n\n\n print(\"training environment name : \" + env_name)\n\n # env = gym.make(env_name)\n\n # state space dimension\n #state_dim = env.observation_space.shape[0] \n state_dim = 32\n #!!! beosim's observation returns a dictionary. I need to remove the keys and convert it into numpy array.\n #state_dim = env.observation_space\n\n # action space dimension\n #action_dim = env.action_space.shape[0]\n action_dim = 4\n #action_dim = np.array([0,0,0,0]).shape\n\n\n\n ###################### logging ######################\n\n #### log files for multiple runs are NOT overwritten\n\n log_dir = \"PPO_logs\"\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n\n log_dir = log_dir + '/' + env_name + '/'\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n\n\n #### get number of log files in log directory\n run_num = 0\n current_num_files = next(os.walk(log_dir))[2]\n run_num = len(current_num_files)\n\n\n #### create new log file for each run\n log_f_name = log_dir + '/PPO_' + env_name + \"_log_\" + str(run_num) + \".csv\"\n\n print(\"current logging run number for \" + env_name + \" : \", run_num)\n print(\"logging at : \" + log_f_name)\n\n #####################################################\n\n\n ################### checkpointing ###################\n\n run_num_pretrained = 0 #### change this to prevent overwriting weights in same env_name folder\n\n directory = \"PPO_preTrained\"\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n directory = directory + '/' + env_name + '/'\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n\n checkpoint_path = directory + \"PPO_{}_{}_{}.pth\".format(env_name, random_seed, run_num_pretrained)\n print(\"save checkpoint path : \" + checkpoint_path)\n\n #####################################################\n\n\n ############# print all hyperparameters #############\n\n print(\"--------------------------------------------------------------------------------------------\")\n\n print(\"max training timesteps : \", max_training_timesteps)\n print(\"max timesteps per episode : \", max_ep_len)\n\n print(\"model saving frequency : \" + str(save_model_freq) + \" timesteps\")\n print(\"log frequency : \" + str(log_freq) + \" timesteps\")\n print(\"printing average reward over episodes in last : \" + str(print_freq) + \" timesteps\")\n\n print(\"--------------------------------------------------------------------------------------------\")\n\n print(\"state space dimension : \", state_dim)\n print(\"action space dimension : \", action_dim)\n\n print(\"--------------------------------------------------------------------------------------------\")\n\n # if has_continuous_action_space:\n print(\"Initializing a continuous action space policy\")\n print(\"--------------------------------------------------------------------------------------------\")\n print(\"starting std of action distribution : \", action_std)\n print(\"decay rate of std of action distribution : \", action_std_decay_rate)\n print(\"minimum std of action distribution : \", min_action_std)\n print(\"decay frequency of std of action distribution : \" + str(action_std_decay_freq) + \" timesteps\")\n\n # else:\n # print(\"Initializing a discrete action space policy\")\n\n print(\"--------------------------------------------------------------------------------------------\")\n\n print(\"PPO update frequency : \" + str(update_timestep) + \" timesteps\")\n print(\"PPO K epochs : \", K_epochs)\n print(\"PPO epsilon clip : \", eps_clip)\n print(\"discount factor (gamma) : \", gamma)\n\n print(\"--------------------------------------------------------------------------------------------\")\n\n print(\"optimizer learning rate actor : \", lr_actor)\n print(\"optimizer learning rate critic : \", lr_critic)\n\n if random_seed:\n print(\"--------------------------------------------------------------------------------------------\")\n print(\"setting random seed to \", random_seed)\n torch.manual_seed(random_seed)\n env.seed(random_seed)\n np.random.seed(random_seed)\n\n #####################################################\n\n print(\"============================================================================================\")\n\n ################# training procedure ################\n\n # initialize a PPO agent\n ppo_agent = PPO(state_dim, action_dim, lr_actor, lr_critic, gamma, K_epochs, eps_clip, has_continuous_action_space, action_std)\n\n # track total training time\n start_time = datetime.now().replace(microsecond=0)\n print(\"Started training at (GMT) : \", start_time)\n\n print(\"============================================================================================\")\n\n\n # logging file\n log_f = open(log_f_name,\"w+\")\n log_f.write('episode,timestep,reward\\n')\n\n\n # printing and logging variables\n print_running_reward = 0\n print_running_episodes = 0\n\n log_running_reward = 0\n log_running_episodes = 0\n\n time_step = 0\n i_episode = 0\n\n num = 0\n\n #uncomment this if you want to restore model from crashes\n #ppo_agent.load(checkpoint_path)\n #print(\"load completed.\")\n\n # tin's helper function\n # given a state, return dist_cube_to_target and dist_effector_to_cube\n def getDist(state):\n cube_position = np.array([state[\"wood_cube_10cm_x\"], state[\"wood_cube_10cm_y\"], state[\"wood_cube_10cm_z\"]])\n end_effector_position = np.array([state[\"ee_to_ref_translation_x\"], state[\"ee_to_ref_translation_y\"], state[\"ee_to_ref_translation_z\"]])\n dist_cube_to_target = np.linalg.norm(targetPosition - cube_position)\n dist_effector_to_cube = np.linalg.norm(end_effector_position - cube_position)\n return dist_cube_to_target, dist_effector_to_cube\n\n # since the value object_0_to_ref_translation_[x/y/z] are not junk value, I replace them to the difference between end-effector and target in [x/y/z] coordinate.\n # Hope it will make the state representation more useful.\n def modifyState(state):\n cube_position = np.array([state[\"wood_cube_10cm_x\"], state[\"wood_cube_10cm_y\"], state[\"wood_cube_10cm_z\"]])\n end_effector_position = np.array([state[\"ee_to_ref_translation_x\"], state[\"ee_to_ref_translation_y\"], state[\"ee_to_ref_translation_z\"]])\n state['object_0_to_ref_translation_x'] = end_effector_position[0] - cube_position[0]\n state['object_0_to_ref_translation_y'] = end_effector_position[1] - cube_position[1]\n state['object_0_to_ref_translation_z'] = end_effector_position[2] - cube_position[2]\n return state\n\n # training loop\n while time_step <= max_training_timesteps:\n\n #state = env.reset(target_object_position=startingPosition)\n\n # Reject the env that the cube is already at the goal and end-effector is not far enough from the cube\n state = env.reset()\n dist_cube_to_target, dist_effector_to_cube = getDist(state)\n while dist_cube_to_target <= 0.2 or dist_effector_to_cube <= 0.3:\n state = env.reset()\n dist_cube_to_target, dist_effector_to_cube = getDist(state)\n\n state = modifyState(state)\n \n current_ep_reward = 0\n\n for t in range(1, max_ep_len+1):\n\n # select action with policy\n action = ppo_agent.select_action(state)\n # print(\"action\",action)\n\n action[action>1] = 1\n action[action<-1] = -1\n\n state, reward, done, info = env.step(action)\n\n state = modifyState(state) # Tin's modification test\n\n #Modification of reward based on collision and goal. Test only. Will move to env wrapper later.\n cube_position = np.array([state[\"wood_cube_10cm_x\"], state[\"wood_cube_10cm_y\"], state[\"wood_cube_10cm_z\"]])\n end_effector_position = np.array([state[\"ee_to_ref_translation_x\"], state[\"ee_to_ref_translation_y\"], state[\"ee_to_ref_translation_z\"]])\n dist_effector_to_cube = np.linalg.norm(cube_position - end_effector_position)\n\n # for test\n dist_cube_to_target = np.linalg.norm(targetPosition - cube_position)\n cube_distance_reward = min(20, max(0, (0.2 - dist_cube_to_target) * 100))\n\n effector_to_cube_reward = (0.5 - dist_effector_to_cube) * 2\n reward += cube_distance_reward + effector_to_cube_reward\n\n if state['in_collision'] == 1 and dist_effector_to_cube > 0.2:\n reward -= 100\n print(\"Collision detected. Restarting...\")\n elif done:\n reward += 300\n print('object reached the goal!')\n print(f\"time_step: {time_step:.2f}, reward: {reward:.2f}, distance_ee_and_cube: {dist_effector_to_cube:.2f}\")\n\n # saving reward and is_terminals\n ppo_agent.buffer.rewards.append(reward)\n ppo_agent.buffer.is_terminals.append(done)\n\n time_step +=1\n current_ep_reward += reward\n\n # update PPO agent\n if time_step % update_timestep == 0:\n ppo_agent.update()\n\n # if continuous action space; then decay action std of ouput action distribution\n if has_continuous_action_space and time_step % action_std_decay_freq == 0:\n ppo_agent.decay_action_std(action_std_decay_rate, min_action_std)\n\n # log in logging file\n if time_step % log_freq == 0:\n\n # log average reward till last episode\n log_avg_reward = log_running_reward / log_running_episodes\n log_avg_reward = round(log_avg_reward, 4)\n\n log_f.write('{},{},{}\\n'.format(i_episode, time_step, log_avg_reward))\n log_f.flush()\n\n log_running_reward = 0\n log_running_episodes = 0\n\n # printing average reward\n if time_step % print_freq == 0:\n\n # print average reward till last episode\n print_avg_reward = print_running_reward / print_running_episodes\n print_avg_reward = round(print_avg_reward, 2)\n\n print(\"Episode : {} \\t\\t Timestep : {} \\t\\t Average Reward : {}\".format(i_episode, time_step, print_avg_reward))\n\n print_running_reward = 0\n print_running_episodes = 0\n\n # save model weights\n if time_step % save_model_freq == 0:\n print(\"--------------------------------------------------------------------------------------------\")\n print(\"saving model at : \" + checkpoint_path + str(time_step))\n ppo_agent.save(checkpoint_path) # latest save\n ppo_agent.save(checkpoint_path + str(time_step))\n ppo_agent.load(checkpoint_path + str(time_step))\n print(\"model saved\")\n print(\"Elapsed Time : \", datetime.now().replace(microsecond=0) - start_time)\n print(\"--------------------------------------------------------------------------------------------\")\n\n # break; if the episode is over\n if done or state['in_collision'] == 1:\n if done:\n print(f\"cube location: {cube_position}\")\n print(f\"end_effector_position: {end_effector_position}\")\n print(f\"dist_cube_to_target: {dist_cube_to_target}\")\n print(f\"dist_endEffector_to_cube: {dist_effector_to_cube}\")\n print(\"state:\")\n print(state)\n break\n\n print_running_reward += current_ep_reward\n print_running_episodes += 1\n\n log_running_reward += current_ep_reward\n log_running_episodes += 1\n\n i_episode += 1\n\n\n log_f.close()\n env.close()\n\n\n\n\n # print total training time\n print(\"============================================================================================\")\n end_time = datetime.now().replace(microsecond=0)\n print(\"Started training at (GMT) : \", start_time)\n print(\"Finished training at (GMT) : \", end_time)\n print(\"Total training time : \", end_time - start_time)\n print(\"============================================================================================\")\n\n\n\n\nif __name__ == '__main__':\n\n train()\n \n \n \n \n \n \n \n \n"
]
| [
[
"torch.manual_seed",
"numpy.array",
"numpy.linalg.norm",
"numpy.random.seed"
]
]
|
jacobbieker/Wide_ASPECS | [
"79ba3f9d42861ebdd9b731b7c4a41857a04cef40"
]
| [
"independent/match_sources.py"
]
| [
"\"\"\"\n\nThis is focused on matching sources in the catalog to those detected in the cubes\n\n\"\"\"\nimport numpy as np\nfrom scipy.interpolate import interp2d, interp1d\n\nimport astropy.units as u\nfrom astropy.table import Table, vstack\nfrom astropy.coordinates import SkyCoord, Angle, SkyOffsetFrame, ICRS, Distance\nfrom astropy.coordinates import match_coordinates_sky, search_around_sky\nfrom stats import comoving_volume, get_kms, has_spec_z, get_co_z, convert_deltaZ_to_kms\n\ntransitions = {\"1-0\": [0.0030, 0.3694, 115.271, 0.2801, 89],\n \"2-1\": [1.0059, 1.7387, 230.538, 1.4277, 1920],\n \"3-2\": [2.0088, 3.1080, 345.796, 2.6129, 3363],\n \"4-3\": [3.0115, 4.4771, 461.041, 3.8030, 4149], }\n\ntransitions1 = {\"1-0\": [0.0030, 0.3694, 115.271, 0.2801, 89],\n \"2-1\": [1.0059, 1.7387, 230.538, 1.4277, 1920],\n \"3-2\": [2.0088, 3.1080, 345.796, 2.6129, 3363],\n \"4-3\": [3.0115, 4.4771, 461.041, 3.8030, 4149],\n \"5-4\": [4.0142, 5.8460, 576.268, 4.9933, 4571],\n \"6-5\": [5.0166, 7.2146, 691.473, 6.1843, 4809],\n \"7-6\": [6.0188, 8.5829, 806.652, 7.3750, 4935],}\ntransitions1 = {\"2-1\": [0.0, 0.0873, 230.538, 0.0656, 1.4],\n \"3-2\": [0.2713, 0.6309, 345.796, 0.4858, 314],\n \"4-3\": [0.6950, 1.1744, 461.041, 0.9543, 1028],\n \"5-4\": [1.1186, 1.7178, 576.268, 1.4297, 1759],\n \"6-5\": [1.5422, 2.2612, 691.473, 1.9078, 2376],\n \"7-6\": [1.9656, 2.8044, 806.652, 2.3859, 2864],}\n\ntemp = {\n \"C1mm\": [0.8094, 1.3212, 492.161, 1.0828, 1233],\n \"C1_2-1mm\": [1.9755, 2.8171, 809.342, 2.3973, 2875],\n \"C2\": [5.9873, 7.9635, 1900.548, 6.9408, 4431],\n \"C1\": [3.2823, 4.8468, 492.161, 4.1242, 4287],\n \"C1_2-1\": [6.0422, 8.6148, 809.342, 7.4031, 4936],\n}\ndef convert_observed_line_to_restframe():\n return NotImplementedError\n\n\ndef calculate_delta_z():\n return NotImplementedError\n\n\ndef estimate_redshift():\n return NotImplementedError\n\ndef construct_fid_mask(catalog):\n \"\"\"\n Constructs the fidelity mask based off my results, not Robertos\n :param catalog:\n :return:\n \"\"\"\n line_widths = [i for i in range(3, 21, 2)]\n fid_catalog = load_table(\"fidelity_snr.out\", start=0)\n fid_limit = 0.4\n\n six_fids = []\n for width in line_widths:\n f = interp1d(fid_catalog[\"fbin\"], fid_catalog[\"pure{}\".format(width)], kind='slinear')\n xdata = np.linspace(5.85, 7.85, 10000)\n six_fids.append(xdata[np.argmax(f(xdata) >= fid_limit)])\n masks = []\n line_widths = [i for i in range(3, 21, 2)]\n #six_fids = [6.3, 6.2, 6.1, 6.15, 6.1, 6.20, 6.1, 6.20, 6.05]\n # six_fids = [6.35, 6.25, 6.15, 6.15, 6.15, 6.25, 6.15, 6.25, 6.05]\n # six_fids = [6.25, 6.2, 6.1, 6.1, 6.1, 6.15, 6.1, 6.15, 6.05]\n for index, width in enumerate(line_widths):\n print(six_fids[index])\n masks.append(catalog[((catalog['width'] == width) & (catalog['rsnrrbin'] >= six_fids[index]))])\n\n total = masks[0]\n t_sum = 0\n for mask in masks[1:]:\n t_sum += len(mask)\n total = vstack((total, mask))\n\n print(\"Total One: {}\".format(len(total)))\n return total\n\ndef match_lines_to_catalog_pilot(lines, catalog, max_redshift=0.3, max_sep=1.0, method='closest'):\n aspecs_table = Table(names=(\n 'RA (J2000)', 'DEC (J2000)', 'Roberto ID', 'Roberto RA', 'Roberto DEC', 'Observed CO (GHz)', 'Restframe CO (GHz)',\n 'Transition', 'Z (Matched)', 'Z (CO)',\n 'Spec Z', 'Delta Z', 'Delta V (Km/s)', 'Km/s', 'Separation (Arcsecond)', 'S/N', 'Flux Density at Peak (Jy/beam)',\n 'Integrated Flux (Jy km/s)', 'Width (Channels)', 'Cosmic Volume (Mpc^3)', 'Log(M*)', 'Error Log(M*)', 'Log(SFR)',\n 'Error Log(SFR)', 'Catalog Index'),\n dtype=(\n 'f8', 'f8', 'int32', 'f8', 'f8', 'f4', 'f4', 'U6', 'f4', 'f4', 'bool', 'f4', 'f8', 'f8', 'f4',\n 'f4', 'f4', 'f4', 'int8', 'f4', 'f4', 'f4', 'f4', 'f4', 'int32'))\n\n \"\"\"\n Steps to do so:\n \n Find separations between line coordinates and catalog coordinates\n \n For those that are within the arcsecond limit, see if the galactic redshift is within the range that ASPECS can find\n \n If so, then get the difference in delta_z to see if that is within the range allowed\n If so, then get the properties and put together a whole entry on it\n If not, see if line matches to a different CO line within that range\n If so, save it out\n If not within range, see which line it could go to and use that one\n \n \n \"\"\"\n\n # first step is to do is get the SkyCoords\n\n catalog_ra = 'ra'\n catalog_dec = 'dc'\n\n # Only choose ones above SN limit\n #lines = lines[lines['rsnrrbin'] >= snr_limit]\n line_skycoords = make_skycoords(lines, ra='rra', dec='rdc')\n catalog_skycoords = make_skycoords(catalog, ra=catalog_ra, dec=catalog_dec)\n #for one in line_skycoords:\n # print(\"{} {}\".format(one.ra.to_string(unit=u.hour, sep=':'),one.dec.to_string(unit=u.deg, sep=':')))\n catalog_ids = []\n print()\n\n # Second step is to calculate the catalog matches\n if method == 'all_closest':\n # This is for getting all the matches, and only keeping the one with the closest redshift\n # Do it where it goes through all matches within a given radius\n idxc, idxcatalog, d2d, d3d = search_around_sky(line_skycoords, catalog_skycoords, max_sep * u.arcsecond)\n #for index, id in enumerate(idxc):\n # print(\"Matched: {} {} To: {} {} Sep: {}\".format(line_skycoords[idxc[index]].ra.to_string(unit=u.hour, sep=':'), line_skycoords[idxc[index]].dec.to_string(unit=u.degree, sep=':'), catalog_skycoords[idxcatalog[index]].ra.to_string(unit=u.hour, sep=':'), catalog_skycoords[idxcatalog[index]].dec.to_string(unit=u.degree, sep=':'), d2d[index]))\n # Get the set of chosen lines, all not chosen ones are sent to the other thing\n chosen_lines = set(idxc)\n full_set = set([i for i in range(len(lines))])\n non_matched_set_indexes = full_set - chosen_lines\n\n for index, separation in enumerate(d2d):\n matched_line = lines[idxc[index]]\n matched_to_galaxy = False\n # In order of lines, so then need to keep only best match here:\n # Also need to keep it so that match to CO is only called once, and only after matched_line changes\n if separation.arcsecond < max_sep:\n # Could be a match!\n # Get the catalog match\n matched_galaxy = catalog[idxcatalog[index]] # index is the index in line_skycoord matched\n # idx[index] is then the index into catalog that is matched to this one\n for key, values in transitions.items():\n if (values[0] - max_redshift) < matched_galaxy['z_1'] < (values[1] + max_redshift):\n # Now within range of this transition\n rest_frame_ghz = convert_to_rest_frame_ghz(matched_galaxy['z_1'],\n matched_line['rfreq'])\n delta_z, matched_key = get_delta_z(matched_galaxy['z_1'], rest_frame_ghz)\n if np.abs(delta_z) <= max_redshift: # Checks that delta z within the range\n # Now check with offset if the z is within the range\n if matched_galaxy['z_1'] + delta_z < (120.4) or (1.1) <= matched_galaxy['z_1'] + delta_z <= (\n 1.8) or (2.2) < matched_galaxy['z_1'] + delta_z < (4.4):\n matched_to_galaxy = True\n # so with offset, the galaxy is now within the range, is above SNR, and have a transition\n # Now get the KMS, if there is a Spec Z, Comoving volume, etc. and add to the table\n volume = comoving_volume(values[0], values[1], 42.6036)\n spec_z = has_spec_z(matched_galaxy)\n co_z = get_co_z(matched_line['rfreq'], matched_key)\n kms = 0#get_kms(matched_line['width'], matched_line['rfreq'])\n delta_v = convert_deltaZ_to_kms(delta_z, co_z)\n add_row = False\n prev_match_mask = (np.isclose(np.round(aspecs_table['RA (J2000)'], 10), np.round(line_skycoords[idxc[index]].ra.degree, 10)) & np.isclose(np.round(aspecs_table['DEC (J2000)'], 10), np.round(line_skycoords[idxc[index]].dec.degree, 10)))\n matched_rows = aspecs_table[prev_match_mask]\n print(matched_galaxy['z_1'])\n print(len(matched_rows))\n if len(matched_rows) > 0:\n if len(matched_rows) > 1:\n print(\"Extra Rows\")\n print(matched_rows)\n else:\n if matched_rows['Delta Z'] < delta_z:\n # Keep current one\n add_row = False\n else:\n add_row = True\n # Now need to remove the current row and get the other row\n print(\"Removing: \")\n print(matched_rows['Catalog Index', 'Z (Matched)', 'Delta Z'])\n print(\"Adding:\")\n print(\"Catalog Index: {} Z: {} Delta Z: {}\".format(idxcatalog[index], matched_galaxy['z_1'], delta_z))\n #aspecs_table.remove_rows(np.nonzero(prev_match_mask))\n else:\n add_row = True\n add_row = True\n if add_row:\n new_row = (line_skycoords[idxc[index]].ra.degree,#np.round(matched_line['rra'], 6),\n line_skycoords[idxc[index]].dec.degree,#np.round(matched_line['rdc'], 6),\n np.int(matched_galaxy['id']),\n catalog_skycoords[idxcatalog[index]].ra.degree,\n catalog_skycoords[idxcatalog[index]].dec.degree,\n matched_line['rfreq'],\n rest_frame_ghz,\n matched_key,\n matched_galaxy['z_1'],\n co_z,\n spec_z,\n delta_z,\n delta_v,\n kms,\n np.round(separation.arcsecond, 4),\n 0,#matched_line['rsnrrbin'],\n 0,#matched_line['rpeak'],\n 0,#matched_line['rflux'],\n 0,#matched_line['width'],\n np.round(volume, 3),\n matched_galaxy['Mstar_50_1'],\n matched_galaxy['Mstar_84_1'] - matched_galaxy['Mstar_50_1'],\n matched_galaxy['SFR_50_1'],\n matched_galaxy['SFR_84_1'] - matched_galaxy['SFR_50_1'],\n idxcatalog[index])\n aspecs_table.add_row(new_row)\n else:\n print(\"Outside of Max Separation (Shouldn't Happen)\")\n if not matched_to_galaxy:\n table_input = match_to_co_line(matched_line, max_redshift=max_redshift, line_coords=line_skycoords[idxc[index]])\n add_row = False\n if table_input is not None:\n try:\n prev_match_mask = (np.isclose(np.round(aspecs_table['RA (J2000)'], 6), np.round(line_skycoords[idxc[index]].ra.degree, 6)) & np.isclose(np.round(aspecs_table['DEC (J2000)'], 6), np.round(line_skycoords[idxc[index]].dec.degree, 6)))\n matched_rows = aspecs_table[prev_match_mask]\n if len(matched_rows) > 1:\n print(\"Extra Rows\")\n print(matched_rows)\n else:\n if matched_rows['Roberto ID'] > 0.:\n if matched_rows['Delta Z'] < delta_z:\n # Keep current one\n add_row = False\n else:\n add_row = True\n # Now need to remove the current row and get the other row\n aspecs_table.remove_rows(np.nonzero(prev_match_mask))\n except:\n add_row = True\n if add_row:\n aspecs_table.add_row(table_input)\n # Now have to do it for the non-matched ones\n for index in non_matched_set_indexes:\n matched_line = lines[index]\n table_input = match_to_co_line(matched_line, max_redshift=max_redshift)\n add_row = False\n if table_input is not None:\n try:\n prev_match_mask = (np.isclose(np.round(aspecs_table['RA (J2000)'], 6), np.round(line_skycoords[idxc[index]].ra.degree, 6)) & np.isclose(np.round(aspecs_table['DEC (J2000)'], 6), np.round(line_skycoords[idxc[index]].dec.degree, 6)))\n matched_rows = aspecs_table[prev_match_mask]\n if len(matched_rows) > 1:\n print(\"Extra Rows\")\n print(matched_rows)\n else:\n if matched_rows['Roberto ID'] > 0.:\n if matched_rows['Delta Z'] < delta_z:\n # Keep current one\n add_row = False\n else:\n add_row = True\n # Now need to remove the current row and get the other row\n aspecs_table.remove_rows(np.nonzero(prev_match_mask))\n except:\n add_row = True\n if add_row:\n aspecs_table.add_row(table_input)\n\n # Now need to clean up table, removing any inadvertently added rows\n prev_row_ra_dec = None\n prev_row_matched = None\n indicies_to_remove = []\n '''\n for index, row in enumerate(aspecs_table):\n if prev_row_ra_dec is not None:\n if np.isclose(np.round(row['RA (J2000)'],6),np.round(prev_row_ra_dec[0],6)) and np.isclose(np.round(row['DEC (J2000)'],6), np.round(prev_row_ra_dec[1],6)):\n # Same one as before, check if galaxy, then check delta Z\n print(row['Roberto ID'])\n if row['Roberto ID'] > 0.:\n # Matched to galaxy\n print(np.round(row['RA (J2000)'],6))\n print(np.round(row['DEC (J2000)'],6))\n if prev_row_matched[0] > 0.:# Previous also matchd to a galaxy\n if np.abs(row['Delta Z']) < np.abs(prev_row_matched[1]):\n indicies_to_remove.append(index-1)\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)'], row['Separation (Arcsecond)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n else: # Not better delta Z, so not add to prev\n indicies_to_remove.append(index)\n else: # Previous is not matched to a galaxy\n indicies_to_remove.append(index-1)\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)'], row['Separation (Arcsecond)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n else: # Not matched to a galaxy\n if row['Roberto ID'] > 0.: # Row is matched to one\n indicies_to_remove.append(index-1)\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)'], row['Separation (Arcsecond)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n else: # Not add to prev since current one is worse\n if np.abs(row['Delta Z']) < np.abs(prev_row_matched[1]):\n indicies_to_remove.append(index-1)\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)'], row['Separation (Arcsecond)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n else:\n indicies_to_remove.append(index)\n else: # Not same galaxy\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)'], row['Separation (Arcsecond)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n\n else: # No previous one\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)'], row['Separation (Arcsecond)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n\n # Remove from the catalog\n aspecs_table.remove_rows(indicies_to_remove)\n '''\n # Now need to only get the catalog ids that are relevant, so not -99999\n catalog_ids = [i['Catalog Index'] for i in aspecs_table if i['Catalog Index'] > 0]\n aspecs_table['Roberto ID'].pprint(max_lines=-1)\n print(\"Catalog IDS: {}\".format(catalog_ids))\n for id in catalog_ids:\n print(catalog[id]['id'])\n print(catalog[catalog_ids]['id', 'Mstar_50_1', 'Mstar_50_2', 'SFR_50_1', 'SFR_50_2', 'z_1', 'z_2'])\n\n if method == 'all':\n # Do it where it goes through all matches within a given radius\n idxc, idxcatalog, d2d, d3d = search_around_sky(line_skycoords, catalog_skycoords, max_sep * u.arcsecond)\n\n # Many to many is way too large to work, so doing it one by one\n print(\"Matching done\")\n print(len(idxc))\n\n # Get the set of chosen lines, all not chosen ones are sent to the other thing\n chosen_lines = set(idxc)\n full_set = set([i for i in range(len(lines))])\n non_matched_set_indexes = full_set - chosen_lines\n\n for index, separation in enumerate(d2d):\n matched_line = lines[idxc[index]]\n matched_to_galaxy = False\n if separation.arcsecond < max_sep:\n # Could be a match!\n # Get the catalog match\n matched_galaxy = catalog[idxcatalog[index]] # index is the index in line_skycoord matched\n # idx[index] is then the index into catalog that is matched to this one\n for key, values in transitions.items():\n if (values[0] - max_redshift) < matched_galaxy['z_1'] < (values[1] + max_redshift):\n # Now within range of this transition\n rest_frame_ghz = convert_to_rest_frame_ghz(matched_galaxy['z_1'],\n matched_line['rfreq'])\n delta_z, matched_key = get_delta_z(matched_galaxy['z_1'], rest_frame_ghz)\n if np.abs(delta_z) <= max_redshift: # Checks that delta z within the range\n # Now check with offset if the z is within the range\n if matched_galaxy['z_1'] + delta_z < (0.4) or (1.1) <= matched_galaxy['z_1'] + delta_z <= (\n 1.8) or (2.2) < matched_galaxy['z_1'] + delta_z < (4.4):\n catalog_ids.append((matched_galaxy['id'], idxcatalog[index]))\n matched_to_galaxy = True\n # so with offset, the galaxy is now within the range, is above SNR, and have a transition\n # Now get the KMS, if there is a Spec Z, Comoving volume, etc. and add to the table\n volume = comoving_volume(values[0], values[1], 42.6036)\n spec_z = has_spec_z(matched_galaxy)\n kms = get_kms(matched_line['width'], matched_line['rfreq'])\n\n co_z = get_co_z(matched_line['rfreq'], matched_key)\n delta_v = convert_deltaZ_to_kms(delta_z, co_z)\n new_row = (np.round(matched_line['rra'], 6),\n np.round(matched_line['rdc'], 6),\n np.int(matched_galaxy['id']),\n np.round(matched_galaxy[catalog_ra], 6),\n np.round(matched_galaxy[catalog_dec], 6),\n matched_line['rfreq'],\n rest_frame_ghz,\n matched_key,\n matched_galaxy['z_1'],\n co_z,\n spec_z,\n delta_z,\n delta_v,\n kms,\n np.round(separation.arcsecond, 4),\n matched_line['rsnrrbin'],\n matched_line['rpeak'],\n matched_line['rflux'],\n matched_line['width'],\n np.round(volume, 3),\n matched_galaxy['Mstar_50_1'],\n matched_galaxy['Mstar_84_1'] - matched_galaxy['Mstar_50_1'],\n matched_galaxy['SFR_50_1'],\n matched_galaxy['SFR_84_1'] - matched_galaxy['SFR_50_1'])\n aspecs_table.add_row(new_row)\n if not matched_to_galaxy:\n table_input = match_to_co_line(matched_line, max_redshift=max_redshift)\n if table_input is not None:\n aspecs_table.add_row(table_input)\n # Now have to do it for the non-matched ones\n for index in non_matched_set_indexes:\n matched_line = lines[index]\n table_input = match_to_co_line(matched_line, max_redshift=max_redshift)\n if table_input is not None:\n aspecs_table.add_row(table_input)\n catalog_ids = [i[1] for i in catalog_ids]\n\n\n if method == 'closest':\n idx, d2d, d3d = match_coordinates_sky(line_skycoords, catalog_skycoords)\n # So now, idx is the index into catalog_skycoords to get the matched coordinate for line_skycoords, shape=line_skycoord\n # d2d is on sky separation between line_skycoords and its closest match\n # So the catalog_skycoord[idx] is the match for the line_skycoord\n\n for index, ident in enumerate(idx):\n matched_line = lines[index]\n matched_to_galaxy = False\n # Check if above the SNR limit\n if d2d[index].arcsecond < max_sep:\n # Could be a match!\n # Get the catalog match\n matched_galaxy = catalog[ident] # index is the index in line_skycoord matched\n # idx[index] is then the index into catalog that is matched to this one\n for key, values in transitions.items():\n if (values[0] - max_redshift) < matched_galaxy['z_1'] < (values[1] + max_redshift):\n # Now within range of this transition\n rest_frame_ghz = convert_to_rest_frame_ghz(matched_galaxy['z_1'],\n matched_line['rfreq'])\n delta_z, matched_key = get_delta_z(matched_galaxy['z_1'], rest_frame_ghz)\n if np.abs(delta_z) <= max_redshift: # Checks that delta z within the range\n # Now check with offset if the z is within the range\n if matched_galaxy['z_1'] + delta_z <= (0.4) or (1.1) <= matched_galaxy['z_1'] + delta_z <= (\n 1.8) or (2.2) <= matched_galaxy['z_1'] + delta_z <= (4.4):\n matched_to_galaxy = True\n catalog_ids.append((matched_galaxy['id'], ident))\n print(matched_galaxy['id'])\n # so with offset, the galaxy is now within the range, is above SNR, and have a transition\n # Now get the KMS, if there is a Spec Z, Comoving volume, etc. and add to the table\n volume = comoving_volume(values[0], values[1], 42.6036)\n spec_z = has_spec_z(matched_galaxy)\n kms = get_kms(matched_line['width'], matched_line['rfreq'])\n co_z = get_co_z(matched_line['rfreq'], matched_key)\n delta_v = convert_deltaZ_to_kms(delta_z, co_z)\n new_row = (np.round(matched_line['rra'], 6),\n np.round(matched_line['rdc'], 6),\n np.int(matched_galaxy['id']),\n np.round(matched_galaxy[catalog_ra], 6),\n np.round(matched_galaxy[catalog_dec], 6),\n matched_line['rfreq'],\n rest_frame_ghz,\n matched_key,\n matched_galaxy['z_1'],\n co_z,\n spec_z,\n delta_z,\n delta_v,\n kms,\n np.round(d2d[index].arcsecond, 4),\n matched_line['rsnrrbin'],\n matched_line['rpeak'],\n matched_line['rflux'],\n matched_line['width'],\n np.round(volume, 3),\n matched_galaxy['Mstar_50_1'],\n matched_galaxy['Mstar_84_1'] - matched_galaxy['Mstar_50_1'],\n matched_galaxy['SFR_50_1'],\n matched_galaxy['SFR_84_1'] - matched_galaxy['SFR_50_1'])\n aspecs_table.add_row(new_row)\n if not matched_to_galaxy:\n table_input = match_to_co_line(matched_line, max_redshift=max_redshift)\n if table_input is not None:\n aspecs_table.add_row(table_input)\n # Now need to clean up table, removing any inadvertently added rows\n prev_row_ra_dec = None\n prev_row_matched = None\n indicies_to_remove = []\n for index, row in enumerate(aspecs_table):\n if prev_row_ra_dec is not None:\n if row['RA (J2000)'] == prev_row_ra_dec[0] and row['DEC (J2000)'] == prev_row_ra_dec[1]:\n # Same one as before, check if galaxy, then check delta Z\n if prev_row_matched[0] > 0. and row['Roberto ID'] > 0.:\n continue\n # Matched to galaxy\n if np.abs(row['Delta Z']) < np.abs(prev_row_matched[1]):\n indicies_to_remove.append(index-1)\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n else: # Not better delta Z, so not add to prev\n indicies_to_remove.append(index)\n else: # Not matched to a galaxy\n if row['Roberto ID'] > 0.: # Row is matched to one\n indicies_to_remove.append(index-1)\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n else: # Not add to prev since current one is worse\n if np.abs(row['Delta Z']) < np.abs(prev_row_matched[1]):\n indicies_to_remove.append(index-1)\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n else:\n indicies_to_remove.append(index)\n else: # Not same galaxy\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n\n else: # No previous one\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n\n # Remove from the catalog\n aspecs_table.remove_rows(indicies_to_remove)\n\n catalog_ids = [i[1] for i in catalog_ids]\n\n # now have the catalog matches:\n aspecs_catalog = catalog[catalog_ids]\n aspecs_catalog['z_co'] = np.zeros(shape=(aspecs_catalog['z_1'].shape))\n # Add CO Z\n for line in aspecs_table:\n for index, row in enumerate(aspecs_catalog):\n if int(line['Roberto ID']) == int(row['id']):\n aspecs_catalog[index]['z_co'] = line[\"Z (CO)\"]\n\n return aspecs_table, aspecs_catalog\n\n\ndef match_to_co_line(single_line, max_redshift=0.3, line_coords=None):\n \"\"\"\n Match a single line to a CO line transition\n :param single_line:\n :return: Data to then be added to the Table\n \"\"\"\n estimated_transition, estimated_z = get_estimated_z(single_line['rfreq'])\n if estimated_z < 0.4 or 1.1 <= estimated_z <= 1.8 or 2.2 < estimated_z < 4.4:\n rest_frame_ghz = convert_to_rest_frame_ghz(estimated_z, single_line['rfreq'])\n delta_z, matched_key = get_delta_z(estimated_z, rest_frame_ghz)\n #if np.abs(delta_z) <= max_redshift: No checking for that, as long as delta_z is between acceptable values, choose that, so not biased as much hopefully\n spec_z = False\n volume = comoving_volume(transitions[estimated_transition][0], transitions[estimated_transition][1], 52.5)\n kms = get_kms(single_line['width'], single_line['rfreq'])\n co_z = get_co_z(single_line['rfreq'], matched_key)\n delta_v = convert_deltaZ_to_kms(delta_z, co_z)\n new_row = (np.round(single_line['rra'], 6),\n np.round(single_line['rdc'], 6),\n -999,\n -999,\n -999,\n single_line['rfreq'],\n rest_frame_ghz,\n matched_key,\n estimated_z,\n co_z,\n spec_z,\n 0,\n 0, # If it matches to a CO line, then no delta Z\n kms,\n -999,\n single_line['rsnrrbin'],\n single_line['rpeak'],\n single_line['rflux'],\n single_line['width'],\n np.round(volume, 3),\n -999,\n -999,\n -999,\n -999,\n -999)\n\n return new_row\n #else:\n # return None\n else:\n return None\n\n\ndef make_skycoords(source, ra='ra', dec='dec', distance=None):\n \"\"\"\n Makes and returns a SkyCoord array from given source\n :param source: Source with information\n :param ra: Key for RA\n :param dec: Key for Dec\n :return: SkyCoord list\n \"\"\"\n try:\n if distance is None:\n skycoords = SkyCoord(source[ra] * u.deg, source[dec] * u.deg, frame='icrs')\n else:\n distances = Distance(z=source[distance])\n skycoords = SkyCoord(source[ra] * u.deg, source[dec] * u.deg, distance=distances, frame='icrs')\n except:\n if distance is None:\n skycoords = SkyCoord(source[ra], source[dec], unit=(u.hour, u.deg), frame='icrs')\n else:\n distances = Distance(z=source[distance])\n skycoords = SkyCoord(source[ra], source[dec], unit=(u.hour, u.deg), distance=distances, frame='icrs')\n\n return skycoords\n\n\ndef get_observed_ghz(z, transition):\n \"\"\"\n Get the observed GHz for given redshift based on transition, from Wide ASPECS paper\n :param z: Z to calculate for\n :param transition:\n :return:\n \"\"\"\n emitted_ghz = transitions[transition][2] * u.GHz\n\n observed_ghz = emitted_ghz / (z + 1)\n\n return observed_ghz\n\n\ndef get_delta_z(z, rest_ghz):\n \"\"\"\n Take a measured GHz value, and calculates the restframe GHz value based on the given z of the matched galaxy\n :param z:\n :param ghz:\n :return:\n \"\"\"\n\n # First step is to convert to nm rom rest frame GHz\n set_zs = []\n for key, values in transitions.items():\n if values[0] - 0.3 <= z <= values[1] + 0.3:\n sghz = values[2] * u.GHz # Gets the GHz of the CO line\n rest_ghz /= (z + 1)\n set_z = np.round((sghz - rest_ghz) / rest_ghz, 3) # (Freq_emitted - Freq_obs)/ Freq_obs = z\n set_z = z - set_z\n rest_ghz *= (z + 1)\n set_zs.append((key, set_z))\n set_z = np.min([np.abs(i[1]) for i in set_zs])\n for element in set_zs:\n if np.isclose(np.abs(element[1]), set_z):\n return element[1], element[0]\n\n\ndef convert_to_rest_frame_ghz(z, ghz):\n \"\"\"\n Take a measured GHz value, and calculates the restframe GHz value based on the given z of the matched galaxy\n :param z:\n :param ghz:\n :return:\n \"\"\"\n\n observed_ghz = ghz * u.GHz\n\n emitted = observed_ghz * (z + 1)\n\n return emitted\n\n\ndef get_z_from_ghz(ghz):\n \"\"\"\n Get the Z from the GhZ directly, so that it can be seen if there is a valid transition, with higher Z having higher\n priority for these things\n\n\n :param ghz:\n :return: transition, estimated z\n \"\"\"\n\n\n differences = []\n for key, values in transitions.items():\n val_differences = []\n # Go through each redshift CO transition bin in 1/100 of the Z\n z_vals = np.arange(start=values[0], stop=values[1], step=0.1)\n # Potentially have to go through one by one\n for index, val in enumerate(z_vals):\n sghz = convert_to_rest_frame_ghz(val, ghz)\n\n # Now have rest frame GHz for each of the z values\n delta_z, matched_key = get_delta_z(val, sghz)\n\n # Since all for same transition, only really need to look at delta_z values\n # Slightly more likely to be higher Z values in same transition\n # Ideally calculate cosmic volume per z value and use that for the whole determination of best one\n\n # Then return best one for each transition\n try:\n volume = comoving_volume(z_vals[index-1], z_vals[index], 52.5)\n except:\n volume = comoving_volume(0, z_vals[index], 52.5)\n vol_prop_delta = delta_z * (1/volume)\n val_differences.append((delta_z, matched_key, val, vol_prop_delta))\n\n # Now determine closest one for this transition\n min_diff = np.min([np.abs(i[0]) for i in val_differences])\n for index, element in enumerate(val_differences):\n if np.isclose(np.abs(element[0]), min_diff):\n # Now that getting the best one, include the cosmic volume of the whole redshift range\n vol_prop_delta = element[0] * (1/values[-1])\n differences.append((element[1], element[0], element[2], vol_prop_delta))\n\n # Now do it for all of them\n min_diff = np.min([np.abs(i[2]) for i in differences])\n\n for index, element in enumerate(differences):\n if np.isclose(np.abs(element[2]), min_diff):\n return element[0], element[2]\n\n\ndef get_estimated_z(ghz):\n \"\"\"\n Estimate the CO line based on Wide-ASPECS one, (3-2), z > 2 or higher J, calculate possible Z's and find which Z is closest\n to the <z> value from Wide ASPECS\n\n Get it from doing the difference times the inverse of the volume of space it looks at\n Smallest one then is the one to choose, as long as its within the z limit\n\n Should test all redshifts within the range of each transition, with higher Z's getting higher chance of being\n right, or actually, just go from GHz to z for the different transitions and see which redshift that would be at\n\n\n :param ghz:\n :return: transition, estimated_z\n \"\"\"\n differences = []\n for key, values in transitions.items():\n # Convert ghz to rest_ghz of the Z value, otherwise always closest to lowest one\n sghz = convert_to_rest_frame_ghz(values[3], ghz)\n delta_z, matched_key = get_delta_z(values[3], sghz)\n # Now multiply by volume covered to get likely one\n vol_prop_delta = delta_z * (1/values[-1])\n differences.append((matched_key, delta_z, vol_prop_delta))\n\n min_diff = np.min([np.abs(i[2]) for i in differences])\n\n for index, element in enumerate(differences):\n if np.isclose(np.abs(element[2]), min_diff):\n return element[0], transitions[element[0]][3]\n\ndef load_table(ascii_table, header=0, start=1):\n ascii_table_data = Table.read(ascii_table, format=\"ascii\", header_start=header, data_start=start)\n return ascii_table_data\n\n\n\n\ndef match_lines_to_catalog(lines, catalog, snr_limit=6., max_sep=1.0, method='closest'):\n aspecs_table = Table(names=(\n 'RA (J2000)', 'DEC (J2000)', 'Roberto ID', 'Roberto RA', 'Roberto DEC', 'Observed CO (GHz)', 'Restframe CO (GHz)',\n 'Transition', 'Z (Matched)', 'Z (CO)',\n 'Spec Z', 'Delta Z', 'Delta V (Km/s)', 'Km/s', 'Separation (Arcsecond)', 'S/N', 'Flux Density at Peak (Jy/beam)',\n 'Integrated Flux (Jy km/s)', 'Width (Channels)', 'Cosmic Volume (Mpc^3)', 'Log(M*)', 'Error Log(M*)', 'Log(SFR)',\n 'Error Log(SFR)', 'Catalog Index'),\n dtype=(\n 'f8', 'f8', 'int32', 'f8', 'f8', 'f4', 'f4', 'U6', 'f4', 'f4', 'bool', 'f4', 'f8', 'f8', 'f4',\n 'f4', 'f4', 'f4', 'int8', 'f4', 'f4', 'f4', 'f4', 'f4', 'int32'))\n\n \"\"\"\n Steps to do so:\n \n Find separations between line coordinates and catalog coordinates\n \n For those that are within the arcsecond limit, see if the galactic redshift is within the range that ASPECS can find\n \n If so, then get the difference in delta_z to see if that is within the range allowed\n If so, then get the properties and put together a whole entry on it\n If not, see if line matches to a different CO line within that range\n If so, save it out\n If not within range, see which line it could go to and use that one\n \n \n \"\"\"\n\n # first step is to do is get the SkyCoords\n\n catalog_ra = 'ra'\n catalog_dec = 'dc'\n\n # Only choose ones above SN limit))\n lines = construct_fid_mask(lines)\n\n line_skycoords = make_skycoords(lines, ra='rra', dec='rdc')\n catalog_skycoords = make_skycoords(catalog, ra=catalog_ra, dec=catalog_dec)\n #for one in line_skycoords:\n # print(\"{} {}\".format(one.ra.to_string(unit=u.hour, sep=':'),one.dec.to_string(unit=u.deg, sep=':')))\n catalog_ids = []\n\n # Second step is to calculate the catalog matches\n if method == 'all_closest':\n # This is for getting all the matches, and only keeping the one with the closest redshift\n # Do it where it goes through all matches within a given radius\n idxc, idxcatalog, d2d, d3d = search_around_sky(line_skycoords, catalog_skycoords, max_sep * u.arcsecond)\n #for index, id in enumerate(idxc):\n # print(\"Matched: {} {} To: {} {} Sep: {}\".format(line_skycoords[idxc[index]].ra.to_string(unit=u.hour, sep=':'), line_skycoords[idxc[index]].dec.to_string(unit=u.degree, sep=':'), catalog_skycoords[idxcatalog[index]].ra.to_string(unit=u.hour, sep=':'), catalog_skycoords[idxcatalog[index]].dec.to_string(unit=u.degree, sep=':'), d2d[index]))\n # Get the set of chosen lines, all not chosen ones are sent to the other thing\n chosen_lines = set(idxc)\n full_set = set([i for i in range(len(lines))])\n non_matched_set_indexes = full_set - chosen_lines\n\n for index, separation in enumerate(d2d):\n matched_line = lines[idxc[index]]\n matched_to_galaxy = False\n # In order of lines, so then need to keep only best match here:\n # Also need to keep it so that match to CO is only called once, and only after matched_line changes\n if separation.arcsecond < max_sep:\n # Could be a match!\n # Get the catalog match\n matched_galaxy = catalog[idxcatalog[index]] # index is the index in line_skycoord matched\n spec_z = has_spec_z(matched_galaxy)\n if spec_z:\n max_redshift = 0.01\n else:\n max_redshift = 0.3\n # idx[index] is then the index into catalog that is matched to this one\n for key, values in transitions.items():\n if (values[0] - max_redshift) < matched_galaxy['z_1'] < (values[1] + max_redshift):\n # Now within range of this transition\n rest_frame_ghz = convert_to_rest_frame_ghz(matched_galaxy['z_1'],\n matched_line['rfreq'])\n delta_z, matched_key = get_delta_z(matched_galaxy['z_1'], rest_frame_ghz)\n if np.abs(delta_z) <= max_redshift: # Checks that delta z within the range\n # Now check with offset if the z is within the range\n if matched_galaxy['z_1'] + delta_z < (0.3694) or (1.1) <= matched_galaxy['z_1'] + delta_z <= (\n 1.8) or (2.2) < matched_galaxy['z_1'] + delta_z < (4.4):\n matched_to_galaxy = True\n # so with offset, the galaxy is now within the range, is above SNR, and have a transition\n # Now get the KMS, if there is a Spec Z, Comoving volume, etc. and add to the table\n volume = comoving_volume(values[0], values[1], 42.6036)\n co_z = get_co_z(matched_line['rfreq'], matched_key)\n kms = get_kms(matched_line['width'], matched_line['rfreq'])\n delta_v = convert_deltaZ_to_kms(delta_z, co_z)\n add_row = False\n try:\n prev_match_mask = (np.isclose(np.round(aspecs_table['RA (J2000)'], 6), np.round(line_skycoords[idxc[index]].ra.degree, 6)) & np.isclose(np.round(aspecs_table['DEC (J2000)'], 6), np.round(line_skycoords[idxc[index]].dec.degree, 6)))\n matched_rows = aspecs_table[prev_match_mask]\n if len(matched_rows) > 1:\n print(\"Extra Rows\")\n print(matched_rows)\n else:\n if matched_rows['Roberto ID'] > 0:\n if np.abs(matched_rows['Delta Z']) < np.abs(delta_z):\n # Keep current one\n add_row = False\n else:\n add_row = True\n # Now need to remove the current row and get the other row\n #aspecs_table.remove_rows(np.nonzero(prev_match_mask))\n else:\n add_row = True\n # Now need to remove the current row and get the other row\n #aspecs_table.remove_rows(np.nonzero(prev_match_mask))\n\n except:\n add_row = True\n if add_row:\n new_row = (np.round(matched_line['rra'], 6),\n np.round(matched_line['rdc'], 6),\n np.int(matched_galaxy['id']),\n catalog_skycoords[idxcatalog[index]].ra.degree,\n catalog_skycoords[idxcatalog[index]].dec.degree,\n matched_line['rfreq'],\n rest_frame_ghz,\n matched_key,\n matched_galaxy['z_1'],\n co_z,\n spec_z,\n delta_z,\n delta_v,\n kms,\n np.round(separation.arcsecond, 4),\n matched_line['rsnrrbin'],\n matched_line['rpeak'],\n matched_line['rflux'],\n matched_line['width'],\n np.round(volume, 3),\n matched_galaxy['Mstar_50_2'],\n matched_galaxy['Mstar_50_2'] - matched_galaxy['Mstar_16_2'],\n matched_galaxy['SFR_50_2'],\n matched_galaxy['SFR_50_2'] - matched_galaxy['SFR_16_2'],\n idxcatalog[index])\n aspecs_table.add_row(new_row)\n else:\n print(\"Outside of Max Separation (Shouldn't Happen)\")\n if True: #not matched_to_galaxy: # Always try to find a match\n max_redshift = 0.3\n table_input = match_to_co_line(matched_line, max_redshift=max_redshift, line_coords=line_skycoords[idxc[index]])\n add_row = False\n if table_input is not None:\n try:\n prev_match_mask = (np.isclose(np.round(aspecs_table['RA (J2000)'], 6), np.round(line_skycoords[idxc[index]].ra.degree, 6)) & np.isclose(np.round(aspecs_table['DEC (J2000)'], 6), np.round(line_skycoords[idxc[index]].dec.degree, 6)))\n matched_rows = aspecs_table[prev_match_mask]\n if len(matched_rows) > 1:\n print(\"Extra Rows\")\n print(matched_rows)\n else:\n if matched_rows['Roberto ID'] > 0.:\n if np.abs(matched_rows['Delta Z']) < np.abs(delta_z):\n # Keep current one\n add_row = False\n else:\n add_row = True\n # Now need to remove the current row and get the other row\n #aspecs_table.remove_rows(np.nonzero(prev_match_mask))\n except:\n add_row = True\n if True: #add_row:\n aspecs_table.add_row(table_input)\n\n # Now have to do it for the non-matched ones\n for index in non_matched_set_indexes:\n matched_line = lines[index]\n max_redshift = 0.3\n table_input = match_to_co_line(matched_line, max_redshift=max_redshift)\n add_row = False\n if table_input is not None:\n try:\n prev_match_mask = (np.isclose(np.round(aspecs_table['RA (J2000)'], 6), np.round(line_skycoords[idxc[index]].ra.degree, 6)) & np.isclose(np.round(aspecs_table['DEC (J2000)'], 6), np.round(line_skycoords[idxc[index]].dec.degree, 6)))\n matched_rows = aspecs_table[prev_match_mask]\n if len(matched_rows) > 1:\n print(\"Extra Rows\")\n print(matched_rows)\n else:\n if matched_rows['Roberto ID'] > 0.:\n if np.abs(matched_rows['Delta Z']) < np.abs(delta_z):\n # Keep current one\n add_row = False\n else:\n add_row = True\n # Now need to remove the current row and get the other row\n #aspecs_table.remove_row(prev_match_mask)\n except:\n add_row = True\n if True: #add_row:\n aspecs_table.add_row(table_input)\n\n # Now need to clean up table, removing any inadvertently added rows\n prev_row_ra_dec = None\n prev_row_matched = None\n indicies_to_remove = []\n \"\"\"\n for index, row in enumerate(aspecs_table):\n if prev_row_ra_dec is not None:\n if np.isclose(np.round(row['RA (J2000)'],6),np.round(prev_row_ra_dec[0],6)) and np.isclose(np.round(row['DEC (J2000)'],6), np.round(prev_row_ra_dec[1],6)):\n # Same one as before, check if galaxy, then check delta Z\n print(row['Roberto ID'])\n if row['Roberto ID'] > 0.:\n # Matched to galaxy\n print(np.round(row['RA (J2000)'],6))\n print(np.round(row['DEC (J2000)'],6))\n if prev_row_matched[0] > 0.:# Previous also matchd to a galaxy\n if np.abs(row['Delta Z']) < np.abs(prev_row_matched[1]):\n indicies_to_remove.append(index-1)\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)'], row['Separation (Arcsecond)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n else: # Not better delta Z, so not add to prev\n indicies_to_remove.append(index)\n else: # Previous is not matched to a galaxy\n indicies_to_remove.append(index-1)\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)'], row['Separation (Arcsecond)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n else: # Not matched to a galaxy\n if row['Roberto ID'] > 0.: # Row is matched to one\n indicies_to_remove.append(index-1)\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)'], row['Separation (Arcsecond)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n else: # Not add to prev since current one is worse\n if np.abs(row['Delta Z']) < np.abs(prev_row_matched[1]):\n indicies_to_remove.append(index-1)\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)'], row['Separation (Arcsecond)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n else:\n indicies_to_remove.append(index)\n else: # Not same galaxy\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)'], row['Separation (Arcsecond)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n\n else: # No previous one\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)'], row['Separation (Arcsecond)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n\n # Remove from the catalog\n aspecs_table.remove_rows(indicies_to_remove)\n \"\"\"\n # Now need to only get the catalog ids that are relevant, so not -99999\n spec_z_catalog_ids = [i['Catalog Index'] for i in aspecs_table if i['Catalog Index'] > 0 and i['Spec Z'] == True]\n no_spec_z_catalog_ids = [i['Catalog Index'] for i in aspecs_table if i['Catalog Index'] > 0 and i['Spec Z'] == False]\n catalog_ids = [i['Catalog Index'] for i in aspecs_table if i['Catalog Index'] > 0]\n aspecs_table['Roberto ID'].pprint(max_lines=-1)\n print(catalog[catalog_ids]['id', 'Mstar_50_1', 'Mstar_50_2', 'SFR_50_1', 'SFR_50_2', 'z_1', 'z_2'])\n\n if method == 'all':\n # Do it where it goes through all matches within a given radius\n idxc, idxcatalog, d2d, d3d = search_around_sky(line_skycoords, catalog_skycoords, max_sep * u.arcsecond)\n\n # Many to many is way too large to work, so doing it one by one\n print(\"Matching done\")\n print(len(idxc))\n\n # Get the set of chosen lines, all not chosen ones are sent to the other thing\n chosen_lines = set(idxc)\n full_set = set([i for i in range(len(lines))])\n non_matched_set_indexes = full_set - chosen_lines\n\n for index, separation in enumerate(d2d):\n matched_line = lines[idxc[index]]\n matched_to_galaxy = False\n if separation.arcsecond < max_sep:\n # Could be a match!\n # Get the catalog match\n matched_galaxy = catalog[idxcatalog[index]] # index is the index in line_skycoord matched\n # idx[index] is then the index into catalog that is matched to this one\n for key, values in transitions.items():\n if (values[0] - max_redshift) < matched_galaxy['z_1'] < (values[1] + max_redshift):\n # Now within range of this transition\n rest_frame_ghz = convert_to_rest_frame_ghz(matched_galaxy['z_1'],\n matched_line['rfreq'])\n delta_z, matched_key = get_delta_z(matched_galaxy['z_1'], rest_frame_ghz)\n if np.abs(delta_z) <= max_redshift: # Checks that delta z within the range\n # Now check with offset if the z is within the range\n if matched_galaxy['z_1'] + delta_z < (0.4) or (1.1) <= matched_galaxy['z_1'] + delta_z <= (\n 1.8) or (2.2) < matched_galaxy['z_1'] + delta_z < (4.4):\n catalog_ids.append((matched_galaxy['id'], idxcatalog[index]))\n matched_to_galaxy = True\n # so with offset, the galaxy is now within the range, is above SNR, and have a transition\n # Now get the KMS, if there is a Spec Z, Comoving volume, etc. and add to the table\n volume = comoving_volume(values[0], values[1], 42.6036)\n spec_z = has_spec_z(matched_galaxy)\n kms = get_kms(matched_line['width'], matched_line['rfreq'])\n\n co_z = get_co_z(matched_line['rfreq'], matched_key)\n delta_v = convert_deltaZ_to_kms(delta_z, co_z)\n new_row = (np.round(matched_line['rra'], 6),\n np.round(matched_line['rdc'], 6),\n np.int(matched_galaxy['id']),\n np.round(matched_galaxy[catalog_ra], 6),\n np.round(matched_galaxy[catalog_dec], 6),\n matched_line['rfreq'],\n rest_frame_ghz,\n matched_key,\n matched_galaxy['z_1'],\n co_z,\n spec_z,\n delta_z,\n delta_v,\n kms,\n np.round(separation.arcsecond, 4),\n matched_line['rsnrrbin'],\n matched_line['rpeak'],\n matched_line['rflux'],\n matched_line['width'],\n np.round(volume, 3),\n matched_galaxy['Mstar_50_1'],\n matched_galaxy['Mstar_84_1'] - matched_galaxy['Mstar_50_1'],\n matched_galaxy['SFR_50_1'],\n matched_galaxy['SFR_84_1'] - matched_galaxy['SFR_50_1'])\n aspecs_table.add_row(new_row)\n if not matched_to_galaxy:\n table_input = match_to_co_line(matched_line, max_redshift=max_redshift)\n if table_input is not None:\n aspecs_table.add_row(table_input)\n # Now have to do it for the non-matched ones\n for index in non_matched_set_indexes:\n matched_line = lines[index]\n table_input = match_to_co_line(matched_line, max_redshift=max_redshift)\n if table_input is not None:\n aspecs_table.add_row(table_input)\n catalog_ids = [i[1] for i in catalog_ids]\n\n\n if method == 'closest':\n idx, d2d, d3d = match_coordinates_sky(line_skycoords, catalog_skycoords)\n # So now, idx is the index into catalog_skycoords to get the matched coordinate for line_skycoords, shape=line_skycoord\n # d2d is on sky separation between line_skycoords and its closest match\n # So the catalog_skycoord[idx] is the match for the line_skycoord\n\n for index, ident in enumerate(idx):\n matched_line = lines[index]\n matched_to_galaxy = False\n # Check if above the SNR limit\n if d2d[index].arcsecond < max_sep:\n # Could be a match!\n # Get the catalog match\n matched_galaxy = catalog[ident] # index is the index in line_skycoord matched\n # idx[index] is then the index into catalog that is matched to this one\n for key, values in transitions.items():\n if (values[0] - max_redshift) < matched_galaxy['z_1'] < (values[1] + max_redshift):\n # Now within range of this transition\n rest_frame_ghz = convert_to_rest_frame_ghz(matched_galaxy['z_1'],\n matched_line['rfreq'])\n delta_z, matched_key = get_delta_z(matched_galaxy['z_1'], rest_frame_ghz)\n if np.abs(delta_z) <= max_redshift: # Checks that delta z within the range\n # Now check with offset if the z is within the range\n if matched_galaxy['z_1'] + delta_z <= (0.4) or (1.1) <= matched_galaxy['z_1'] + delta_z <= (\n 1.8) or (2.2) <= matched_galaxy['z_1'] + delta_z <= (4.4):\n matched_to_galaxy = True\n catalog_ids.append((matched_galaxy['id'], ident))\n print(matched_galaxy['id'])\n # so with offset, the galaxy is now within the range, is above SNR, and have a transition\n # Now get the KMS, if there is a Spec Z, Comoving volume, etc. and add to the table\n volume = comoving_volume(values[0], values[1], 42.6036)\n spec_z = has_spec_z(matched_galaxy)\n kms = get_kms(matched_line['width'], matched_line['rfreq'])\n co_z = get_co_z(matched_line['rfreq'], matched_key)\n delta_v = convert_deltaZ_to_kms(delta_z, co_z)\n new_row = (np.round(matched_line['rra'], 6),\n np.round(matched_line['rdc'], 6),\n np.int(matched_galaxy['id']),\n np.round(matched_galaxy[catalog_ra], 6),\n np.round(matched_galaxy[catalog_dec], 6),\n matched_line['rfreq'],\n rest_frame_ghz,\n matched_key,\n matched_galaxy['z_1'],\n co_z,\n spec_z,\n delta_z,\n delta_v,\n kms,\n np.round(d2d[index].arcsecond, 4),\n matched_line['rsnrrbin'],\n matched_line['rpeak'],\n matched_line['rflux'],\n matched_line['width'],\n np.round(volume, 3),\n matched_galaxy['Mstar_50_1'],\n matched_galaxy['Mstar_84_1'] - matched_galaxy['Mstar_50_1'],\n matched_galaxy['SFR_50_1'],\n matched_galaxy['SFR_84_1'] - matched_galaxy['SFR_50_1'])\n aspecs_table.add_row(new_row)\n if not matched_to_galaxy:\n table_input = match_to_co_line(matched_line, max_redshift=max_redshift)\n if table_input is not None:\n aspecs_table.add_row(table_input)\n # Now need to clean up table, removing any inadvertently added rows\n prev_row_ra_dec = None\n prev_row_matched = None\n indicies_to_remove = []\n for index, row in enumerate(aspecs_table):\n if prev_row_ra_dec is not None:\n if row['RA (J2000)'] == prev_row_ra_dec[0] and row['DEC (J2000)'] == prev_row_ra_dec[1]:\n # Same one as before, check if galaxy, then check delta Z\n if prev_row_matched[0] > 0. and row['Roberto ID'] > 0.:\n # Matched to galaxy\n if np.abs(row['Delta Z']) < np.abs(prev_row_matched[1]):\n indicies_to_remove.append(index-1)\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n else: # Not better delta Z, so not add to prev\n indicies_to_remove.append(index)\n else: # Not matched to a galaxy\n if row['Roberto ID'] > 0.: # Row is matched to one\n indicies_to_remove.append(index-1)\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n else: # Not add to prev since current one is worse\n if np.abs(row['Delta Z']) < np.abs(prev_row_matched[1]):\n indicies_to_remove.append(index-1)\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n else:\n indicies_to_remove.append(index)\n else: # Not same galaxy\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n\n else: # No previous one\n prev_row_ra_dec = [row['RA (J2000)'], row['DEC (J2000)']]\n prev_row_matched = [row['Roberto ID'], row['Delta Z']]\n\n # Remove from the catalog\n aspecs_table.remove_rows(indicies_to_remove)\n\n catalog_ids = [i[1] for i in catalog_ids]\n\n # now have the catalog matches:\n spec_z_catalog = catalog[spec_z_catalog_ids]\n spec_z_catalog['z_co'] = np.zeros(shape=(spec_z_catalog['z_1'].shape))\n\n no_spec_z_catalog = catalog[no_spec_z_catalog_ids]\n no_spec_z_catalog['z_co'] = np.zeros(shape=(no_spec_z_catalog['z_1'].shape))\n\n aspecs_catalog = catalog[catalog_ids]\n aspecs_catalog['z_co'] = np.zeros(shape=(aspecs_catalog['z_1'].shape))\n # Add CO Z\n for line in aspecs_table:\n for index, row in enumerate(aspecs_catalog):\n if int(line['Roberto ID']) == int(row['id']):\n aspecs_catalog[index]['z_co'] = line[\"Z (CO)\"]\n for index, row in enumerate(spec_z_catalog):\n if int(line['Roberto ID']) == int(row['id']):\n spec_z_catalog[index]['z_co'] = line[\"Z (CO)\"]\n for index, row in enumerate(no_spec_z_catalog):\n if int(line['Roberto ID']) == int(row['id']):\n no_spec_z_catalog[index]['z_co'] = line[\"Z (CO)\"]\n\n return aspecs_table, aspecs_catalog, spec_z_catalog, no_spec_z_catalog\n\n"
]
| [
[
"numpy.int",
"numpy.zeros",
"numpy.round",
"numpy.nonzero",
"numpy.arange",
"numpy.abs",
"numpy.linspace"
]
]
|
hugolarzabal/hackathonbaobab2020 | [
"288e533bbe0a6fa2832fc388301d46b2a3b2169d"
]
| [
"core/batch.py"
]
| [
"# /usr/bin/python3\n\nfrom . import experiment as exp\nfrom . import tools as di\n\nimport pytups.tuplist as tl\nimport pytups.superdict as sd\n\nimport orloge as ol\nimport os\nimport zipfile\nimport pandas as pd\nimport shutil\nimport re\n\n\nclass Batch(object):\n \"\"\"\n This is a group of experiments.\n It reads a path of the form /PATH/TO/BATCH/ where:\n /PATH/TO/BATCH/scenario1/instance1/\n /PATH/TO/BATCH/scenario1/instance2/\n /PATH/TO/BATCH/scenario2/instance2/\n ...\n /PATH/TO/BATCH/scenarioX/instanceY/\n\n /PATH/TO/BATCH/scenario1/instance1/ is assumed to be the path for an experiment.\n i.e., exp.Experiment.from_dir('/PATH/TO/BATCH/scenario1/instance1/') should work.\n names are obtained by inspection so it can be any name for scenario or instance.\n\n if no_scenario is True:\n /PATH/TO/BATCH/instance1/\n /PATH/TO/BATCH/instance2/\n ...\n /PATH/TO/BATCH/instanceY/\n \"\"\"\n\n def __init__(self, path, no_scenario=False, scenarios=None, exp_obj=None):\n \"\"\"\n\n :param path: path to results\n :param no_scenario: if True, there is no scenarios, instances directly\n :param scenarios: in order to filter the scenarios to load\n \"\"\"\n self.path = path\n self.cases = None\n self.logs = None\n self.errors = None\n self.options = None\n self.seeds = None\n self.no_scenario = no_scenario\n self.scenarios = scenarios\n if exp_obj is None:\n self.load_experiment = exp.Experiment.from_json\n else:\n self.load_experiment = exp_obj.from_json\n\n def get_instances_paths(self):\n scenarios = self.scenarios\n if scenarios is None:\n scenarios = os.listdir(self.path)\n scenario_paths = {s: os.path.join(self.path, s) for s in scenarios}\n if self.no_scenario:\n return sd.SuperDict.from_dict(scenario_paths)\n scenario_instances = {s: os.listdir(v) for s, v in scenario_paths.items() if os.path.isdir(v)}\n scenario_paths_in, instances_paths_in = self.re_make_paths(scenario_instances)\n return sd.SuperDict.from_dict(instances_paths_in).to_dictup()\n\n def re_make_paths(self, scenario_instances):\n scenario_paths = {s: os.path.join(self.path, s) for s in scenario_instances}\n instances_paths = {s: {i: os.path.join(scenario_paths[s], i) for i in instances}\n for s, instances in scenario_instances.items()}\n return scenario_paths, instances_paths\n\n def get_cases(self):\n if self.cases is not None:\n return self.cases\n\n load_data = self.load_experiment\n self.cases = self.get_instances_paths().vapply(load_data)\n return self.cases\n\n def get_solver(self):\n opt_info = self.get_options()\n available_solvers = ['CPLEX', 'GUROBI', 'CBC']\n default = 'CPLEX'\n try:\n el = list(opt_info.keys())[0]\n engine = opt_info[el]['solver']\n except:\n return default\n if '.' in engine:\n engine, solver = engine.split('.')\n else:\n solver = engine\n if solver in available_solvers:\n return solver\n # one last try\n for s in available_solvers:\n if re.search(s, solver):\n return s\n return default\n\n def get_logs(self, get_progress=False):\n if self.logs is not None:\n return self.logs\n\n solver = self.get_solver()\n\n self.logs = \\\n self.get_instances_paths(). \\\n vapply(lambda v: os.path.join(v, 'results.log')).\\\n clean(func=os.path.exists). \\\n vapply(lambda v: ol.get_info_solver(v, solver, get_progress=get_progress))\n return self.logs\n\n def get_json(self, name):\n load_data = di.load_data\n\n return \\\n self.get_instances_paths().\\\n vapply(lambda v: os.path.join(v, name)). \\\n vapply(load_data). \\\n clean(). \\\n vapply(sd.SuperDict.from_dict)\n\n def get_errors(self):\n if self.errors is not None:\n return self.errors\n\n self.errors = self.get_cases().vapply(lambda v: v.check_solution()).to_lendict()\n return self.errors\n\n def get_objective_function(self):\n return self.get_cases().vapply(lambda v: v.get_objective())\n\n def get_options(self):\n if self.options is not None:\n return self.options\n self.options = self.get_json('options.json')\n return self.options\n\n def get_errors_df(self):\n errors = self.get_errors()\n return self.format_df(errors).rename(columns={0: 'errors'})\n\n def get_seeds(self):\n if self.seeds is not None:\n return self.seeds\n self.seeds = self.get_options().get_property('simulation').get_property('seed')\n return self.seeds\n\n def format_df(self, table):\n seeds = self.get_seeds()\n table = table.to_df(orient='index')\n axis_name = 'name'\n if not self.no_scenario:\n table.index = pd.MultiIndex.from_tuples(table.index)\n axis_name = ('scenario', 'name')\n table['instance'] = table.index.map(seeds)\n return table.rename_axis(axis_name).reset_index()\n\n def get_log_df(self, **kwargs):\n log_info = self.get_logs(**kwargs)\n table = self.format_df(log_info)\n\n for name in ['matrix', 'presolve', 'matrix_post']:\n try:\n aux_table = table[name].apply(pd.Series)\n aux_table.columns = [name + '_' + c for c in aux_table.columns]\n table = pd.concat([table, aux_table], axis=1)\n except:\n pass\n\n return table\n\n def get_status_df(self):\n table = self.get_log_df()\n vars_extract = ['scenario', 'name', 'sol_code', 'status_code',\n 'time', 'gap', 'best_bound', 'best_solution']\n\n master = \\\n pd.DataFrame({'sol_code': [ol.LpSolutionIntegerFeasible, ol.LpSolutionOptimal,\n ol.LpSolutionInfeasible, ol.LpSolutionNoSolutionFound],\n 'status': ['IntegerFeasible', 'Optimal', 'Infeasible', 'NoIntegerFound']})\n\n status_df = table.filter(vars_extract).merge(master, on='sol_code')\n\n status_df['gap_abs'] = status_df.best_solution - status_df.best_bound\n return status_df\n\n def list_experiments(self, exp_list=None, get_log_info=True, get_exp_info=True):\n \"\"\"\n\n :param exp_list: a list to filter cases to return\n :param get_log_info: whether to get or not information on the log files\n :param get_exp_info: whether to get or not information on the instances\n :return: dictionary of examples per each instance\n \"\"\"\n notNone = lambda x: x is not None\n exp_info = {}\n log_info = {}\n opt_info = self.get_options()\n if get_exp_info:\n cases = self.get_cases().clean(func=notNone)\n exp_info = cases.vapply(lambda v: v.instance.get_param())\n inst_info = cases.vapply(lambda v: v.instance.get_info())\n exp_info.update(inst_info)\n if get_log_info:\n log_info = self.get_logs()\n exp_info.update(log_info)\n exp_info.update(opt_info)\n if exp_list:\n return exp_info.filter(exp_list)\n return exp_info\n\n def clean_experiments(self, clean=True, func=None):\n \"\"\"\n loads and cleans all experiments that are incomplete\n :param clean: if set to false it only shows the files instead of deleting them\n :param func: optional function to filter cases\n :return: deleted experiments\n \"\"\"\n\n cases = self.get_cases()\n if func is not None:\n func = lambda x: x is None\n cases = cases.clean(func=func)\n paths = self.get_instances_paths().filter(cases.keys_l())\n\n if clean:\n for path in paths.values():\n shutil.rmtree(path)\n return paths.values_l()\n\n\nclass ZipBatch(Batch):\n \"\"\"\n Only difference is it's contained inside a zip file.\n \"\"\"\n def __init__(self, path, *args, **kwargs):\n name, ext = os.path.splitext(path)\n zip_ext = '.zip'\n if not ext:\n path = name + zip_ext\n elif ext != zip_ext:\n raise ValueError('Only zip is supported')\n super().__init__(path, *args, **kwargs)\n\n def get_instances_paths(self):\n num_slashes = 2\n keys_positions = [1, 2]\n if self.no_scenario:\n num_slashes = 1\n keys_positions = 1\n zipobj = zipfile.ZipFile(self.path)\n all_files = tl.TupList(di.dirs_in_zip(zipobj))\n scenario_instances = \\\n all_files.\\\n vfilter(lambda f: f.count(\"/\") == num_slashes)\n keys = \\\n scenario_instances.\\\n vapply(str.split, '/').\\\n vapply(tuple).\\\n take(keys_positions)\n result_dict = sd.SuperDict(zip(keys, scenario_instances))\n if self.scenarios:\n scenarios = set(self.scenarios)\n return result_dict.kfilter(lambda k: k[0] in scenarios)\n else:\n return result_dict\n\n def get_cases(self):\n if self.cases is not None:\n return self.cases\n\n zipobj = zipfile.ZipFile(self.path)\n load_data = lambda e: exp.Experiment.from_zipped_json(zipobj, e)\n self.cases = self.get_instances_paths().vapply(load_data)\n return self.cases\n\n def get_logs(self, get_progress=False, solver=None):\n if self.logs is not None:\n return self.logs\n\n zipobj = zipfile.ZipFile(self.path)\n if not solver:\n solver = self.get_solver()\n\n def _read_zip(x):\n try:\n return zipobj.read(x)\n except:\n return 0\n\n func_to_get_log = ol.get_info_solver\n filename = '/results.log'\n\n self.logs = \\\n self.get_instances_paths(). \\\n vapply(lambda v: v + filename).\\\n vapply(_read_zip). \\\n clean(). \\\n vapply(lambda x: str(x, 'utf-8')). \\\n vapply(lambda v: func_to_get_log(v, solver, get_progress=get_progress, content=True))\n return self.logs\n\n def get_json(self, name):\n zipobj = zipfile.ZipFile(self.path)\n load_data = lambda v: di.load_data_zip(zipobj=zipobj, path=v)\n\n return \\\n self.get_instances_paths().\\\n vapply(lambda v: v + '/' + name). \\\n vapply(load_data). \\\n clean(). \\\n vapply(sd.SuperDict.from_dict)\n\n"
]
| [
[
"pandas.DataFrame",
"pandas.MultiIndex.from_tuples",
"pandas.concat"
]
]
|
Originofamonia/SHOT | [
"d79909009e5dd06658fa15e951fed97f1a89496b"
]
| [
"digit/data_load/utils.py"
]
| [
"import os\nimport os.path\nimport hashlib\nimport gzip\nimport errno\nimport tarfile\nimport zipfile\n\nimport torch\nfrom torch.utils.model_zoo import tqdm\n\n\ndef gen_bar_updater():\n pbar = tqdm(total=None)\n\n def bar_update(count, block_size, total_size):\n if pbar.total is None and total_size:\n pbar.total = total_size\n progress_bytes = count * block_size\n pbar.update(progress_bytes - pbar.n)\n\n return bar_update\n\n\ndef calculate_md5(fpath, chunk_size=1024 * 1024):\n md5 = hashlib.md5()\n with open(fpath, 'rb') as f:\n for chunk in iter(lambda: f.read(chunk_size), b''):\n md5.update(chunk)\n return md5.hexdigest()\n\n\ndef check_md5(fpath, md5, **kwargs):\n return md5 == calculate_md5(fpath, **kwargs)\n\n\ndef check_integrity(fpath, md5=None):\n if not os.path.isfile(fpath):\n return False\n if md5 is None:\n return True\n return check_md5(fpath, md5)\n\n\ndef download_url(url, root, filename=None, md5=None):\n \"\"\"Download a file from a url and place it in root.\n\n Args:\n url (str): URL to download file from\n root (str): Directory to place downloaded file in\n filename (str, optional): Name to save the file under. If None, use the basename of the URL\n md5 (str, optional): MD5 checksum of the download. If None, do not check\n \"\"\"\n import urllib\n\n root = os.path.expanduser(root)\n if not filename:\n filename = os.path.basename(url)\n fpath = os.path.join(root, filename)\n\n os.makedirs(root, exist_ok=True)\n\n # check if file is already present locally\n if check_integrity(fpath, md5):\n print('Using downloaded and verified file: ' + fpath)\n else: # download the file\n try:\n print('Downloading ' + url + ' to ' + fpath)\n urllib.request.urlretrieve(\n url, fpath,\n reporthook=gen_bar_updater()\n )\n except (urllib.error.URLError, IOError) as e:\n if url[:5] == 'https':\n url = url.replace('https:', 'http:')\n print('Failed download. Trying https -> http instead.'\n ' Downloading ' + url + ' to ' + fpath)\n urllib.request.urlretrieve(\n url, fpath,\n reporthook=gen_bar_updater()\n )\n else:\n raise e\n # check integrity of downloaded file\n if not check_integrity(fpath, md5):\n raise RuntimeError(\"File not found or corrupted.\")\n\n\ndef list_dir(root, prefix=False):\n \"\"\"List all directories at a given root\n\n Args:\n root (str): Path to directory whose folders need to be listed\n prefix (bool, optional): If true, prepends the path to each result, otherwise\n only returns the name of the directories found\n \"\"\"\n root = os.path.expanduser(root)\n directories = list(\n filter(\n lambda p: os.path.isdir(os.path.join(root, p)),\n os.listdir(root)\n )\n )\n\n if prefix is True:\n directories = [os.path.join(root, d) for d in directories]\n\n return directories\n\n\ndef list_files(root, suffix, prefix=False):\n \"\"\"List all files ending with a suffix at a given root\n\n Args:\n root (str): Path to directory whose folders need to be listed\n suffix (str or tuple): Suffix of the files to match, e.g. '.png' or ('.jpg', '.png').\n It uses the Python \"str.endswith\" method and is passed directly\n prefix (bool, optional): If true, prepends the path to each result, otherwise\n only returns the name of the files found\n \"\"\"\n root = os.path.expanduser(root)\n files = list(\n filter(\n lambda p: os.path.isfile(os.path.join(root, p)) and p.endswith(suffix),\n os.listdir(root)\n )\n )\n\n if prefix is True:\n files = [os.path.join(root, d) for d in files]\n\n return files\n\n\ndef download_file_from_google_drive(file_id, root, filename=None, md5=None):\n \"\"\"Download a Google Drive file from and place it in root.\n\n Args:\n file_id (str): id of file to be downloaded\n root (str): Directory to place downloaded file in\n filename (str, optional): Name to save the file under. If None, use the id of the file.\n md5 (str, optional): MD5 checksum of the download. If None, do not check\n \"\"\"\n # Based on https://stackoverflow.com/questions/38511444/python-download-files-from-google-drive-using-url\n import requests\n url = \"https://docs.google.com/uc?export=download\"\n\n root = os.path.expanduser(root)\n if not filename:\n filename = file_id\n fpath = os.path.join(root, filename)\n\n os.makedirs(root, exist_ok=True)\n\n if os.path.isfile(fpath) and check_integrity(fpath, md5):\n print('Using downloaded and verified file: ' + fpath)\n else:\n session = requests.Session()\n\n response = session.get(url, params={'id': file_id}, stream=True)\n token = _get_confirm_token(response)\n\n if token:\n params = {'id': file_id, 'confirm': token}\n response = session.get(url, params=params, stream=True)\n\n _save_response_content(response, fpath)\n\n\ndef _get_confirm_token(response):\n for key, value in response.cookies.items():\n if key.startswith('download_warning'):\n return value\n\n return None\n\n\ndef _save_response_content(response, destination, chunk_size=32768):\n with open(destination, \"wb\") as f:\n pbar = tqdm(total=None)\n progress = 0\n for chunk in response.iter_content(chunk_size):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n progress += len(chunk)\n pbar.update(progress - pbar.n)\n pbar.close()\n\n\ndef _is_tarxz(filename):\n return filename.endswith(\".tar.xz\")\n\n\ndef _is_tar(filename):\n return filename.endswith(\".tar\")\n\n\ndef _is_targz(filename):\n return filename.endswith(\".tar.gz\")\n\n\ndef _is_tgz(filename):\n return filename.endswith(\".tgz\")\n\n\ndef _is_gzip(filename):\n return filename.endswith(\".gz\") and not filename.endswith(\".tar.gz\")\n\n\ndef _is_zip(filename):\n return filename.endswith(\".zip\")\n\n\ndef extract_archive(from_path, to_path=None, remove_finished=False):\n if to_path is None:\n to_path = os.path.dirname(from_path)\n\n if _is_tar(from_path):\n with tarfile.open(from_path, 'r') as tar:\n tar.extractall(path=to_path)\n elif _is_targz(from_path) or _is_tgz(from_path):\n with tarfile.open(from_path, 'r:gz') as tar:\n tar.extractall(path=to_path)\n elif _is_tarxz(from_path):\n with tarfile.open(from_path, 'r:xz') as tar:\n tar.extractall(path=to_path)\n elif _is_gzip(from_path):\n to_path = os.path.join(to_path, os.path.splitext(os.path.basename(from_path))[0])\n with open(to_path, \"wb\") as out_f, gzip.GzipFile(from_path) as zip_f:\n out_f.write(zip_f.read())\n elif _is_zip(from_path):\n with zipfile.ZipFile(from_path, 'r') as z:\n z.extractall(to_path)\n else:\n raise ValueError(\"Extraction of {} not supported\".format(from_path))\n\n if remove_finished:\n os.remove(from_path)\n\n\ndef download_and_extract_archive(url, download_root, extract_root=None, filename=None,\n md5=None, remove_finished=False):\n download_root = os.path.expanduser(download_root)\n if extract_root is None:\n extract_root = download_root\n if not filename:\n filename = os.path.basename(url)\n\n download_url(url, download_root, filename, md5)\n\n archive = os.path.join(download_root, filename)\n print(\"Extracting {} to {}\".format(archive, extract_root))\n extract_archive(archive, extract_root, remove_finished)\n\n\ndef iterable_to_str(iterable):\n return \"'\" + \"', '\".join([str(item) for item in iterable]) + \"'\"\n\n\ndef verify_str_arg(value, arg=None, valid_values=None, custom_msg=None):\n if not isinstance(value, torch._six.string_classes):\n if arg is None:\n msg = \"Expected type str, but got type {type}.\"\n else:\n msg = \"Expected type str for argument {arg}, but got type {type}.\"\n msg = msg.format(type=type(value), arg=arg)\n raise ValueError(msg)\n\n if valid_values is None:\n return value\n\n if value not in valid_values:\n if custom_msg is not None:\n msg = custom_msg\n else:\n msg = (\"Unknown value '{value}' for argument {arg}. \"\n \"Valid values are {{{valid_values}}}.\")\n msg = msg.format(value=value, arg=arg,\n valid_values=iterable_to_str(valid_values))\n raise ValueError(msg)\n\n return value"
]
| [
[
"torch.utils.model_zoo.tqdm"
]
]
|
JohnySilva/mlhep-2021-comp2-code | [
"3b4f91e91a8ad833f6e4bd7d21af5cd1adba4da7"
]
| [
"idao/model.py"
]
| [
"import pytorch_lightning as pl\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n#%%\n\nclass Print(nn.Module):\n \"\"\"Debugging only\"\"\"\n\n def forward(self, x):\n print(x.size())\n return x\n\nclass Clamp(nn.Module):\n \"\"\"Clamp energy output\"\"\"\n\n def forward(self, x):\n x = torch.clamp(x, min=0, max=30)\n return x\n\n#%%\nclass SimpleConv(pl.LightningModule):\n def __init__(self, mode: [\"classification\", \"regression\"] = \"classification\"):\n super().__init__()\n self.mode = mode\n self.layer1 = nn.Sequential(\n nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),\n nn.BatchNorm2d(16),\n nn.ReLU(),\n ##\n #nn.Dropout(),\n nn.Conv2d(16, 16, kernel_size=5, stride=1, padding=2),\n nn.BatchNorm2d(16),\n nn.ReLU(),\n ##\n nn.MaxPool2d(kernel_size=19, stride=7),\n nn.Flatten(),\n )\n self.drop_out = nn.Dropout()\n \n #feature maps need to be 60x60 here\n self.fc1 = nn.Linear(3600, 500)\n #self.fc1 = nn.Linear(114*114, 500)\n self.fc2 = nn.Linear(500, 2) # for classification\n self.fc3 = nn.Linear(500, 1) # for regression\n\n\n self.stem = nn.Sequential(\n self.layer1, self.drop_out, self.fc1,# nn.ReLU()\n )\n if self.mode == \"classification\":\n self.classification = nn.Sequential(self.stem, self.fc2)\n else:\n self.regression = nn.Sequential(self.stem, self.fc3)\n\n self.train_acc = pl.metrics.Accuracy()\n self.valid_acc = pl.metrics.Accuracy()\n self.test_acc = pl.metrics.Accuracy()\n\n def training_step(self, batch, batch_idx):\n # --------------------------\n x_target, class_target, reg_target, _ = batch\n if self.mode == \"classification\":\n class_pred = self.classification(x_target.float())\n class_loss = F.binary_cross_entropy_with_logits(\n class_pred, class_target.float()\n )\n self.train_acc(torch.sigmoid(class_pred), class_target)\n self.log(\"train_acc\", self.train_acc, on_step=True, on_epoch=False)\n self.log(\"classification_loss\", class_loss)\n\n return class_loss\n\n else:\n reg_pred = self.regression(x_target.float())\n # reg_loss = F.l1_loss(reg_pred, reg_target.float().view(-1, 1))\n reg_loss = F.mse_loss(reg_pred, reg_target.float().view(-1, 1))\n\n #reg_loss = torch.sum(torch.abs(reg_pred - reg_target.float().view(-1, 1)) / reg_target.float().view(-1, 1))\n self.log(\"regression_loss\", reg_loss)\n self.log(\"train_loss\", reg_loss, on_step=False, on_epoch=True, prog_bar=True)\n return reg_loss\n\n def training_epoch_end(self, outs):\n # log epoch metric\n if self.mode == \"classification\":\n self.log(\"train_acc_epoch\", self.train_acc.compute())\n else:\n pass\n\n def validation_step(self, batch, batch_idx):\n x_target, class_target, reg_target, _ = batch\n if self.mode == \"classification\":\n class_pred = self.classification(x_target.float())\n class_loss = F.binary_cross_entropy_with_logits(\n class_pred, class_target.float()\n )\n self.valid_acc(torch.sigmoid(class_pred), class_target)\n self.log(\"valid_acc\", self.valid_acc.compute())\n self.log(\"classification_loss\", class_loss)\n return class_loss\n\n else:\n reg_pred = self.regression(x_target.float())\n # reg_loss = F.l1_loss(reg_pred, reg_target.float().view(-1, 1))\n reg_loss = F.mse_loss(reg_pred, reg_target.float().view(-1, 1))\n\n #reg_loss = torch.sum(torch.abs(reg_pred - reg_target.float().view(-1, 1)) / reg_target.float().view(-1, 1))\n self.log(\"regression_loss\", reg_loss)\n self.log(\"val_loss\", reg_loss, on_step=False, on_epoch=True, prog_bar=True)\n return reg_loss\n \n # def test_step(self, batch, batch_idx):\n# # --------------------------\n# x_target, class_target, _, reg_target = batch\n# if self.mode == \"classification\":\n# class_pred = self.classification(x_target.float())\n# class_loss = F.binary_cross_entropy_with_logits(\n# class_pred, class_target.float()\n# )\n# self.test_acc(torch.sigmoid(class_pred), class_target)\n# self.log(\"test_acc\", self.train_acc, on_step=True, on_epoch=False)\n# self.log(\"classification_loss\", class_loss)\n# return class_loss\n#\n# else:\n# reg_pred = self.regression(x_target.float())\n# # reg_loss = F.l1_loss(reg_pred, reg_target.float().view(-1, 1))\n# reg_loss = F.mse_loss(reg_pred, reg_target.float().view(-1, 1))\n#\n# # reg_loss = torch.sum(torch.abs(reg_pred - reg_target.float().view(-1, 1)) /reg_target.float().view(-1, 1))\n# self.log(\"regression_loss\", reg_loss)\n# return reg_loss\n\n # return exp_predicted, class_target\n\n # --------------------------\n\n# def test_epoch_end(self, test_step_outputs):\n# print(self.test_acc.compute())\n#\n def configure_optimizers(self):\n #optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)\n #optimizer = torch.optim.Adam(self.parameters(), lr=1e-4, weight_decay=1e-3)\n optimizer = torch.optim.Adam(self.parameters(), lr=1e-4, weight_decay=1e-3)\n #scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.82)\n return optimizer\n\n def forward(self, x):\n if self.mode == \"classification\":\n class_pred = self.classification(x.float())\n return {\"class\": torch.sigmoid(class_pred)}\n else:\n reg_pred = self.regression(x.float())\n return {\"energy\": reg_pred}\n#%%"
]
| [
[
"torch.nn.Linear",
"torch.sigmoid",
"torch.nn.Dropout",
"torch.nn.MaxPool2d",
"torch.nn.Sequential",
"torch.nn.BatchNorm2d",
"torch.clamp",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.nn.Flatten"
]
]
|
StonedCoal/OakNet-Multiroom-Audio-System | [
"2d1a71c70055e2646187efb5955aa48de3076ca6"
]
| [
"Receiver/audioBackendPyAudio.py"
]
| [
"import pyaudio\nimport audioop\nimport array\nimport datetime\nimport network\nfrom datetime import timedelta, datetime\nimport asyncio\n\nimport pyaudio\n\nimport numpy\n\np = pyaudio.PyAudio()\ninfo = p.get_host_api_info_by_index(0)\nnumdevices = info.get('deviceCount')\navailableInputDevices = dict()\navailableOutputDevices = dict()\n\nfor i in range(0, numdevices):\n if (p.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:\n availableInputDevices[i] = p.get_device_info_by_host_api_device_index(0, i).get('name');\n \n\nfor i in range(0, numdevices):\n if (p.get_device_info_by_host_api_device_index(0, i).get('maxOutputChannels')) > 0:\n availableOutputDevices[i] = p.get_device_info_by_host_api_device_index(0, i).get('name');\n #print(\"Output Device id \", i, \" - \", p.get_device_info_by_host_api_device_index(0, i).get('name'))\n\nactiveInputDevice = 5\np = pyaudio.PyAudio()\npeaks = dict()\nbuffer = list()\nisBuffering = 0\nbufferGoal = 50\nbufferRange = 5\nbufferRangeTight = 3\nbufferTightCyclus = 850\nlastTimestamp=0\nframeBufferSizeMultiplicator = 1\nbufferSizeMedian = list()\nbufferSizeMedianValue = 0\nmaxVolume = 100\nvolume = 100\n\nisInitialized = False\n\nframesPerBuffer = (network.packetSize/4)*frameBufferSizeMultiplicator\n\n\ndef getAvailableInputDevices():\n return availableInputDevices\n\ndef getAvailableOutputDevices():\n return availableOutputDevices\n\ndef getCurrentBufferSize():\n return bufferSizeMedianValue\n\ndef getVolume():\n return volume\n\ndef setVolume(value):\n volume = value\n\ndef setConfig(config):\n global bufferGoal, bufferRange, bufferRangeTight, frameBufferSizeMultiplicator, framesPerBuffer, maxVolume\n bufferGoal = config[\"audioBackend\"][\"bufferGoal\"]\n bufferRange = config[\"audioBackend\"][\"bufferRange\"]\n bufferRangeTight = config[\"audioBackend\"][\"bufferRangeTight\"]\n frameBufferSizeMultiplicator = config[\"audioBackend\"][\"frameBufferSizeMultiplicator\"]\n maxVolume = config[\"audioBackend\"][\"maxVolume\"]\n framesPerBuffer = (network.packetSize/4)*frameBufferSizeMultiplicator\n \ndef changeVolume(chunkRaw, volume):\n global maxVolume\n volumeNormalized = (maxVolume/100.0)*volume\n sound_level = (volumeNormalized / 100.0)\n\n dt = numpy.dtype(numpy.int16)\n dt = dt.newbyteorder(\"<\")\n chunkNumpy = numpy.frombuffer(chunkRaw, dtype=dt)\n chunkNumpy = chunkNumpy * sound_level\n chunkNumpy = chunkNumpy.astype(dt)\n return chunkNumpy.tobytes()\n\n\nasync def send(data):\n network.sendBatch(data)\n\nasync def calcPeak(data, deviceId):\n peakVal = audioop.rms(data, 2) \n peaks[deviceId] = peakVal\n\ndef createCallback(deviceId):\n def callbackFunc(in_data, frame_count, time_info, status):\n in_data = bytearray(in_data)\n asyncio.run(calcPeak(in_data[:128], deviceId))\n if(activeInputDevice == deviceId):\n asyncio.run(send(in_data))\n return None, pyaudio.paContinue\n return callbackFunc\n\ndef addInputDevice(inDeviceId):\n stream = p.open(format=p.get_format_from_width(2), channels=2,rate=44100, input=True,input_device_index = inDeviceId, frames_per_buffer=int(framesPerBuffer), stream_callback=createCallback(inDeviceId))\n stream.start_stream()\n\ndef outCallback(inData, frame_count, time_info, status):\n global isBuffering, isInitialized, bufferRange, bufferRangeTight, bufferTightCyclus, lastTimestamp, bufferSizeMedian, bufferSizeMedianValue, volume\n bufferSizeMedian.append(len(buffer))\n if(not isInitialized):\n if(len(buffer) < bufferGoal):\n return b'\\x00'*(network.packetSize*frameBufferSizeMultiplicator), pyaudio.paContinue\n else:\n isInitialized = True\n \n if(len(buffer) == 0):\n isInitialized = False\n \n if(lastTimestamp<=0):\n sum = 0\n for value in bufferSizeMedian:\n sum = sum + value;\n bufferSizeMedianValue = int(sum / len(bufferSizeMedian))\n print(\"Current Buffer Size: \" + str(bufferSizeMedianValue) + \" | Goal: \" + str(bufferGoal) + \" | Tight Range: \" + str(bufferRangeTight))\n bufferSizeMedian.clear()\n divisor = abs(bufferSizeMedianValue-bufferGoal) - bufferRangeTight\n if(divisor < 1):\n divisor = 1\n lastTimestamp = bufferTightCyclus / divisor\n if(bufferSizeMedianValue>bufferGoal+bufferRangeTight):\n buffer.pop(0)\n print(\"Tight Adjustment removed a Frame\")\n elif(bufferSizeMedianValue<bufferGoal-bufferRangeTight):\n print(\"Tight Adjustment added a Frame\")\n return b'\\x00'*(network.packetSize*frameBufferSizeMultiplicator), pyaudio.paContinue\n \n else:\n lastTimestamp=lastTimestamp-1\n if(len(buffer) < bufferGoal - bufferRange):\n print(\"Underrun\")\n if(isBuffering>0):\n isBuffering=isBuffering-1\n return b'\\x00'*(network.packetSize*frameBufferSizeMultiplicator), pyaudio.paContinue\n else:\n isBuffering = frameBufferSizeMultiplicator\n if(len(buffer) > bufferGoal + bufferRange):\n print(\"Overflow\")\n buffer.pop(0)\n if(len(buffer)<frameBufferSizeMultiplicator):\n return b'\\x00'*(network.packetSize*frameBufferSizeMultiplicator), pyaudio.paContinue\n buildBuffer=buffer.pop(0)\n for i in range(0, frameBufferSizeMultiplicator-1):\n buildBuffer= buildBuffer+buffer.pop(0)\n \n buildBuffer = changeVolume(buildBuffer, volume)\n \n return buildBuffer, pyaudio.paContinue\n\ninStream=None\nlastDeviceId=None\ndef setOutputDevice(outDeviceId):\n global lastDeviceId, inStream\n if(outDeviceId == None):\n outDeviceId=lastDeviceId\n else:\n lastDeviceId=outDeviceId\n\n if (inStream != None):\n inStream.close()\n\n inStream = p.open(format = p.get_format_from_width(2), channels = 2, rate = 44100, output = True, output_device_index=outDeviceId, stream_callback=outCallback, frames_per_buffer=int(framesPerBuffer))\n print(\"Starting Audio Stream on Device: \"+ str(outDeviceId))\n inStream.start_stream()"
]
| [
[
"numpy.dtype",
"numpy.frombuffer"
]
]
|
yanpei18345156216/COMBO_Python3 | [
"666a116dfece71e6236291e89ea2ab4d6db0ead9"
]
| [
"combo/blm/lik/linear.py"
]
| [
"import numpy as np\n\n\nclass linear(object):\n def __init__(self, basis, params=None, bias=None):\n self.basis = basis\n self.nbasis = basis.nbasis\n self._init_params = params\n self.bias = bias\n self.params = params\n\n if params is None:\n self.params = np.zeros(self.nbasis)\n self.nparams = self.nbasis\n\n def get_mean(self, X, Psi=None, params=None, bias=None):\n if params is None:\n params = np.copy(self.params)\n\n if bias is None:\n bias = np.copy(self.bias)\n\n if Psi is None:\n Psi = self.get_basis(X)\n\n return Psi.dot(params) + bias\n\n def set_params(self, params):\n self.params = params\n\n def set_bias(self, bias):\n self.bias = bias\n\n def _init_params(self, params):\n if params is None:\n self.params = np.zeros(self.nbasis)\n\n self.params = params\n\n def _init_bias(self, bias):\n if bias is None:\n self.bias = 0\n\n self.bias = bias\n"
]
| [
[
"numpy.copy",
"numpy.zeros"
]
]
|
tteeoo/robotfrost | [
"5dfd13e1338e84a3eb5cbcc23100328967566b49"
]
| [
"robotfrost.py"
]
| [
"#!/usr/bin/env python3\nimport argparse\n\n# Define args\nparser = argparse.ArgumentParser()\nparser.add_argument(\n '-e',\n '--epochs',\n type = int,\n help = 'the number of epochs to go through when training',\n default = 20\n)\nparser.add_argument(\n '-b',\n '--batch-size',\n type = int,\n help = 'the batch size to be used when training',\n default = 128\n)\nparser.add_argument(\n '-s',\n '--sequence-length',\n type = int,\n help = 'the sequence length to be used when training',\n default = 16\n)\nparser.add_argument(\n '-c',\n '--cuda',\n type = bool,\n help = 'wether or not to use the gpu when training',\n default = False\n)\nparser.add_argument(\n '-g',\n '--generate',\n type = bool,\n help = 'set to True to generate a poem instead of train',\n default = False\n)\nparser.add_argument(\n '-t',\n '--starting-text',\n help = 'the starting text to be used when generating',\n type = str,\n default = ''\n)\nparser.add_argument(\n '-l',\n '--poem-length',\n help = 'the length of the poem to generate (in words)',\n type = int,\n default = 75\n)\nargs = parser.parse_args()\n\n# Import here so not to have a delay for --help\nfrom torch import load, save, device\nfrom train import train\nfrom poem import poem\nfrom model import RobotFrost\nfrom dataset import GutenbergDataset\n\n# Instantiate model and dataset\ndataset = GutenbergDataset(args.sequence_length)\nmodel = RobotFrost(dataset)\n\n# Try to load model\ntry:\n model.load_state_dict(load('./state.dict.pth', map_location=device('cpu')))\nexcept Exception as e:\n print('exception,', e, '... using new model')\n\n# Predict\nif args.generate:\n print(poem(model, dataset, args.starting_text, args.poem_length))\n exit(0)\n\n# Train\ntry:\n if args.cuda: model = model.to('cuda')\n train(model, dataset, args.epochs, args.batch_size, args.sequence_length, args.cuda)\nexcept KeyboardInterrupt:\n pass\n\n# Save model\nsave(model.state_dict(), './state.dict.pth')\n"
]
| [
[
"torch.device"
]
]
|
zfjsail/transfer | [
"2cc2a73b579fb57714079f94a9f4ffe6b8a4acb4"
]
| [
"train_cnn_match.py"
]
| [
"from __future__ import unicode_literals\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nfrom os.path import join\nimport os\nimport numpy as np\nimport time\n\nimport torch\nfrom torch.utils.data import DataLoader\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom sklearn.metrics import precision_recall_fscore_support\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import precision_recall_curve\n\nfrom dataset import ProcessedCNNInputDataset\nfrom models.cnn import CNNMatchModel\nfrom utils.data_utils import ChunkSampler\nfrom utils import settings\n\nimport logging\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') # include timestamp\n\n# Training settings\nparser = argparse.ArgumentParser()\nparser.add_argument('--no-cuda', action='store_true', default=False, help='Disables CUDA training.')\nparser.add_argument('--matrix-size1', type=int, default=7, help='Matrix size 1.')\nparser.add_argument('--matrix-size2', type=int, default=4, help='Matrix size 2.')\nparser.add_argument('--mat1-channel1', type=int, default=4, help='Matrix1 number of channels1.')\nparser.add_argument('--mat1-kernel-size1', type=int, default=3, help='Matrix1 kernel size1.')\nparser.add_argument('--mat1-channel2', type=int, default=8, help='Matrix1 number of channel2.')\nparser.add_argument('--mat1-kernel-size2', type=int, default=2, help='Matrix1 kernel size2.')\nparser.add_argument('--mat1-hidden', type=int, default=64, help='Matrix1 hidden dim.')\nparser.add_argument('--mat2-channel1', type=int, default=4, help='Matrix2 number of channels1.')\nparser.add_argument('--mat2-kernel-size1', type=int, default=2, help='Matrix2 kernel size1.')\nparser.add_argument('--mat2-hidden', type=int, default=64, help='Matrix2 hidden dim')\nparser.add_argument('--build-index-window', type=int, default=5, help='Matrix2 hidden dim')\nparser.add_argument('--seed', type=int, default=42, help='Random seed.')\nparser.add_argument('--seed-delta', type=int, default=0, help='Random seed.')\nparser.add_argument('--epochs', type=int, default=200, help='Number of epochs to train.')\nparser.add_argument('--lr', type=float, default=1e-2, help='Initial learning rate.')\nparser.add_argument('--initial-accumulator-value', type=float, default=0.01, help='Initial accumulator value.')\nparser.add_argument('--weight-decay', type=float, default=1e-3,\n help='Weight decay (L2 loss on parameters).')\nparser.add_argument('--dropout', type=float, default=0.2,\n help='Dropout rate (1 - keep probability).')\nparser.add_argument('--batch', type=int, default=32, help=\"Batch size\")\nparser.add_argument('--check-point', type=int, default=2, help=\"Check point\")\nparser.add_argument('--shuffle', action='store_true', default=True, help=\"Shuffle dataset\")\nparser.add_argument('--entity-type', type=str, default=\"aff\", help=\"Types of entities to match\")\n\nparser.add_argument('--file-dir', type=str, default=settings.AFF_DATA_DIR, help=\"Input file directory\")\nparser.add_argument('--train-ratio', type=float, default=10, help=\"Training ratio (0, 100)\")\nparser.add_argument('--valid-ratio', type=float, default=10, help=\"Validation ratio (0, 100)\")\n\n\nargs = parser.parse_args()\n\nwriter = SummaryWriter('runs/{}_cnn_{}'.format(args.entity_type, args.seed_delta))\n\n\ndef train(epoch, train_loader, valid_loader, test_loader, model, optimizer, args=args):\n model.train()\n\n loss = 0.\n total = 0.\n\n for i_batch, batch in enumerate(train_loader):\n X_title, X_author, Y = batch\n\n bs = Y.shape[0]\n\n if args.cuda:\n X_title = X_title.cuda()\n X_author = X_author.cuda()\n Y = Y.cuda()\n\n optimizer.zero_grad()\n output, hidden = model(X_title.float(), X_author.float())\n\n loss_train = F.nll_loss(output, Y.long())\n loss += bs * loss_train.item()\n total += bs\n loss_train.backward()\n optimizer.step()\n logger.info(\"train loss epoch %d: %f\", epoch, loss / total)\n\n writer.add_scalar('training_loss',\n loss / total,\n epoch)\n\n metrics_val = None\n metrics_test = None\n\n if (epoch + 1) % args.check_point == 0:\n logger.info(\"epoch %d, checkpoint! validation...\", epoch)\n best_thr, metrics_val = evaluate(epoch, valid_loader, model, return_best_thr=True, args=args)\n logger.info('eval on test data!...')\n _, metrics_test = evaluate(epoch, test_loader, model, thr=best_thr, args=args)\n\n return metrics_val, metrics_test\n\n\ndef evaluate(epoch, loader, model, thr=None, return_best_thr=False, args=args):\n model.eval()\n total = 0.\n loss = 0.\n y_true, y_pred, y_score = [], [], []\n\n for i_batch, batch in enumerate(loader):\n X_title, X_author, Y = batch\n bs = len(Y)\n\n if args.cuda:\n X_title = X_title.cuda()\n X_author = X_author.cuda()\n Y = Y.cuda()\n\n output, _ = model(X_title.float(), X_author.float())\n loss_batch = F.nll_loss(output, Y.long())\n loss += bs * loss_batch.item()\n\n y_true += Y.data.tolist()\n y_pred += output.max(1)[1].data.tolist()\n y_score += output[:, 1].data.tolist()\n total += bs\n\n model.train()\n\n if thr is not None:\n logger.info(\"using threshold %.4f\", thr)\n y_score = np.array(y_score)\n y_pred = np.zeros_like(y_score)\n y_pred[y_score > thr] = 1\n\n prec, rec, f1, _ = precision_recall_fscore_support(y_true, y_pred, average=\"binary\")\n auc = roc_auc_score(y_true, y_score)\n logger.info(\"loss: %.4f AUC: %.4f Prec: %.4f Rec: %.4f F1: %.4f\",\n loss / total, auc, prec, rec, f1)\n\n metrics = [loss/total, auc, prec, rec, f1]\n\n if return_best_thr: # valid\n precs, recs, thrs = precision_recall_curve(y_true, y_score)\n f1s = 2 * precs * recs / (precs + recs)\n f1s = f1s[:-1]\n thrs = thrs[~np.isnan(f1s)]\n f1s = f1s[~np.isnan(f1s)]\n best_thr = thrs[np.argmax(f1s)]\n logger.info(\"best threshold=%4f, f1=%.4f\", best_thr, np.max(f1s))\n writer.add_scalar('val_loss',\n loss / total,\n epoch)\n return best_thr, metrics\n else:\n writer.add_scalar('test_f1',\n f1,\n epoch)\n return None, metrics\n\n\ndef main(args=args):\n args.cuda = not args.no_cuda and torch.cuda.is_available()\n logger.info('cuda is available %s', args.cuda)\n\n np.random.seed(args.seed)\n torch.manual_seed(args.seed + args.seed_delta)\n if args.cuda:\n torch.cuda.manual_seed(args.seed + args.seed_delta)\n\n dataset = ProcessedCNNInputDataset(args.entity_type, \"train\")\n dataset_valid = ProcessedCNNInputDataset(args.entity_type, \"valid\")\n dataset_test = ProcessedCNNInputDataset(args.entity_type, \"test\")\n N = len(dataset)\n N_valid = len(dataset_valid)\n N_test = len(dataset_test)\n train_loader = DataLoader(dataset, batch_size=args.batch,\n sampler=ChunkSampler(N, 0))\n valid_loader = DataLoader(dataset_valid, batch_size=args.batch,\n sampler=ChunkSampler(N_valid, 0))\n test_loader = DataLoader(dataset_test, batch_size=args.batch,\n sampler=ChunkSampler(N_test, 0))\n model = CNNMatchModel(input_matrix_size1=args.matrix_size1, input_matrix_size2=args.matrix_size2,\n mat1_channel1=args.mat1_channel1, mat1_kernel_size1=args.mat1_kernel_size1,\n mat1_channel2=args.mat1_channel2, mat1_kernel_size2=args.mat1_kernel_size2,\n mat1_hidden=args.mat1_hidden, mat2_channel1=args.mat2_channel1,\n mat2_kernel_size1=args.mat2_kernel_size1, mat2_hidden=args.mat2_hidden)\n model = model.float()\n\n if args.cuda:\n model.cuda()\n\n optimizer = optim.Adagrad(model.parameters(), lr=args.lr,\n # initial_accumulator_value=args.initial_accumulator_value,\n weight_decay=args.weight_decay)\n t_total = time.time()\n logger.info(\"training...\")\n\n model_dir = join(settings.OUT_DIR, args.entity_type)\n os.makedirs(model_dir, exist_ok=True)\n\n # model.load_state_dict(torch.load(join(settings.OUT_VENUE_DIR, \"venue-matching-cnn.mdl\")))\n evaluate(0, test_loader, model, thr=None, args=args)\n min_loss_val = None\n best_test_metrics = None\n for epoch in range(args.epochs):\n print(\"training epoch\", epoch)\n metrics_val, metrics_test = train(epoch, train_loader, valid_loader, test_loader, model, optimizer, args=args)\n if metrics_val is not None:\n if min_loss_val is None or min_loss_val > metrics_val[0]:\n min_loss_val = metrics_val[0]\n best_test_metrics = metrics_test\n torch.save(model.state_dict(), join(model_dir, \"cnn-match-best-now.mdl\"))\n\n logger.info(\"optimization Finished!\")\n logger.info(\"total time elapsed: {:.4f}s\".format(time.time() - t_total))\n\n # torch.save(model.state_dict(), join(model_dir, 'paper-matching-cnn.mdl'))\n # logger.info('paper matching CNN model saved')\n\n print(\"min valid loss {:.4f}, best test metrics: AUC: {:.2f}, Prec: {:.4f}, Rec: {:.4f}, F1: {:.4f}\".format(\n min_loss_val, best_test_metrics[1], best_test_metrics[2], best_test_metrics[3], best_test_metrics[4]\n ))\n\n # evaluate(args.epochs, test_loader, model, thr=best_thr, args=args)\n writer.close()\n\n\nif __name__ == '__main__':\n main(args=args)\n"
]
| [
[
"numpy.max",
"numpy.array",
"numpy.zeros_like",
"torch.cuda.manual_seed",
"numpy.isnan",
"sklearn.metrics.precision_recall_curve",
"numpy.random.seed",
"sklearn.metrics.precision_recall_fscore_support",
"torch.manual_seed",
"torch.cuda.is_available",
"numpy.argmax",
"sklearn.metrics.roc_auc_score"
]
]
|
EricZhu-42/KDD_Cup_2020_Adversial_Attack_on_Graph_Data | [
"854cc664ab9fb4dd65df9e15c1a087c4ec972724"
]
| [
"utils/utils.py"
]
| [
"import numpy as np\nimport scipy.sparse as sp\nimport torch\nimport torch.nn.functional as F\nimport torch.sparse as ts\nfrom sklearn.model_selection import train_test_split\n\ndef encode_onehot(labels):\n eye = np.eye(labels.max() + 1)\n onehot_mx = eye[labels]\n return onehot_mx\n\ndef tensor2onehot(labels):\n eye = torch.eye(labels.max() + 1)\n onehot_mx = eye[labels]\n return onehot_mx.to(labels.device)\n\ndef to_tensor(adj, features, labels=None, device='cpu'):\n if sp.issparse(adj):\n adj = sparse_mx_to_torch_sparse_tensor(adj)\n else:\n adj = torch.FloatTensor(adj)\n if sp.issparse(features):\n features = sparse_mx_to_torch_sparse_tensor(features)\n else:\n features = torch.FloatTensor(np.array(features))\n\n if labels is None:\n return adj.to(device), features.to(device)\n else:\n labels = torch.LongTensor(labels)\n return adj.to(device), features.to(device), labels.to(device)\n\ndef normalize_feature(mx):\n \"\"\"Row-normalize sparse matrix\"\"\"\n if type(mx) is not sp.lil.lil_matrix:\n mx = mx.tolil()\n rowsum = np.array(mx.sum(1))\n r_inv = np.power(rowsum, -1).flatten()\n r_inv[np.isinf(r_inv)] = 0.\n r_mat_inv = sp.diags(r_inv)\n mx = r_mat_inv.dot(mx)\n return mx\n\ndef normalize_adj(mx):\n \"\"\"Row-normalize sparse matrix\"\"\"\n if type(mx) is not sp.lil.lil_matrix:\n mx = mx.tolil()\n if mx[0, 0] == 0 :\n mx = mx + sp.eye(mx.shape[0])\n rowsum = np.array(mx.sum(1))\n r_inv = np.power(rowsum, -1/2).flatten()\n r_inv[np.isinf(r_inv)] = 0.\n r_mat_inv = sp.diags(r_inv)\n mx = r_mat_inv.dot(mx)\n mx = mx.dot(r_mat_inv)\n return mx\n\ndef normalize_sparse_tensor(adj, fill_value=1):\n edge_index = adj._indices()\n edge_weight = adj._values()\n num_nodes= adj.size(0)\n edge_index, edge_weight = add_self_loops(\n\tedge_index, edge_weight, fill_value, num_nodes)\n\n row, col = edge_index\n from torch_scatter import scatter_add\n deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes)\n deg_inv_sqrt = deg.pow(-0.5)\n deg_inv_sqrt[deg_inv_sqrt == float('inf')] = 0\n\n values = deg_inv_sqrt[row] * edge_weight * deg_inv_sqrt[col]\n\n shape = adj.shape\n return torch.sparse.FloatTensor(edge_index, values, shape)\n\ndef add_self_loops(edge_index, edge_weight=None, fill_value=1, num_nodes=None):\n loop_index = torch.arange(0, num_nodes, dtype=torch.long,\n device=edge_index.device)\n loop_index = loop_index.unsqueeze(0).repeat(2, 1)\n\n if edge_weight is not None:\n assert edge_weight.numel() == edge_index.size(1)\n loop_weight = edge_weight.new_full((num_nodes, ), fill_value)\n edge_weight = torch.cat([edge_weight, loop_weight], dim=0)\n\n edge_index = torch.cat([edge_index, loop_index], dim=1)\n\n return edge_index, edge_weight\n\ndef normalize_adj_tensor(adj, sparse=False):\n\n device = torch.device(\"cuda\" if adj.is_cuda else \"cpu\")\n if sparse:\n #return normalize_sparse_tensor(adj)\n adj = to_scipy(adj)\n mx = normalize_adj(adj)\n return sparse_mx_to_torch_sparse_tensor(mx).to(device)\n else:\n mx = adj + torch.eye(adj.shape[0]).to(device)\n rowsum = mx.sum(1)\n r_inv = rowsum.pow(-1/2).flatten()\n r_inv[torch.isinf(r_inv)] = 0.\n r_mat_inv = torch.diag(r_inv)\n mx = r_mat_inv @ mx\n mx = mx @ r_mat_inv\n return mx\n\ndef degree_normalize_adj(mx):\n \"\"\"Row-normalize sparse matrix\"\"\"\n mx = mx.tolil()\n if mx[0, 0] == 0 :\n mx = mx + sp.eye(mx.shape[0])\n rowsum = np.array(mx.sum(1))\n r_inv = np.power(rowsum, -1).flatten()\n r_inv[np.isinf(r_inv)] = 0.\n r_mat_inv = sp.diags(r_inv)\n mx = r_mat_inv.dot(mx)\n return mx\n\ndef degree_normalize_sparse_tensor(adj, fill_value=1):\n edge_index = adj._indices()\n edge_weight = adj._values()\n num_nodes= adj.size(0)\n\n edge_index, edge_weight = add_self_loops(\n\tedge_index, edge_weight, fill_value, num_nodes)\n\n row, col = edge_index\n from torch_scatter import scatter_add\n deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes)\n deg_inv_sqrt = deg.pow(-1)\n deg_inv_sqrt[deg_inv_sqrt == float('inf')] = 0\n\n values = deg_inv_sqrt[row] * edge_weight\n shape = adj.shape\n return torch.sparse.FloatTensor(edge_index, values, shape)\n\ndef degree_normalize_adj_tensor(adj, sparse=True):\n\n device = torch.device(\"cuda\" if adj.is_cuda else \"cpu\")\n if sparse:\n adj = to_scipy(adj)\n mx = degree_normalize_adj(adj)\n return sparse_mx_to_torch_sparse_tensor(mx).to(device)\n else:\n mx = adj + torch.eye(adj.shape[0]).to(device)\n rowsum = mx.sum(1)\n r_inv = rowsum.pow(-1).flatten()\n r_inv[torch.isinf(r_inv)] = 0.\n r_mat_inv = torch.diag(r_inv)\n mx = r_mat_inv @ mx\n return mx\n\ndef accuracy(output, labels):\n if type(labels) is not torch.Tensor:\n labels = torch.LongTensor(labels)\n preds = output.max(1)[1].type_as(labels)\n correct = preds.eq(labels).double()\n correct = correct.sum()\n return correct / len(labels)\n\ndef loss_acc(output, labels, targets, avg_loss=True):\n if type(labels) is not torch.Tensor:\n labels = torch.LongTensor(labels)\n preds = output.max(1)[1].type_as(labels)\n correct = preds.eq(labels).double()[targets]\n loss = F.nll_loss(output[targets], labels[targets], reduction='mean' if avg_loss else 'none')\n\n if avg_loss:\n return loss, correct.sum() / len(targets)\n return loss, correct\n\ndef classification_margin(output, true_label):\n '''probs_true_label - probs_best_second_class'''\n probs = torch.exp(output)\n probs_true_label = probs[true_label].clone()\n probs[true_label] = 0\n probs_best_second_class = probs[probs.argmax()]\n return (probs_true_label - probs_best_second_class).item()\n\ndef sparse_mx_to_torch_sparse_tensor(sparse_mx):\n \"\"\"Convert a scipy sparse matrix to a torch sparse tensor.\"\"\"\n sparse_mx = sparse_mx.tocoo().astype(np.float32)\n indices = torch.from_numpy(\n np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))\n values = torch.from_numpy(sparse_mx.data)\n shape = torch.Size(sparse_mx.shape)\n return torch.sparse.FloatTensor(indices, values, shape)\n\ndef to_scipy(tensor):\n \"\"\"Convert a dense/sparse tensor to \"\"\"\n if is_sparse_tensor(tensor):\n values = tensor._values()\n indices = tensor._indices()\n return sp.csr_matrix((values.cpu().numpy(), indices.cpu().numpy()), shape=tensor.shape)\n else:\n indices = tensor.nonzero().t()\n values = tensor[indices[0], indices[1]]\n return sp.csr_matrix((values.cpu().numpy(), indices.cpu().numpy()), shape=tensor.shape)\n\ndef is_sparse_tensor(tensor):\n if tensor.layout == torch.sparse_coo:\n return True\n else:\n return False\n\ndef get_train_val_test(nnodes, val_size=0.1, test_size=0.8, stratify=None, seed=None):\n '''\n This setting follows nettack/mettack, where we split the nodes\n into 10% training, 10% validation and 80% testing data\n '''\n assert stratify is not None, 'stratify cannot be None!'\n\n if seed is not None:\n np.random.seed(seed)\n\n idx = np.arange(nnodes)\n train_size = 1 - val_size - test_size\n idx_train_and_val, idx_test = train_test_split(idx,\n random_state=None,\n train_size=train_size + val_size,\n test_size=test_size,\n stratify=stratify)\n\n if stratify is not None:\n stratify = stratify[idx_train_and_val]\n\n idx_train, idx_val = train_test_split(idx_train_and_val,\n random_state=None,\n train_size=(train_size / (train_size + val_size)),\n test_size=(val_size / (train_size + val_size)),\n stratify=stratify)\n\n return idx_train, idx_val, idx_test\n\ndef get_train_test(nnodes, test_size=0.8, stratify=None, seed=None):\n '''\n This function returns training and test set without validation.\n It can be used for settings of different label rates.\n '''\n assert stratify is not None, 'stratify cannot be None!'\n\n if seed is not None:\n np.random.seed(seed)\n\n idx = np.arange(nnodes)\n train_size = 1 - test_size\n idx_train, idx_test = train_test_split(idx, random_state=None,\n train_size=train_size,\n test_size=test_size,\n stratify=stratify)\n\n return idx_train, idx_test\n\ndef get_train_val_test_gcn(labels, seed=None):\n '''\n This setting follows gcn, where we randomly sample 20 instances for each class\n as training data, 500 instances as validation data, 1000 instances as test data.\n '''\n if seed is not None:\n np.random.seed(seed)\n\n idx = np.arange(len(labels))\n nclass = labels.max() + 1\n idx_train = []\n idx_unlabeled = []\n for i in range(nclass):\n labels_i = idx[labels==i]\n labels_i = np.random.permutation(labels_i)\n idx_train = np.hstack((idx_train, labels_i[: 20])).astype(np.int)\n idx_unlabeled = np.hstack((idx_unlabeled, labels_i[20: ])).astype(np.int)\n\n idx_unlabeled = np.random.permutation(idx_unlabeled)\n idx_val = idx_unlabeled[: 500]\n idx_test = idx_unlabeled[500: 1500]\n return idx_train, idx_val, idx_test\n\ndef get_train_test_labelrate(labels, label_rate):\n nclass = labels.max() + 1\n train_size = int(round(len(labels) * label_rate / nclass))\n print(\"=== train_size = %s ===\" % train_size)\n idx_train, idx_val, idx_test = get_splits_each_class(labels, train_size=train_size)\n return idx_train, idx_test\n\ndef get_splits_each_class(labels, train_size):\n '''\n This setting follows gcn, where we randomly sample n instances for class,\n where n=train_size\n '''\n idx = np.arange(len(labels))\n nclass = labels.max() + 1\n idx_train = []\n idx_val = []\n idx_test = []\n for i in range(nclass):\n labels_i = idx[labels==i]\n labels_i = np.random.permutation(labels_i)\n idx_train = np.hstack((idx_train, labels_i[: train_size])).astype(np.int)\n idx_val = np.hstack((idx_val, labels_i[train_size: 2*train_size])).astype(np.int)\n idx_test = np.hstack((idx_test, labels_i[2*train_size: ])).astype(np.int)\n\n return np.random.permutation(idx_train), np.random.permutation(idx_val), \\\n np.random.permutation(idx_test)\n\n\ndef unravel_index(index, array_shape):\n rows = index // array_shape[1]\n cols = index % array_shape[1]\n return rows, cols\n\n\ndef get_degree_squence(adj):\n try:\n return adj.sum(0)\n except:\n return ts.sum(adj, dim=1).to_dense()\n\ndef likelihood_ratio_filter(node_pairs, modified_adjacency, original_adjacency, d_min, threshold=0.004):\n \"\"\"\n Filter the input node pairs based on the likelihood ratio test proposed by Zügner et al. 2018, see\n https://dl.acm.org/citation.cfm?id=3220078. In essence, for each node pair return 1 if adding/removing the edge\n between the two nodes does not violate the unnoticeability constraint, and return 0 otherwise. Assumes unweighted\n and undirected graphs.\n \"\"\"\n\n N = int(modified_adjacency.shape[0])\n # original_degree_sequence = get_degree_squence(original_adjacency)\n # current_degree_sequence = get_degree_squence(modified_adjacency)\n original_degree_sequence = original_adjacency.sum(0)\n current_degree_sequence = modified_adjacency.sum(0)\n\n concat_degree_sequence = torch.cat((current_degree_sequence, original_degree_sequence))\n\n # Compute the log likelihood values of the original, modified, and combined degree sequences.\n ll_orig, alpha_orig, n_orig, sum_log_degrees_original = degree_sequence_log_likelihood(original_degree_sequence, d_min)\n ll_current, alpha_current, n_current, sum_log_degrees_current = degree_sequence_log_likelihood(current_degree_sequence, d_min)\n\n ll_comb, alpha_comb, n_comb, sum_log_degrees_combined = degree_sequence_log_likelihood(concat_degree_sequence, d_min)\n\n # Compute the log likelihood ratio\n current_ratio = -2 * ll_comb + 2 * (ll_orig + ll_current)\n\n # Compute new log likelihood values that would arise if we add/remove the edges corresponding to each node pair.\n new_lls, new_alphas, new_ns, new_sum_log_degrees = updated_log_likelihood_for_edge_changes(node_pairs,\n modified_adjacency, d_min)\n\n # Combination of the original degree distribution with the distributions corresponding to each node pair.\n n_combined = n_orig + new_ns\n new_sum_log_degrees_combined = sum_log_degrees_original + new_sum_log_degrees\n alpha_combined = compute_alpha(n_combined, new_sum_log_degrees_combined, d_min)\n new_ll_combined = compute_log_likelihood(n_combined, alpha_combined, new_sum_log_degrees_combined, d_min)\n new_ratios = -2 * new_ll_combined + 2 * (new_lls + ll_orig)\n\n # Allowed edges are only those for which the resulting likelihood ratio measure is < than the threshold\n allowed_edges = new_ratios < threshold\n\n if allowed_edges.is_cuda:\n filtered_edges = node_pairs[allowed_edges.cpu().numpy().astype(np.bool)]\n else:\n filtered_edges = node_pairs[allowed_edges.numpy().astype(np.bool)]\n\n allowed_mask = torch.zeros(modified_adjacency.shape)\n allowed_mask[filtered_edges.T] = 1\n allowed_mask += allowed_mask.t()\n return allowed_mask, current_ratio\n\n\ndef degree_sequence_log_likelihood(degree_sequence, d_min):\n \"\"\"\n Compute the (maximum) log likelihood of the Powerlaw distribution fit on a degree distribution.\n \"\"\"\n\n # Determine which degrees are to be considered, i.e. >= d_min.\n D_G = degree_sequence[(degree_sequence >= d_min.item())]\n try:\n sum_log_degrees = torch.log(D_G).sum()\n except:\n sum_log_degrees = np.log(D_G).sum()\n n = len(D_G)\n\n alpha = compute_alpha(n, sum_log_degrees, d_min)\n ll = compute_log_likelihood(n, alpha, sum_log_degrees, d_min)\n return ll, alpha, n, sum_log_degrees\n\ndef updated_log_likelihood_for_edge_changes(node_pairs, adjacency_matrix, d_min):\n\n # For each node pair find out whether there is an edge or not in the input adjacency matrix.\n\n edge_entries_before = adjacency_matrix[node_pairs.T]\n degree_sequence = adjacency_matrix.sum(1)\n D_G = degree_sequence[degree_sequence >= d_min.item()]\n sum_log_degrees = torch.log(D_G).sum()\n n = len(D_G)\n deltas = -2 * edge_entries_before + 1\n d_edges_before = degree_sequence[node_pairs]\n\n d_edges_after = degree_sequence[node_pairs] + deltas[:, None]\n\n # Sum the log of the degrees after the potential changes which are >= d_min\n sum_log_degrees_after, new_n = update_sum_log_degrees(sum_log_degrees, n, d_edges_before, d_edges_after, d_min)\n # Updated estimates of the Powerlaw exponents\n new_alpha = compute_alpha(new_n, sum_log_degrees_after, d_min)\n # Updated log likelihood values for the Powerlaw distributions\n new_ll = compute_log_likelihood(new_n, new_alpha, sum_log_degrees_after, d_min)\n return new_ll, new_alpha, new_n, sum_log_degrees_after\n\n\ndef update_sum_log_degrees(sum_log_degrees_before, n_old, d_old, d_new, d_min):\n # Find out whether the degrees before and after the change are above the threshold d_min.\n old_in_range = d_old >= d_min\n new_in_range = d_new >= d_min\n d_old_in_range = d_old * old_in_range.float()\n d_new_in_range = d_new * new_in_range.float()\n\n # Update the sum by subtracting the old values and then adding the updated logs of the degrees.\n sum_log_degrees_after = sum_log_degrees_before - (torch.log(torch.clamp(d_old_in_range, min=1))).sum(1) \\\n + (torch.log(torch.clamp(d_new_in_range, min=1))).sum(1)\n\n # Update the number of degrees >= d_min\n\n new_n = n_old - (old_in_range!=0).sum(1) + (new_in_range!=0).sum(1)\n new_n = new_n.float()\n return sum_log_degrees_after, new_n\n\ndef compute_alpha(n, sum_log_degrees, d_min):\n try:\n alpha = 1 + n / (sum_log_degrees - n * torch.log(d_min - 0.5))\n except:\n alpha = 1 + n / (sum_log_degrees - n * np.log(d_min - 0.5))\n return alpha\n\ndef compute_log_likelihood(n, alpha, sum_log_degrees, d_min):\n # Log likelihood under alpha\n try:\n ll = n * torch.log(alpha) + n * alpha * torch.log(d_min) + (alpha + 1) * sum_log_degrees\n except:\n ll = n * np.log(alpha) + n * alpha * np.log(d_min) + (alpha + 1) * sum_log_degrees\n\n return ll\n\ndef ravel_multiple_indices(ixs, shape, reverse=False):\n \"\"\"\n \"Flattens\" multiple 2D input indices into indices on the flattened matrix, similar to np.ravel_multi_index.\n Does the same as ravel_index but for multiple indices at once.\n Parameters\n ----------\n ixs: array of ints shape (n, 2)\n The array of n indices that will be flattened.\n\n shape: list or tuple of ints of length 2\n The shape of the corresponding matrix.\n\n Returns\n -------\n array of n ints between 0 and shape[0]*shape[1]-1\n The indices on the flattened matrix corresponding to the 2D input indices.\n\n \"\"\"\n if reverse:\n return ixs[:, 1] * shape[1] + ixs[:, 0]\n\n return ixs[:, 0] * shape[1] + ixs[:, 1]\n\ndef visualize(your_var):\n '''visualize computation graph'''\n from graphviz import Digraph\n import torch\n from torch.autograd import Variable\n from torchviz import make_dot\n make_dot(your_var).view()\n\ndef reshape_mx(mx, shape):\n indices = mx.nonzero()\n return sp.csr_matrix((mx.data, (indices[0], indices[1])), shape=shape)\n\n# def check_path(file_path):\n# if not osp.exists(file_path):\n# os.system(f'mkdir -p {file_path}')\n\ndef deal_adj(adj):\n adj = adj + adj.T\n # adj = adj.tolil()\n adj[adj > 1] = 1\n # whether to set diag=0?\n adj.setdiag(0)\n adj = adj.astype(\"float32\").tocsr()\n adj.eliminate_zeros()\n A_hat = adj\n degree = np.array(np.sum(A_hat, axis=0))[0]\n D_hat = sp.diags(degree)\n '''\n rowsum = np.array(mx.sum(1))\n r_inv = np.power(rowsum, -1).flatten()\n r_inv[np.isinf(r_inv)] = 0.\n r_mat_inv = sp.diags(r_inv)\n '''\n degree_reverse = degree ** (-1 / 2)\n degree_reverse[np.isinf(degree_reverse)] = 0.\n D_hat_reverse = sp.diags(degree_reverse)\n # adj = D_hat +A_hat\n adj = D_hat_reverse * (D_hat + A_hat) * D_hat_reverse\n return adj\n\ndef to_sparse(x):\n \"\"\" converts dense tensor x to sparse format \"\"\"\n x_typename = torch.typename(x).split('.')[-1]\n sparse_tensortype = getattr(torch.sparse, x_typename)\n\n indices = torch.nonzero(x)\n if len(indices.shape) == 0: # if all elements are zeros\n return sparse_tensortype(*x.shape)\n indices = indices.t()\n values = x[tuple(indices[i] for i in range(indices.shape[0]))]\n return sparse_tensortype(indices, values, x.size())\n\ndef get_device(use_cuda, desc=\"Running\"):\n if use_cuda and torch.cuda.is_available():\n device = torch.device('cuda')\n print(\"%s with GPU %s\" % (desc, torch.cuda.get_device_name(device)))\n else:\n device = torch.device('cpu')\n print(\"%s with CPU\" % (desc))\n return device\n"
]
| [
[
"torch.cat",
"torch.cuda.is_available",
"torch.LongTensor",
"torch.eye",
"torch.nn.functional.nll_loss",
"torch.exp",
"torch.Size",
"scipy.sparse.diags",
"numpy.log",
"torch.FloatTensor",
"torch.typename",
"scipy.sparse.eye",
"numpy.arange",
"scipy.sparse.csr_matrix",
"numpy.vstack",
"torch.zeros",
"scipy.sparse.issparse",
"torch.device",
"torch.nonzero",
"numpy.array",
"torch.cuda.get_device_name",
"torch.clamp",
"numpy.power",
"torch.isinf",
"sklearn.model_selection.train_test_split",
"numpy.hstack",
"torch.log",
"numpy.isinf",
"torch.arange",
"numpy.random.seed",
"numpy.sum",
"numpy.random.permutation",
"torch.sparse.FloatTensor",
"torch.from_numpy",
"torch.diag",
"torch.sparse.sum"
]
]
|
Xiaosheng-Zhao/21cmDELFI | [
"6f7662aadc8f38920de1258199963d3a289df727"
]
| [
"tutorial/Active_learning.py"
]
| [
"import logging, sys, os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pydelfi.priors as priors\nimport pydelfi.ndes as ndes\nimport pydelfi.delfi as delfi\nimport tensorflow as tf\nimport pickle\nfrom getdist import plots, MCSamples\nimport getdist\n\nlogger = logging.getLogger('21cmFAST')\nlogger.setLevel(logging.INFO)\nimport py21cmfast as p21c\nfrom py21cmfast import plotting\nfrom py21cmfast import cache_tools\nfrom tpower import get_power\nimport random\nfrom mpi4py import MPI\n\nrestore=False\n# One set of parameters could correspond to multiple (n_noise) realizations of noise\nn_noise=1\n# Number of spline points to be used in the summaries, the same param in 'tpower.py'\nNSplinePoints = 8\n# List of co-eval redshifts\nredshift = [7.668188,8.003182,8.357909,8.716638,9.108561,9.524624,9.966855,10.437500,10.939049,11.474274]\n\n# 21cmFAST Simulator\ndef simulator(theta,seed,simulator_args,batch=1,n_noise=n_noise):\n p21c.config['direc'] = \"./data/cache\"\n HII_DIM = 66\n BOX_LEN = 100\n\n coeval8 = p21c.run_coeval(\n redshift = redshift,\n write=False,\n user_params = {\"HII_DIM\": HII_DIM, \"BOX_LEN\": BOX_LEN},\n cosmo_params = p21c.CosmoParams(SIGMA_8=0.815,hlittle=0.678,OMm=0.308,OMb=0.048425,POWER_INDEX=0.968),\n astro_params = p21c.AstroParams({\"HII_EFF_FACTOR\":pow(10,theta[1]),\"ION_Tvir_MIN\":theta[0]}),\n random_seed=seed)\n ps = np.concatenate((get_power(coeval8[0],HII_DIM,BOX_LEN,n_noise,redshift[0]),get_power(coeval8[1],HII_DIM,BOX_LEN,n_noise,redshift[1]),get_power(coeval8[2],HII_DIM,BOX_LEN,n_noise,redshift[2]),get_power(coeval8[3],HII_DIM,BOX_LEN,n_noise,redshift[3]),get_power(coeval8[4],HII_DIM,BOX_LEN,n_noise,redshift[4]),get_power(coeval8[5],HII_DIM,BOX_LEN,n_noise,redshift[5]),get_power(coeval8[6],HII_DIM,BOX_LEN,n_noise,redshift[6]),get_power(coeval8[7],HII_DIM,BOX_LEN,n_noise,redshift[7]),get_power(coeval8[8],HII_DIM,BOX_LEN,n_noise,redshift[8]),get_power(coeval8[9],HII_DIM,BOX_LEN,n_noise,redshift[9])),axis=1)\n return ps\n\n# Simulator arguments\nsimulator_args = None\n\n# Data compressor\ndef compressor(d, compressor_args):\n return d\n\n# Compressor arguments\ncompressor_args = None\n\n# Define the priors parameters\nlower = np.array([4,1])\nupper = np.array([6,2.398])\nprior = priors.Uniform(lower, upper)\ntheta_fiducial = np.array([5.47712125,2.30103])\n\n# Initialize the random seed\nseed = 4101110\n\n# The dimension of the final summary\nnout = NSplinePoints*len(redshift)\n\n# Load the prepared mock data which can be re-simulated with the simulator\ndata=np.load('/scratch/zxs/delfi_fast/data/21cmdelfi_mock/back_1003/bright_hera.npy')\ncompressed_data = compressor(data, compressor_args)\n\n# Create an ensemble of NDEs\nNDEs = [ndes.ConditionalMaskedAutoregressiveFlow(n_parameters=2, n_data=nout, n_hiddens=[50,50], n_mades=5, act_fun=tf.tanh, index=0),\n ndes.ConditionalMaskedAutoregressiveFlow(n_parameters=2, n_data=nout, n_hiddens=[50,50], n_mades=5, act_fun=tf.tanh, index=1),\n ndes.ConditionalMaskedAutoregressiveFlow(n_parameters=2, n_data=nout, n_hiddens=[50,50], n_mades=5, act_fun=tf.tanh, index=2),\n ndes.ConditionalMaskedAutoregressiveFlow(n_parameters=2, n_data=nout, n_hiddens=[50,50], n_mades=5, act_fun=tf.tanh, index=3)]\n\n# Initiate the MPI setting\nworld_comm=MPI.COMM_WORLD\nprint (world_comm.Get_rank(),flush=True)\n# Create the DELFI object\nDelfiEnsemble = delfi.Delfi(compressed_data, prior, NDEs, Finv=None, theta_fiducial=theta_fiducial,\n param_limits = [lower, upper],\n param_names =['\\mathrm{log_{10}\\,T_{vir}}', '\\mathrm{log_{10}\\,\\zeta}'],\n results_dir = \"./data/results\",\n restore = restore,\n n_procs = 10,\n comm=world_comm,\n red_op=MPI.SUM,\n n_noise=n_noise,\n rank=world_comm.Get_rank(),\n input_normalization=None)\n\n# Initial samples, batch size for population samples, number of populations\nn_initial = 500\nn_batch = 500\nn_populations = 60\n\n# Do the SNL training\nDelfiEnsemble.sequential_training(simulator, compressor, n_initial, n_batch, n_populations, patience=20, batch_size = 100,plot = False,save_intermediate_posteriors=True)\nx0 = DelfiEnsemble.posterior_samples[np.random.choice(np.arange(len(DelfiEnsemble.posterior_samples)), p=DelfiEnsemble.posterior_weights.astype(np.float32)/sum(DelfiEnsemble.posterior_weights), replace=False, size=DelfiEnsemble.nwalkers),:]\nposterior_samples = DelfiEnsemble.emcee_sample(x0=x0,main_chain=2000)\n\nwith open('data/posterior_samples/po_mock_active.pkl', 'wb') as f:\n pickle.dump(posterior_samples,f)\n"
]
| [
[
"numpy.array",
"numpy.load"
]
]
|
felixdittrich92/DeepLearning-tensorflow-keras | [
"2880d8ed28ba87f28851affa92b6fa99d2e47be9"
]
| [
"7_DeepLearning-GANs/04_Generative_Adversarial_Attacks/plotting.py"
]
| [
"import matplotlib.pyplot as plt\r\n\r\ndef plot_img(image, cmap=\"gray\"):\r\n plt.imshow(image.squeeze(), cmap=cmap)\r\n plt.axis(\"off\")\r\n plt.show()\r\n\r\ndef plot_attack(image_true, image_adversarial):\r\n # Plot the attack\r\n plt.figure()\r\n plt.subplot(1, 3, 1)\r\n plt.title(\"Original\")\r\n plt.imshow(image_true.reshape((28,28)), cmap=\"gray\")\r\n plt.axis(\"off\")\r\n\r\n plt.subplot(1, 3, 2)\r\n plt.title(\"image_adversarial\")\r\n plt.imshow(image_adversarial.reshape((28,28)), cmap=\"gray\")\r\n plt.axis(\"off\")\r\n\r\n plt.subplot(1, 3, 3)\r\n plt.title(\"Difference\")\r\n difference = image_adversarial - image_true\r\n plt.imshow(difference.reshape((28,28)), cmap=\"gray\")\r\n plt.axis(\"off\")\r\n plt.show()\r\n"
]
| [
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.subplot"
]
]
|
nilanjan-cse/google-research | [
"e727e8e9e6286a058515308d814eace3eb07fcdf"
]
| [
"graph_compression/compression_lib/compression_op.py"
]
| [
"# coding=utf-8\n# Copyright 2020 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Matrix compression operator.\n\nHelper functions to have an automated process to take any matrix compression\nalgorithm and create a tensorflow operator that can be applied on a tensorflow\nmatrix variable to compress it on the fly during training.\n\nThe class MatrixCompressorInferface can be used to implement any matrix\ncompression algorithm in the method static_matrix_compressor. The other class\nCompressionOpInterface is used to create a tensorflow operator that injects\nany matrix compression method dynamically into a tensorflow layer. This is\ndone by specifying in the spec during initialization a\nMatrixCompressorInferface object that implements the method.\nThe get_apply_compression_op return such a tensorflow operator.\nFurther a tensorflow operator to update variables needs to be invoked\nperiodically depending on the method. Such an operator is created using\nthe get_update_op method.\n\nDerived classes of these interfaces can be used to create compression OPs that\nimplement different compression methods. Such OPs have been implemented using\nderived classes such as LowRankDecompMatrixCompressor, CompressionOp for low\nrank decomposition, SimhashMatrixCompressor, SimhashCompressionOp for simhash,\nDLMatrixCompressor for dictionary learning.\n\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport copy\n\nfrom absl import logging\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nfrom graph_compression.compression_lib import compression_op_utils as comp_op_utils\nfrom tensorflow.contrib import training as contrib_training\n\n\nclass MatrixCompressorInferface(object):\n \"\"\"Interface for any matrix compressor algorithm.\n\n This MatrixCompressorInferface class can be implemented by any third party to\n implement any compression algorithm.\n \"\"\"\n\n @abc.abstractmethod\n def __init__(self, spec):\n pass\n\n def static_matrix_compressor(self, a_matrix):\n \"\"\"Implements the matrix compression algorithm of choice to compress.\n\n Args:\n a_matrix: input matrix.\n\n Returns:\n The factor(s) or any compressed representation of a_matrix.\n \"\"\"\n raise NotImplementedError()\n\n def default_matrix(self):\n \"\"\"Returns default matrix for initialization.\n\n Size is taken from spec.\n \"\"\"\n raise NotImplementedError()\n\n\nclass LowRankDecompMatrixCompressor(MatrixCompressorInferface):\n \"\"\"Low rank decomposition compressor.\n\n Implements matrix compression interface for the low rank decomposition\n algorithm.\n \"\"\"\n\n def __init__(self, spec):\n \"\"\"Initializer.\n\n Args:\n spec: hparams object with default value given by\n self.get_default_hparams().\n \"\"\"\n super(LowRankDecompMatrixCompressor, self).__init__(spec)\n self._spec = spec\n\n self.uncompressed_size = 0\n self.compressed_size = 0\n\n def get_spec(self):\n return self._spec\n\n @staticmethod\n def get_default_hparams():\n \"\"\"Get a tf.HParams object with the default values for the hyperparameters.\n\n name: string\n name of the low-rank matrix decompressor specification.\n rank: integer\n rank of the low-rank decomposition that is performed.\n num_rows: integer\n number of rows of given matrix.\n num_cols: integer\n number of columns of given matrix.\n use_tpu: False\n experimental flag; indicates whether to use tensorflow operations (True)\n or python operations (False). For TPU, TF operations are preferred.\n compressor_option: integer\n indicates what type of factorization (if any) is used.\n is_b_matrix_trainable: bool\n indicates whether the b_matrix matrix in the factorization is to be\n trained.\n is_c_matrix_trainable: bool\n indicates whether the c_matrix matrix in the factorization is to be\n trained.\n\n Returns:\n tf.HParams object initialized to default values.\n \"\"\"\n return contrib_training.HParams(\n name='model_compression',\n rank=100,\n num_rows=10,\n num_cols=10,\n use_tpu=False,\n compressor_option=0,\n is_b_matrix_trainable=True,\n is_c_matrix_trainable=True,\n is_c_matrix_present=True,\n block_size=1,\n pruning_fraction=0.0,\n use_lsh=False)\n\n def static_matrix_compressor(self, a_matrix):\n \"\"\"Low-rank decomposition of a_matrix.\n\n Args:\n a_matrix: input matrix.\n\n Returns:\n A list [b_matrix,c_matrix] which is the low-rank decomposition of\n a_matrix. Rank is taken from spec.rank.\n \"\"\"\n u, s, vh = np.linalg.svd(a_matrix)\n logging.info(\n 'Inside static_matrix_compressor: u,s,vh shapes are: %s, %s, %s',\n u.shape, s.shape, vh.shape)\n # If matrix dimension is smaller than rank specified then adjust rank\n rank = comp_op_utils.compute_compressed_rank_from_matrix_shape(\n a_matrix.shape, self._spec.rank)\n b_matrix = u[:, :rank]\n c_matrix = vh[:rank, :]\n s_mat = np.diag(np.sqrt(s[:rank]))\n b_matrix = np.matmul(b_matrix, s_mat)\n c_matrix = np.matmul(s_mat, c_matrix)\n logging.info(\n 'Inside static_matrix_compressor: a_matrix,b_matrix,c_matrix shapes '\n 'are: %s, %s, %s', a_matrix.shape, b_matrix.shape, c_matrix.shape)\n\n self.uncompressed_size = a_matrix.size\n self.compressed_size = b_matrix.size + c_matrix.size\n\n return [b_matrix, c_matrix]\n\n def tpu_matrix_compressor(self, a_matrix):\n \"\"\"Low-rank decomposition of a_matrix using tpu operations.\n\n For training on tpus, we only use basic tf operations (as py_func is not\n supported).\n\n Args:\n a_matrix: input matrix.\n\n Returns:\n A list of two matrices [b_matrix,c_matrix] which is the low-rank\n decomposition of a_matrix. Rank is taken from spec.rank.\n \"\"\"\n s, u, v = tf.linalg.svd(a_matrix)\n logging.info('Inside tpu_matrix_compressor: u,s,v shapes are: %s, %s, %s',\n u.shape, s.shape, v.shape)\n rank = comp_op_utils.compute_compressed_rank_from_matrix_shape(\n tuple(a_matrix.shape.dims), self._spec.rank)\n b_matrix = u[:, :rank]\n c_matrix = tf.transpose(a=v)[:rank, :]\n s_mat = tf.linalg.tensor_diag(tf.sqrt(s[:rank]))\n b_matrix = tf.matmul(b_matrix, s_mat)\n c_matrix = tf.matmul(s_mat, c_matrix)\n logging.info(\n 'Inside tpu_matrix_compressor: a_matrix,b_matrix,c_matrix'\n 'shapes are: %s, %s, %s', a_matrix.shape, b_matrix.shape,\n c_matrix.shape)\n return [b_matrix, c_matrix]\n\n def default_matrix(self):\n \"\"\"Returns default matrix of zeros of size specified in spec.\"\"\"\n\n a_matrix = np.zeros(shape=[self._spec.num_rows, self._spec.num_cols])\n return a_matrix\n\n\nclass CompressionOpInterface(object):\n \"\"\"Interface for a compression op.\n\n Class to take a matrix compression algorithm and create a tensorflow\n compression operator to inject that compression dynamically during training.\n The compression algorithm is specified using an object of\n MatrixCompressorInferface class.\n \"\"\"\n\n @abc.abstractmethod\n def __init__(self, scope='default_scope', spec=None, global_step=None):\n pass\n\n def get_apply_compression_op(self,\n a_matrix_tfvar,\n matrix_compressor,\n scope='default_scope'):\n \"\"\"Returns compressed tensorflow operator.\n\n Does it for variable a_matrix_tfvar for compression method specified in\n matrix_compressor.\n\n Args:\n a_matrix_tfvar: TF variable representing a tensor variable in a model.\n matrix_compressor: MatrixCompressorInferface object to specify the\n compression algorithm.\n scope: TF scope used for creating new TF variables.\n\n Returns:\n A TF node that has the compressed version of a_matrix_tfvar.\n \"\"\"\n raise NotImplementedError()\n\n def get_update_op(self):\n \"\"\"Update operator.\n\n Returns:\n TF operator that implements the update steps that may need to\n be applied periodically.\n \"\"\"\n raise NotImplementedError()\n\n\nclass CompressionOp(CompressionOpInterface):\n \"\"\"Implements a compression OP.\n\n Does this based on any matrix factorization compression algorithm by\n replacing a variable a_matrix by alpha*a_matrix +\n (1-alpha)b_matrix*c_matrix. See the doc linked in the directory README for\n details.\n \"\"\"\n\n def __init__(self, scope='default_scope', spec=None, global_step=None):\n \"\"\"Initializer.\n\n Args:\n scope: TF scope used for creating new TF variables.\n spec: compression hyper parameters default value given by\n self.get_default_hparams().\n global_step: tf variable that has the global step.\n \"\"\"\n super(CompressionOp, self).__init__(scope, spec, global_step)\n # Compression specification\n self._spec = spec if spec else self.get_compression_hparams()\n logging.info('Compression spec in init CompressionOp is: ')\n self.print_hparams()\n\n # Sanity check for compression hparams\n self._validate_spec()\n self._global_step = self._setup_global_step(global_step)\n\n # public member variables to track the compressor, the variables and\n # other tf nodes corresponding to this OP.\n self.matrix_compressor = None\n self.a_matrix_tfvar = None\n self.b_matrix_tfvar = None\n self.c_matrix_tfvar = None\n self.alpha = None\n self.final_op = None\n\n self.update_op = None\n self._last_alpha_update_step = self._setup_last_alpha_update_step()\n self._last_update_step = -1\n self._alpha_update_tf_op = None\n\n self.uncompressed_size = 0\n self.compressed_size = 0\n self.a_matrix_read = None\n self.run_update_count = 0\n self.last_alpha_value = 1\n\n @staticmethod\n def get_default_hparams():\n \"\"\"Get a tf.HParams object with the default values for the hyperparameters.\n\n name: string\n name of the compression specification. Used for adding summaries and ops\n under a common tensorflow name_scope.\n alpha_decrement_value: float\n a positive real number by which alpha is decremented at each update.\n begin_compression_step: integer\n the global step at which to begin compression.\n end_compression_step: integer\n the global step at which to terminate compression. Defaults to -1\n implying that compression continues till the training stops.\n use_tpu: False\n indicates whether to use TPU.\n compression_option: integer\n indicates what type of factorization (if any) is used.\n rank: integer\n indicates what type of factorization (if any) is used.\n update_option: integer\n indicates how the update logic is being run. More specifically:\n 0 - run the update logic in TF; needed when using GPU/TPU.\n 1 - run the update logic in regular python as opposed to TF.\n\n Returns:\n tf.HParams object initialized to default values.\n\n \"\"\"\n return contrib_training.HParams(\n name='model_compression',\n alpha_decrement_value=0.01,\n begin_compression_step=0,\n end_compression_step=-1,\n compression_frequency=10,\n use_tpu=False,\n compression_option=0,\n rank=7,\n update_option=0,\n run_update_interval_check=1,\n block_size=1,\n pruning_fraction=0.0)\n\n def add_compression_summaries(self):\n \"\"\"Adds summaries of alpha value, new variables, and last update step.\"\"\"\n with tf.compat.v1.name_scope(self._spec.name + '_summaries'):\n tf.compat.v1.summary.scalar(\n self._last_alpha_update_step.op.name + '/last_alpha_update_step',\n self._last_alpha_update_step)\n tf.compat.v1.summary.scalar(self.alpha.op.name + '/alpha', self.alpha)\n tf.compat.v1.summary.scalar(\n self.a_matrix_tfvar.op.name + '/a_matrix_norm',\n tf.norm(tensor=self.a_matrix_tfvar))\n tf.compat.v1.summary.scalar(\n self.b_matrix_tfvar.op.name + '/b_matrix_norm',\n tf.norm(tensor=self.b_matrix_tfvar))\n tf.compat.v1.summary.scalar(\n self.c_matrix_tfvar.op.name + '/c_matrix_norm',\n tf.norm(tensor=self.c_matrix_tfvar))\n\n def _setup_last_alpha_update_step(self):\n \"\"\"Setup to track last alpha update step.\"\"\"\n with tf.compat.v1.variable_scope(\n self._spec.name, use_resource=True) as scope:\n try:\n last_alpha_update_step = tf.compat.v1.get_variable(\n 'last_alpha_update_step',\n initializer=-1,\n trainable=False,\n dtype=tf.int32)\n except ValueError:\n scope.reuse_variables()\n last_alpha_update_step = tf.compat.v1.get_variable(\n 'last_alpha_update_step', dtype=tf.int32)\n return last_alpha_update_step\n\n def _alpha_update_op(self):\n \"\"\"Update alpha along with last_alpha_update_step.\"\"\"\n with tf.compat.v1.name_scope(self._spec.name):\n with tf.control_dependencies([\n tf.compat.v1.assign(\n self._last_alpha_update_step,\n tf.cast(self._global_step, tf.int32),\n name='last_alpha_update_step_assign')\n ]):\n with tf.control_dependencies([self._alpha_assign_op()]):\n logging.info('Updating alpha.')\n return tf.no_op('alpha_update')\n\n def _alpha_assign_op(self):\n new_alpha = tf.maximum(self.alpha - self._spec.alpha_decrement_value, 0)\n alpha_assign_op = tf.compat.v1.assign(\n self.alpha, new_alpha, name='alpha_assign_op')\n return alpha_assign_op\n\n def _compressor_op(self, matrix_compressor, a_matrix_tfvar):\n \"\"\"Creates compressor op based on matrix_compressor.\n\n Meant to create the factors once at begin_compression_step.\n\n Args:\n matrix_compressor: specifies the matrix compressor object.\n a_matrix_tfvar: the tf tensor to be compressed.\n \"\"\"\n # py_func is not supported on TPU so need non py_func implementation\n use_tpu = self._spec.use_tpu\n # Seeing some tf.py_func error because of which the\n # following may be needed, so enforcing TF operation updates.\n if use_tpu:\n [b_matrix_out,\n c_matrix_out] = matrix_compressor.tpu_matrix_compressor(a_matrix_tfvar)\n else:\n [b_matrix_out, c_matrix_out\n ] = tf.compat.v1.py_func(matrix_compressor.static_matrix_compressor,\n [a_matrix_tfvar], [tf.float32, tf.float32])\n\n b_matrix_assign_op = tf.compat.v1.assign(\n self.b_matrix_tfvar, b_matrix_out, name='b_matrix_assign_op')\n c_matrix_assign_op = tf.compat.v1.assign(\n self.c_matrix_tfvar, c_matrix_out, name='c_matrix_assign_op')\n with tf.control_dependencies([b_matrix_assign_op, c_matrix_assign_op]):\n logging.info('Updating b_matrix,c_matrix.')\n return tf.no_op('compresor_b_matrix_and_c_matrix_update')\n\n def _compressor_and_alpha_update_op(self):\n \"\"\"Applies compressor and also updates alpha.\"\"\"\n\n def compressor_op():\n return self._compressor_op(self.matrix_compressor, self.a_matrix_tfvar)\n\n def tf_no_op():\n return tf.no_op()\n\n cond_compressor_op = tf.cond(\n pred=self._last_alpha_update_step < 0,\n true_fn=compressor_op,\n false_fn=tf_no_op)\n\n with tf.control_dependencies([cond_compressor_op]):\n with tf.control_dependencies([self._alpha_update_op()]):\n return tf.no_op('alpha_update')\n\n def _create_update_op(self):\n \"\"\"Creates tensoflow update op for the compression.\"\"\"\n\n def maybe_update_alpha():\n \"\"\"Operator to update alpha.\n\n Checks if global_step is between begin_compression_step and\n end_compression_step.\n \"\"\"\n with tf.compat.v1.name_scope(self._spec.name):\n # prune if current step is more than begin_compression_step and\n # less than end_compression_step (unless it's negative)\n is_step_within_compression_range = tf.logical_and(\n tf.greater_equal(\n tf.cast(self._global_step, tf.int32),\n self._spec.begin_compression_step),\n tf.logical_or(\n tf.less_equal(\n tf.cast(self._global_step, tf.int32),\n self._spec.end_compression_step),\n tf.less(self._spec.end_compression_step, 0)))\n is_compression_step = tf.less_equal(\n tf.add(self._last_alpha_update_step,\n self._spec.compression_frequency),\n tf.cast(self._global_step, tf.int32))\n return tf.logical_and(is_step_within_compression_range,\n is_compression_step)\n\n def no_update_op():\n return tf.no_op()\n\n def compressor_and_alpha_update_op_fn():\n return self._compressor_and_alpha_update_op()\n\n cond_alpha_update_op = tf.cond(\n pred=maybe_update_alpha(),\n true_fn=compressor_and_alpha_update_op_fn,\n false_fn=no_update_op)\n self.update_op = cond_alpha_update_op\n return self.update_op\n\n def get_apply_compression_op(self,\n a_matrix_tfvar,\n matrix_compressor,\n scope='default_scope'):\n \"\"\"Returns compressed tensorflow operator.\n\n Does this for variable a_matrix_tfvar for\n compression method specified in matrix_compressor that must be based on some\n matrix factorization compression algorithm by replacing a variable\n a_matrix by alpha*a_matrix + (1-alpha)b_matrix*c_matrix.\n\n Args:\n a_matrix_tfvar: TF variable representihg a tensor variable in a model.\n matrix_compressor: MatrixCompressorInferface object to specify the\n compression algorithm. Must return two matrices b_matrix,c_matrix in its\n compression.\n scope: TF scope used for creating new TF variables.\n\n Returns:\n A TF node that has the compressed version of a_matrix_tfvar.\n \"\"\"\n self.matrix_compressor = matrix_compressor\n a_matrix = np.zeros(shape=a_matrix_tfvar.shape)\n [b_matrix, c_matrix] = matrix_compressor.static_matrix_compressor(a_matrix)\n with tf.compat.v1.variable_scope(scope, use_resource=True):\n self.b_matrix_tfvar = tf.compat.v1.get_variable(\n 'b_matrix',\n dtype=tf.float32,\n initializer=b_matrix.astype(np.float32),\n trainable=self.matrix_compressor.get_spec().is_b_matrix_trainable)\n self.c_matrix_tfvar = tf.compat.v1.get_variable(\n 'c_matrix',\n dtype=tf.float32,\n initializer=c_matrix.astype(np.float32),\n trainable=self.matrix_compressor.get_spec().is_c_matrix_trainable)\n self.alpha = tf.compat.v1.get_variable(\n 'alpha', dtype=tf.float32, trainable=False, initializer=1.0)\n\n self.a_matrix_tfvar = a_matrix_tfvar\n\n if self._spec.update_option == 0:\n self.update_op = self._create_update_op()\n else:\n self.setup_update_explicit()\n\n self.final_op = self.alpha * self.a_matrix_tfvar + (\n 1 - self.alpha) * tf.matmul(self.b_matrix_tfvar, self.c_matrix_tfvar)\n\n self.add_compression_summaries()\n return [self.final_op, self.update_op]\n\n def get_apply_embedding_lookup(self, ids):\n \"\"\"Returns compressed tensorflow operator for embedding_lookup.\n\n This method returns a TensorFlow node that performs embedding lookup as\n alpha * tf.nn.embedding_lookup(a_matrix_tfvar, ids) +\n (1 - alpha) * tf.nn.embedding_lookup(b_matrix_tfvar, ids) if c_matrix is\n not present, and alpha * tf.nn.embedding_lookup(a_matrix_tfvar, ids) +\n (1 - alpha) * tf.matmul(tf.nn.embedding_lookup(b_matrix_tfvar, ids),\n c_matrix) if c_matrix is present, where b_matrix_tfvar and c_matrix_tfvar\n are the factor matrices for the compressed embedding table.\n\n Args:\n ids: A Tensor with type int32 or int64 containing the ids to be looked up\n in the embedding table (the a_matrix_tfvar variable).\n\n Returns:\n embedding_op: a TensorFlow node that performs compressed embedding lookup.\n \"\"\"\n if self.matrix_compressor.get_spec().is_c_matrix_present:\n embedding_op = self.alpha * tf.nn.embedding_lookup(\n self.a_matrix_tfvar, ids) + (1 - self.alpha) * tf.matmul(\n tf.nn.embedding_lookup(self.b_matrix_tfvar, ids),\n self.c_matrix_tfvar)\n else:\n embedding_op = self.alpha * tf.nn.embedding_lookup(\n self.a_matrix_tfvar, ids) + (1 - self.alpha) * tf.nn.embedding_lookup(\n self.b_matrix_tfvar, ids)\n\n return embedding_op\n\n def get_apply_matmul(self, left_operand):\n \"\"\"Returns compressed TensorFlow node for matmul.\n\n This method performs matmul (on the right) with the compressed matrix.\n\n Args:\n left_operand: a Tensor that is the left operand in matmul.\n\n Returns:\n matmul_op: a TensorFlow node that performs matmul of left_operand with the\n compressed a_matrix_tfvar.\n \"\"\"\n # Applies matmul on the right\n if self.matrix_compressor.get_spec().is_c_matrix_present:\n matmul_op = self.alpha * tf.matmul(\n left_operand, tf.transpose(\n self.a_matrix_tfvar)) + (1 - self.alpha) * tf.matmul(\n tf.matmul(left_operand, tf.transpose(self.c_matrix_tfvar)),\n tf.transpose(self.b_matrix_tfvar))\n else:\n matmul_op = self.alpha * tf.matmul(\n left_operand, tf.transpose(\n self.a_matrix_tfvar)) + (1 - self.alpha) * tf.matmul(\n left_operand, tf.transpose(self.b_matrix_tfvar))\n\n return matmul_op\n\n @staticmethod\n def all_update_op(update_ops_list, scope='default_scope'):\n \"\"\"Method to create a complete update op.\n\n Args:\n update_ops_list: list of individual update ops.\n scope: tf scope for creating update op.\n \"\"\"\n with tf.compat.v1.name_scope(scope):\n with tf.control_dependencies(update_ops_list):\n logging.info('Updating all compression_ops.')\n return tf.no_op('update_all_compression_ops')\n\n def _validate_spec(self):\n spec = self._spec\n if spec.begin_compression_step < 0:\n raise ValueError('Illegal value for begin_compression_step')\n\n if spec.begin_compression_step >= spec.end_compression_step:\n if spec.end_compression_step != -1:\n raise ValueError(\n 'Compression must begin before it can end. begin_step=%d, '\n 'end_step=%d. Set end_compression_step to -1 if compression is '\n 'required till training stops' %\n (spec.begin_compression_step, spec.end_compression_step))\n\n def _setup_global_step(self, global_step):\n graph_global_step = global_step\n if graph_global_step is None:\n graph_global_step = tf.get_global_step()\n logging.info('graph_global_step: %s', graph_global_step)\n return tf.cast(graph_global_step, tf.int32)\n\n def print_hparams(self):\n logging.info(self._spec.to_json())\n\n def setup_update_explicit(self):\n self._alpha_update_tf_op = self._alpha_update_op()\n return self._alpha_update_tf_op\n\n def run_update_step(self, session, step_number=None):\n \"\"\"Returns the combine update tf OP.\"\"\"\n logging.info('running run_update_step self._global_step is %s name is %s',\n self._global_step, self.a_matrix_tfvar.op.name)\n if step_number is None:\n if self._spec.run_update_interval_check != 0:\n logging.info(\n 'running run_update_step step_num is null self.globalstep is %s',\n self._global_step)\n step_number = session.run(self._global_step)\n logging.info('running run_update_step step_num is %s', step_number)\n else:\n step_number = 1\n\n logging.info(\n 'In compression op.run_update_step: '\n 'step_number is %s, begin, end and update_count are: %s %s %s ',\n step_number, self._spec.begin_compression_step,\n self._spec.end_compression_step, self.run_update_count)\n if (step_number >= self._spec.begin_compression_step and\n step_number < self._spec.end_compression_step):\n logging.info(\n 'In compression op.run_update_step:'\n 'step_number is %s, begin, end and update_count are: %s %s %s ',\n step_number, self._spec.begin_compression_step,\n self._spec.end_compression_step, self.run_update_count)\n self.run_update_count += 1\n logging.info('inside compression interval')\n\n # Need to persist these python state variables in TF as if a task gets\n # aborted things get out of sync.\n self._last_update_step = session.run(self._last_alpha_update_step)\n logging.info(\n 'In compression op.run_update_step: '\n 'step_number is %s, begin, end, update_count, last_alpha_update'\n ' are: %s %s %s %s',\n step_number, self._spec.begin_compression_step,\n self._spec.end_compression_step, self.run_update_count,\n self._last_update_step)\n if self._last_update_step == -1:\n logging.info(\n 'In compression op.run_update_step: step_number is %s, '\n 'begin, end, update_count are: %s %s %s ',\n step_number, self._spec.begin_compression_step,\n self._spec.end_compression_step, self.run_update_count)\n print('inside compression interval: initial decomposition step')\n a_matrix = session.run(self.a_matrix_tfvar)\n logging.info(\n 'In compression op.run_update_step: '\n 'a_matrix.shape is %s norm is %d',\n a_matrix.shape, np.linalg.norm(a_matrix))\n if self.matrix_compressor.get_spec().is_c_matrix_present:\n logging.info(\n 'In compression op.run_update_step: '\n 'step_number is %s, begin, end and update_count are: %s %s %s ',\n step_number, self._spec.begin_compression_step,\n self._spec.end_compression_step, self.run_update_count)\n [b_matrix,\n c_matrix] = self.matrix_compressor.static_matrix_compressor(a_matrix)\n session.run(tf.assign(self.b_matrix_tfvar, b_matrix))\n session.run(tf.assign(self.c_matrix_tfvar, c_matrix))\n else:\n [b_matrix] = self.matrix_compressor.static_matrix_compressor(a_matrix)\n session.run(tf.assign(self.b_matrix_tfvar, b_matrix))\n logging.info(\n 'In compression op.run_update_step: '\n 'step_number is %s, begin, end and update_count are: %s %s %s ',\n step_number, self._spec.begin_compression_step,\n self._spec.end_compression_step, self.run_update_count)\n\n alpha = session.run(self.alpha)\n self.last_alpha_value = alpha\n if self.last_alpha_value > 0:\n make_a_zero = False\n new_alpha = max(alpha - self._spec.alpha_decrement_value, 0)\n if make_a_zero and new_alpha == 0:\n logging.info('Making a_matrix all zero for %s',\n self.a_matrix_tfvar.op.name)\n a_matrix = np.zeros(shape=self.a_matrix_tfvar.shape)\n session.run(tf.assign(self.a_matrix_tfvar, a_matrix))\n logging.info('in run_update_step decrementing alpha, alpha value is %d',\n self.last_alpha_value)\n\n logging.info(\n 'running run_update_step self._global_step is %s new and old alpha are %d %d',\n self._global_step, alpha, new_alpha)\n session.run(tf.assign(self.alpha, new_alpha))\n self.last_alpha_value = new_alpha\n self._last_update_step = step_number\n session.run(tf.assign(self._last_alpha_update_step, step_number))\n logging.info(\n 'In compression op.run_update_step: '\n 'step_number is %s, begin, end and update_count are: %s %s %s ',\n step_number, self._spec.begin_compression_step,\n self._spec.end_compression_step, self.run_update_count)\n\n\nclass ApplyCompression(object):\n \"\"\"Wrapper class.\n\n This is to repeatedly invoke above compression operator to different\n layers in a model.\n\n Intialized by specifying the compressor and compression_spec.\n\n After that apply_compression can be called several times for different\n matrices in the model.\n\n Finally all_update_op returns the combined update OP from all these\n compressions.\n \"\"\"\n\n def __init__(self, scope, compression_spec, compressor, global_step=None):\n \"\"\"Initializer.\n\n Args:\n scope: TF scope used for creating new TF variables.\n compression_spec: compression hyper parameters.\n compressor: matrix compressor object of class MatrixCompressorInferface.\n global_step: tf variable that has the global step.\n \"\"\"\n logging.info('Entering ApplyCompression constructor')\n self._compression_op_spec = compression_spec\n self._scope = scope\n self._global_step = global_step\n self._matrix_compressor = compressor\n self._compression_ops = []\n self._update_ops = []\n self._all_update_op = None\n\n self.uncompressed_size = 0\n self.compressed_size = 0\n\n def apply_compression(self, a_matrix_tfvar, scope='default_scope'):\n \"\"\"Applies matrix compression OP on a_matrix_tfvar as specified in spec.\n\n Args:\n a_matrix_tfvar: TF variable representing a tensor variable in a model.\n scope: TF scope used for creating new TF variables.\n\n Returns:\n TF node that represents the compressed version of a_matrix_tfvar.\n \"\"\"\n c = CompressionOp(\n scope=scope,\n spec=self._compression_op_spec,\n global_step=self._global_step)\n self._compression_ops.append(c)\n [a_matrix_compressed, a_matrix_update_op] = c.get_apply_compression_op(\n a_matrix_tfvar, self._matrix_compressor, scope=scope)\n self._update_ops.append(a_matrix_update_op)\n\n self.uncompressed_size = self.uncompressed_size + c.uncompressed_size\n self.compressed_size = self.compressed_size + c.compressed_size\n\n return a_matrix_compressed\n\n def get_last_compression_op(self):\n return self._compression_ops[-1]\n\n def all_update_op(self):\n \"\"\"Returns the combine update tf OP.\"\"\"\n self._all_update_op = CompressionOp.all_update_op(self._update_ops,\n self._scope)\n return self._all_update_op\n\n def run_update_step(self, session=None, step_number=None):\n \"\"\"Returns the combine update tf OP.\"\"\"\n logging.info('running AC run_update_step step_num is %s', step_number)\n\n for comp_op in self._compression_ops:\n logging.info('running run_update_step step_num is %s', step_number)\n comp_op.run_update_step(session=session, step_number=step_number)\n logging.info('Finished running run_update_step step_num is %s',\n step_number)\n\n def get_operator_hparam(self, hparam):\n \"\"\"Returns the value of queried hparam of the compression operator.\"\"\"\n return self._compression_op_spec.get(hparam)\n\n def get_compression_ops(self):\n \"\"\"Returns the compression operators used during the update steps.\n\n Returns:\n A list of CompressionOp objects.\n \"\"\"\n return copy.copy(self._compression_ops)\n\n def get_spec(self):\n \"\"\"Get the spec / hparams used to create the Pruning object.\"\"\"\n return self._compression_op_spec\n\n\nclass CompressionOpEager(tf.keras.layers.Layer):\n \"\"\"CompressionOp class that supports eager execution.\n\n It replaces the alpha_update_op in CompressionOp by an explicit\n run_update_step method, and relies on clients to pass in a step_number.\n \"\"\"\n\n def __init__(self, last_alpha_update_step=-1, spec=None):\n super(CompressionOpEager, self).__init__()\n\n self._spec = spec if spec else self.get_default_hparams()\n logging.info('Compression spec in init CompressionOpEager is: %s',\n self._spec)\n\n self.last_alpha_update_step = tf.Variable(\n last_alpha_update_step, dtype=tf.int32, trainable=False)\n self.alpha = tf.Variable(1.0, dtype=tf.float32, trainable=False)\n\n @staticmethod\n def get_default_hparams():\n \"\"\"Get a tf.HParams object with the default values for the hyperparameters.\n\n name: string\n name of the compression specification. Used for adding summaries and ops\n under a common tensorflow name_scope.\n alpha_decrement_value: float\n a positive real number by which alpha is decremented at each update.\n begin_compression_step: integer\n the global step at which to begin compression.\n end_compression_step: integer\n the global step at which to terminate compression. Defaults to -1\n implying that compression continues till the training stops.\n use_tpu: False\n indicates whether to use TPU.\n compression_option: integer\n indicates what type of factorization (if any) is used.\n rank: integer\n indicates what type of factorization (if any) is used.\n update_option: integer\n indicates how the update logic is being run. More specifically:\n 0 - run the update logic in TF; needed when using GPU/TPU.\n 1 - run the update logic in regular python as opposed to TF.\n\n Returns:\n tf.HParams object initialized to default values.\n\n \"\"\"\n return contrib_training.HParams(\n name='model_compression',\n alpha_decrement_value=0.01,\n begin_compression_step=0,\n end_compression_step=-1,\n compression_frequency=10,\n use_tpu=False,\n compression_option=0,\n rank=7,\n update_option=0)\n\n def set_up_variables(self, a_matrix_tfvar, matrix_compressor):\n \"\"\"Creates compression specific variables.\n\n Args:\n a_matrix_tfvar: the matrix to be compressed, Tensor\n matrix_compressor: a matrix compressor object (instance of a sub-class of\n MatrixCompressorInterface)\n \"\"\"\n self.matrix_compressor = matrix_compressor\n a_matrix = np.zeros(shape=a_matrix_tfvar.shape)\n b_matrix, c_matrix = matrix_compressor.static_matrix_compressor(a_matrix)\n self.b_matrix_tfvar = tf.Variable(\n b_matrix,\n name='b_matrix',\n dtype=tf.float32,\n trainable=self.matrix_compressor.get_spec().is_b_matrix_trainable)\n self.c_matrix_tfvar = tf.Variable(\n c_matrix,\n name='c_matrix',\n dtype=tf.float32,\n trainable=self.matrix_compressor.get_spec().is_c_matrix_trainable)\n self.a_matrix_tfvar = a_matrix_tfvar\n\n @tf.function\n def _get_apply_compression(self, alpha, a_matrix_tfvar, b_matrix_tfvar,\n c_matrix_tfvar):\n final_op = alpha * a_matrix_tfvar + (1 - alpha) * tf.matmul(\n b_matrix_tfvar, c_matrix_tfvar)\n return final_op\n\n def get_apply_compression(self):\n self.final_op = self._get_apply_compression(self.alpha, self.a_matrix_tfvar,\n self.b_matrix_tfvar,\n self.c_matrix_tfvar)\n return self.final_op\n\n def run_update_step(self, step_number):\n \"\"\"Run matrix and alpha update step if criterion is met.\n\n Args:\n step_number: step number in the training process.\n Note: This method should only be called during training.\n \"\"\"\n if (step_number >= self._spec.begin_compression_step and\n (step_number < self._spec.end_compression_step or\n self._spec.end_compression_step == -1)):\n if self.last_alpha_update_step.numpy() == -1:\n a_matrix = self.a_matrix_tfvar.numpy()\n b_matrix, c_matrix = self.matrix_compressor.static_matrix_compressor(\n a_matrix)\n self.b_matrix_tfvar.assign(b_matrix)\n self.c_matrix_tfvar.assign(c_matrix)\n if self.alpha.numpy() > 0:\n self.alpha.assign(\n max(self.alpha.numpy() - self._spec.alpha_decrement_value, 0))\n self.last_alpha_update_step.assign(step_number)\n"
]
| [
[
"tensorflow.compat.v1.assign",
"tensorflow.compat.v1.transpose",
"tensorflow.compat.v1.matmul",
"tensorflow.compat.v1.less",
"numpy.linalg.norm",
"tensorflow.compat.v1.logical_and",
"tensorflow.compat.v1.sqrt",
"numpy.sqrt",
"tensorflow.compat.v1.compat.v1.get_variable",
"tensorflow.contrib.training.HParams",
"tensorflow.compat.v1.cast",
"tensorflow.compat.v1.add",
"numpy.matmul",
"numpy.zeros",
"tensorflow.compat.v1.compat.v1.assign",
"tensorflow.compat.v1.compat.v1.name_scope",
"tensorflow.compat.v1.linalg.svd",
"tensorflow.compat.v1.compat.v1.summary.scalar",
"tensorflow.compat.v1.control_dependencies",
"tensorflow.compat.v1.maximum",
"numpy.linalg.svd",
"tensorflow.compat.v1.cond",
"tensorflow.compat.v1.norm",
"tensorflow.compat.v1.compat.v1.variable_scope",
"tensorflow.compat.v1.nn.embedding_lookup",
"tensorflow.compat.v1.get_global_step",
"tensorflow.compat.v1.no_op",
"tensorflow.compat.v1.compat.v1.py_func",
"tensorflow.compat.v1.Variable"
]
]
|
matejklemen/morphological-dependency-parsing | [
"2ab24b8621debe6e3288ade01c9604a06f9bd453"
]
| [
"supar/modules/biaffine.py"
]
| [
"# -*- coding: utf-8 -*-\n\nimport torch\nimport torch.nn as nn\n\n\nclass Biaffine(nn.Module):\n \"\"\"\n Biaffine layer for first-order scoring.\n\n This function has a tensor of weights `W` and bias terms if needed.\n The score `s(x, y)` of the vector pair `(x, y)` is computed as `x^T W y`,\n in which `x` and `y` can be concatenated with bias terms.\n\n References:\n - Timothy Dozat and Christopher D. Manning (ICLR'17)\n Deep Biaffine Attention for Neural Dependency Parsing\n https://openreview.net/pdf?id=Hk95PK9le/\n\n Args:\n n_in (int):\n The dimension of the input feature.\n n_out (int):\n The number of output channels.\n bias_x (bool):\n If True, add a bias term for tensor x. Default: False.\n bias_y (bool):\n If True, add a bias term for tensor y. Default: False.\n \"\"\"\n\n def __init__(self, n_in, n_out=1, bias_x=True, bias_y=True):\n super().__init__()\n\n self.n_in = n_in\n self.n_out = n_out\n self.bias_x = bias_x\n self.bias_y = bias_y\n self.weight = nn.Parameter(torch.Tensor(n_out,\n n_in + bias_x,\n n_in + bias_y))\n self.reset_parameters()\n\n def extra_repr(self):\n s = f\"n_in={self.n_in}, n_out={self.n_out}\"\n if self.bias_x:\n s += f\", bias_x={self.bias_x}\"\n if self.bias_y:\n s += f\", bias_y={self.bias_y}\"\n\n return s\n\n def reset_parameters(self):\n nn.init.zeros_(self.weight)\n\n def forward(self, x, y):\n \"\"\"\n Args:\n x (torch.Tensor): [batch_size, seq_len, n_in]\n y (torch.Tensor): [batch_size, seq_len, n_in]\n\n Returns:\n s (torch.Tensor): [batch_size, n_out, seq_len, seq_len]\n If n_out is 1, the dimension of n_out will be squeezed automatically.\n \"\"\"\n\n if self.bias_x:\n x = torch.cat((x, torch.ones_like(x[..., :1])), -1)\n if self.bias_y:\n y = torch.cat((y, torch.ones_like(y[..., :1])), -1)\n # [batch_size, n_out, seq_len, seq_len]\n s = torch.einsum('bxi,oij,byj->boxy', x, self.weight, y)\n # remove dim 1 if n_out == 1\n s = s.squeeze(1)\n\n return s\n"
]
| [
[
"torch.ones_like",
"torch.nn.init.zeros_",
"torch.Tensor",
"torch.einsum"
]
]
|
bsugerman/falcon | [
"8990cc1874b75773a27eb7838610e4052c6020c8"
]
| [
"eval.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCalculate mAP for YOLO model on some annotation dataset\n\"\"\"\nimport os, argparse, time\nimport numpy as np\nimport operator\nfrom operator import mul\nfrom functools import reduce\nfrom PIL import Image\nfrom collections import OrderedDict\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\nfrom tensorflow.keras.models import load_model\nimport tensorflow.keras.backend as K\nimport tensorflow as tf\nimport MNN\nimport onnxruntime\n\nfrom yolo3.postprocess_np import yolo3_postprocess_np\nfrom yolo2.postprocess_np import yolo2_postprocess_np\nfrom common.data_utils import preprocess_image\nfrom common.utils import get_dataset, get_classes, get_anchors, get_colors, draw_boxes, optimize_tf_gpu, get_custom_objects\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\noptimize_tf_gpu(tf, K)\n\n\ndef annotation_parse(annotation_lines, class_names):\n '''\n parse annotation lines to get image dict and ground truth class dict\n\n image dict would be like:\n annotation_records = {\n '/path/to/000001.jpg': {'100,120,200,235':'dog', '85,63,156,128':'car', ...},\n ...\n }\n\n ground truth class dict would be like:\n classes_records = {\n 'car': [\n ['000001.jpg','100,120,200,235'],\n ['000002.jpg','85,63,156,128'],\n ...\n ],\n ...\n }\n '''\n annotation_records = OrderedDict()\n classes_records = OrderedDict({class_name: [] for class_name in class_names})\n\n for line in annotation_lines:\n box_records = {}\n image_name = line.split(' ')[0]\n boxes = line.split(' ')[1:]\n for box in boxes:\n #strip box coordinate and class\n class_name = class_names[int(box.split(',')[-1])]\n coordinate = ','.join(box.split(',')[:-1])\n box_records[coordinate] = class_name\n #append or add ground truth class item\n record = [os.path.basename(image_name), coordinate]\n if class_name in classes_records:\n classes_records[class_name].append(record)\n else:\n classes_records[class_name] = list([record])\n annotation_records[image_name] = box_records\n\n return annotation_records, classes_records\n\n\ndef transform_gt_record(gt_records, class_names):\n '''\n Transform the Ground Truth records of a image to prediction format, in\n order to show & compare in result pic.\n\n Ground Truth records is a dict with format:\n {'100,120,200,235':'dog', '85,63,156,128':'car', ...}\n\n Prediction format:\n (boxes, classes, scores)\n '''\n if gt_records is None or len(gt_records) == 0:\n return [], [], []\n\n gt_boxes = []\n gt_classes = []\n gt_scores = []\n for (coordinate, class_name) in gt_records.items():\n gt_box = [int(x) for x in coordinate.split(',')]\n gt_class = class_names.index(class_name)\n\n gt_boxes.append(gt_box)\n gt_classes.append(gt_class)\n gt_scores.append(1.0)\n\n return np.array(gt_boxes), np.array(gt_classes), np.array(gt_scores)\n\n\n\ndef yolo_predict_tflite(interpreter, image, anchors, num_classes, conf_threshold):\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\n\n # check the type of the input tensor\n #if input_details[0]['dtype'] == np.float32:\n #floating_model = True\n\n height = input_details[0]['shape'][1]\n width = input_details[0]['shape'][2]\n model_image_size = (height, width)\n\n image_data = preprocess_image(image, model_image_size)\n #origin image shape, in (height, width) format\n image_shape = tuple(reversed(image.size))\n\n interpreter.set_tensor(input_details[0]['index'], image_data)\n interpreter.invoke()\n\n prediction = []\n for output_detail in output_details:\n output_data = interpreter.get_tensor(output_detail['index'])\n prediction.append(output_data)\n\n prediction.sort(key=lambda x: len(x[0]))\n if len(anchors) == 5:\n # YOLOv2 use 5 anchors and have only 1 prediction\n assert len(prediction) == 1, 'invalid YOLOv2 prediction number.'\n pred_boxes, pred_classes, pred_scores = yolo2_postprocess_np(prediction[0], image_shape, anchors, num_classes, model_image_size, max_boxes=100, confidence=conf_threshold)\n else:\n pred_boxes, pred_classes, pred_scores = yolo3_postprocess_np(prediction, image_shape, anchors, num_classes, model_image_size, max_boxes=100, confidence=conf_threshold)\n\n return pred_boxes, pred_classes, pred_scores\n\n\ndef yolo_predict_mnn(interpreter, session, image, anchors, num_classes, conf_threshold):\n # assume only 1 input tensor for image\n input_tensor = interpreter.getSessionInput(session)\n # get input shape\n input_shape = input_tensor.getShape()\n if input_tensor.getDimensionType() == MNN.Tensor_DimensionType_Tensorflow:\n batch, height, width, channel = input_shape\n elif input_tensor.getDimensionType() == MNN.Tensor_DimensionType_Caffe:\n batch, channel, height, width = input_shape\n else:\n # should be MNN.Tensor_DimensionType_Caffe_C4, unsupported now\n raise ValueError('unsupported input tensor dimension type')\n\n model_image_size = (height, width)\n\n # prepare input image\n image_data = preprocess_image(image, model_image_size)\n #origin image shape, in (height, width) format\n image_shape = tuple(reversed(image.size))\n\n # use a temp tensor to copy data\n tmp_input = MNN.Tensor(input_shape, input_tensor.getDataType(),\\\n image_data, input_tensor.getDimensionType())\n\n input_tensor.copyFrom(tmp_input)\n interpreter.runSession(session)\n\n def get_tensor_list(output_tensors):\n # transform the output tensor dict to ordered tensor list, for further postprocess\n #\n # output tensor list should be like (for YOLOv3):\n # [\n # (name, tensor) for (13, 13, 3, num_classes+5),\n # (name, tensor) for (26, 26, 3, num_classes+5),\n # (name, tensor) for (52, 52, 3, num_classes+5)\n # ]\n output_list = []\n\n for (output_tensor_name, output_tensor) in output_tensors.items():\n tensor_shape = output_tensor.getShape()\n dim_type = output_tensor.getDimensionType()\n tensor_height, tensor_width = tensor_shape[2:4] if dim_type == MNN.Tensor_DimensionType_Caffe else tensor_shape[1:3]\n\n if len(anchors) == 6:\n # Tiny YOLOv3\n if tensor_height == height//32:\n output_list.insert(0, (output_tensor_name, output_tensor))\n elif tensor_height == height//16:\n output_list.insert(1, (output_tensor_name, output_tensor))\n else:\n raise ValueError('invalid tensor shape')\n elif len(anchors) == 9:\n # YOLOv3\n if tensor_height == height//32:\n output_list.insert(0, (output_tensor_name, output_tensor))\n elif tensor_height == height//16:\n output_list.insert(1, (output_tensor_name, output_tensor))\n elif tensor_height == height//8:\n output_list.insert(2, (output_tensor_name, output_tensor))\n else:\n raise ValueError('invalid tensor shape')\n elif len(anchors) == 5:\n # YOLOv2 use 5 anchors and have only 1 prediction\n assert len(output_tensors) == 1, 'YOLOv2 model should have only 1 output tensor.'\n output_list.insert(0, (output_tensor_name, output_tensor))\n else:\n raise ValueError('invalid anchor number')\n\n return output_list\n\n output_tensors = interpreter.getSessionOutputAll(session)\n output_tensor_list = get_tensor_list(output_tensors)\n\n prediction = []\n for (output_tensor_name, output_tensor) in output_tensor_list:\n output_shape = output_tensor.getShape()\n output_elementsize = reduce(mul, output_shape)\n\n assert output_tensor.getDataType() == MNN.Halide_Type_Float\n\n # copy output tensor to host, for further postprocess\n tmp_output = MNN.Tensor(output_shape, output_tensor.getDataType(),\\\n #np.zeros(output_shape, dtype=float), output_tensor.getDimensionType())\n tuple(np.zeros(output_shape, dtype=float).reshape(output_elementsize, -1)), output_tensor.getDimensionType())\n\n output_tensor.copyToHostTensor(tmp_output)\n #tmp_output.printTensorData()\n\n output_data = np.array(tmp_output.getData(), dtype=float).reshape(output_shape)\n # our postprocess code based on TF channel last format, so if the output format\n # doesn't match, we need to transpose\n if output_tensor.getDimensionType() == MNN.Tensor_DimensionType_Caffe:\n output_data = output_data.transpose((0,2,3,1))\n elif output_tensor.getDimensionType() == MNN.Tensor_DimensionType_Caffe_C4:\n raise ValueError('unsupported output tensor dimension type')\n\n prediction.append(output_data)\n\n prediction.sort(key=lambda x: len(x[0]))\n if len(anchors) == 5:\n # YOLOv2 use 5 anchors and have only 1 prediction\n assert len(prediction) == 1, 'invalid YOLOv2 prediction number.'\n pred_boxes, pred_classes, pred_scores = yolo2_postprocess_np(prediction[0], image_shape, anchors, num_classes, model_image_size, max_boxes=100, confidence=conf_threshold)\n else:\n pred_boxes, pred_classes, pred_scores = yolo3_postprocess_np(prediction, image_shape, anchors, num_classes, model_image_size, max_boxes=100, confidence=conf_threshold)\n\n return pred_boxes, pred_classes, pred_scores\n\n\ndef yolo_predict_pb(model, image, anchors, num_classes, model_image_size, conf_threshold):\n # NOTE: TF 1.x frozen pb graph need to specify input/output tensor name\n # so we need to hardcode the input/output tensor names here to get them from model\n if len(anchors) == 6:\n output_tensor_names = ['graph/predict_conv_1/BiasAdd:0', 'graph/predict_conv_2/BiasAdd:0']\n elif len(anchors) == 9:\n output_tensor_names = ['graph/predict_conv_1/BiasAdd:0', 'graph/predict_conv_2/BiasAdd:0', 'graph/predict_conv_3/BiasAdd:0']\n elif len(anchors) == 5:\n # YOLOv2 use 5 anchors and have only 1 prediction\n output_tensor_names = ['graph/predict_conv/BiasAdd:0']\n else:\n raise ValueError('invalid anchor number')\n\n # assume only 1 input tensor for image\n input_tensor_name = 'graph/image_input:0'\n\n # get input/output tensors\n image_input = model.get_tensor_by_name(input_tensor_name)\n output_tensors = [model.get_tensor_by_name(output_tensor_name) for output_tensor_name in output_tensor_names]\n\n batch, height, width, channel = image_input.shape\n model_image_size = (int(height), int(width))\n\n # prepare input image\n image_data = preprocess_image(image, model_image_size)\n #origin image shape, in (height, width) format\n image_shape = tuple(reversed(image.size))\n\n with tf.Session(graph=model) as sess:\n prediction = sess.run(output_tensors, feed_dict={\n image_input: image_data\n })\n\n prediction.sort(key=lambda x: len(x[0]))\n if len(anchors) == 5:\n # YOLOv2 use 5 anchors and have only 1 prediction\n assert len(prediction) == 1, 'invalid YOLOv2 prediction number.'\n pred_boxes, pred_classes, pred_scores = yolo2_postprocess_np(prediction[0], image_shape, anchors, num_classes, model_image_size, max_boxes=100, confidence=conf_threshold)\n else:\n pred_boxes, pred_classes, pred_scores = yolo3_postprocess_np(prediction, image_shape, anchors, num_classes, model_image_size, max_boxes=100, confidence=conf_threshold)\n\n return pred_boxes, pred_classes, pred_scores\n\n\ndef yolo_predict_onnx(model, image, anchors, num_classes, conf_threshold):\n input_tensors = []\n for i, input_tensor in enumerate(model.get_inputs()):\n input_tensors.append(input_tensor)\n\n # assume only 1 input tensor for image\n assert len(input_tensors) == 1, 'invalid input tensor number.'\n\n batch, height, width, channel = input_tensors[0].shape\n model_image_size = (height, width)\n\n # prepare input image\n image_data = preprocess_image(image, model_image_size)\n #origin image shape, in (height, width) format\n image_shape = tuple(reversed(image.size))\n\n feed = {input_tensors[0].name: image_data}\n prediction = model.run(None, feed)\n\n prediction.sort(key=lambda x: len(x[0]))\n if len(anchors) == 5:\n # YOLOv2 use 5 anchors and have only 1 prediction\n assert len(prediction) == 1, 'invalid YOLOv2 prediction number.'\n pred_boxes, pred_classes, pred_scores = yolo2_postprocess_np(prediction[0], image_shape, anchors, num_classes, model_image_size, max_boxes=100, confidence=conf_threshold)\n else:\n pred_boxes, pred_classes, pred_scores = yolo3_postprocess_np(prediction, image_shape, anchors, num_classes, model_image_size, max_boxes=100, confidence=conf_threshold)\n\n return pred_boxes, pred_classes, pred_scores\n\n\ndef yolo_predict_keras(model, image, anchors, num_classes, model_image_size, conf_threshold):\n image_data = preprocess_image(image, model_image_size)\n #origin image shape, in (height, width) format\n image_shape = tuple(reversed(image.size))\n\n prediction = model.predict([image_data])\n if len(anchors) == 5:\n # YOLOv2 use 5 anchors\n pred_boxes, pred_classes, pred_scores = yolo2_postprocess_np(prediction, image_shape, anchors, num_classes, model_image_size, max_boxes=100, confidence=conf_threshold)\n else:\n pred_boxes, pred_classes, pred_scores = yolo3_postprocess_np(prediction, image_shape, anchors, num_classes, model_image_size, max_boxes=100, confidence=conf_threshold)\n\n return pred_boxes, pred_classes, pred_scores\n\n\ndef get_prediction_class_records(model, model_format, annotation_records, anchors, class_names, model_image_size, conf_threshold, save_result):\n '''\n Do the predict with YOLO model on annotation images to get predict class dict\n\n predict class dict would contain image_name, coordinary and score, and\n sorted by score:\n pred_classes_records = {\n 'car': [\n ['000001.jpg','94,115,203,232',0.98],\n ['000002.jpg','82,64,154,128',0.93],\n ...\n ],\n ...\n }\n '''\n if model_format == 'MNN':\n #MNN inference engine need create session\n session = model.createSession()\n\n # create txt file to save prediction result, with\n # save format as annotation file but adding score, like:\n #\n # path/to/img1.jpg 50,100,150,200,0,0.86 30,50,200,120,3,0.95\n #\n os.makedirs('result', exist_ok=True)\n result_file = open(os.path.join('result','detection_result.txt'), 'w')\n\n pred_classes_records = OrderedDict()\n pbar = tqdm(total=len(annotation_records), desc='Eval model')\n for (image_name, gt_records) in annotation_records.items():\n image = Image.open(image_name)\n if image.mode != 'RGB':\n image = image.convert('RGB')\n image_array = np.array(image, dtype='uint8')\n\n # support of tflite model\n if model_format == 'TFLITE':\n pred_boxes, pred_classes, pred_scores = yolo_predict_tflite(model, image, anchors, len(class_names), conf_threshold)\n # support of MNN model\n elif model_format == 'MNN':\n pred_boxes, pred_classes, pred_scores = yolo_predict_mnn(model, session, image, anchors, len(class_names), conf_threshold)\n # support of TF 1.x frozen pb model\n elif model_format == 'PB':\n pred_boxes, pred_classes, pred_scores = yolo_predict_pb(model, image, anchors, len(class_names), model_image_size, conf_threshold)\n # support of ONNX model\n elif model_format == 'ONNX':\n pred_boxes, pred_classes, pred_scores = yolo_predict_onnx(model, image, anchors, len(class_names), conf_threshold)\n # normal keras h5 model\n elif model_format == 'H5':\n pred_boxes, pred_classes, pred_scores = yolo_predict_keras(model, image, anchors, len(class_names), model_image_size, conf_threshold)\n else:\n raise ValueError('invalid model format')\n\n #print('Found {} boxes for {}'.format(len(pred_boxes), image_name))\n pbar.update(1)\n\n # save prediction result to txt\n result_file.write(image_name)\n for box, cls, score in zip(pred_boxes, pred_classes, pred_scores):\n xmin, ymin, xmax, ymax = box\n box_annotation = \" %d,%d,%d,%d,%d,%f\" % (\n xmin, ymin, xmax, ymax, cls, score)\n result_file.write(box_annotation)\n result_file.write('\\n')\n result_file.flush()\n\n if save_result:\n\n gt_boxes, gt_classes, gt_scores = transform_gt_record(gt_records, class_names)\n\n result_dir=os.path.join('result','detection')\n os.makedirs(result_dir, exist_ok=True)\n colors = get_colors(class_names)\n image_array = draw_boxes(image_array, gt_boxes, gt_classes, gt_scores, class_names, colors=None, show_score=False)\n image_array = draw_boxes(image_array, pred_boxes, pred_classes, pred_scores, class_names, colors)\n image = Image.fromarray(image_array)\n # here we handle the RGBA image\n if(len(image.split()) == 4):\n r, g, b, a = image.split()\n image = Image.merge(\"RGB\", (r, g, b))\n image.save(os.path.join(result_dir, image_name.split(os.path.sep)[-1]))\n\n # Nothing detected\n if pred_boxes is None or len(pred_boxes) == 0:\n continue\n\n for box, cls, score in zip(pred_boxes, pred_classes, pred_scores):\n pred_class_name = class_names[cls]\n xmin, ymin, xmax, ymax = box\n coordinate = \"{},{},{},{}\".format(xmin, ymin, xmax, ymax)\n\n #append or add predict class item\n record = [os.path.basename(image_name), coordinate, score]\n if pred_class_name in pred_classes_records:\n pred_classes_records[pred_class_name].append(record)\n else:\n pred_classes_records[pred_class_name] = list([record])\n\n # sort pred_classes_records for each class according to score\n for pred_class_list in pred_classes_records.values():\n pred_class_list.sort(key=lambda ele: ele[2], reverse=True)\n\n pbar.close()\n result_file.close()\n return pred_classes_records\n\n\ndef box_iou(pred_box, gt_box):\n '''\n Calculate iou for predict box and ground truth box\n Param\n pred_box: predict box coordinate\n (xmin,ymin,xmax,ymax) format\n gt_box: ground truth box coordinate\n (xmin,ymin,xmax,ymax) format\n Return\n iou value\n '''\n # get intersection box\n inter_box = [max(pred_box[0], gt_box[0]), max(pred_box[1], gt_box[1]), min(pred_box[2], gt_box[2]), min(pred_box[3], gt_box[3])]\n inter_w = max(0.0, inter_box[2] - inter_box[0] + 1)\n inter_h = max(0.0, inter_box[3] - inter_box[1] + 1)\n\n # compute overlap (IoU) = area of intersection / area of union\n pred_area = (pred_box[2] - pred_box[0] + 1) * (pred_box[3] - pred_box[1] + 1)\n gt_area = (gt_box[2] - gt_box[0] + 1) * (gt_box[3] - gt_box[1] + 1)\n inter_area = inter_w * inter_h\n union_area = pred_area + gt_area - inter_area\n return 0 if union_area == 0 else float(inter_area) / float(union_area)\n\n\ndef match_gt_box(pred_record, gt_records, iou_threshold=0.5):\n '''\n Search gt_records list and try to find a matching box for the predict box\n\n Param\n pred_record: with format ['image_file', 'xmin,ymin,xmax,ymax', score]\n gt_records: record list with format\n [\n ['image_file', 'xmin,ymin,xmax,ymax', 'usage'],\n ['image_file', 'xmin,ymin,xmax,ymax', 'usage'],\n ...\n ]\n iou_threshold:\n\n pred_record and gt_records should be from same annotation image file\n\n Return\n matching gt_record index. -1 when there's no matching gt\n '''\n max_iou = 0.0\n max_index = -1\n #get predict box coordinate\n pred_box = [float(x) for x in pred_record[1].split(',')]\n\n for i, gt_record in enumerate(gt_records):\n #get ground truth box coordinate\n gt_box = [float(x) for x in gt_record[1].split(',')]\n iou = box_iou(pred_box, gt_box)\n\n # if the ground truth has been assigned to other\n # prediction, we couldn't reuse it\n if iou > max_iou and gt_record[2] == 'unused' and pred_record[0] == gt_record[0]:\n max_iou = iou\n max_index = i\n\n # drop the prediction if couldn't match iou threshold\n if max_iou < iou_threshold:\n max_index = -1\n\n return max_index\n\ndef voc_ap(rec, prec):\n \"\"\"\n --- Official matlab code VOC2012---\n mrec=[0 ; rec ; 1];\n mpre=[0 ; prec ; 0];\n for i=numel(mpre)-1:-1:1\n mpre(i)=max(mpre(i),mpre(i+1));\n end\n i=find(mrec(2:end)~=mrec(1:end-1))+1;\n ap=sum((mrec(i)-mrec(i-1)).*mpre(i));\n \"\"\"\n rec.insert(0, 0.0) # insert 0.0 at begining of list\n rec.append(1.0) # insert 1.0 at end of list\n mrec = rec[:]\n prec.insert(0, 0.0) # insert 0.0 at begining of list\n prec.append(0.0) # insert 0.0 at end of list\n mpre = prec[:]\n \"\"\"\n This part makes the precision monotonically decreasing\n (goes from the end to the beginning)\n \"\"\"\n # matlab indexes start in 1 but python in 0, so I have to do:\n # range(start=(len(mpre) - 2), end=0, step=-1)\n # also the python function range excludes the end, resulting in:\n # range(start=(len(mpre) - 2), end=-1, step=-1)\n for i in range(len(mpre) - 2, -1, -1):\n mpre[i] = max(mpre[i], mpre[i + 1])\n \"\"\"\n This part creates a list of indexes where the recall changes\n \"\"\"\n # matlab: i=find(mrec(2:end)~=mrec(1:end-1))+1;\n i_list = []\n for i in range(1, len(mrec)):\n if mrec[i] != mrec[i - 1]:\n i_list.append(i) # if it was matlab would be i + 1\n \"\"\"\n The Average Precision (AP) is the area under the curve\n (numerical integration)\n \"\"\"\n # matlab: ap=sum((mrec(i)-mrec(i-1)).*mpre(i));\n ap = 0.0\n for i in i_list:\n ap += ((mrec[i] - mrec[i - 1]) * mpre[i])\n return ap, mrec, mpre\n\n'''\ndef voc_ap(rec, prec, use_07_metric=False):\n if use_07_metric:\n # 11 point metric\n ap = 0.\n for t in np.arange(0., 1.1, 0.1):\n if np.sum(rec >= t) == 0:\n p = 0\n else:\n p = np.max(prec[rec >= t])\n ap = ap + p / 11.\n else:\n mrec = np.concatenate(([0.], rec, [1.]))\n mpre = np.concatenate(([0.], prec, [0.]))\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n i = np.where(mrec[1:] != mrec[:-1])[0]\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap, mrec, mpre\n'''\n\n\ndef get_rec_prec(true_positive, false_positive, gt_records):\n '''\n Calculate precision/recall based on true_positive, false_positive\n result.\n '''\n cumsum = 0\n for idx, val in enumerate(false_positive):\n false_positive[idx] += cumsum\n cumsum += val\n\n cumsum = 0\n for idx, val in enumerate(true_positive):\n true_positive[idx] += cumsum\n cumsum += val\n\n rec = true_positive[:]\n for idx, val in enumerate(true_positive):\n rec[idx] = (float(true_positive[idx]) / len(gt_records)) if len(gt_records) != 0 else 0\n\n prec = true_positive[:]\n for idx, val in enumerate(true_positive):\n prec[idx] = float(true_positive[idx]) / (false_positive[idx] + true_positive[idx])\n\n return rec, prec\n\n\ndef draw_rec_prec(rec, prec, mrec, mprec, class_name, ap):\n \"\"\"\n Draw plot\n \"\"\"\n plt.plot(rec, prec, '-o')\n # add a new penultimate point to the list (mrec[-2], 0.0)\n # since the last line segment (and respective area) do not affect the AP value\n area_under_curve_x = mrec[:-1] + [mrec[-2]] + [mrec[-1]]\n area_under_curve_y = mprec[:-1] + [0.0] + [mprec[-1]]\n plt.fill_between(area_under_curve_x, 0, area_under_curve_y, alpha=0.2, edgecolor='r')\n # set window title\n fig = plt.gcf() # gcf - get current figure\n fig.canvas.set_window_title('AP ' + class_name)\n # set plot title\n plt.title('class: ' + class_name + ' AP = {}%'.format(ap*100))\n #plt.suptitle('This is a somewhat long figure title', fontsize=16)\n # set axis titles\n plt.xlabel('Recall')\n plt.ylabel('Precision')\n # optional - set axes\n axes = plt.gca() # gca - get current axes\n axes.set_xlim([0.0,1.0])\n axes.set_ylim([0.0,1.05]) # .05 to give some extra space\n # Alternative option -> wait for button to be pressed\n #while not plt.waitforbuttonpress(): pass # wait for key display\n # Alternative option -> normal display\n #plt.show()\n # save the plot\n rec_prec_plot_path = os.path.join('result','classes')\n os.makedirs(rec_prec_plot_path, exist_ok=True)\n fig.savefig(os.path.join(rec_prec_plot_path, class_name + \".png\"))\n plt.cla() # clear axes for next plot\n\n\ndef adjust_axes(r, t, fig, axes):\n \"\"\"\n Plot - adjust axes\n \"\"\"\n # get text width for re-scaling\n bb = t.get_window_extent(renderer=r)\n text_width_inches = bb.width / fig.dpi\n # get axis width in inches\n current_fig_width = fig.get_figwidth()\n new_fig_width = current_fig_width + text_width_inches\n propotion = new_fig_width / current_fig_width\n # get axis limit\n x_lim = axes.get_xlim()\n axes.set_xlim([x_lim[0], x_lim[1]*propotion])\n\n\ndef draw_plot_func(dictionary, n_classes, window_title, plot_title, x_label, output_path, to_show, plot_color, true_p_bar):\n \"\"\"\n Draw plot using Matplotlib\n \"\"\"\n # sort the dictionary by decreasing value, into a list of tuples\n sorted_dic_by_value = sorted(dictionary.items(), key=operator.itemgetter(1))\n # unpacking the list of tuples into two lists\n sorted_keys, sorted_values = zip(*sorted_dic_by_value)\n #\n if true_p_bar != \"\":\n \"\"\"\n Special case to draw in (green=true predictions) & (red=false predictions)\n \"\"\"\n fp_sorted = []\n tp_sorted = []\n for key in sorted_keys:\n fp_sorted.append(dictionary[key] - true_p_bar[key])\n tp_sorted.append(true_p_bar[key])\n plt.barh(range(n_classes), fp_sorted, align='center', color='crimson', label='False Predictions')\n plt.barh(range(n_classes), tp_sorted, align='center', color='forestgreen', label='True Predictions', left=fp_sorted)\n # add legend\n plt.legend(loc='lower right')\n \"\"\"\n Write number on side of bar\n \"\"\"\n fig = plt.gcf() # gcf - get current figure\n axes = plt.gca()\n r = fig.canvas.get_renderer()\n for i, val in enumerate(sorted_values):\n fp_val = fp_sorted[i]\n tp_val = tp_sorted[i]\n fp_str_val = \" \" + str(fp_val)\n tp_str_val = fp_str_val + \" \" + str(tp_val)\n # trick to paint multicolor with offset:\n # first paint everything and then repaint the first number\n t = plt.text(val, i, tp_str_val, color='forestgreen', va='center', fontweight='bold')\n plt.text(val, i, fp_str_val, color='crimson', va='center', fontweight='bold')\n if i == (len(sorted_values)-1): # largest bar\n adjust_axes(r, t, fig, axes)\n else:\n plt.barh(range(n_classes), sorted_values, color=plot_color)\n \"\"\"\n Write number on side of bar\n \"\"\"\n fig = plt.gcf() # gcf - get current figure\n axes = plt.gca()\n r = fig.canvas.get_renderer()\n for i, val in enumerate(sorted_values):\n str_val = \" \" + str(val) # add a space before\n if val < 1.0:\n str_val = \" {0:.2f}\".format(val)\n t = plt.text(val, i, str_val, color=plot_color, va='center', fontweight='bold')\n # re-set axes to show number inside the figure\n if i == (len(sorted_values)-1): # largest bar\n adjust_axes(r, t, fig, axes)\n # set window title\n fig.canvas.set_window_title(window_title)\n # write classes in y axis\n tick_font_size = 12\n plt.yticks(range(n_classes), sorted_keys, fontsize=tick_font_size)\n \"\"\"\n Re-scale height accordingly\n \"\"\"\n init_height = fig.get_figheight()\n # comput the matrix height in points and inches\n dpi = fig.dpi\n height_pt = n_classes * (tick_font_size * 1.4) # 1.4 (some spacing)\n height_in = height_pt / dpi\n # compute the required figure height\n top_margin = 0.15 # in percentage of the figure height\n bottom_margin = 0.05 # in percentage of the figure height\n figure_height = height_in / (1 - top_margin - bottom_margin)\n # set new height\n if figure_height > init_height:\n fig.set_figheight(figure_height)\n\n # set plot title\n plt.title(plot_title, fontsize=14)\n # set axis titles\n # plt.xlabel('classes')\n plt.xlabel(x_label, fontsize='large')\n # adjust size of window\n fig.tight_layout()\n # save the plot\n fig.savefig(output_path)\n # show image\n if to_show:\n plt.show()\n # close the plot\n plt.close()\n\n\ndef calc_AP(gt_records, pred_records, class_name, iou_threshold, show_result):\n '''\n Calculate AP value for one class records\n\n Param\n gt_records: ground truth records list for one class, with format:\n [\n ['image_file', 'xmin,ymin,xmax,ymax'],\n ['image_file', 'xmin,ymin,xmax,ymax'],\n ...\n ]\n pred_record: predict records for one class, with format:\n [\n ['image_file', 'xmin,ymin,xmax,ymax', score],\n ['image_file', 'xmin,ymin,xmax,ymax', score],\n ...\n ]\n Return\n AP value for the class\n '''\n # append usage flag in gt_records for matching gt search\n gt_records = [gt_record + ['unused'] for gt_record in gt_records]\n\n # init true_positive and false_positive list\n nd = len(pred_records) # number of predict data\n true_positive = [0] * nd\n false_positive = [0] * nd\n true_positive_count = 0\n # assign predictions to ground truth objects\n for idx, pred_record in enumerate(pred_records):\n # filter out gt record from same image\n image_gt_records = [ gt_record for gt_record in gt_records if gt_record[0] == pred_record[0]]\n\n i = match_gt_box(pred_record, image_gt_records, iou_threshold=iou_threshold)\n if i != -1:\n # find a valid gt obj to assign, set\n # true_positive list and mark image_gt_records.\n #\n # trick: gt_records will also be marked\n # as 'used', since image_gt_records is a\n # reference list\n image_gt_records[i][2] = 'used'\n true_positive[idx] = 1\n true_positive_count += 1\n else:\n false_positive[idx] = 1\n\n # compute precision/recall\n rec, prec = get_rec_prec(true_positive, false_positive, gt_records)\n ap, mrec, mprec = voc_ap(rec, prec)\n if show_result:\n draw_rec_prec(rec, prec, mrec, mprec, class_name, ap)\n\n return ap, true_positive_count\n\n\ndef plot_Pascal_AP_result(count_images, count_true_positives, num_classes,\n gt_counter_per_class, pred_counter_per_class,\n precision_dict, recall_dict, mPrec, mRec,\n APs, mAP, iou_threshold):\n '''\n Plot the total number of occurences of each class in the ground-truth\n '''\n window_title = \"Ground-Truth Info\"\n plot_title = \"Ground-Truth\\n\" + \"(\" + str(count_images) + \" files and \" + str(num_classes) + \" classes)\"\n x_label = \"Number of objects per class\"\n output_path = os.path.join('result','Ground-Truth_Info.png')\n draw_plot_func(gt_counter_per_class, num_classes, window_title, plot_title, x_label, output_path, to_show=False, plot_color='forestgreen', true_p_bar='')\n\n '''\n Plot the total number of occurences of each class in the \"predicted\" folder\n '''\n window_title = \"Predicted Objects Info\"\n # Plot title\n plot_title = \"Predicted Objects\\n\" + \"(\" + str(count_images) + \" files and \"\n count_non_zero_values_in_dictionary = sum(int(x) > 0 for x in list(pred_counter_per_class.values()))\n plot_title += str(count_non_zero_values_in_dictionary) + \" detected classes)\"\n # end Plot title\n x_label = \"Number of objects per class\"\n output_path = os.path.join('result','Predicted_Objects_Info.png')\n draw_plot_func(pred_counter_per_class, len(pred_counter_per_class), window_title, plot_title, x_label, output_path, to_show=False, plot_color='forestgreen', true_p_bar=count_true_positives)\n\n '''\n Draw mAP plot (Show AP's of all classes in decreasing order)\n '''\n window_title = \"mAP\"\n plot_title = \"mAP@IoU={0}: {1:.2f}%\".format(iou_threshold, mAP)\n x_label = \"Average Precision\"\n output_path = os.path.join('result','mAP.png')\n draw_plot_func(APs, num_classes, window_title, plot_title, x_label, output_path, to_show=False, plot_color='royalblue', true_p_bar='')\n\n '''\n Draw Precision plot (Show Precision of all classes in decreasing order)\n '''\n window_title = \"Precision\"\n plot_title = \"mPrec@IoU={0}: {1:.2f}%\".format(iou_threshold, mPrec)\n x_label = \"Precision rate\"\n output_path = os.path.join('result','Precision.png')\n draw_plot_func(precision_dict, len(precision_dict), window_title, plot_title, x_label, output_path, to_show=False, plot_color='royalblue', true_p_bar='')\n\n '''\n Draw Recall plot (Show Recall of all classes in decreasing order)\n '''\n window_title = \"Recall\"\n plot_title = \"mRec@IoU={0}: {1:.2f}%\".format(iou_threshold, mRec)\n x_label = \"Recall rate\"\n output_path = os.path.join('result','Recall.png')\n draw_plot_func(recall_dict, len(recall_dict), window_title, plot_title, x_label, output_path, to_show=False, plot_color='royalblue', true_p_bar='')\n\n\ndef get_mean_metric(metric_records, gt_classes_records):\n '''\n Calculate mean metric, but only count classes which have ground truth object\n\n Param\n metric_records: metric dict like:\n metric_records = {\n 'aeroplane': 0.79,\n 'bicycle': 0.79,\n ...\n 'tvmonitor': 0.71,\n }\n gt_classes_records: ground truth class dict like:\n gt_classes_records = {\n 'car': [\n ['000001.jpg','100,120,200,235'],\n ['000002.jpg','85,63,156,128'],\n ...\n ],\n ...\n }\n Return\n mean_metric: float value of mean metric\n '''\n mean_metric = 0.0\n count = 0\n for (class_name, metric) in metric_records.items():\n if (class_name in gt_classes_records) and (len(gt_classes_records[class_name]) != 0):\n mean_metric += metric\n count += 1\n mean_metric = (mean_metric/count)*100 if count != 0 else 0.0\n return mean_metric\n\n\ndef compute_mAP_PascalVOC(annotation_records, gt_classes_records, pred_classes_records, class_names, iou_threshold, show_result=True):\n '''\n Compute PascalVOC style mAP\n '''\n APs = {}\n count_true_positives = {class_name: 0 for class_name in list(gt_classes_records.keys())}\n #get AP value for each of the ground truth classes\n for _, class_name in enumerate(class_names):\n #if there's no gt obj for a class, record 0\n if class_name not in gt_classes_records:\n APs[class_name] = 0.\n continue\n gt_records = gt_classes_records[class_name]\n #if we didn't detect any obj for a class, record 0\n if class_name not in pred_classes_records:\n APs[class_name] = 0.\n continue\n pred_records = pred_classes_records[class_name]\n ap, true_positive_count = calc_AP(gt_records, pred_records, class_name, iou_threshold, show_result)\n APs[class_name] = ap\n count_true_positives[class_name] = true_positive_count\n\n #sort AP result by value, in descending order\n APs = OrderedDict(sorted(APs.items(), key=operator.itemgetter(1), reverse=True))\n\n #get mAP percentage value\n #mAP = np.mean(list(APs.values()))*100\n mAP = get_mean_metric(APs, gt_classes_records)\n\n #get GroundTruth count per class\n gt_counter_per_class = {}\n for (class_name, info_list) in gt_classes_records.items():\n gt_counter_per_class[class_name] = len(info_list)\n\n #get Precision count per class\n pred_counter_per_class = {class_name: 0 for class_name in list(gt_classes_records.keys())}\n for (class_name, info_list) in pred_classes_records.items():\n pred_counter_per_class[class_name] = len(info_list)\n\n\n #get the precision & recall\n precision_dict = {}\n recall_dict = {}\n for (class_name, gt_count) in gt_counter_per_class.items():\n if (class_name not in pred_counter_per_class) or (class_name not in count_true_positives) or pred_counter_per_class[class_name] == 0:\n precision_dict[class_name] = 0.\n else:\n precision_dict[class_name] = float(count_true_positives[class_name]) / pred_counter_per_class[class_name]\n\n if class_name not in count_true_positives or gt_count == 0:\n recall_dict[class_name] = 0.\n else:\n recall_dict[class_name] = float(count_true_positives[class_name]) / gt_count\n\n #get mPrec, mRec\n #mPrec = np.mean(list(precision_dict.values()))*100\n #mRec = np.mean(list(recall_dict.values()))*100\n mPrec = get_mean_metric(precision_dict, gt_classes_records)\n mRec = get_mean_metric(recall_dict, gt_classes_records)\n\n\n if show_result:\n plot_Pascal_AP_result(len(annotation_records), count_true_positives, len(gt_classes_records),\n gt_counter_per_class, pred_counter_per_class,\n precision_dict, recall_dict, mPrec, mRec,\n APs, mAP, iou_threshold)\n #show result\n print('\\nPascal VOC AP evaluation')\n for (class_name, AP) in APs.items():\n print('%s: AP %.4f, precision %.4f, recall %.4f' % (class_name, AP, precision_dict[class_name], recall_dict[class_name]))\n print('mAP@IoU=%.2f result: %f' % (iou_threshold, mAP))\n print('mPrec@IoU=%.2f result: %f' % (iou_threshold, mPrec))\n print('mRec@IoU=%.2f result: %f' % (iou_threshold, mRec))\n\n #return mAP percentage value\n return mAP, APs\n\n\n\ndef compute_AP_COCO(annotation_records, gt_classes_records, pred_classes_records, class_names, show_result=True):\n '''\n Compute MSCOCO AP list on AP 0.5:0.05:0.95\n '''\n iou_threshold_list = np.arange(0.50, 1.00, 0.05)\n APs = {}\n pbar = tqdm(total=len(iou_threshold_list), desc='Eval COCO')\n for iou_threshold in iou_threshold_list:\n iou_threshold = round(iou_threshold, 2)\n mAP, _ = compute_mAP_PascalVOC(annotation_records, gt_classes_records, pred_classes_records, class_names, iou_threshold, show_result=False)\n APs[iou_threshold] = round(mAP, 6)\n pbar.update(1)\n\n pbar.close()\n\n #sort AP result by value, in descending order\n APs = OrderedDict(sorted(APs.items(), key=operator.itemgetter(1), reverse=True))\n\n #get overall AP percentage value\n AP = np.mean(list(APs.values()))\n\n if show_result:\n '''\n Draw MS COCO AP plot\n '''\n os.makedirs('result', exist_ok=True)\n window_title = \"MSCOCO AP on different IOU\"\n plot_title = \"COCO AP = {0:.2f}%\".format(AP)\n x_label = \"Average Precision\"\n output_path = os.path.join('result','COCO_AP.png')\n draw_plot_func(APs, len(APs), window_title, plot_title, x_label, output_path, to_show=False, plot_color='royalblue', true_p_bar='')\n\n print('\\nMS COCO AP evaluation')\n for (iou_threshold, AP_value) in APs.items():\n print('IOU %.2f: AP %f' % (iou_threshold, AP_value))\n print('total AP: %f' % (AP))\n\n #return AP percentage value\n return AP, APs\n\n\ndef compute_AP_COCO_Scale(annotation_records, scale_gt_classes_records, pred_classes_records, class_names):\n '''\n Compute MSCOCO AP on different scale object: small, medium, large\n '''\n scale_APs = {}\n for scale_key in ['small','medium','large']:\n gt_classes_records = scale_gt_classes_records[scale_key]\n scale_AP, _ = compute_AP_COCO(annotation_records, gt_classes_records, pred_classes_records, class_names, show_result=False)\n scale_APs[scale_key] = round(scale_AP, 4)\n\n #get overall AP percentage value\n scale_mAP = np.mean(list(scale_APs.values()))\n\n '''\n Draw Scale AP plot\n '''\n os.makedirs('result', exist_ok=True)\n window_title = \"MSCOCO AP on different scale\"\n plot_title = \"scale mAP = {0:.2f}%\".format(scale_mAP)\n x_label = \"Average Precision\"\n output_path = os.path.join('result','COCO_scale_AP.png')\n draw_plot_func(scale_APs, len(scale_APs), window_title, plot_title, x_label, output_path, to_show=False, plot_color='royalblue', true_p_bar='')\n\n '''\n Draw Scale Object Sum plot\n '''\n for scale_key in ['small','medium','large']:\n gt_classes_records = scale_gt_classes_records[scale_key]\n gt_classes_sum = {}\n\n for _, class_name in enumerate(class_names):\n # summarize the gt object number for every class on different scale\n gt_classes_sum[class_name] = np.sum(len(gt_classes_records[class_name])) if class_name in gt_classes_records else 0\n\n total_sum = np.sum(list(gt_classes_sum.values()))\n\n window_title = \"{} object number\".format(scale_key)\n plot_title = \"total {} object number = {}\".format(scale_key, total_sum)\n x_label = \"Object Number\"\n output_path = os.path.join('result','{}_object_number.png'.format(scale_key))\n draw_plot_func(gt_classes_sum, len(gt_classes_sum), window_title, plot_title, x_label, output_path, to_show=False, plot_color='royalblue', true_p_bar='')\n\n print('\\nMS COCO AP evaluation on different scale')\n for (scale, AP_value) in scale_APs.items():\n print('%s scale: AP %f' % (scale, AP_value))\n print('total AP: %f' % (scale_mAP))\n\n\ndef add_gt_record(gt_records, gt_record, class_name):\n # append or add ground truth class item\n if class_name in gt_records:\n gt_records[class_name].append(gt_record)\n else:\n gt_records[class_name] = list([gt_record])\n\n return gt_records\n\n\ndef get_scale_gt_dict(gt_classes_records, class_names):\n '''\n Get ground truth class dict on different object scales, according to MS COCO metrics definition:\n small objects: area < 32^2\n medium objects: 32^2 < area < 96^2\n large objects: area > 96^2\n\n input gt_classes_records would be like:\n gt_classes_records = {\n 'car': [\n ['000001.jpg','100,120,200,235'],\n ['000002.jpg','85,63,156,128'],\n ...\n ],\n ...\n }\n return a record dict with following format, for AP/AR eval on different scale:\n scale_gt_classes_records = {\n 'small': {\n 'car': [\n ['000001.jpg','100,120,200,235'],\n ['000002.jpg','85,63,156,128'],\n ...\n ],\n ...\n },\n\n 'medium': {\n 'car': [\n ['000003.jpg','100,120,200,235'],\n ['000004.jpg','85,63,156,128'],\n ...\n ],\n ...\n },\n\n 'large': {\n 'car': [\n ['000005.jpg','100,120,200,235'],\n ['000006.jpg','85,63,156,128'],\n ...\n ],\n ...\n }\n }\n '''\n scale_gt_classes_records = {}\n small_gt_records = {}\n medium_gt_records = {}\n large_gt_records = {}\n\n for _, class_name in enumerate(class_names):\n gt_records = gt_classes_records[class_name]\n\n for (image_file, box) in gt_records:\n # get box area based on coordinate\n box_coord = [int(p) for p in box.split(',')]\n box_area = (box_coord[2] - box_coord[0]) * (box_coord[3] - box_coord[1])\n\n # add to corresponding gt records dict according to area size\n if box_area <= 32*32:\n small_gt_records = add_gt_record(small_gt_records, [image_file, box], class_name)\n elif box_area > 32*32 and box_area <= 96*96:\n medium_gt_records = add_gt_record(medium_gt_records, [image_file, box], class_name)\n elif box_area > 96*96:\n large_gt_records = add_gt_record(large_gt_records, [image_file, box], class_name)\n\n # form up scale_gt_classes_records\n scale_gt_classes_records['small'] = small_gt_records\n scale_gt_classes_records['medium'] = medium_gt_records\n scale_gt_classes_records['large'] = large_gt_records\n\n return scale_gt_classes_records\n\n\n\ndef eval_AP(model, model_format, annotation_lines, anchors, class_names, model_image_size, eval_type, iou_threshold, conf_threshold, save_result):\n '''\n Compute AP for detection model on annotation dataset\n '''\n annotation_records, gt_classes_records = annotation_parse(annotation_lines, class_names)\n pred_classes_records = get_prediction_class_records(model, model_format, annotation_records, anchors, class_names, model_image_size, conf_threshold, save_result)\n AP = 0.0\n\n if eval_type == 'VOC':\n AP, _ = compute_mAP_PascalVOC(annotation_records, gt_classes_records, pred_classes_records, class_names, iou_threshold)\n elif eval_type == 'COCO':\n AP, _ = compute_AP_COCO(annotation_records, gt_classes_records, pred_classes_records, class_names)\n # get AP for different scale: small, medium, large\n scale_gt_classes_records = get_scale_gt_dict(gt_classes_records, class_names)\n compute_AP_COCO_Scale(annotation_records, scale_gt_classes_records, pred_classes_records, class_names)\n else:\n raise ValueError('Unsupported evaluation type')\n\n return AP\n\n\n#load TF 1.x frozen pb graph\ndef load_graph(model_path):\n # We parse the graph_def file\n with tf.gfile.GFile(model_path, \"rb\") as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n\n # We load the graph_def in the default graph\n with tf.Graph().as_default() as graph:\n tf.import_graph_def(\n graph_def,\n input_map=None,\n return_elements=None,\n name=\"graph\",\n op_dict=None,\n producer_op_list=None\n )\n return graph\n\n\ndef load_eval_model(model_path):\n # support of tflite model\n if model_path.endswith('.tflite'):\n from tensorflow.lite.python import interpreter as interpreter_wrapper\n model = interpreter_wrapper.Interpreter(model_path=model_path)\n model.allocate_tensors()\n model_format = 'TFLITE'\n\n # support of MNN model\n elif model_path.endswith('.mnn'):\n model = MNN.Interpreter(model_path)\n model_format = 'MNN'\n\n # support of TF 1.x frozen pb model\n elif model_path.endswith('.pb'):\n model = load_graph(model_path)\n model_format = 'PB'\n\n # support of ONNX model\n elif model_path.endswith('.onnx'):\n model = onnxruntime.InferenceSession(model_path)\n model_format = 'ONNX'\n\n # normal keras h5 model\n elif model_path.endswith('.h5'):\n custom_object_dict = get_custom_objects()\n\n model = load_model(model_path, compile=False, custom_objects=custom_object_dict)\n model_format = 'H5'\n K.set_learning_phase(0)\n else:\n raise ValueError('invalid model file')\n\n return model, model_format\n\n\ndef main():\n # class YOLO defines the default value, so suppress any default here\n parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS, description='evaluate YOLO model (h5/pb/onnx/tflite/mnn) with test dataset')\n '''\n Command line options\n '''\n parser.add_argument(\n '--model_path', type=str, required=True,\n help='path to model file')\n\n parser.add_argument(\n '--anchors_path', type=str, required=True,\n help='path to anchor definitions')\n\n parser.add_argument(\n '--classes_path', type=str, required=False,\n help='path to class definitions, default configs/voc_classes.txt', default=os.path.join('configs' , 'voc_classes.txt'))\n\n parser.add_argument(\n '--annotation_file', type=str, required=True,\n help='test annotation txt file')\n\n parser.add_argument(\n '--eval_type', type=str,\n help='evaluation type (VOC/COCO), default=VOC', default='VOC')\n\n parser.add_argument(\n '--iou_threshold', type=float,\n help='IOU threshold for PascalVOC mAP, default=0.5', default=0.5)\n\n parser.add_argument(\n '--conf_threshold', type=float,\n help='confidence threshold for filtering box in postprocess, default=0.001', default=0.001)\n\n parser.add_argument(\n '--model_image_size', type=str,\n help='model image input size as <height>x<width>, default 416x416', default='416x416')\n\n parser.add_argument(\n '--save_result', default=False, action=\"store_true\",\n help='Save the detection result image in result/detection dir'\n )\n\n args = parser.parse_args()\n\n # param parse\n anchors = get_anchors(args.anchors_path)\n class_names = get_classes(args.classes_path)\n height, width = args.model_image_size.split('x')\n model_image_size = (int(height), int(width))\n assert (model_image_size[0]%32 == 0 and model_image_size[1]%32 == 0), 'model_image_size should be multiples of 32'\n\n annotation_lines = get_dataset(args.annotation_file, shuffle=False)\n model, model_format = load_eval_model(args.model_path)\n\n start = time.time()\n eval_AP(model, model_format, annotation_lines, anchors, class_names, model_image_size, args.eval_type, args.iou_threshold, args.conf_threshold, args.save_result)\n end = time.time()\n print(\"Evaluation time cost: {:.6f}s\".format(end - start))\n\n\nif __name__ == '__main__':\n main()\n"
]
| [
[
"matplotlib.pyplot.text",
"tensorflow.import_graph_def",
"matplotlib.pyplot.gcf",
"tensorflow.lite.python.interpreter.Interpreter",
"matplotlib.pyplot.fill_between",
"numpy.arange",
"matplotlib.pyplot.gca",
"numpy.array",
"numpy.zeros",
"tensorflow.GraphDef",
"matplotlib.pyplot.title",
"tensorflow.Session",
"matplotlib.pyplot.close",
"tensorflow.gfile.GFile",
"tensorflow.keras.models.load_model",
"matplotlib.pyplot.show",
"matplotlib.pyplot.xlabel",
"tensorflow.Graph",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.cla",
"matplotlib.pyplot.ylabel",
"tensorflow.keras.backend.set_learning_phase"
]
]
|
skymind-talent/openCV-python-labs | [
"5506831e8454633a3419349fdb01fda8a83c6e37"
]
| [
"src/Day 2/3_filter/sharpening/custom_2D_kernel.py"
]
| [
"import cv2\r\nimport numpy as np\r\n\r\nimage = cv2.imread(r'C:\\Users\\harrizazham98\\Desktop\\OpenCVForPython\\resources\\Day 2\\wood.jpg')\r\n\r\n# Print error message if image is null\r\nif image is None:\r\n print('Could not read image')\r\n\r\n\"\"\"\r\nApply sharpening using kernel\r\n\"\"\"\r\nkernel3 = np.array([[0, -1, 0],\r\n [-1, 5, -1],\r\n [0, -1, 0]])\r\nsharp_img = cv2.filter2D(src=image, ddepth=-1, kernel=kernel3)\r\n\r\ncv2.imshow('Original', image)\r\ncv2.imshow('Sharpened', sharp_img)\r\n\r\ncv2.waitKey()\r\n#cv2.imwrite('sharp_image.jpg', sharp_img)\r\ncv2.destroyAllWindows()"
]
| [
[
"numpy.array"
]
]
|
gabriel-milan/distributed-systems | [
"7c016eb5dda7ae7d68c33fc3048397aae9b9bc5f"
]
| [
"tp2/semaphores/plot_chart.py"
]
| [
"import matplotlib.pyplot as plt\n\ndata = {\n 1: {\n (1, 1) : 6.274645810597576,\n (2, 1) : 6.468804593296954,\n (4, 1) : 6.574014662398258,\n (8, 1) : 6.604240996198496,\n (16,1) : 6.628235584497451,\n (1, 2) : 4.215760689496529,\n (1, 4) : 3.710197771602543,\n (1, 8) : 3.698875323397806,\n (1,16) : 3.7194846995000264,\n },\n 2: {\n (1, 1) : 4.605861424998148,\n (2, 1) : 5.154702678503236,\n (4, 1) : 5.494890148902778,\n (8, 1) : 5.369842817797325,\n (16,1) : 5.338877402502112,\n (1, 2) : 2.6676929477020166,\n (1, 4) : 2.0312221530999524,\n (1, 8) : 2.373183822503779,\n (1,16) : 2.349348051799461,\n },\n 4: {\n (1, 1) : 4.095674105000216,\n (2, 1) : 5.147023267904297,\n (4, 1) : 5.378732551896246,\n (8, 1) : 5.273013718699803,\n (16,1) : 5.275664518703707,\n (1, 2) : 2.3448924871976486,\n (1, 4) : 1.6711500748991965,\n (1, 8) : 1.977809672500007,\n (1,16) : 2.2132157785992606,\n },\n 16: {\n (1, 1) : 4.090659649099689,\n (2, 1) : 5.202900149399648,\n (4, 1) : 5.432632463402115,\n (8, 1) : 5.324755800602725,\n (16,1) : 5.258976852503838,\n (1, 2) : 2.367942911700811,\n (1, 4) : 1.7973453193961177,\n (1, 8) : 2.2311260781018065,\n (1,16) : 2.2691946229024325,\n },\n 32: {\n (1, 1) : 4.095506394904805,\n (2, 1) : 5.175703358295141,\n (4, 1) : 5.342044799099677,\n (8, 1) : 5.2985242502996694,\n (16,1) : 5.268460953800241,\n (1, 2) : 2.3813159354031086,\n (1, 4) : 1.7957859887974337,\n (1, 8) : 2.243157755996799,\n (1,16) : 2.279153504798887,\n },\n}\n\n# Generate line plot for producers\nplt.figure (figsize=(20,20))\nplt.title (\"Tempo vs. #Produtores\")\nlegend = []\nfor N in data.keys():\n X = [1, 2, 4, 8, 16]\n y = [data[N][(x,1)] for x in X]\n plt.plot(X, y)\n legend.append(\"N={}\".format(N))\nplt.legend(legend)\nplt.show()\n\n# Generate line plot for consumers\nplt.figure (figsize=(20,20))\nplt.title (\"Tempo vs. #Consumidores\")\nlegend = []\nfor N in data.keys():\n X = [1, 2, 4, 8, 16]\n y = [data[N][(1,x)] for x in X]\n plt.plot(X, y)\n legend.append(\"N={}\".format(N))\nplt.legend(legend)\nplt.show()\n"
]
| [
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show"
]
]
|
TuongL94/MasterThesis | [
"25cc6e4d43d49777f28ac31ed3a5a0c6c7d90bf9"
]
| [
"SiameseFingerprint/fingerprint_parser.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 2 15:31:04 2018\n\n@author: Tuong Lam & Simon Nilsson\n\"\"\"\n\nimport imageio as imio\nimport numpy as np\nimport re\nimport os\nimport sys\n\ndef fingerprint_parser(index_file_dir, index_file_name):\n \"\"\" Parser for Precise Biometrics fingerprint database with alignment data.\n \n Input:\n index_file_dir - directory of the index file (ending with a forward slash \"/\")\n index_file_name - name of the index file\n Returns: lists with information used in the siamese network for fingerprint verification \n \"\"\"\n person_id = []\n finger_id = []\n fingerprints = []\n translation = []\n rotation = []\n \n new_origin_counter = 0\n curr_finger = 0\n\n with open(index_file_dir + index_file_name,\"r\") as file:\n for line in file:\n words = re.split(\"\\t\",line)\n if len(words) > 4 and words[0] != \"#\":\n if len(words[4]) > 40: # only consider data that contains alignment information\n curr_finger = int(words[1]) \n last_word = re.split(\":\",words[-1])\n alignment_word = last_word[-1].split()\n person_id.append(int(words[0]))\n\n fingerprint_path = last_word[0].strip()\n# if counter % 100 == 0:\n# print(counter)\n finger = imio.imread(index_file_dir + fingerprint_path)\n fingerprints.append(np.ndarray.flatten(np.array(finger)))\n translation.append([int(alignment_word[1]),int(alignment_word[2])])\n rotation.append(int(alignment_word[3]))\n \n if new_origin_counter == 46:\n finger_id.append(-curr_finger)\n new_origin_counter = 0\n elif len(finger_id) > 0 and curr_finger == -finger_id[-1]:\n finger_id.append(-curr_finger)\n elif len(finger_id) > 0 and curr_finger != finger_id[-1]:\n finger_id.append(curr_finger)\n new_origin_counter = 0\n else:\n finger_id.append(curr_finger)\n \n new_origin_counter += 1\n \n return person_id, finger_id, fingerprints, translation, rotation\n \n\ndef main(argv):\n dir_path = os.path.dirname(os.path.realpath(__file__)) # directory of file being executed\n person_id, finger_id, fingerprints, translation, rotation = fingerprint_parser(argv[0],argv[1])\n \n # convert to numpy arrays and corrects scaling \n# person_id = np.array(person_id,dtype='int32')\n finger_id = np.array(finger_id,dtype='int32')\n# fingerprints = np.array(fingerprints,dtype='float32')/255\n# translation = np.array(translation,dtype='float32')/256\n# rotation = np.array(rotation,dtype='float32')/65536*360\n\n # save paths\n# filename_1 = dir_path + \"/person_id_new\"\n filename_2 = dir_path + \"/finger_id_mt_vt_112_new\"\n# filename_3 = dir_path + \"/fingerprints_new\" \n# filename_4 = dir_path + \"/translation_new\" \n# filename_5 = dir_path + \"/rotation_new\"\n \n # saves numpy arrays\n# np.save(filename_1,person_id)\n np.save(filename_2,finger_id)\n# np.save(filename_3,fingerprints)\n# np.save(filename_4, translation)\n# np.save(filename_5, rotation)\n \nif __name__ == \"__main__\":\n main(sys.argv[1:])\n"
]
| [
[
"numpy.array",
"numpy.save"
]
]
|
Srheft/desispec | [
"f7adfd70e245cfe861b1e6eb781d1216017bed28"
]
| [
"py/desispec/bootcalib.py"
]
| [
"\"\"\"\ndesispec.bootcalib\n==================\n\nUtility functions to perform a quick calibration of DESI data\n\nTODO:\n1. Expand to r, i cameras\n2. QA plots\n3. Test with CR data\n\"\"\"\nfrom __future__ import print_function, absolute_import, division\n\nimport numpy as np\nimport copy\nimport pdb\nimport imp\nimport yaml\nimport glob\nimport math\nimport time\nimport os\nimport sys\nimport argparse\nimport locale\nfrom pkg_resources import resource_exists, resource_filename\n\nfrom astropy.modeling import models, fitting\nfrom astropy.stats import sigma_clip\nfrom astropy.table import Table, Column, vstack\nfrom astropy.io import fits\n\nfrom desispec.util import set_backend\nset_backend()\n\nfrom matplotlib import pyplot as plt\nimport matplotlib\nimport matplotlib.gridspec as gridspec\nimport matplotlib.cm as cm\nfrom matplotlib.backends.backend_pdf import PdfPages\n\nfrom desiutil.log import get_logger\nfrom desiutil import funcfits as dufits\nfrom numpy.polynomial.legendre import legval\n\nglbl_figsz = (16,9)\n\n########################################################\n# High level wrapper\n# TODO: This was ported from the original bin/desi_bootcalib so that it could\n# be called independently by quicklook, but it needs to be coordinated with\n# desispec.scripts.bootcalib.main()\n########################################################\n\ndef bootcalib(deg,flatimage,arcimage):\n \"\"\"\n Args:\n deg: Legendre polynomial degree to use to fit\n flatimage: desispec.image.Image object of flatfield\n arcimage: desispec.image.Image object of arc\n\n Mostly inherited from desispec/bin/desi_bootcalib directly as needed\n\n Returns:\n xfit, fdicts, gauss, all_wave_soln\n\n TODO: document what those return objects are\n \"\"\"\n\n camera=flatimage.camera\n flat=flatimage.pix\n ny=flat.shape[0]\n\n xpk,ypos,cut=find_fiber_peaks(flat)\n xset,xerr=trace_crude_init(flat,xpk,ypos)\n xfit,fdicts=fit_traces(xset,xerr)\n gauss=fiber_gauss(flat,xfit,xerr)\n\n #- Also need wavelength solution not just trace\n\n arc=arcimage.pix\n arc_ivar=arcimage.ivar\n all_spec=extract_sngfibers_gaussianpsf(arc,arc_ivar,xfit,gauss)\n llist=load_arcline_list(camera)\n ### dlamb,wmark,gd_lines,line_guess=load_gdarc_lines(camera)\n dlamb, gd_lines = load_gdarc_lines(camera, llist)\n\n #- Solve for wavelengths\n all_wv_soln=[]\n all_dlamb=[]\n for ii in range(all_spec.shape[1]):\n spec=all_spec[:,ii]\n pixpk=find_arc_lines(spec)\n id_dict=id_arc_lines(pixpk,gd_lines,dlamb,wmark,line_guess=line_guess)\n id_dict['fiber']=ii\n #- Find the other good ones\n if camera == 'z':\n inpoly = 3 # The solution in the z-camera has greater curvature\n else:\n inpoly = 2\n add_gdarc_lines(id_dict, pixpk, gd_lines, inpoly=inpoly)\n #- Now the rest\n id_remainder(id_dict, pixpk, llist)\n #- Final fit wave vs. pix too\n final_fit, mask = dufits.iter_fit(np.array(id_dict['id_wave']), np.array(id_dict['id_pix']), 'polynomial', 3, xmin=0., xmax=1.)\n rms = np.sqrt(np.mean((dufits.func_val(np.array(id_dict['id_wave'])[mask==0],final_fit)-np.array(id_dict['id_pix'])[mask==0])**2))\n final_fit_pix,mask2 = dufits.iter_fit(np.array(id_dict['id_pix']), np.array(id_dict['id_wave']),'legendre',deg, niter=5)\n\n id_dict['final_fit'] = final_fit\n id_dict['rms'] = rms\n id_dict['final_fit_pix'] = final_fit_pix\n id_dict['wave_min'] = dufits.func_val(0,final_fit_pix)\n id_dict['wave_max'] = dufits.func_val(ny-1,final_fit_pix)\n id_dict['mask'] = mask\n all_wv_soln.append(id_dict)\n\n return xfit, fdicts, gauss,all_wv_soln\n\n\n########################################################\n# Arc/Wavelength Routines (Linelists come next)\n########################################################\n\ndef find_arc_lines(spec,rms_thresh=7.,nwidth=5):\n \"\"\"Find and centroid arc lines in an input spectrum\n\n Parameters\n ----------\n spec : ndarray\n Arc line spectrum\n rms_thresh : float\n RMS threshold scale\n nwidth : int\n Line width to test over\n \"\"\"\n # Threshold criterion\n npix = spec.size\n spec_mask = sigma_clip(spec, sigma=4., iters=5)\n rms = np.std(spec_mask)\n thresh = rms*rms_thresh\n #print(\"thresh = {:g}\".format(thresh))\n gdp = spec > thresh\n\n # Avoid edges\n gdp = gdp & (np.arange(npix) > 2.*nwidth) & (np.arange(npix) < (npix-2.*nwidth))\n\n # Roll to find peaks (simple algorithm)\n # nwidth = 5\n nstep = max(1,nwidth // 2)\n for kk in range(-nstep,nstep):\n if kk < 0:\n test = np.roll(spec,kk) < np.roll(spec,kk+1)\n else:\n test = np.roll(spec,kk) > np.roll(spec,kk+1)\n # Compare\n gdp = gdp & test\n\n # Center\n gdpix = np.where(gdp)[0]\n ngd = gdpix.size\n xpk = np.zeros(ngd)\n flux = np.zeros(ngd)\n\n for jj,igdpix in enumerate(gdpix):\n # Simple flux-weight\n pix = np.arange(igdpix-nstep,igdpix+nstep+1,dtype=int)\n flux[jj] = np.sum(spec[pix])\n xpk[jj] = np.sum(pix*spec[pix]) / flux[jj]\n\n # Finish\n return xpk , flux\n\n\n\ndef remove_duplicates_w_id(wy,w,y_id,w_id) :\n # might be several identical w_id\n y_id=np.array(y_id).astype(int)\n w_id=np.array(w_id).astype(int)\n y_id2=[]\n w_id2=[]\n for j in np.unique(w_id) :\n w_id2.append(j)\n ii=y_id[w_id==j]\n if ii.size==1 :\n y_id2.append(ii[0])\n else :\n i=np.argmin(np.abs(wy[ii]-w[j]))\n y_id2.append(ii[i])\n y_id2=np.array(y_id2).astype(int)\n w_id2=np.array(w_id2).astype(int)\n tmp=np.argsort(w[w_id2])\n y_id2=y_id2[tmp]\n w_id2=w_id2[tmp]\n return y_id2,w_id2\n\ndef remove_duplicates_y_id(yw,y,y_id,w_id) :\n # might be several identical y_id\n w_id=np.array(w_id).astype(int)\n y_id=np.array(y_id).astype(int)\n w_id2=[]\n y_id2=[]\n for j in np.unique(y_id) :\n y_id2.append(j)\n ii=w_id[y_id==j]\n if ii.size==1 :\n w_id2.append(ii[0])\n else :\n i=np.argmin(np.abs(yw[ii]-y[j]))\n w_id2.append(ii[i])\n w_id2=np.array(w_id2).astype(int)\n y_id2=np.array(y_id2).astype(int)\n tmp=np.argsort(y[y_id2])\n w_id2=w_id2[tmp]\n y_id2=y_id2[tmp]\n return y_id2,w_id2\n\n\ndef refine_solution(y,w,y_id,w_id,deg=3,tolerance=5.) :\n\n log = get_logger()\n\n # remove duplicates\n transfo=np.poly1d(np.polyfit(y[y_id],w[w_id],deg=deg))\n wy=transfo(y)\n y_id,w_id=remove_duplicates_w_id(wy,w,y_id,w_id)\n transfo=np.poly1d(np.polyfit(w[w_id],y[y_id],deg=deg))\n yw=transfo(w)\n y_id,w_id=remove_duplicates_y_id(yw,y,y_id,w_id)\n\n if len(y_id) != len(np.unique(y_id)) :\n log.error(\"duplicate AT INIT y_id={:s}\".format(str(y_id)))\n if len(w_id) != len(np.unique(w_id)) :\n log.error(\"duplicate AT INIT w_id={:s}\".format(str(w_id)))\n\n nmatch=len(y_id)\n #log.info(\"init nmatch=%d rms=%f wave=%s\"%(nmatch,np.std(wy[y_id]-w[w_id]),w[w_id]))\n #log.info(\"init nmatch=%d rms=%f\"%(nmatch,np.std(wy[y_id]-w[w_id])))\n if nmatch<deg+1 :\n log.error(\"error : init nmatch too small\")\n return y_id,w_id,1000.,0\n\n rms=0.\n\n # loop on fit of transfo, pairing, cleaning\n for loop in range(200) :\n\n # compute transfo\n transfo=np.poly1d(np.polyfit(y[y_id],w[w_id],deg=deg))\n\n # apply transfo to measurements\n wy=transfo(y)\n\n previous_rms = rms+0.\n rms=np.std(wy[y_id]-w[w_id])\n\n # match lines\n mdiff0=min(tolerance,max(2.,rms*2.)) # this is a difficult parameter to tune, either loose lever arm, or have false matches !!\n mdiff1=tolerance # this is a difficult parameter to tune, either loose lever arm, or have false matches !!\n unmatched_indices=np.setdiff1d(np.arange(y.size),y_id)\n for i,wi in zip(unmatched_indices,wy[unmatched_indices]) :\n dist=np.abs(wi-w)\n jj=np.argsort(dist)\n for j,o in enumerate(jj) :\n if j in w_id :\n continue\n if dist[j]<mdiff0 or ( o<jj.size-1 and dist[j]<mdiff1 and dist[j]<0.3*dist[jj[o+1]]) :\n y_id=np.append(y_id,i)\n w_id=np.append(w_id,j)\n break\n\n previous_nmatch = nmatch+0\n nmatch=len(y_id)\n\n #log.info(\"iter #%d nmatch=%d rms=%f\"%(loop,nmatch,rms))\n if nmatch < deg+1 :\n log.error(\"error init nmatch too small\")\n y_id=[]\n w_id=[]\n rms=100000.\n return y_id,w_id,rms,loop\n\n if nmatch==previous_nmatch and abs(rms-previous_rms)<0.01 and loop>=1 :\n break\n if nmatch>=min(w.size,y.size) :\n #print(\"break because %d>=min(%d,%d)\"%(nmatch,w.size,y.size))\n break\n\n return y_id,w_id,rms,loop\n\ndef id_remainder(id_dict, llist, deg=4, tolerance=1., verbose=False) :\n\n log = get_logger()\n\n y_id=np.array(id_dict['id_idx']).astype(int)\n all_y=np.array(id_dict['pixpk'])\n\n all_known_waves = np.sort(np.array(llist[\"wave\"]))\n identified_waves = np.array(id_dict[\"id_wave\"]) # lines identified at previous steps\n\n w_id=[]\n for w in identified_waves :\n i=np.argmin(np.abs(all_known_waves-w))\n diff=np.abs(all_known_waves[i]-w)\n if diff>0.1 :\n log.warning(\"discrepant wavelength\".format(w,all_known_waves[i]))\n w_id.append(i)\n w_id = np.array(w_id).astype(int)\n y_id,w_id,rms,niter=refine_solution(all_y,all_known_waves,y_id,w_id,deg=deg,tolerance=tolerance)\n\n id_dict['id_idx'] = np.sort(y_id)\n id_dict['id_pix'] = np.sort(all_y[y_id])\n id_dict['id_wave'] = np.sort(all_known_waves[w_id])\n id_dict['rms'] = rms\n\n log.info(\"{:d} matched for {:d} detected and {:d} known, rms = {:g}\".format(len(y_id),len(all_y),len(all_known_waves),rms))\n\n\ndef compute_triplets(wave) :\n\n triplets=[]\n wave=np.sort(wave)\n for i1,w1 in enumerate(wave[:-1]) :\n for i2,w2 in enumerate(wave[i1+1:]) :\n for i3,w3 in enumerate(wave[i1+i2+2:]) :\n triplet=[w1,w2,w3,i1,i1+1+i2,i1+i2+2+i3,w2-w1,w3-w1,w2**2-w1**2,w3**2-w1**2]\n #print(triplet)\n #print(wave[i1],wave[i1+1+i2],wave[i1+i2+2+i3])\n triplets.append(triplet)\n return np.array(triplets)\n\ndef id_arc_lines_using_triplets(id_dict,w,dwdy_prior,d2wdy2_prior=1.5e-5,toler=0.2,ntrack=50,nmax=40):\n \"\"\"Match (as best possible), a set of the input list of expected arc lines to the detected list\n\n Parameters\n ----------\n id_dict : dictionnary with Pixel locations of detected arc lines in \"pixpk\" and fluxes in \"flux\"\n w : ndarray\n array of expected arc lines to be detected and identified\n dwdy : float\n Average dispersion in the spectrum\n d2wdy2_prior : float\n Prior on second derivative\n toler : float, optional\n Tolerance for matching (20%)\n ntrack : max. number of solutions to be tracked\n\n Returns\n -------\n id_dict : dict\n dict of identified lines\n \"\"\"\n\n log=get_logger()\n #log.info(\"y=%s\"%str(y))\n #log.info(\"w=%s\"%str(w))\n\n\n y = id_dict[\"pixpk\"]\n\n log.info(\"ny=%d nw=%d\"%(len(y),len(w)))\n\n if nmax<10 :\n nmax=10\n log.warning(\"force nmax=10 (arg was too small: {:d})\".format(nmax))\n\n if len(y)>nmax :\n # log.info(\"down-selecting the number of detected lines from {:d} to {:d}\".format(len(y),nmax))\n # keep at least the edges\n margin=3\n new_y=np.append(y[:margin],y[-margin:])\n # now look at the flux to select the other ones\n flux=id_dict[\"flux\"][margin:-margin]\n ii=np.argsort(flux)\n new_y=np.append(new_y,y[margin:-margin][ii[-(nmax-2*margin):]])\n y = np.sort(new_y)\n\n # compute triplets of waves of y positions\n y_triplets = compute_triplets(y)\n w_triplets = compute_triplets(w)\n\n # each pair of triplet defines a 2nd order polynomial (chosen centered on y=2000)\n # w = a*(y-2000)**2+b*(y-2000)+c\n # w = a*y**2-4000*a*y+b*y+cst\n # w = a*(y**2-4000*y)+b*y+cst\n # dw_12 = a*(dy2_12-4000*dy_12)+b*dy_12\n # dw_13 = a*(dy2_13-4000*dy_13)+b*dy_12\n # dw_12 = a*cdy2_12+b*dy_12\n # dw_13 = a*cdy2_13+b*dy_13\n # with cdy2_12=dy2_12-4000*dy_12\n # and cdy2_13=dy2_13-4000*dy_13\n # idet = 1./(dy_13*cdy2_12-dy_12*cdy2_13)\n # a = idet*(dy_13*dw_12-dy_12*dw_13)\n # b = idet*(-cdy2_13*dw_12+cdy2_12*dw_13)\n\n #triplet=[w1,w2,w3,i1,i1+1+i2,i1+i2+2+i3,w2-w1,w3-w1,w2**2-w1**2,w3**2-w1**2]\n dy_12=y_triplets[:,6]\n dy_13=y_triplets[:,7]\n #dy2_12=y_triplets[:,8]\n #dy2_13=y_triplets[:,9]\n # centered version\n cdy2_12=y_triplets[:,8]-4000.*y_triplets[:,6]\n cdy2_13=y_triplets[:,9]-4000.*y_triplets[:,7]\n idet=1./(dy_13*cdy2_12-dy_12*cdy2_13)\n\n # fill histogram with polynomial coefs and first index of each triplet in the pair for all pairs of triplets(y,w)\n # create the 4D histogram\n ndwdy = 41\n nd2wdy2 = 21\n dwdy_min = dwdy_prior*(1-toler)\n dwdy_max = dwdy_prior*(1+toler)\n dwdy_step = (dwdy_max-dwdy_min)/ndwdy\n d2wdy2_min = -d2wdy2_prior\n d2wdy2_max = +d2wdy2_prior\n d2wdy2_step = (d2wdy2_max-d2wdy2_min)/nd2wdy2\n histogram = np.zeros((ndwdy,nd2wdy2,len(y),len(w))) # definition of the histogram\n\n # fill the histogram\n for w_triplet in w_triplets :\n #d2wdy2 = idet*(dy_13*w_triplet[6]-dy_12*w_triplet[7])\n #dwdy = idet*(-cdy2_13*w_triplet[6]+cdy2_12*w_triplet[7])\n # bins in the histogram\n dwdy_bin = ((idet*(-cdy2_13*w_triplet[6]+cdy2_12*w_triplet[7])-dwdy_min)/dwdy_step).astype(int)\n d2wdy2_bin = ((idet*(dy_13*w_triplet[6]-dy_12*w_triplet[7])-d2wdy2_min)/d2wdy2_step).astype(int)\n pairs_in_histo=np.where((dwdy_bin>=0)&(dwdy_bin<ndwdy)&(d2wdy2_bin>=0)&(d2wdy2_bin<nd2wdy2))[0]\n # fill histo\n iw=int(w_triplet[3])\n for a,b,c in zip(dwdy_bin[pairs_in_histo],d2wdy2_bin[pairs_in_histo],y_triplets[pairs_in_histo,3].astype(int)) :\n histogram[a,b,c,iw] += 1\n\n # find max bins in the histo\n histogram_ravel = histogram.ravel()\n best_histo_bins = histogram_ravel.argsort()[::-1]\n #log.info(\"nmatch in first bins=%s\"%histogram.ravel()[best_histo_bins[:3]])\n\n best_y_id=[]\n best_w_id=[]\n best_rms=1000.\n\n # loop on best matches ( = most populated bins)\n count=0\n for histo_bin in best_histo_bins[:ntrack] :\n\n if histogram_ravel[histo_bin]<4 and count>3 :\n log.warning(\"stopping here\")\n break\n count += 1\n dwdy_best_bin,d2wdy2_best_bin,iy_best_bin,iw_best_bin = np.unravel_index(histo_bin, histogram.shape) # bin coord\n #print(\"bins=\",dwdy_best_bin,d2wdy2_best_bin,iy_best_bin,iw_best_bin)\n\n # pairs of triplets in this histo bin\n w_id=np.array([])\n y_id=np.array([])\n wok=np.where(w_triplets[:,3]==iw_best_bin)[0]\n yok=np.where(y_triplets[:,3]==iy_best_bin)[0]\n for w_triplet in w_triplets[wok] :\n #d2wdy2 = idet[yok]*(dy_13[yok]*w_triplet[6]-dy_12[yok]*w_triplet[7])\n #dwdy = idet[yok]*(-cdy2_13[yok]*w_triplet[6]+cdy2_12[yok]*w_triplet[7])\n # bins in the histogram\n dwdy_bin = ((idet[yok]*(-cdy2_13[yok]*w_triplet[6]+cdy2_12[yok]*w_triplet[7])-dwdy_min)/dwdy_step).astype(int)\n d2wdy2_bin = ((idet[yok]*(dy_13[yok]*w_triplet[6]-dy_12[yok]*w_triplet[7])-d2wdy2_min)/d2wdy2_step).astype(int)\n wyok=yok[np.where((dwdy_bin==dwdy_best_bin)&(d2wdy2_bin==d2wdy2_best_bin))[0]]\n for y_triplet in y_triplets[wyok] :\n y_id=np.append(y_id,y_triplet[3:6])\n w_id=np.append(w_id,w_triplet[3:6])\n\n # now need to rm duplicates\n nw=len(w)\n ny=len(y)\n unique_common_id=np.unique(y_id.astype(int)*nw+w_id.astype(int))\n y_id=(unique_common_id/nw).astype(int)\n w_id=(unique_common_id%nw).astype(int)\n ordering=np.argsort(y[y_id])\n y_id=y_id[ordering]\n w_id=w_id[ordering]\n # refine\n y_id,w_id,rms,niter=refine_solution(y,w,y_id,w_id)\n #log.info(\"get solution with %d match and rms=%f (niter=%d)\"%(len(y_id),rms,niter))\n if (len(y_id)>len(best_y_id) and rms<max(1,best_rms)) or (len(y_id)==len(best_y_id) and rms<best_rms) or (best_rms>1 and rms<1 and len(y_id)>=8) :\n #log.info(\"new best solution #%d with %d match and rms=%f (niter=%d)\"%(count,len(y_id),rms,niter))\n #log.info(\"previous had %d match and rms=%f\"%(len(best_y_id),best_rms))\n best_y_id = y_id\n best_w_id = w_id\n best_rms = rms\n\n # stop at some moment\n if best_rms<0.2 and len(y_id)>=min(15,min(len(y),len(w))) :\n #log.info(\"stop here because we have a correct solution\")\n break\n\n if len(y) != len(id_dict[\"pixpk\"]) :\n #log.info(\"re-indexing the result\")\n tmp_y_id = []\n for i in best_y_id :\n tmp_y_id.append(np.argmin(np.abs(id_dict[\"pixpk\"]-y[i])))\n best_y_id = np.array(tmp_y_id).astype(int)\n y = id_dict[\"pixpk\"]\n\n if len(best_w_id) == 0 :\n log.error(\"failed, no match\")\n id_dict[\"status\"]=\"failed\"\n id_dict[\"id_idx\"]=[]\n id_dict[\"id_pix\"]=[]\n id_dict[\"id_wave\"]=[]\n id_dict[\"rms\"]=999.\n id_dict[\"fit\"]=None\n return\n\n id_dict[\"status\"]=\"ok\"\n id_dict[\"id_idx\"]=best_y_id\n id_dict[\"id_pix\"]=y[best_y_id]\n id_dict[\"id_wave\"]=w[best_w_id]\n id_dict[\"rms\"]=best_rms\n deg=max(1,min(3,best_y_id.size-2))\n id_dict[\"fit\"]= dufits.func_fit(w[best_w_id],y[best_y_id],'polynomial',deg,xmin=0.,xmax=1.)\n\n log.info(\"{:d} matched for {:d} detected and {:d} known as good, rms = {:g}\".format(len(best_y_id),len(y),len(w),best_rms))\n\n\n\n########################################################\n# Linelist routines\n########################################################\n\n\ndef parse_nist(ion, vacuum=True):\n \"\"\"Parse a NIST ASCII table.\n\n Note that the long ---- should have\n been commented out and also the few lines at the start.\n\n Taken from PYPIT\n\n Parameters\n ----------\n ion : str\n Name of ion\n vaccuum : bool, optional\n Use vacuum wavelengths\n \"\"\"\n log=get_logger()\n # Find file\n medium = 'vacuum'\n if not vacuum:\n log.info(\"Using air wavelengths\")\n medium = 'air'\n srch_file = \"data/arc_lines/{0}_{1}.ascii\".format(ion, medium)\n if not resource_exists('desispec', srch_file):\n log.error(\"Cannot find NIST file {:s}\".format(srch_file))\n raise Exception(\"Cannot find NIST file {:s}\".format(srch_file))\n # Read, while working around non-ASCII characters in NIST line lists\n nist_file = resource_filename('desispec', srch_file)\n log.info(\"reading NIST file {:s}\".format(nist_file))\n default_locale = locale.getlocale(locale.LC_CTYPE)\n locale.setlocale(locale.LC_CTYPE, 'en_US.UTF-8')\n nist_tbl = Table.read(nist_file, format='ascii.fixed_width')\n locale.setlocale(locale.LC_CTYPE, default_locale)\n gdrow = nist_tbl['Observed'] > 0. # Eliminate dummy lines\n nist_tbl = nist_tbl[gdrow]\n # Now unique values only (no duplicates)\n uniq, indices = np.unique(nist_tbl['Observed'],return_index=True)\n nist_tbl = nist_tbl[indices]\n # Deal with Rel\n agdrel = []\n for row in nist_tbl:\n try:\n gdrel = int(row['Rel.'])\n except:\n try:\n gdrel = int(row['Rel.'][:-1])\n except:\n gdrel = 0\n agdrel.append(gdrel)\n agdrel = np.array(agdrel)\n # Remove and add\n nist_tbl.remove_column('Rel.')\n nist_tbl.remove_column('Ritz')\n nist_tbl.add_column(Column(agdrel,name='RelInt'))\n nist_tbl.add_column(Column([ion]*len(nist_tbl), name='Ion', dtype=(str, 5)))\n nist_tbl.rename_column('Observed','wave')\n # Return\n return nist_tbl\n\n\ndef load_arcline_list(camera, vacuum=True,lamps=None):\n\n \"\"\"Loads arc line list from NIST files\n Parses and rejects\n\n Taken from PYPIT\n\n Parameters\n ----------\n lines : list\n List of ions to load\n vacuum : bool, optional\n Use vacuum wavelengths\n lamps : optional numpy array of ions, ex np.array([\"HgI\",\"CdI\",\"ArI\",\"NeI\"])\n\n Returns\n -------\n alist : Table\n Table of arc lines\n \"\"\"\n log=get_logger()\n wvmnx = None\n if lamps is None :\n if camera[0] == 'b':\n lamps = ['CdI','ArI','HgI','NeI','KrI']\n elif camera[0] == 'r':\n lamps = ['CdI','ArI','HgI','NeI','KrI']\n elif camera[0] == 'z':\n lamps = ['CdI','ArI','HgI','NeI','KrI']\n elif camera == 'all': # Used for specex\n lamps = ['CdI','ArI','HgI','NeI','KrI']\n else:\n log.error(\"Not ready for this camera\")\n\n # Get the parse dict\n parse_dict = load_parse_dict()\n # Read rejection file\n medium = 'vacuum'\n if not vacuum:\n log.info(\"Using air wavelengths\")\n medium = 'air'\n rej_file = resource_filename('desispec', \"data/arc_lines/rejected_lines_{0}.yaml\".format(medium))\n with open(rej_file, 'r') as infile:\n rej_dict = yaml.load(infile)\n # Loop through the NIST Tables\n tbls = []\n for iline in lamps:\n # Load\n tbl = parse_nist(iline, vacuum=vacuum)\n # Parse\n if iline in parse_dict:\n tbl = parse_nist_tbl(tbl,parse_dict[iline])\n # Reject\n if iline in rej_dict:\n log.info(\"Rejecting select {:s} lines\".format(iline))\n tbl = reject_lines(tbl,rej_dict[iline])\n #print(\"DEBUG\",iline)\n #print(\"DEBUG\",tbl[['Ion','wave','RelInt']])\n tbls.append(tbl[['Ion','wave','RelInt']])\n # Stack\n alist = vstack(tbls)\n\n # wvmnx?\n if wvmnx is not None:\n print('Cutting down line list by wvmnx: {:g},{:g}'.format(wvmnx[0],wvmnx[1]))\n gdwv = (alist['wave'] >= wvmnx[0]) & (alist['wave'] <= wvmnx[1])\n alist = alist[gdwv]\n # Return\n return alist\n\n\ndef reject_lines(tbl,rej_dict, rej_tol=0.1):\n \"\"\"Rejects lines from a NIST table\n\n Taken from PYPIT\n\n Parameters\n ----------\n tbl : Table\n Read previously from NIST ASCII file\n rej_dict : dict\n Dict of rejected lines\n rej_tol : float, optional\n Tolerance for matching a line to reject to linelist (Angstroms)\n\n Returns\n -------\n tbl : Table\n Rows not rejected\n \"\"\"\n msk = tbl['wave'] == tbl['wave']\n # Loop on rejected lines\n for wave in rej_dict:\n close = np.where(np.abs(wave-tbl['wave']) < rej_tol)[0]\n if rej_dict[wave] == 'all':\n msk[close] = False\n else:\n raise ValueError('Not ready for this')\n # Return\n return tbl[msk]\n\ndef parse_nist_tbl(tbl,parse_dict):\n \"\"\"Parses a NIST table using various criteria\n\n Parameters\n ----------\n tbl : Table\n Read previously from NIST ASCII file\n parse_dict : dict\n Dict of parsing criteria. Read from load_parse_dict\n\n Returns\n -------\n tbl : Table\n Rows meeting the criteria\n \"\"\"\n # Parse\n gdI = tbl['RelInt'] >= parse_dict['min_intensity']\n gdA = tbl['Aki'] >= parse_dict['min_Aki']\n gdw = tbl['wave'] >= parse_dict['min_wave']\n # Combine\n allgd = gdI & gdA & gdw\n # Return\n return tbl[allgd]\n\ndef load_parse_dict():\n \"\"\"Dicts for parsing Arc line lists from NIST\n\n Rejected lines are in the rejected_lines.yaml file\n \"\"\"\n dict_parse = dict(min_intensity=0., min_Aki=0., min_wave=0.)\n arcline_parse = {}\n # ArI\n arcline_parse['ArI'] = copy.deepcopy(dict_parse)\n arcline_parse['ArI']['min_intensity'] = 1000. # NOT PICKING UP REDDEST LINES\n # HgI\n arcline_parse['HgI'] = copy.deepcopy(dict_parse)\n arcline_parse['HgI']['min_intensity'] = 800.\n # HeI\n arcline_parse['HeI'] = copy.deepcopy(dict_parse)\n arcline_parse['HeI']['min_intensity'] = 20.\n # NeI\n arcline_parse['NeI'] = copy.deepcopy(dict_parse)\n arcline_parse['NeI']['min_intensity'] = 999.\n #arcline_parse['NeI']['min_Aki'] = 1. # NOT GOOD FOR DEIMOS, DESI\n #arcline_parse['NeI']['min_wave'] = 5700.\n arcline_parse['NeI']['min_wave'] = 5850. # NOT GOOD FOR DEIMOS?\n # ZnI\n arcline_parse['ZnI'] = copy.deepcopy(dict_parse)\n arcline_parse['ZnI']['min_intensity'] = 50.\n # KrI\n arcline_parse['KrI'] = copy.deepcopy(dict_parse)\n arcline_parse['KrI']['min_intensity'] = 50.\n return arcline_parse\n\n\ndef load_gdarc_lines(camera, llist, vacuum=True,lamps=None,good_lines_filename=None):\n\n \"\"\"Loads a select set of arc lines for initial calibrating\n\n Parameters\n ----------\n camera : str\n Camera ('b', 'g', 'r')\n llist : table of lines to use, with columns Ion, wave\n vacuum : bool, optional\n Use vacuum wavelengths\n lamps : optional numpy array of ions, ex np.array([\"HgI\",\"CdI\",\"ArI\",\"NeI\"])\n\n Returns\n -------\n dlamb : float\n Dispersion for input camera\n wmark : float\n wavelength to key off of [???]\n gd_lines : ndarray\n Array of lines expected to be recorded and good for ID\n line_guess : int or None\n Guess at the line index corresponding to wmark (default is to guess the 1/2 way point)\n \"\"\"\n log=get_logger()\n\n if lamps is None :\n lamps=np.array([\"HgI\",\"CdI\",\"ArI\",\"NeI\"])\n\n lines={}\n\n dlamb=0.6\n if camera[0] == 'b':\n dlamb = 0.589\n elif camera[0] == 'r':\n dlamb = 0.527\n elif camera[0] == 'z':\n #dlamb = 0.599 # Ang\n dlamb = 0.608 # Ang (from teststand, ranges (fiber & wave) from 0.54 to 0.66)\n # read good lines\n if good_lines_filename is not None :\n filename = good_lines_filename\n else :\n if vacuum :\n filename = resource_filename('desispec', \"data/arc_lines/goodlines_vacuum.ascii\")\n else :\n filename = resource_filename('desispec', \"data/arc_lines/goodlines_air.ascii\")\n\n log.info(\"Reading good lines in {:s}\".format(filename))\n lines={}\n ifile=open(filename)\n for line in ifile.readlines() :\n if line[0]==\"#\" :\n continue\n vals=line.strip().split()\n if len(vals)<3 :\n log.warning(\"ignoring line '{:s}' in {:s}\".format(line.strip(),filename))\n continue\n cameras=vals[2]\n if cameras.find(camera[0].upper()) < 0 :\n continue\n ion=vals[1]\n wave=float(vals[0])\n if ion in lines:\n lines[ion].append(wave)\n else :\n lines[ion]=[wave,]\n ifile.close()\n log.info(\"Good lines = {:s}\".format(str(lines)))\n\n log.info(\"Checking consistency with full line list\")\n nbad=0\n for ion in lines:\n ii=np.where(llist[\"Ion\"]==ion)[0]\n if ii.size == 0 :\n continue\n all_waves=np.array(llist[\"wave\"][ii])\n for j,w in enumerate(lines[ion]) :\n i=np.argmin(np.abs(w-all_waves))\n if np.abs(w-all_waves[i])>0.2 :\n log.error(\"cannot find good line {:f} of {:s} in full line list. nearest is {:f}\".format(w,ion,all_waves[i]))\n nbad += 1\n elif np.abs(w-all_waves[i])>0.001 :\n log.warning(\"adjusting hardcoded {:s} line {:f} -> {:f} (the NIST line list is the truth)\".format(w,ion,all_waves[i]))\n lines[ion][j]=all_waves[i]\n if nbad>0 :\n log.error(\"{:d} inconsistent hardcoded lines, exiting\".format(nbad))\n sys.exit(12)\n\n gd_lines=np.array([])\n for lamp in lamps :\n if lamp in lines:\n gd_lines=np.append(gd_lines,lines[lamp])\n\n # Sort and return\n gd_lines.sort()\n return dlamb, gd_lines\n\n########################################################\n# Fiber routines\n########################################################\n\ndef fiber_gauss(flat, xtrc, xerr, box_radius=2, max_iter=5, debug=False, verbose=False) :\n return fiber_gauss_new(flat, xtrc, xerr, box_radius, max_iter)\n\ndef fiber_gauss_new(flat, xtrc, xerr, box_radius=2, max_iter=5, debug=False, verbose=False):\n \"\"\"Find the PSF sigma for each fiber\n This serves as an initial guess to what follows\n\n Parameters\n ----------\n flat : ndarray of fiber flat image\n xtrc: ndarray of fiber traces\n xerr: ndarray of error in fiber traces\n box_radius: int, optinal\n Radius of boxcar extraction in pixels\n max_iter : int, optional\n Maximum number of iterations for rejection\n\n Returns\n -------\n gauss\n list of Gaussian sigma\n \"\"\"\n log=get_logger()\n\n npix_y = flat.shape[0]\n npix_x = flat.shape[1]\n ny = xtrc.shape[0] # number of ccd rows in trace\n assert(ny==npix_y)\n\n nfiber = xtrc.shape[1]\n\n minflux=1. # minimal flux in a row to include in the fit\n\n # Loop on fibers\n gauss = []\n start = 0\n for ii in range(nfiber):\n if (ii % 25 == 0): # & verbose:\n stop=time.time()\n if start==0 :\n log.info(\"Working on fiber {:d} of {:d}\".format(ii,nfiber))\n else :\n log.info(\"Working on fiber %d of %d (25 done in %3.2f sec)\"%(ii,nfiber,stop-start))\n start=stop\n\n # collect data\n central_xpix=np.floor(xtrc[:,ii]+0.5)\n begin_xpix=(central_xpix-box_radius).astype(int)\n end_xpix=(central_xpix+box_radius+1).astype(int)\n dx=[]\n flux=[]\n for y in range(ny) :\n yflux=flat[y,begin_xpix[y]:end_xpix[y]]\n syflux=np.sum(yflux)\n if syflux<minflux :\n continue\n dx.append(np.arange(begin_xpix[y],end_xpix[y])-(xtrc[y,ii]))\n flux.append(yflux/syflux)\n dx=np.array(dx)\n flux=np.array(flux)\n\n # compute profile\n # one way to get something robust is to compute median in bins\n # it's a bit biasing but the PSF is not a Gaussian anyway\n bins=np.linspace(-box_radius,box_radius,100)\n bstep=bins[1]-bins[0]\n bdx=[]\n bflux=[]\n for b in bins :\n ok=(dx>=b)&(dx<(b+bstep))\n if np.sum(ok)>0 :\n bdx.append(np.mean(dx[ok]))\n bflux.append(np.median(flux[ok]))\n if len(bdx)<10 :\n log.error(\"sigma fit failed for fiber #%02d\"%ii)\n log.error(\"this should only occur for the fiber near the center of the detector (if at all)\")\n log.error(\"using the sigma value from the previous fiber\")\n gauss.append(gauss[-1])\n continue\n # this is the profile :\n bdx=np.array(bdx)\n bflux=np.array(bflux)\n\n # fast iterative gaussian fit\n sigma = 1.0\n sq2 = math.sqrt(2.)\n for i in range(10) :\n nsigma = sq2*np.sqrt(np.mean(bdx**2*bflux*np.exp(-bdx**2/2/sigma**2))/np.mean(bflux*np.exp(-bdx**2/2/sigma**2)))\n if abs(nsigma-sigma) < 0.001 :\n break\n sigma = nsigma\n gauss.append(sigma)\n\n return np.array(gauss)\n\n\n\ndef fiber_gauss_old(flat, xtrc, xerr, box_radius=2, max_iter=5, debug=False, verbose=False):\n \"\"\"Find the PSF sigma for each fiber\n This serves as an initial guess to what follows\n\n Parameters\n ----------\n flat : ndarray of fiber flat image\n xtrc: ndarray of fiber traces\n xerr: ndarray of error in fiber traces\n box_radius: int, optinal\n Radius of boxcar extraction in pixels\n max_iter : int, optional\n Maximum number of iterations for rejection\n\n Returns\n -------\n gauss\n list of Gaussian sigma\n \"\"\"\n log=get_logger()\n log.warning(\"fiber_gauss uses astropy.modeling. Consider an alternative\")\n # Init\n nfiber = xtrc.shape[1]\n ny = xtrc.shape[0]\n iy = np.arange(ny).astype(int)\n # Mask\n mask = np.zeros_like(flat,dtype=int)\n # Sub images\n xpix_img = np.outer(np.ones(flat.shape[0]),np.arange(flat.shape[1]))\n # Gaussian fit\n g_init = models.Gaussian1D(amplitude=1., mean=0., stddev=1.)\n g_init.amplitude.fixed = True\n g_init.mean.fixed = True\n fitter = fitting.LevMarLSQFitter()\n\n # Loop on fibers\n gauss = []\n start = 0\n for ii in range(nfiber):\n if (ii % 25 == 0): # & verbose:\n stop=time.time()\n if start==0 :\n log.info(\"Working on fiber {:d} of {:d}\".format(ii,nfiber))\n else :\n log.info(\"Working on fiber %d of %d (done 25 in %3.2f sec)\"%(ii,nfiber,stop-start))\n start=stop\n\n mask[:] = 0\n ixt = np.round(xtrc[:,ii]).astype(int)\n for jj,ibox in enumerate(range(-box_radius,box_radius+1)):\n ix = ixt + ibox\n mask[iy,ix] = 1\n dx_img = xpix_img - np.outer(xtrc[:,ii],np.ones(flat.shape[1]))\n # Sum\n flux = np.sum(mask*flat,axis=1)\n flux = np.maximum(flux,1.)\n # Normalize\n nrm_img = flat / np.outer(flux,np.ones(flat.shape[1]))\n # Gaussian\n cpix = np.where(np.abs(dx_img)<0.10)\n if len(cpix[0]) < 50:\n cpix = np.where(np.abs(dx_img)<0.40)\n amp = np.median(nrm_img[cpix])\n g_init.amplitude.value = amp # Fixed\n fdimg = dx_img[mask==1].flatten()\n fnimg = nrm_img[mask==1].flatten()\n # Guess at sigma\n gdfn = (fnimg < amp) & (fnimg > 0.)\n all_sig = np.abs(fdimg[gdfn]) / np.sqrt( np.log(amp)-np.log(fnimg[gdfn]) )\n g_init.stddev.value = np.median(all_sig[np.where((np.abs(fdimg[gdfn])>1) & (np.abs(fdimg[gdfn])<1.5) & (np.isfinite(all_sig)))])\n\n # Initial fit (need to mask!)\n parm = fitter(g_init, fdimg, fnimg)\n\n # Iterate\n iterate = True\n nrej = 0\n niter = 0\n while iterate & (niter < max_iter):\n # Clip\n resid = parm(fdimg) - fnimg\n resid_mask = sigma_clip(resid, sigma=4., iters=5)\n # Fit\n gdp = ~resid_mask.mask\n parm = fitter(g_init, fdimg[gdp], fnimg[gdp])\n # Again?\n if np.sum(resid_mask.mask) <= nrej:\n iterate = False\n else:\n nrej = np.sum(resid_mask.mask)\n niter += 1\n if verbose:\n log.info(\"Rejected {:d} in {:d} iterations\".format(nrej,niter))\n\n #debug = False\n if debug:\n plt.clf()\n plt.scatter(fdimg[gdp], fnimg[gdp])\n x= np.linspace(-box_radius, box_radius, 200)\n plt.plot(x, parm(x), 'r-')\n plt.show()\n plt.close()\n pdb.set_trace()\n # Save\n gauss.append(parm.stddev.value)\n #\n return np.array(gauss)\n\ndef find_fiber_peaks(flat, ypos=None, nwidth=5, debug=False) :\n \"\"\"Find the peaks of the fiber flat spectra\n Preforms book-keeping error checking\n\n Args:\n flat : ndarray of fiber flat image\n ypos : int [optional] Row for finding peaks\n Default is half-way up the image\n nwidth : int [optional] Width of peak (end-to-end)\n debug: bool, optional\n\n Returns:\n xpk, ypos, cut\n list of xpk (nearest pixel) at ypos\n ndarray of cut through the image\n \"\"\"\n log=get_logger()\n log.info(\"starting\")\n # Init\n Nbundle = 20\n Nfiber = 25 # Fibers per bundle\n # Set ypos for peak finding\n if ypos is None:\n ypos = flat.shape[0]//2\n\n # Cut image\n cutimg = flat[ypos-50:ypos+50, :]\n\n # Smash\n cut = np.median(cutimg, axis=0)\n\n # Set flux threshold\n #srt = np.sort(cutimg.flatten()) # this does not work for sparse fibers\n #thresh = srt[int(cutimg.size*0.95)] / 2. # this does not work for sparse fibers\n\n thresh = np.max(cut)/20.\n pixels_below_threshold=np.where(cut<thresh)[0]\n if pixels_below_threshold.size>2 :\n values_below_threshold = sigma_clip(cut[pixels_below_threshold],sigma=3,iters=200)\n if values_below_threshold.size>2 :\n rms=np.std(values_below_threshold)\n nsig=7\n new_thresh=max(thresh,nsig*rms)\n log.info(\"Threshold: {:f} -> {:f} ({:d}*rms: {:f})\".format(thresh,new_thresh,nsig,nsig*rms))\n thresh=new_thresh\n\n #gdp = cut > thresh\n # Roll to find peaks (simple algorithm)\n #nstep = nwidth // 2\n #for kk in range(-nstep,nstep):\n # if kk < 0:\n # test = np.roll(cut,kk) < np.roll(cut,kk+1)\n # else:\n # test = np.roll(cut,kk) > np.roll(cut,kk+1)\n # # Compare\n # gdp = gdp & test\n #xpk = np.where(gdp)[0]\n\n # Find clusters of adjacent points\n clusters=[]\n gdp=np.where(cut > thresh)[0]\n cluster=[gdp[0]]\n for i in gdp[1:] :\n if i==cluster[-1]+1 :\n cluster.append(i)\n else :\n clusters.append(cluster)\n cluster=[i]\n clusters.append(cluster)\n\n\n log.info(\"Number of clusters found: {:d}\".format(len(clusters)))\n\n # Record max of each cluster\n xpk=np.zeros((len(clusters)), dtype=np.int64)\n for i in range(len(clusters)) :\n t=np.argmax(cut[clusters[i]])\n xpk[i]=clusters[i][t]\n\n if debug:\n #pdb.xplot(cut, xtwo=xpk, ytwo=cut[xpk],mtwo='o')\n pdb.set_trace()\n\n # Book-keeping and some error checking\n if len(xpk) != Nbundle*Nfiber:\n log.warning('Found the wrong number of total fibers: {:d}'.format(len(xpk)))\n else:\n log.info('Found {:d} fibers'.format(len(xpk)))\n # Find bundles\n xsep = np.roll(xpk,-1) - xpk\n medsep = np.median(xsep)\n bundle_ends = np.where(np.abs(xsep-medsep) > 0.5*medsep)[0]\n if len(bundle_ends) != Nbundle:\n log.warning('Found the wrong number of bundles: {:d}'.format(len(bundle_ends)))\n else:\n log.info('Found {:d} bundles'.format(len(bundle_ends)))\n # Confirm correct number of fibers per bundle\n bad = ((bundle_ends+1) % Nfiber) != 0\n if np.sum(bad) > 0:\n log.warning('Wrong number of fibers in a bundle')\n #raise ValueError('Wrong number of fibers in a bundle')\n\n # Return\n return xpk, ypos, cut\n\n\ndef fit_traces(xset, xerr, func='legendre', order=6, sigrej=20.,\n RMS_TOLER=0.03, verbose=False):\n \"\"\"Fit the traces\n Default is 6th order Legendre polynomials\n\n Parameters\n ----------\n xset : ndarray\n traces\n xerr : ndarray\n Error in the trace values (999.=Bad)\n RMS_TOLER : float, optional [0.02]\n Tolerance on size of RMS in fit\n\n Returns\n -------\n xnew, fits\n xnew : ndarray\n New fit values (without error)\n fits : list\n List of the fit dicts\n \"\"\"\n log=get_logger()\n ny = xset.shape[0]\n ntrace = xset.shape[1]\n xnew = np.zeros_like(xset)\n fits = []\n yval = np.arange(ny)\n for ii in range(ntrace):\n mask = xerr[:,ii] > 900.\n nmask = np.sum(mask)\n # Fit with rejection\n dfit, mask = dufits.iter_fit(yval, xset[:,ii], func, order, sig_rej=sigrej,\n weights=1./xerr[:,ii], initialmask=mask, maxone=True)#, sigma=xerr[:,ii])\n # Stats on residuals\n nmask_new = np.sum(mask)-nmask\n if nmask_new > 200:\n log.error(\"Rejected many points ({:d}) in fiber {:d}\".format(nmask_new, ii))\n # Save\n xnew[:,ii] = dufits.func_val(yval,dfit)\n fits.append(dfit)\n # Residuas\n gdval = mask==0\n resid = xnew[:,ii][gdval] - xset[:,ii][gdval]\n rms = np.std(resid)\n if verbose:\n print('RMS of FIT= {:g}'.format(rms))\n if rms > RMS_TOLER:\n #from xastropy.xutils import xdebug as xdb\n #xdb.xplot(yval, xnew[:,ii], xtwo=yval[gdval],ytwo=xset[:,ii][gdval], mtwo='o')\n log.error(\"RMS {:g} exceeded tolerance for fiber {:d}\".format(rms, ii))\n # Return\n return xnew, fits\n\n\ndef extract_sngfibers_gaussianpsf(img, img_ivar, xtrc, sigma, box_radius=2, verbose=True):\n \"\"\"Extract spectrum for fibers one-by-one using a Gaussian PSF\n\n Parameters\n ----------\n img : ndarray\n Image\n img_ivar : ndarray\n Image inverse variance\n xtrc : ndarray\n fiber trace\n sigma : float\n Gaussian sigma for PSF\n box_radius : int, optional\n Radius for extraction (+/-)\n\n Returns\n -------\n spec : ndarray\n Extracted spectrum\n \"\"\"\n\n # Init\n xpix_img = np.outer(np.ones(img.shape[0]),np.arange(img.shape[1]))\n mask = np.zeros_like(img,dtype=int)\n iy = np.arange(img.shape[0],dtype=int)\n\n log = get_logger()\n\n #\n all_spec = np.zeros_like(xtrc)\n cst = 1./np.sqrt(2*np.pi)\n start=0\n for qq in range(xtrc.shape[1]):\n if verbose & (qq % 25 == 0):\n stop=time.time()\n if start>0 :\n log.info(\"Working on fiber %d of %d (done 25 in %3.2f sec)\"%(qq,xtrc.shape[1],stop-start))\n else :\n log.info(\"Working on fiber %d of %d\"%(qq,xtrc.shape[1]))\n start=stop\n\n # Mask\n mask[:,:] = 0\n ixt = np.round(xtrc[:,qq]).astype(int)\n for jj,ibox in enumerate(range(-box_radius,box_radius+1)):\n ix = ixt + ibox\n mask[iy,ix] = 1\n # Sub-image (for speed, not convenience)\n gdp = np.where(mask == 1)\n minx = np.min(gdp[1])\n maxx = np.max(gdp[1])\n nx = (maxx-minx)+1\n\n # Generate PSF\n dx_img = xpix_img[:,minx:maxx+1] - np.outer(xtrc[:,qq], np.ones(nx))\n psf = cst*np.exp(-0.5 * (dx_img/sigma[qq])**2)/sigma[qq]\n\n #dx_img = xpix_img[:,minx:maxx+1] - np.outer(xtrc[:,qq],np.ones(img.shape[1]))\n #g_init = models.Gaussian1D(amplitude=1., mean=0., stddev=sigma[qq])\n #psf = mask * g_init(dx_img)\n # Extract\n #all_spec[:,qq] = np.sum(psf*img,axis=1) / np.sum(psf,axis=1)\n #all_spec[:,qq] = np.sum(psf*img[:,minx:maxx+1],axis=1) / np.sum(psf,axis=1)\n a=np.sum(img_ivar[:,minx:maxx+1]*psf**2,axis=1)\n b=np.sum(img_ivar[:,minx:maxx+1]*psf*img[:,minx:maxx+1],axis=1)\n ok=(a>1.e-6)\n all_spec[ok,qq] = b[ok] / a[ok]\n\n #import astropy.io.fits as pyfits\n #h=pyfits.HDUList([pyfits.PrimaryHDU(),\n # pyfits.ImageHDU(img[:,minx:maxx+1],name=\"FLUX\"),\n # pyfits.ImageHDU(img_ivar[:,minx:maxx+1],name=\"IVAR\"),\n # pyfits.ImageHDU(psf,name=\"PSF\"),\n # pyfits.ImageHDU(a,name=\"A\"),\n # pyfits.ImageHDU(b,name=\"B\")])\n #h.writeto(\"test.fits\")\n #sys.exit(12)\n\n\n\n\n\n # Return\n return all_spec\n\n\ndef trace_crude_init(image, xinit0, ypass, invvar=None, radius=2.,\n maxshift0=0.5, maxshift=0.15, maxerr=0.2):\n# xset, xerr, maxerr, maxshift, maxshift0\n \"\"\"Python port of trace_crude_idl.pro from IDLUTILS\n\n Modified for initial guess\n\n Parameters\n ----------\n image : 2D ndarray\n Image for tracing\n xinit : ndarray\n Initial guesses for trace peak at ypass\n ypass : int\n Row for initial guesses\n\n Returns\n -------\n xset : Trace for each fiber\n xerr : Estimated error in that trace\n \"\"\"\n # Init\n xinit = xinit0.astype(float)\n #xinit = xinit[0:3]\n ntrace = xinit.size\n ny = image.shape[0]\n xset = np.zeros((ny,ntrace))\n xerr = np.zeros((ny,ntrace))\n if invvar is None:\n invvar = np.zeros_like(image) + 1.\n\n #\n # Recenter INITIAL Row for all traces simultaneously\n #\n iy = ypass * np.ones(ntrace,dtype=int)\n xfit,xfiterr = trace_fweight(image, xinit, iy, invvar=invvar, radius=radius)\n # Shift\n xshift = np.clip(xfit-xinit, -1*maxshift0, maxshift0) * (xfiterr < maxerr)\n xset[ypass,:] = xinit + xshift\n xerr[ypass,:] = xfiterr * (xfiterr < maxerr) + 999.0 * (xfiterr >= maxerr)\n\n # /* LOOP FROM INITIAL (COL,ROW) NUMBER TO LARGER ROW NUMBERS */\n for iy in range(ypass+1, ny):\n xinit = xset[iy-1, :]\n ycen = iy * np.ones(ntrace,dtype=int)\n xfit,xfiterr = trace_fweight(image, xinit, ycen, invvar=invvar, radius=radius)\n # Shift\n xshift = np.clip(xfit-xinit, -1*maxshift, maxshift) * (xfiterr < maxerr)\n # Save\n xset[iy,:] = xinit + xshift\n xerr[iy,:] = xfiterr * (xfiterr < maxerr) + 999.0 * (xfiterr >= maxerr)\n # /* LOOP FROM INITIAL (COL,ROW) NUMBER TO SMALLER ROW NUMBERS */\n for iy in range(ypass-1, -1,-1):\n xinit = xset[iy+1, :]\n ycen = iy * np.ones(ntrace,dtype=int)\n xfit,xfiterr = trace_fweight(image, xinit, ycen, invvar=invvar, radius=radius)\n # Shift\n xshift = np.clip(xfit-xinit, -1*maxshift, maxshift) * (xfiterr < maxerr)\n # Save\n xset[iy,:] = xinit + xshift\n xerr[iy,:] = xfiterr * (xfiterr < maxerr) + 999.0 * (xfiterr >= maxerr)\n\n return xset, xerr\n\n\ndef trace_fweight(fimage, xinit, ycen=None, invvar=None, radius=2., debug=False):\n '''Python port of trace_fweight.pro from IDLUTILS\n\n Parameters\n ----------\n fimage: 2D ndarray\n Image for tracing\n xinit: ndarray\n Initial guesses for x-trace\n invvar: ndarray, optional\n Inverse variance array for the image\n radius: float, optional\n Radius for centroiding; default to 3.0\n '''\n # Definitions for Cython\n #cdef int nx,ny,ncen\n\n # Init\n nx = fimage.shape[1]\n ny = fimage.shape[0]\n ncen = len(xinit)\n # Create xnew, xerr\n xnew = xinit.astype(float)\n xerr = np.zeros(ncen) + 999.\n\n # ycen\n if ycen is None:\n if ncen != ny:\n raise ValueError('Bad input')\n ycen = np.arange(ny, dtype=int)\n else:\n if len(ycen) != ncen:\n raise ValueError('Bad ycen input. Wrong length')\n x1 = xinit - radius + 0.5\n x2 = xinit + radius + 0.5\n ix1 = np.floor(x1).astype(int)\n ix2 = np.floor(x2).astype(int)\n\n fullpix = int(np.maximum(np.min(ix2-ix1)-1,0))\n sumw = np.zeros(ncen)\n sumxw = np.zeros(ncen)\n sumwt = np.zeros(ncen)\n sumsx1 = np.zeros(ncen)\n sumsx2 = np.zeros(ncen)\n qbad = np.array([False]*ncen)\n\n if invvar is None:\n invvar = np.zeros_like(fimage) + 1.\n\n # Compute\n for ii in range(0,fullpix+3):\n spot = ix1 - 1 + ii\n ih = np.clip(spot,0,nx-1)\n xdiff = spot - xinit\n #\n wt = np.clip(radius - np.abs(xdiff) + 0.5,0,1) * ((spot >= 0) & (spot < nx))\n sumw = sumw + fimage[ycen,ih] * wt\n sumwt = sumwt + wt\n sumxw = sumxw + fimage[ycen,ih] * xdiff * wt\n var_term = wt**2 / (invvar[ycen,ih] + (invvar[ycen,ih] == 0))\n sumsx2 = sumsx2 + var_term\n sumsx1 = sumsx1 + xdiff**2 * var_term\n #qbad = qbad or (invvar[ycen,ih] <= 0)\n qbad = np.any([qbad, invvar[ycen,ih] <= 0], axis=0)\n\n if debug:\n pdb.set_trace()\n\n # Fill up\n good = (sumw > 0) & (~qbad)\n if np.sum(good) > 0:\n delta_x = sumxw[good]/sumw[good]\n xnew[good] = delta_x + xinit[good]\n xerr[good] = np.sqrt(sumsx1[good] + sumsx2[good]*delta_x**2)/sumw[good]\n\n bad = np.any([np.abs(xnew-xinit) > radius + 0.5,xinit < radius - 0.5,xinit > nx - 0.5 - radius],axis=0)\n if np.sum(bad) > 0:\n xnew[bad] = xinit[bad]\n xerr[bad] = 999.0\n\n # Return\n return xnew, xerr\n\n\ndef fix_ycoeff_outliers(xcoeff, ycoeff, deg=5, tolerance=2):\n '''\n Fix outliers in coefficients for wavelength solution, assuming a continuous function of CCD coordinates\n\n Args:\n xcoeff[nfiber, ncoeff] : 2D array of Legendre coefficients for X(wavelength)\n ycoeff[nfiber, ncoeff] : 2D array of Legendre coefficients for Y(wavelength)\n\n Options:\n deg : integer degree of polynomial to fit\n tolerance : replace fibers with difference of wavelength solution larger than this number of pixels after interpolation\n\n Returns:\n new_ycoeff[nfiber, ncoeff] with outliers replaced by interpolations\n\n For each coefficient, fit a polynomial vs. fiber number with one\n pass of sigma clipping. Remaining outliers are than replaced with\n the interpolated fit value.\n '''\n\n log = get_logger()\n\n nfibers=ycoeff.shape[0]\n if nfibers < 3 :\n log.warning(\"only {:d} fibers, cannot interpolate coefs\".format(nfibers))\n return ycoeff\n deg=min(deg,nfibers-1)\n\n nwave=ycoeff.shape[1]+1\n wave_nodes = np.linspace(-1,1,nwave)\n\n # get traces using fit coefs\n x=np.zeros((nfibers,nwave))\n y=np.zeros((nfibers,nwave))\n\n for i in range(nfibers) :\n x[i] = legval(wave_nodes,xcoeff[i])\n y[i] = legval(wave_nodes,ycoeff[i])\n\n new_ycoeff=ycoeff.copy()\n\n bad_fibers=None\n while True : # loop to discard one fiber at a time\n\n # polynomial fit as a function of x for each wave\n yf=np.zeros((nfibers,nwave))\n xx=2*(x - np.min(x)) / (np.max(x) - np.min(x)) - 1\n for i in range(nwave) :\n c=np.polyfit(xx[:,i], y[:,i], deg)\n yf[:,i]=np.polyval(c, xx[:,i])\n\n diff=np.max(np.abs(y-yf),axis=1)\n\n for f in range(nfibers) :\n log.info(\"fiber {:d} maxdiff= {:f}\".format(f,diff[f]))\n\n\n worst = np.argmax(diff)\n if diff[worst] > tolerance :\n log.warning(\"replace fiber {:d} trace by interpolation\".format(worst))\n leg_fit = dufits.func_fit(wave_nodes, yf[worst], 'legendre', ycoeff.shape[1]-1, xmin=-1, xmax=1)\n new_ycoeff[worst] = leg_fit['coeff']\n y[worst] = legval(wave_nodes,new_ycoeff[worst])\n if bad_fibers is None :\n bad_fibers = np.array([worst])\n else :\n bad_fibers=np.append(bad_fibers, worst)\n bad_fibers=np.unique(bad_fibers)\n continue\n break\n\n return new_ycoeff\n\n\n#####################################################################\n#####################################################################\n# Output\n#####################################################################\n\ndef write_psf(outfile, xfit, fdicts, gauss, wv_solns, legendre_deg=5, without_arc=False,\n XCOEFF=None, fiberflat_header=None, arc_header=None):\n \"\"\" Write the output to a Base PSF format\n\n Parameters\n ----------\n outfile : str\n Output file\n xfit : ndarray\n Traces\n gauss : list\n List of gaussian sigmas\n fdicts : list\n List of trace fits\n wv_solns : list\n List of wavelength calibrations\n ncoeff : int\n Number of Legendre coefficients in fits\n \"\"\"\n #\n\n # check legendre degree makes sense based on number of lines\n if not without_arc:\n nlines=10000\n for ii,id_dict in enumerate(wv_solns):\n if len(id_dict['id_pix']) > 0 :\n nlines_in_fiber=(np.array(id_dict['id_pix'])[id_dict['mask']==0]).size\n #print(\"fiber #%d nlines=%d\"%(ii,nlines_in_fiber))\n nlines=min(nlines,nlines_in_fiber)\n if nlines < legendre_deg+2 :\n legendre_deg=nlines-2\n print(\"reducing legendre degree to %d because the min. number of emission lines found is %d\"%(legendre_deg,nlines))\n\n ny = xfit.shape[0]\n nfiber = xfit.shape[1]\n ncoeff=legendre_deg+1\n if XCOEFF is None:\n XCOEFF = np.zeros((nfiber, ncoeff))\n YCOEFF = np.zeros((nfiber, ncoeff))\n\n # Find WAVEMIN, WAVEMAX\n if without_arc:\n WAVEMIN = 0.\n WAVEMAX = ny-1.\n wv_solns = [None]*nfiber\n else:\n WAVEMIN = 10000000.\n WAVEMAX = 0.\n for id_dict in wv_solns :\n if 'wave_min' in id_dict :\n WAVEMIN = min(WAVEMIN,id_dict['wave_min'])\n if 'wave_max' in id_dict :\n WAVEMAX = max(WAVEMAX,id_dict['wave_max'])\n WAVEMIN -= 1.\n WAVEMAX += 1.\n\n wv_array = np.linspace(WAVEMIN, WAVEMAX, num=ny)\n # Fit Legendre to y vs. wave\n for ii,id_dict in enumerate(wv_solns):\n\n\n\n # Fit y vs. wave\n if without_arc:\n yleg_fit, mask = dufits.iter_fit(wv_array, np.arange(ny), 'legendre', ncoeff-1, xmin=WAVEMIN, xmax=WAVEMAX, niter=1)\n else:\n if len(id_dict['id_wave']) > 0 :\n yleg_fit, mask = dufits.iter_fit(np.array(id_dict['id_wave'])[id_dict['mask']==0], np.array(id_dict['id_pix'])[id_dict['mask']==0], 'legendre', ncoeff-1, xmin=WAVEMIN, xmax=WAVEMAX, sig_rej=100000.)\n else :\n yleg_fit = None\n mask = None\n\n if yleg_fit is None :\n continue\n\n YCOEFF[ii, :] = yleg_fit['coeff']\n\n # Fit x vs. wave\n yval = dufits.func_val(wv_array, yleg_fit)\n if fdicts is None:\n if XCOEFF is None:\n raise IOError(\"Need to set either fdicts or XCOEFF!\")\n else:\n xtrc = dufits.func_val(yval, fdicts[ii])\n xleg_fit,mask = dufits.iter_fit(wv_array, xtrc, 'legendre', ncoeff-1, xmin=WAVEMIN, xmax=WAVEMAX, niter=5, sig_rej=100000.)\n XCOEFF[ii, :] = xleg_fit['coeff']\n\n # Fix outliers assuming that coefficients vary smoothly vs. CCD coordinates\n YCOEFF = fix_ycoeff_outliers(XCOEFF,YCOEFF,tolerance=2)\n\n # Write the FITS file\n prihdu = fits.PrimaryHDU(XCOEFF)\n prihdu.header['WAVEMIN'] = WAVEMIN\n prihdu.header['WAVEMAX'] = WAVEMAX\n prihdu.header['EXTNAME'] = 'XTRACE'\n prihdu.header['PSFTYPE'] = 'bootcalib'\n\n from desiutil.depend import add_dependencies\n add_dependencies(prihdu.header)\n\n # Add informations for headers\n if arc_header is not None :\n if \"NIGHT\" in arc_header:\n prihdu.header[\"ARCNIGHT\"] = arc_header[\"NIGHT\"]\n if \"EXPID\" in arc_header:\n prihdu.header[\"ARCEXPID\"] = arc_header[\"EXPID\"]\n if \"CAMERA\" in arc_header:\n prihdu.header[\"CAMERA\"] = arc_header[\"CAMERA\"]\n prihdu.header['NPIX_X'] = arc_header['NAXIS1']\n prihdu.header['NPIX_Y'] = arc_header['NAXIS2']\n if fiberflat_header is not None :\n if 'NPIX_X' not in prihdu.header:\n prihdu.header['NPIX_X'] = fiberflat_header['NAXIS1']\n prihdu.header['NPIX_Y'] = fiberflat_header['NAXIS2']\n if \"NIGHT\" in fiberflat_header:\n prihdu.header[\"FLANIGHT\"] = fiberflat_header[\"NIGHT\"]\n if \"EXPID\" in fiberflat_header:\n prihdu.header[\"FLAEXPID\"] = fiberflat_header[\"EXPID\"]\n\n yhdu = fits.ImageHDU(YCOEFF, name='YTRACE')\n\n # also save wavemin wavemax in yhdu\n yhdu.header['WAVEMIN'] = WAVEMIN\n yhdu.header['WAVEMAX'] = WAVEMAX\n\n gausshdu = fits.ImageHDU(np.array(gauss), name='XSIGMA')\n\n hdulist = fits.HDUList([prihdu, yhdu, gausshdu])\n\n\n hdulist.writeto(outfile, overwrite=True)\n\ndef write_line_list(filename,all_wv_soln,llist) :\n wave = np.array([])\n for id_dict in all_wv_soln :\n wave=np.append(wave,id_dict[\"id_wave\"])\n wave=np.unique(wave)\n\n ofile=open(filename,\"w\")\n ofile.write(\"# from bootcalib\\n\")\n ofile.write(\"Ion wave score RelInt\\n\")\n for w in wave :\n ii=np.argmin(np.abs(llist[\"wave\"]-w))\n print(w,llist[\"wave\"][ii],llist[\"Ion\"][ii])\n ofile.write(\"{:s} {:f} 1 1\\n\".format(llist[\"Ion\"][ii],w))\n ofile.close()\n\n\n\n\n\n#####################################################################\n#####################################################################\n# Utilities\n#####################################################################\n\ndef script_bootcalib(arc_idx, flat_idx, cameras=None, channels=None, nproc=10):\n \"\"\" Runs desi_bootcalib on a series of preproc files\n\n Returns:\n script_bootcalib([0,1,2,3,4,5,6,7,8,9], [10,11,12,13,14])\n\n \"\"\"\n from subprocess import Popen\n #\n if cameras is None:\n cameras = ['0','1','2','3','4','5','6','7','8','9']\n if channels is None:\n channels = ['b','r','z']\n #channels = ['b']#,'r','z']\n nchannels = len(channels)\n ncameras = len(cameras)\n #\n narc = len(arc_idx)\n nflat = len(flat_idx)\n ntrial = narc*nflat*ncameras*nchannels\n\n # Loop on the systems\n nrun = -1\n #nrun = 123\n while(nrun < ntrial):\n\n proc = []\n ofiles = []\n for ss in range(nproc):\n nrun += 1\n iarc = nrun % narc\n jflat = (nrun//narc) % nflat\n kcamera = (nrun//(narc*nflat)) % ncameras\n lchannel = nrun // (narc*nflat*ncameras)\n #pdb.set_trace()\n if nrun == ntrial:\n break\n # Names\n #- TODO: update to use desispec.io.findfile instead\n afile = str('preproc-{:s}{:s}-{:08d}.fits'.format(channels[lchannel], cameras[kcamera], arc_idx[iarc]))\n ffile = str('preproc-{:s}{:s}-{:08d}.fits'.format(channels[lchannel], cameras[kcamera], flat_idx[jflat]))\n ofile = str('boot_psf-{:s}{:s}-{:d}{:d}.fits'.format(channels[lchannel], cameras[kcamera],\n arc_idx[iarc], flat_idx[jflat]))\n qfile = str('qa_boot-{:s}{:s}-{:d}{:d}.pdf'.format(channels[lchannel], cameras[kcamera],\n arc_idx[iarc], flat_idx[jflat]))\n lfile = str('boot-{:s}{:s}-{:d}{:d}.log'.format(channels[lchannel], cameras[kcamera],\n arc_idx[iarc], flat_idx[jflat]))\n ## Run\n script = [str('desi_bootcalib.py'), str('--fiberflat={:s}'.format(ffile)),\n str('--arcfile={:s}'.format(afile)),\n str('--outfile={:s}'.format(ofile)),\n str('--qafile={:s}'.format(qfile))]#,\n #str('>'),\n #str('{:s}'.format(lfile))]\n f = open(lfile, \"w\")\n proc.append(Popen(script, stdout=f))\n ofiles.append(f)\n exit_codes = [p.wait() for p in proc]\n for ofile in ofiles:\n ofile.close()\n\n\n#####################################################################\n#####################################################################\n#####################################################################\n# QA\n#####################################################################\n\ndef qa_fiber_peaks(xpk, cut, pp=None, figsz=None, nper=100):\n \"\"\" Generate a QA plot for the fiber peaks\n\n Args:\n xpk: x positions on the CCD of the fiber peaks at a ypos\n cut: Spatial cut through the detector\n pp: PDF file pointer\n figsz: figure size, optional\n nper: number of fibers per row in the plot, optional\n\n \"\"\"\n # Init\n if figsz is None:\n figsz = glbl_figsz\n\n nfiber = xpk.size\n nrow = (nfiber // nper) + ((nfiber % nper) > 0)\n xplt = np.arange(cut.size)\n # Plots\n gs = gridspec.GridSpec(nrow, 1)\n plt.figure(figsize=figsz)\n # Loop\n for ii in range(nrow):\n ax = plt.subplot(gs[ii])\n i0 = ii*nper\n i1 = i0 + nper\n ax.plot(xplt,cut, 'k-')\n ax.plot(xpk, cut[xpk],'go')\n xmin = np.min(xpk[i0:i1])-10.\n xmax = np.max(xpk[i0:i1])+10.\n ax.set_xlim(xmin,xmax)\n # Save and close\n if pp is not None:\n pp.savefig(bbox_inches='tight')\n else:\n plt.show()\n plt.close()\n\n\ndef qa_fiber_Dx(xfit, fdicts, pp=None, figsz=None):\n \"\"\" Show the spread in the trace per fiber\n\n Used to diagnose the traces\n\n Args:\n xfit: traces\n fdicts: dict of the traces\n pp: PDF file pointer\n figsz: figure size, optional\n\n \"\"\"\n #\n if figsz is None:\n figsz = glbl_figsz\n # Calculate Dx\n nfiber = xfit.shape[1]\n Dx = []\n for ii in range(nfiber):\n Dx.append(np.max(xfit[:, ii])-np.min(xfit[:, ii]))\n # Plot\n plt.figure(figsize=figsz)\n plt.scatter(np.arange(nfiber), np.array(Dx))\n # Label\n plt.xlabel('Fiber', fontsize=17.)\n plt.ylabel(r'$\\Delta x$ (pixels)', fontsize=17.)\n # Save and close\n if pp is None:\n plt.show()\n else:\n pp.savefig(bbox_inches='tight')\n plt.close()\n\ndef qa_fiber_gauss(gauss, pp=None, figsz=None):\n \"\"\" Show the Gaussian (sigma) fits to each fiber\n\n Args:\n gauss: Gaussian of each fiber\n pp: PDF file pointer\n figsz: figure size, optional\n\n \"\"\"\n #\n if figsz is None:\n figsz = glbl_figsz\n # Calculate Dx\n nfiber = gauss.size\n # Plot\n plt.figure(figsize=figsz)\n plt.scatter(np.arange(nfiber), gauss)\n # Label\n plt.xlabel('Fiber', fontsize=17.)\n plt.ylabel('Gaussian sigma (pixels)', fontsize=17.)\n # Save and close\n if pp is None:\n plt.show()\n else:\n pp.savefig(bbox_inches='tight')\n plt.close()\n\ndef qa_arc_spec(all_spec, all_soln, pp, figsz=None):\n \"\"\" Generate QA plots of the arc spectra with IDs\n\n Args:\n all_spec: Arc 1D fiber spectra\n all_soln: Wavelength solutions\n pp: PDF file pointer\n figsz: figure size, optional\n\n \"\"\"\n # Init\n if figsz is None:\n figsz = glbl_figsz\n nfiber = len(all_soln)\n npix = all_spec.shape[0]\n #\n nrow = 2\n ncol = 3\n # Plots\n gs = gridspec.GridSpec(nrow, ncol)\n plt.figure(figsize=figsz)\n # Loop\n for ii in range(nrow*ncol):\n ax = plt.subplot(gs[ii])\n idx = ii * (nfiber//(nrow*ncol))\n yspec = np.log10(np.maximum(all_spec[:,idx],1))\n ax.plot(np.arange(npix), yspec, 'k-')\n ax.set_xlabel('Pixel')\n ax.set_ylabel('log Flux')\n # ID\n id_dict = all_soln[idx]\n for jj,xpixpk in enumerate(id_dict['id_pix']):\n ax.text(xpixpk, yspec[int(np.round(xpixpk))], '{:g}'.format(id_dict['id_wave'][jj]), ha='center',color='red', rotation=90.)\n\n # Save and close\n pp.savefig(bbox_inches='tight')\n plt.close()\n\n\ndef qa_fiber_arcrms(all_soln, pp, figsz=None):\n \"\"\" Show the RMS of the wavelength solutions vs. fiber\n\n Args:\n all_soln: Wavelength solutions\n pp: PDF file pointer\n figsz: figure size, optional\n\n \"\"\"\n #\n if figsz is None:\n figsz = glbl_figsz\n # Calculate Dx\n nfiber = len(all_soln)\n rms = [id_dict['rms'] for id_dict in all_soln]\n # Plot\n plt.figure(figsize=figsz)\n plt.scatter(np.arange(nfiber), np.array(rms))\n # Label\n plt.xlabel('Fiber', fontsize=17.)\n plt.ylabel('RMS (pixels)', fontsize=17.)\n # Save and close\n pp.savefig(bbox_inches='tight')\n plt.close()\n\n\ndef qa_fiber_dlamb(all_spec, all_soln, pp, figsz=None):\n \"\"\" Show the Dlamb of the wavelength solutions vs. fiber\n\n Args:\n all_soln: Wavelength solutions\n pp: PDF file pointer\n figsz: figure size, optional\n\n \"\"\"\n #\n if figsz is None:\n figsz = glbl_figsz\n # Calculate Dx\n nfiber = len(all_soln)\n npix = all_spec.shape[0]\n xval = np.arange(npix)\n dlamb = []\n for ii in range(nfiber):\n idict = all_soln[ii]\n wave = dufits.func_val(xval,idict['final_fit_pix'])\n dlamb.append(np.median(np.abs(wave-np.roll(wave,1))))\n # Plot\n plt.figure(figsize=figsz)\n plt.scatter(np.arange(nfiber), np.array(dlamb))\n # Label\n plt.xlabel('Fiber', fontsize=17.)\n plt.ylabel(r'$\\Delta \\lambda$ (Ang)', fontsize=17.)\n # Save and close\n pp.savefig(bbox_inches='tight')\n plt.close()\n\n\ndef qa_fiber_trace(flat, xtrc, outfil=None, Nfiber=25, isclmin=0.5):\n ''' Generate a QA plot for the fiber traces\n\n Parameters\n ----------\n flat: ndarray\n image\n xtrc: ndarray\n Trace array\n isclmin: float, optional [0.5]\n Fraction of 90 percentile flux to scale image by\n outfil: str, optional\n Output file\n normalize: bool, optional\n Normalize the flat? If not, use zscale for output\n '''\n\n ticks_font = matplotlib.font_manager.FontProperties(family='times new roman',\n style='normal', size=16, weight='normal', stretch='normal')\n plt.rcParams['font.family']= 'times new roman'\n cmm = cm.Greys_r\n # Outfil\n if outfil is None:\n outfil = 'fiber_trace_qa.pdf'\n ntrc = xtrc.shape[1]\n ycen = np.arange(flat.shape[0])\n\n # Plot\n pp = PdfPages(outfil)\n plt.clf()\n fig = plt.figure(figsize=(8, 5.0),dpi=1200)\n #fig.set_size_inches(10.0,6.5)\n Nbundle = ntrc // Nfiber + (ntrc%Nfiber > 0)\n for qq in range(Nbundle):\n ax = plt.gca()\n for label in ax.get_yticklabels() :\n label.set_fontproperties(ticks_font)\n for label in ax.get_xticklabels() :\n label.set_fontproperties(ticks_font)\n\n # Cut image\n i0 = qq*Nfiber\n i1 = np.minimum((qq+1)*Nfiber,ntrc)\n x0 = np.maximum(int(np.min(xtrc[:,i0:i1]))-3,0)\n x1 = np.minimum(int(np.max(xtrc[:,i0:i1]))+3,flat.shape[1])\n sub_flat = flat[:,x0:x1].T\n # Scale\n srt = np.sort(sub_flat.flatten())\n sclmax = srt[int(sub_flat.size*0.9)]\n sclmin = isclmin * sclmax\n # Plot\n mplt = plt.imshow(sub_flat,origin='lower', cmap=cmm,\n extent=(0., sub_flat.shape[1]-1, x0,x1-1), aspect='auto')\n #extent=(0., sub_flat.shape[1]-1, x0,x1))\n #mplt.set_clim(vmin=sclmin, vmax=sclmax)\n\n # Axes\n #plt.xlim(0., sub_flat.shape[1]-1)\n plt.xlim(0., sub_flat.shape[1]-1)\n plt.ylim(x0,x1)\n\n # Traces\n for ii in range(i0,i1):\n # Left\n plt.plot(ycen, xtrc[:,ii], 'r-',alpha=0.7, linewidth=0.5)\n # Label\n #iy = int(frame.shape[0]/2.)\n #plt.text(ltrace[iy,ii], ycen[iy], '{:d}'.format(ii+1), color='red', ha='center')\n #plt.text(rtrace[iy,ii], ycen[iy], '{:d}'.format(ii+1), color='green', ha='center')\n\n pp.savefig(bbox_inches='tight')\n plt.close()\n # Finish\n print('Writing {:s} QA for fiber trace'.format(outfil))\n pp.close()\n"
]
| [
[
"matplotlib.pyplot.xlim",
"numpy.minimum",
"numpy.median",
"numpy.min",
"numpy.exp",
"numpy.mean",
"numpy.where",
"numpy.sort",
"matplotlib.pyplot.imshow",
"numpy.max",
"numpy.zeros_like",
"matplotlib.font_manager.FontProperties",
"numpy.log",
"numpy.unravel_index",
"numpy.polyval",
"numpy.arange",
"numpy.polyfit",
"numpy.argmax",
"numpy.append",
"numpy.sqrt",
"numpy.isfinite",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.subplot",
"numpy.array",
"numpy.zeros",
"numpy.round",
"matplotlib.backends.backend_pdf.PdfPages",
"numpy.roll",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"numpy.std",
"numpy.argsort",
"numpy.clip",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.show",
"numpy.polynomial.legendre.legval",
"matplotlib.gridspec.GridSpec",
"numpy.floor",
"matplotlib.pyplot.xlabel",
"numpy.sum",
"numpy.ones",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.plot",
"numpy.any",
"matplotlib.pyplot.ylabel",
"numpy.abs",
"matplotlib.pyplot.scatter",
"numpy.linspace",
"numpy.unique",
"numpy.maximum"
]
]
|
sandialabs/shadow | [
"a817e43b1051ded51e471bb31346ea7d710d3dd2"
]
| [
"src/shadow/mt.py"
]
| [
"import torch\nimport numpy as np\nimport copy\nimport shadow.losses\nimport shadow.module_wrapper\n\n\ndef ema_update_model(student_model, ema_model, alpha, global_step):\n r\"\"\"Exponential moving average update of a model.\n\n Update `ema_model` to be the moving average of consecutive `student_model` updates via an\n exponential weighting (as defined in [Tarvainen17]_). Update is performed in-place.\n\n Args:\n student_model (torch.nn.Module): The student model.\n ema_model (torch.nn.Module): The model to update (teacher model). Update is\n performed in-place.\n alpha (float): Exponential moving average smoothing coefficient, between [0, 1].\n global_step (int): A running count of exponential update steps (typically mini-batch\n updates).\n \"\"\"\n if alpha < 0 or alpha > 1:\n raise ValueError(\"Smoothing coefficient must be on [0, 1].\")\n # Use the true average until the exponential average is more correct\n alpha = min(1 - 1 / (global_step + 1), alpha)\n for ema_param, param in zip(ema_model.parameters(), student_model.parameters()):\n ema_param.data.mul_(alpha).add_(param.data, alpha=(1 - alpha))\n\n\nclass MT(shadow.module_wrapper.ModuleWrapper):\n r\"\"\"Mean Teacher [Tarvainen17]_ model wrapper for consistency regularization.\n\n Mean Teacher model wrapper the provides both student and teacher model implementation.\n The teacher model is a running average of the student weights, and is updated during training.\n When switched to eval mode, the teacher model is used for predictions instead of the student.\n As the wrapper handles the hand off between student and teacher models, the wrapper should be\n used instead of the student model directly.\n\n Args:\n model (torch.nn.Module): The student model.\n alpha (float, optional): The teacher exponential moving average smoothing coefficient.\n Defaults to 0.999.\n noise (float, optional): If > 0.0, the standard deviation of gaussian noise to apply to\n the input. Specifically, generates random numbers from a normal distribution with\n mean 0 and variance 1, and then scales them by this factor and adds to the input data.\n Defaults to 0.1.\n consistency_type ({'kl', 'mse', 'mse_regress'}, optional): Cost function used to measure consistency.\n Defaults to `'mse'` (mean squared error).\n \"\"\"\n def __init__(self, model, alpha=0.999, noise=0.1, consistency_type=\"mse\"):\n super(MT, self).__init__(model)\n # model is the 'student' model.\n # the 'teacher' model is the EMA model. It starts as a copy of the student model.\n self.teacher_model = copy.deepcopy(self.model)\n # We don't want the teacher model to be updated by optimizer.\n for param in self.teacher_model.parameters():\n param.requires_grad = False\n\n self.alpha = alpha\n self.student_noise = noise\n self.teacher_noise = noise\n\n if consistency_type == 'mse':\n self.consistency_criterion = shadow.losses.softmax_mse_loss\n elif consistency_type == 'kl':\n self.consistency_criterion = shadow.losses.softmax_kl_loss\n elif consistency_type == 'mse_regress':\n self.consistency_criterion = shadow.losses.mse_regress_loss\n else:\n raise ValueError(\n \"Unknown consistency type. Should be 'mse', 'kl', or 'mse_regress', but is \" + str(consistency_type)\n )\n\n # The global step is the count of the student and teacher training passes. It is essentially\n # a cumulative count of the batches, starting at 1.\n self.global_step = 1\n\n def calc_student_logits(self, x):\n r\"\"\"Student model logits, with noise added to the input data.\n\n Args:\n x (torch.Tensor): Input data.\n\n Returns:\n torch.Tensor: The student logits.\n \"\"\"\n model_input = x\n with torch.no_grad():\n if not np.isclose(self.student_noise, 0.0) and self.student_noise > 0.0:\n model_input = (torch.randn_like(x) * self.student_noise) + x\n return self.model(model_input)\n\n def calc_teacher_logits(self, x):\n r\"\"\"Teacher model logits.\n\n The teacher model logits, with noise added to the input data. Does not propagate gradients\n in the teacher forward pass.\n\n Args:\n x (torch.Tensor): Input data.\n Returns:\n torch.Tensor: The teacher logits.\n \"\"\"\n model_input = x\n with torch.no_grad():\n if not np.isclose(self.teacher_noise, 0.0) and self.teacher_noise > 0.0:\n model_input = (torch.randn_like(x) * self.teacher_noise) + x\n # Don't want to update teacher model gradients\n return self.teacher_model(model_input)\n\n def forward(self, x):\n r\"\"\"Model forward pass.\n\n During model training, adds noise to the input data and passes through the student model.\n During model evaluation, does not add noise and passes through the teacher model.\n\n Args:\n x (torch.Tensor): Input data.\n Returns:\n torch.Tensor: Model output.\n \"\"\"\n if self.training:\n return self.calc_student_logits(x)\n else:\n return self.teacher_model(x)\n\n def get_technique_cost(self, x):\n r\"\"\"Consistency cost between student and teacher models.\n\n Consistency cost between the student and teacher, updates teacher weights via exponential\n moving average of the student weights. Noise is sampled and applied to student and teacher\n separately.\n\n Args:\n x (torch.Tensor): Input data.\n\n Returns:\n torch.Tensor: Consistency cost between the student and teacher model outputs.\n \"\"\"\n # Update the teacher model if not the first step.\n if self.model.training:\n if self.global_step > 1:\n ema_update_model(self.model, self.teacher_model, self.alpha, self.global_step)\n self.global_step += 1\n\n # Calc teacher logits (non-normalized model output)\n ema_logits = self.calc_teacher_logits(x)\n\n # Calc student logits (non-normalized model output)\n model_logits = self.calc_student_logits(x)\n\n # The minibatch size is required in order to find the mean loss\n minibatch_size = x.shape[0]\n consistency_loss = self.consistency_criterion(model_logits, ema_logits) / minibatch_size\n return consistency_loss\n\n def update_ema_model(self):\n r\"\"\"Exponential moving average update of the teacher model.\"\"\"\n ema_update_model(self.model, self.teacher_model, self.alpha, self.global_step)\n\n def get_evaluation_model(self):\n r\"\"\"The teacher model, which should be used for prediction during evaluation.\n\n Returns:\n torch.nn.Module: The teacher model.\n \"\"\"\n return self.teacher_model\n"
]
| [
[
"torch.randn_like",
"torch.no_grad",
"numpy.isclose"
]
]
|
Data-Science-Community-SRM/Forecasting-US-Elections | [
"ccde6973e8b40efeb3e8f7fa96babe9f7b52b6be"
]
| [
"Extraction/Extracting Tweets/Scrape Trump.py"
]
| [
"import tweepy \nimport pandas as pd\n\nconsumer_key= \"XXX\"\nconsumer_secret = \"XXX\"\naccess_token =\"XXX\"\naccess_token_secret= \"XXX\"\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret) \n# authentication of access token and secret \nauth.set_access_token(access_token, access_token_secret) \napi = tweepy.API(auth,wait_on_rate_limit = True)\n\n\ndate1 = \"2020-07-09\"\ndate2 = \"2020-07-19\"\n\n\ndate =[]\nuser_id = []\nverified = []\ntext = []\nuser = []\nlocation = []\nsource = []\nlikes = []\nfollowers = []\nfollowing = []\nretweets = []\n\n\ndef get_tweets(date1,date2,word):\n count = 0\n for tweet in tweepy.Cursor(api.search , q=word,count =1000,lang=\"en\",since_id = date1,until = date2).items():\n print(tweet.created_at)\n date.append(tweet.created_at)\n print(tweet.id)\n user_id.append(tweet.id)\n print(tweet.user.verified)\n verified.append(tweet.user.verified)\n print(tweet.text)\n text.append(tweet.text)\n print(tweet.user.screen_name)\n user.append(tweet.user.screen_name)\n print(tweet.user.location)\n location.append(tweet.user.location)\n print(tweet.source)\n source.append(tweet.source)\n print(tweet.favorite_count)\n likes.append(tweet.favorite_count)\n print(tweet.user.followers_count)\n followers.append(tweet.user.followers_count)\n print(tweet.user.friends_count)\n following.append(tweet.user.friends_count)\n print(tweet.retweet_count)\n retweets.append(tweet.retweet_count)\n \n print('<--------------------------------------------------->')\n count+=1\n print(count)\n \nget_tweets(date1,date2,\"#trump\") \n \ndata1 = list(zip(date,user_id,verified,text,user,location,source,likes,followers,following,retweets))\ndf1 = pd.DataFrame(data =data1, columns =[\"Date\",\"Tweet_id\",\"Verified\",\"Tweet\",\n \"User\",\"Location\",\"Source\",\"Likes\",\"Followers\",\"Following\",\"Retweets\"])\n\ndf1.to_csv('tweets_trump.csv') "
]
| [
[
"pandas.DataFrame"
]
]
|
PMitura/smiles-neural-network | [
"8182c221e59186fc3084a2726cf38c73b5b9a1d3"
]
| [
"rnn/rnn.py"
]
| [
"import data, utility, metrics\nimport time\n\nimport numpy as np\nfrom math import sqrt, exp, log, ceil\nfrom scipy.stats.stats import pearsonr\nfrom sklearn.metrics import roc_auc_score\n\nimport db.db as db\nimport visualization\n\nfrom config import config as cc\nimport yaml\n\nimport pandas as pd\n\nimport socket\n\n# not used to relieve MetaCentrum of some dependencies\n\n# TODO: Remove unused imports after experiments are done\nfrom keras.models import Sequential\nfrom keras.layers import Activation, Dense, Dropout, LSTM, AveragePooling1D\nfrom keras.layers import TimeDistributed, SimpleRNN, GRU\nfrom keras.layers import BatchNormalization, Embedding, Merge\nfrom keras.optimizers import Adam, RMSprop, Adadelta, Adagrad\nfrom keras.regularizers import l2, activity_l2\nimport keras.callbacks\n# from keras.regularizers import l1\n\n# handy aliases for config\nRP = cc.exp['params']['rnn']\nRD = cc.exp['params']['data']\nRG = cc.exp['grid']\n\n\n# manual eval where needed\nRP['chained_labels'] = eval(str(cc.exp['params']['rnn']['chained_labels']))\nRP['chained_predict'] = eval(str(cc.exp['params']['rnn']['chained_predict']))\nRP['chained_test_labels'] = eval(str(cc.exp['params']['rnn']['chained_test_labels']))\nRP['freeze_idxs'] = eval(str(cc.exp['params']['rnn']['freeze_idxs']))\nRP['label_idxs'] = eval(str(cc.exp['params']['rnn']['label_idxs']))\n\nOPTIMIZER = Adam(lr = RP['learning_rate'], clipnorm = 1.)\n\ndef configureModel(input, outputLen = len(RD['labels'])):\n print(' Initializing and compiling...')\n\n alphaSize = input.shape[2]\n\n model = Sequential()\n\n '''\n if RD['use_embedding']:\n # second value in nomiSize tuple is shift while using embedding\n model.add(Embedding(1 << nomiSize[1], RP['embedding_outputs']))\n model.add(TimeDistributed(Dense(int(RP['td_layer_multiplier'] * (alphaSize +\n nomiSize[0])), activation = 'tanh', trainable = RP['trainable_inner'])))\n else:\n '''\n\n\n model.add(TimeDistributed(Dense(300*RG['ratios'][0], activation = 'tanh', trainable = RP['trainable_inner']), input_shape = (None, alphaSize )))\n model.add(Dropout(0.30))\n model.add(GRU(300*RG['ratios'][1], trainable = RP['trainable_inner'], return_sequences = True))\n model.add(Activation('tanh', trainable = RP['trainable_inner']))\n model.add(Dropout(0.30))\n model.add(GRU(300*RG['ratios'][2], trainable = RP['trainable_inner']))\n model.add(Activation('tanh', trainable = RP['trainable_inner']))\n model.add(Dropout(0.30))\n model.add(Dense(outputLen))\n\n # molweight\n # model = utility.loadModel('b3d9609da78bfbf0ad1a62ee6740df3b52f104b4', 'mol_')\n # all compounds\n # model = utility.loadModel('eab15a05a70b35d119c02fcc36b1cfaf27a0f36a', 'mol_')\n # maccs\n # model = utility.loadModel('67b51a1543b5d32b05671e4a08d193eed702ca54', 'mol_')\n\n # model.pop()\n # model.pop()\n\n # for i in xrange(len(model.layers)):\n # model.layers[0].trainable = False\n\n '''\n model.add(Dropout(0.50))\n model.add(Dense(500))\n model.add(Activation('relu'))\n model.add(Dropout(0.50))\n model.add(Dense(500))\n model.add(Activation('relu'))\n model.add(Dropout(0.30))\n '''\n # model.add(Dense(outputLen))\n\n if RP['classify']:\n model.add(Activation(RP['classify_activation'], trainable = RP['trainable_inner']))\n\n metrics = []\n if RP['classify']:\n metrics.append('accuracy')\n\n model.compile(loss = RP['objective'], optimizer = OPTIMIZER, metrics = metrics)\n\n print(' ...done')\n return model\n\ndef configureEdgeModel(inputSmiles, inputFasta):\n print(' Initializing edge model and compiling...')\n\n smilesGRUInputShape = (None, inputSmiles.shape[2])\n # smilesGRUSize = int(RP['gru_layer_multiplier'] * smilesGRUInputShape[1])\n\n fastaGRUInputShape = (None, inputFasta.shape[2])\n # fastaGRUSize = int(RP['fasta_gru_layer_multiplier'] * fastaGRUInputShape[1])\n\n mergedOutputLen = len(RD['labels'])\n\n smilesModel = Sequential()\n smilesModel.add(TimeDistributed(Dense(300, activation = 'tanh', trainable = RP['trainable_inner']), input_shape = smilesGRUInputShape))\n smilesModel.add(Dropout(0.30))\n smilesModel.add(GRU(300, trainable = RP['trainable_inner'], return_sequences = True))\n smilesModel.add(Activation('tanh', trainable = RP['trainable_inner']))\n smilesModel.add(Dropout(0.30))\n smilesModel.add(GRU(300, trainable = RP['trainable_inner']))\n smilesModel.add(Activation('tanh', trainable = RP['trainable_inner']))\n\n # utility.setModelConsumeLess(smilesModel, 'mem')\n\n '''\n smilesModel = utility.loadModel('24e62794bb6d5b5c562e41a3a2cccc3525fa625f', 'smiles_')\n smilesModel.pop() # output\n smilesModel.pop() # dropout\n '''\n # utility.setModelConsumeLess(smilesModel, 'gpu')\n fastaModel = Sequential()\n fastaModel.add(TimeDistributed(Dense(300, activation = 'tanh', trainable = RP['trainable_inner']), input_shape = fastaGRUInputShape))\n fastaModel.add(Dropout(0.30))\n fastaModel.add(GRU(300, trainable = RP['trainable_inner'], return_sequences = True))\n fastaModel.add(Activation('tanh', trainable = RP['trainable_inner']))\n fastaModel.add(Dropout(0.30))\n fastaModel.add(GRU(300, trainable = RP['trainable_inner']))\n fastaModel.add(Activation('tanh', trainable = RP['trainable_inner']))\n\n # utility.setModelConsumeLess(fastaModel, 'mem')\n\n '''\n fastaModel = utility.loadModel('e6beb8b7e146b9ab46a71db8f3001bf62d96ff08', 'fasta_')\n fastaModel.pop() # activation\n fastaModel.pop() # output\n fastaModel.pop() # dropout\n '''\n\n # utility.setModelConsumeLess(fastaModel, 'gpu')\n\n merged = Merge([smilesModel, fastaModel], mode='concat')\n\n mergedModel = Sequential()\n mergedModel.add(merged)\n\n mergedModel.add(Dense(300))\n mergedModel.add(Activation('relu'))\n mergedModel.add(Dropout(0.3))\n\n mergedModel.add(Dense(300))\n mergedModel.add(Activation('relu'))\n mergedModel.add(Dropout(0.3))\n\n mergedModel.add(Dense(mergedOutputLen))\n\n if RP['classify']:\n mergedModel.add(Activation(RP['classify_activation'], trainable = RP['trainable_inner']))\n\n metrics = []\n if RP['classify']:\n metrics.append('accuracy')\n\n mergedModel.compile(loss = RP['objective'], optimizer = OPTIMIZER, metrics = metrics)\n\n print(' ...done')\n return mergedModel\n\n\ndef learningRateDecayer(epoch):\n if not RP['learning_rate_decay']:\n return RP['learning_rate']\n\n if RP['learning_rate_decay_type'] == 'step':\n drop = np.floor((epoch)/RP['learning_rate_decay_step_config_steps'])\n new_lr = float(RP['learning_rate'] * np.power(RP['learning_rate_decay_step_config_ratio'],drop))\n print('lr',epoch,new_lr)\n return new_lr\n elif RP['learning_rate_decay_type'] == 'time':\n raise NotImplementedError('learning rate decay: time')\n elif RP['learning_rate_decay_type'] == 'peter':\n raise NotImplementedError('learning rate decay: peter')\n else:\n raise RuntimeError('learning rate decat: unknown type {}'.format(RP['learning_rate_decay_type']))\n\n\ndef train(model, nnInput, labels, validation, makePlot = True,\n labelIndexes = RP['label_idxs']):\n print(' Training model...')\n\n\n # needed format is orthogonal to ours\n '''\n formattedLabels = np.zeros((len(labels[0]), len(labelIndexes)))\n formattedValid = np.zeros((len(validation[1][labelIndexes[0]]),\n len(labelIndexes)))\n for i in range(len(labelIndexes)):\n for j in range(len(labels[0])):\n formattedLabels[j][i] = labels[labelIndexes[i]][j]\n for j in range(len(validation[1][labelIndexes[i]])):\n formattedValid[j][i] = validation[1][labelIndexes[i]][j]\n '''\n early = keras.callbacks.EarlyStopping(monitor = 'val_loss',\n patience = RP['early_stop'])\n\n learningRateScheduler = keras.callbacks.LearningRateScheduler(learningRateDecayer)\n\n modelLogger = visualization.ModelLogger()\n\n history = model.fit(nnInput, labels, nb_epoch = RP['epochs'],\n batch_size = RP['batch'], callbacks = [early],\n validation_data = (validation[0], validation[1]))\n\n if makePlot:\n values = np.zeros((len(history.history['loss']), 2))\n for i in range(len(history.history['loss'])):\n values[i][0] = history.history['loss'][i]\n values[i][1] = history.history['val_loss'][i]\n utility.plotLoss(values)\n\n visualization.histograms(modelLogger)\n\n print(' Model weights:')\n print(model.summary())\n # print(model.get_weights())\n print(' ...done')\n return len(history.history['loss'])\n\ndef run(grid = None):\n stats = {}\n stats['runtime_second'] = time.time()\n\n # initialize using the same seed (to get stable results on comparisons)\n np.random.seed(RP['seed'])\n\n # grab the commit at start\n stats['git_commit'] = utility.getGitCommitHash()\n\n # get the training and testing datasets along with some meta info\n\n if RP['edge_prediction']:\n trainIn, trainLabel, testIn, testLabel, preprocessMeta = data.preprocessEdgeData(db.getData())\n else:\n trainIn, trainLabel, testIn, testLabel, preprocessMeta = data.preprocessData(db.getData())\n # trainIn, trainLabel, testIn, testLabel, preprocessMeta = data.preprocessFastaOneHotData(db.getData())\n\n stats['training_row_count'] = len(testLabel)\n stats['testing_row_count'] = len(testLabel)\n\n # load model from file or create and train one from scratch\n if RP['load_model']:\n model = utility.loadModel(RP['load_model'])\n else:\n if RP['edge_prediction']:\n model = configureEdgeModel(trainIn[0],trainIn[1])\n elif RP['discrete_label']:\n model = configureModel(trainIn, len(trainLabel[0]))\n else:\n model = configureModel(trainIn)\n stats['epoch_count'] = train(model, trainIn, trainLabel, (testIn, testLabel))\n\n # persistence first\n if cc.cfg['persistence']['model']:\n name = '{}_rg_{}'.format(stats['git_commit'],':'.join([str(x) for x in RG['ratios']]))\n # name = stats['git_commit']\n stats['persistent_model_name'] = name\n utility.saveModel(model, name)\n\n # compute metrics for the model based on the task for both testing and training data\n print('\\nGetting metrics for training data:')\n if RP['classify']:\n if RP['discrete_label']:\n trainMetrics = metrics.discreteClassify(model, trainIn, trainLabel, preprocessMeta)\n else:\n trainMetrics = metrics.classify(model, trainIn, trainLabel, preprocessMeta)\n else:\n trainMetrics = metrics.predict(model, trainIn, trainLabel, preprocessMeta)\n\n print('\\nGetting metrics for test data:')\n if RP['classify']:\n if RP['discrete_label']:\n testMetrics = metrics.discreteClassify(model, testIn, testLabel, preprocessMeta)\n else:\n testMetrics = metrics.classify(model, testIn, testLabel, preprocessMeta)\n else:\n testMetrics = metrics.predict(model, testIn, testLabel, preprocessMeta)\n\n\n # utilities and visualizations\n if cc.cfg['plots']['layer_activations']:\n visualization.layerActivations(model, testIn, testLabel)\n\n if cc.cfg['plots']['seq_output']:\n df = pd.DataFrame(cc.cfg['plots']['seq_output_seq_input'], columns=[RD['fasta'] if cc.cfg['plots']['seq_output_seq_input_name'] == 'fasta' else RD['smiles']])\n visualization.visualizeSequentialOutput(model, cc.cfg['plots']['seq_output_layer_idx'], df)\n\n if cc.cfg['plots']['print_pred']:\n visualization.printPrediction(model, cc.cfg['plots']['print_pred_smiles'])\n\n if cc.cfg['plots']['print_train_test_pred']:\n visualization.printTrainTestPred(model, cc.cfg['plots']['print_train_test_pred_cnt'], trainIn, trainLabel, testIn, testLabel, preprocessMeta)\n\n # statistics to send to journal\n stats['runtime_second'] = time.time() - stats['runtime_second']\n stats['memory_pm_mb'], stats['memory_vm_mb'] = utility.getMemoryUsage()\n stats['comment'] = RP['comment']\n stats['hostname'] = socket.gethostname()\n stats['experiment_config'] = yaml.dump(cc.exp,default_flow_style=False)\n\n stats['model'] = utility.modelToString(model)\n stats['loaded_model'] = RP['load_model']\n stats['parameter_count'] = model.count_params()\n stats['task'] = 'classification' if RP['classify'] else 'regression'\n\n stats['dataset_name'] = cc.exp['fetch']['table']\n stats['split_name'] = RD['testing']\n stats['label_name'] = ','.join(RD['labels'])\n\n stats['epoch_max'] = RP['epochs']\n stats['learning_rate'] = RP['learning_rate']\n stats['optimization_method'] = OPTIMIZER.__class__.__name__\n stats['batch_size'] = RP['batch']\n stats['seed'] = RP['seed']\n stats['objective'] = RP['objective']\n stats['learning_curve'] = {'val':open('{}/{}'.format(cc.cfg['plots']['dir'], utility.PLOT_NAME),'rb').read(),'type':'bin'}\n\n # metric statistics to send\n metricStats = {}\n\n if RP['classify']:\n metricStats['relevance_training'] = trainMetrics['acc_avg']\n metricStats['relevance_training_std'] = trainMetrics['acc_std']\n metricStats['relevance_testing'] = testMetrics['acc_avg']\n metricStats['relevance_testing_std'] = testMetrics['acc_std']\n metricStats['log_loss'] = testMetrics['log_loss_avg']\n metricStats['log_loss_std'] = testMetrics['log_loss_std']\n metricStats['auc'] = testMetrics['auc_avg']\n metricStats['auc_std'] = testMetrics['auc_std']\n metricStats['auc_micro'] = testMetrics['auc_avg']\n metricStats['auc_micro_std'] = testMetrics['auc_std']\n else:\n metricStats['relevance_training'] = trainMetrics['r2_avg']\n metricStats['relevance_training_std'] = trainMetrics['r2_std']\n metricStats['relevance_testing'] = testMetrics['r2_avg']\n metricStats['relevance_testing_std'] = testMetrics['r2_std']\n metricStats['mse'] = testMetrics['mse_avg']\n metricStats['mse_std'] = testMetrics['mse_std']\n metricStats['mae'] = testMetrics['mae_avg']\n metricStats['mae_std'] = testMetrics['mae_std']\n\n stats.update(metricStats)\n db.sendStatistics(**stats)\n\n utility.freeModel(model)\n"
]
| [
[
"numpy.random.seed",
"pandas.DataFrame",
"numpy.power",
"numpy.floor"
]
]
|
wergeld/my_ml_service | [
"6bfade2db0f609e45938ff27e2b4c985f8eafa41"
]
| [
"backend/server/apps/endpoints/views.py"
]
| [
"import json\r\nfrom numpy.random import rand\r\nfrom rest_framework import views, status\r\nfrom rest_framework.response import Response\r\nfrom apps.ml.registry import MLRegistry\r\nfrom server.wsgi import registry\r\n\r\nfrom rest_framework import viewsets\r\nfrom rest_framework import mixins\r\nfrom rest_framework.exceptions import APIException\r\n\r\nfrom django.db import transaction\r\n\r\nfrom .models import Endpoint\r\nfrom .serializers import EndpointSerializer\r\n\r\nfrom .models import MLAlgorithm\r\nfrom .serializers import MLAlgorithmSerializer\r\n\r\nfrom .models import MLAlgorithmStatus\r\nfrom .serializers import MLAlgorithmStatusSerializer\r\n\r\nfrom .models import MLRequest\r\nfrom .serializers import MLRequestSerializer\r\n\r\n\r\nclass EndpointViewSet(\r\n mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet\r\n):\r\n serializer_class = EndpointSerializer\r\n queryset = Endpoint.objects.all()\r\n\r\n\r\nclass MLAlgorithmViewSet(\r\n mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet\r\n):\r\n serializer_class = MLAlgorithmSerializer\r\n queryset = MLAlgorithm.objects.all()\r\n\r\n\r\ndef deactivate_other_statuses(instance):\r\n old_statuses = MLAlgorithmStatus.objects.filter(parent_mlalgorithm=instance.parent_mlalgorithm,\r\n created_at__lt=instance.created_at,\r\n active=True)\r\n for i in range(len(old_statuses)):\r\n old_statuses[i].active = False\r\n MLAlgorithmStatus.objects.bulk_update(old_statuses, [\"active\"])\r\n\r\n\r\nclass MLAlgorithmStatusViewSet(\r\n mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet,\r\n mixins.CreateModelMixin\r\n):\r\n serializer_class = MLAlgorithmStatusSerializer\r\n queryset = MLAlgorithmStatus.objects.all()\r\n\r\n def perform_create(self, serializer):\r\n try:\r\n with transaction.atomic():\r\n instance = serializer.save(active=True)\r\n # set active=False for other statuses\r\n deactivate_other_statuses(instance)\r\n\r\n except Exception as e:\r\n raise APIException(str(e))\r\n\r\n\r\nclass MLRequestViewSet(\r\n mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet,\r\n mixins.UpdateModelMixin\r\n):\r\n serializer_class = MLRequestSerializer\r\n queryset = MLRequest.objects.all()\r\n\r\n\r\nclass PredictView(views.APIView):\r\n def post(self, request, endpoint_name, format=None):\r\n\r\n algorithm_status = self.request.query_params.get(\r\n \"status\", \"production\")\r\n algorithm_version = self.request.query_params.get(\"version\")\r\n\r\n algs = MLAlgorithm.objects.filter(\r\n parent_endpoint__name=endpoint_name, status__status=algorithm_status, status__active=True)\r\n\r\n if algorithm_version is not None:\r\n algs = algs.filter(version=algorithm_version)\r\n\r\n if len(algs) == 0:\r\n return Response(\r\n {\"status\": \"Error\", \"message\": \"ML algorithm is not available\"},\r\n status=status.HTTP_400_BAD_REQUEST,\r\n )\r\n if len(algs) != 1 and algorithm_status != \"ab_testing\":\r\n return Response(\r\n {\"status\": \"Error\", \"message\": \"ML algorithm selection is ambiguous. Please specify algorithm version.\"},\r\n status=status.HTTP_400_BAD_REQUEST,\r\n )\r\n alg_index = 0\r\n if algorithm_status == \"ab_testing\":\r\n alg_index = 0 if rand() < 0.5 else 1\r\n\r\n algorithm_object = registry.endpoints[algs[alg_index].id]\r\n prediction = algorithm_object.compute_prediction(request.data)\r\n\r\n label = prediction[\"label\"] if \"label\" in prediction else \"error\"\r\n ml_request = MLRequest(\r\n input_data=json.dumps(request.data),\r\n full_response=prediction,\r\n response=label,\r\n feedback=\"\",\r\n parent_mlalgorithm=algs[alg_index],\r\n )\r\n ml_request.save()\r\n\r\n prediction[\"request_id\"] = ml_request.id\r\n\r\n return Response(prediction)\r\n"
]
| [
[
"numpy.random.rand"
]
]
|
lianming03/deep_sort_pytorch | [
"968e393f51f22a0b998170c1b3de4db2d330eb98"
]
| [
"deep_sort/deep/test.py"
]
| [
"import torch\r\nimport torch.backends.cudnn as cudnn\r\nimport torchvision\r\n\r\nimport argparse\r\nimport os\r\n\r\nfrom model import Net\r\n\r\nparser = argparse.ArgumentParser(description=\"Train on market1501\")\r\nparser.add_argument(\"--data-dir\",default='data',type=str)\r\nparser.add_argument(\"--num-classes\",default=751,type=int)\r\nparser.add_argument(\"--no-cuda\",action=\"store_true\")\r\nparser.add_argument(\"--gpu-id\",default=0,type=int)\r\nargs = parser.parse_args()\r\n\r\n# device\r\ndevice = \"cuda:{}\".format(args.gpu_id) if torch.cuda.is_available() and not args.no_cuda else \"cpu\"\r\nif torch.cuda.is_available() and not args.no_cuda:\r\n cudnn.benchmark = True\r\n\r\n# data loader\r\nroot = args.data_dir\r\nquery_dir = os.path.join(root,\"query\")\r\ngallery_dir = os.path.join(root,\"gallery\")\r\ntransform = torchvision.transforms.Compose([\r\n torchvision.transforms.Resize((128,64)),\r\n torchvision.transforms.ToTensor(),\r\n torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\r\n])\r\nqueryloader = torch.utils.data.DataLoader(\r\n torchvision.datasets.ImageFolder(query_dir, transform=transform),\r\n batch_size=64, shuffle=False\r\n)\r\ngalleryloader = torch.utils.data.DataLoader(\r\n torchvision.datasets.ImageFolder(gallery_dir, transform=transform),\r\n batch_size=64, shuffle=False\r\n)\r\n\r\n# net definition\r\nnum_classes = args.num_classes\r\nnet = Net(num_classes=num_classes, reid=True)\r\nassert os.path.isfile(\"./checkpoint/ckpt.t7\"), \"Error: no checkpoint file found!\"\r\nprint('Loading from checkpoint/ckpt.t7')\r\ncheckpoint = torch.load(\"./checkpoint/ckpt.t7\")\r\nnet_dict = checkpoint['net_dict']\r\nnet.load_state_dict(net_dict, strict=False)\r\nnet.eval()\r\nnet.to(device)\r\n\r\n# compute features\r\nquery_features = torch.tensor([]).float()\r\nquery_labels = torch.tensor([]).long()\r\ngallery_features = torch.tensor([]).float()\r\ngallery_labels = torch.tensor([]).long()\r\n\r\nwith torch.no_grad():\r\n for idx,(inputs,labels) in enumerate(queryloader):\r\n inputs = inputs.to(device)\r\n features = net(inputs).cpu()\r\n query_features = torch.cat((query_features, features), dim=0)\r\n query_labels = torch.cat((query_labels, labels))\r\n\r\n for idx,(inputs,labels) in enumerate(galleryloader):\r\n inputs = inputs.to(device)\r\n features = net(inputs).cpu()\r\n gallery_features = torch.cat((gallery_features, features), dim=0)\r\n gallery_labels = torch.cat((gallery_labels, labels))\r\n\r\ngallery_labels -= 2\r\n\r\n# save features\r\nfeatures = {\r\n \"qf\": query_features,\r\n \"ql\": query_labels,\r\n \"gf\": gallery_features,\r\n \"gl\": gallery_labels\r\n}\r\ntorch.save(features,\"features.pth\")\r\n"
]
| [
[
"torch.cat",
"torch.save",
"torch.no_grad",
"torch.cuda.is_available",
"torch.tensor",
"torch.load"
]
]
|
Ant1ng2/nums | [
"f04097f25b63d0654b230d801967bb64acf00436"
]
| [
"tests/core/array/test_ho_ops.py"
]
| [
"# coding=utf-8\n# Copyright (C) 2020 NumS Development Team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport numpy as np\n\nfrom nums.core.storage.storage import BimodalGaussian\nfrom nums.core.array.application import ArrayApplication\n\n\ndef test_log(app_inst: ArrayApplication):\n real_X, _ = BimodalGaussian.get_dataset(100, 9)\n X = app_inst.array(real_X, block_shape=(10, 2))\n assert np.allclose(app_inst.log(X).get(), np.log(real_X))\n\n\ndef test_stats(app_inst: ArrayApplication):\n real_X, _ = BimodalGaussian.get_dataset(3, 2)\n X = app_inst.array(real_X, block_shape=(2, 1))\n assert np.allclose(app_inst.mean(X, axis=0).get(), np.mean(real_X, axis=0))\n assert np.allclose(app_inst.std(X, axis=1).get(), np.std(real_X, axis=1))\n\n real_X, _ = BimodalGaussian.get_dataset(100, 9)\n X = app_inst.array(real_X, block_shape=(10, 2))\n assert np.allclose(app_inst.mean(X, axis=0).get(), np.mean(real_X, axis=0))\n assert np.allclose(app_inst.std(X, axis=1).get(), np.std(real_X, axis=1))\n\n\ndef test_sum(app_inst: ArrayApplication):\n shape = (5, 6, 7)\n real_X = np.random.random_sample(np.product(shape)).reshape(shape)\n X = app_inst.array(real_X, block_shape=(2, 1, 4))\n assert np.allclose(app_inst.sum(X, axis=1).get(), np.sum(real_X, axis=1))\n\n\nif __name__ == \"__main__\":\n # pylint: disable=import-error\n from tests import conftest\n\n app_inst = conftest.get_app(\"serial\")\n test_log(app_inst)\n test_stats(app_inst)\n test_sum(app_inst)\n"
]
| [
[
"numpy.product",
"numpy.log",
"numpy.sum",
"numpy.mean",
"numpy.std"
]
]
|
jiangnanboy/CNN4IE | [
"dcbd46fea0023d88b485b479bf65c56df9609efa"
]
| [
"cnn4ie/dcnn/model.py"
]
| [
"import torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nfrom cnn4ie.util import crf\nfrom cnn4ie.dcnn.dynamic_conv import DynamicConv1dTBC\n\nDEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\n\nclass Encoder(nn.Module):\n def __init__(self, emb_dim, hid_dim, n_layers, kernel_size, dropout):\n '''\n define encoder\n :param emb_dim:\n :param hid_dim:\n :param n_layers:\n :param kernel_size:\n :param dropout:\n '''\n super(Encoder, self).__init__()\n\n # for kernel in kernel_size:\n assert kernel_size % 2 == 1, 'kernel size must be odd!' # kernel is odd, which is convenient for PAD processing on both sides of the sequence\n\n self.scale = torch.sqrt(torch.FloatTensor([0.5])).to(DEVICE) # the variance of the entire network does not change significantly\n\n self.emb2hid = nn.Linear(emb_dim, hid_dim) # fc: emb_dim -> hid_dim\n self.hid2emb = nn.Linear(hid_dim, emb_dim) # fc: hid_dim -> emb_dim\n\n # convolution block\n\n self.convs = nn.ModuleList([DynamicConv1dTBC(input_size=hid_dim,\n out_dim=2 * hid_dim, # the dimension of convolution output,2*hid_dim -> GLU activation function\n kernel_size=kernel_size,\n padding_l=(kernel_size - 1) // 2,# padding zero for both side of the sequence, keeping the dimension does't change\n num_heads=4,\n weight_dropout=dropout)\n for _ in range(n_layers)]) # convolution layer\n\n self.dropout = nn.Dropout(dropout)\n\n #self.BN = nn.BatchNorm1d()\n\n def forward(self, encoder_output):\n # encoder_output:[batch_size, src_len, emb_dim]\n\n # emb_dim -> hid_dim, as the input of convolution layers\n conv_input = self.emb2hid(encoder_output) # [batch_size, src_len, hid_dim]\n # change dimension,convolve the last dimension of input\n conv_input = conv_input.permute(1, 0, 2) # [src_len, batch_size, hid_dim]\n\n # convolution block\n for i, conv in enumerate(self.convs):\n conved = conv(self.dropout(conv_input)) # [src_len, batch_size, 2 * out_dim]\n\n #conved = self.BN(conved) # [batch_size, 2*hid_dim, src_len]\n\n # GLU activation function\n conved = F.glu(conved, dim=-1) # [src_len, batch_size, out_dim]\n\n # residual connection\n conved = (conved + conv_input) * self.scale # [src_len, batch_size, out_dim]\n\n # input of the next convolution layer\n conv_input = conved\n\n # hid_dim -> emb_dim,as the output of convolution block\n conved = self.hid2emb(conved.permute(1, 0, 2)) # [batch_size, src_len, emb_dim]\n\n # residual connection,as the joint output feature of encoder\n combined = (conved + encoder_output) * self.scale # [batch_size, src_len, emb_dim]\n\n return conved, combined\n\nclass MultiLayerResDYCNN(nn.Module):\n def __init__(self, input_dim, output_dim, emb_dim, hid_dim, cnn_layers, encoder_layers, kernel_size, dropout, PAD_IDX, max_length=100, use_crf = True):\n '''\n define berc model\n :param input_dim:\n :param output_dim:\n :param emb_dim:\n :param hid_dim:\n :param cnn_layers:\n :param encoder_layers:\n :param kernel_size:\n :param dropout:\n :param padding_idx:\n :param max_length:\n '''\n super(MultiLayerResDYCNN, self).__init__()\n\n self.tok_embedding = nn.Embedding(input_dim, emb_dim, padding_idx=PAD_IDX) # token embedding\n self.pos_embedding = nn.Embedding(max_length, emb_dim, padding_idx=PAD_IDX) # position embedding\n\n self.encoder = nn.ModuleList([Encoder(emb_dim, hid_dim, cnn_layers, kernel_size, dropout)\n for _ in range(encoder_layers)])\n self.dropout = nn.Dropout(dropout)\n self.fc_out = nn.Linear(emb_dim, output_dim)\n self.crf = crf.CRF(output_dim, batch_first=True)\n self.use_crf = use_crf\n\n def forward(self, token_tensor):\n '''\n :param token_tensor: [batch_size, src_len]\n :return:\n '''\n # token, position embedding\n tok_embedded = self.tok_embedding(token_tensor) # [batch_size, src_len, emb_dim]\n # 构建位置tensor -> [batch_size, src_len],位置序号从(0)开始到(src_len-1)\n position = torch.arange(0, token_tensor.shape[1]).unsqueeze(0).repeat(token_tensor.shape[0], 1).to(DEVICE)\n pos_embedded = self.pos_embedding(position.long()) # [batch_size, src_len, emb_dim]\n\n # token embedded + pos_embedded\n embedded = self.dropout(tok_embedded + pos_embedded) # [batch_size, src_len, emb_dim]\n encoder_output = embedded\n\n # encoder block\n for i, encoder in enumerate(self.encoder):\n # encoding\n conved, encoder_output = encoder(self.dropout(encoder_output)) # [batch_size, src_len, emb_dim]\n\n # pooling, predict class of the entire sentence\n # encoder_output = F.avg_pool1d(encoder_output.permute(0, 2, 1), encoder_output.shape[1]).squeeze(2) # [batch_size, emb_dim]\n # output = self.fc_out(encoder_output) # [batch_size, output_dim]\n\n # fc outuput\n output = self.fc_out(encoder_output) # [batch_size, src_len, output_dim]\n\n if self.use_crf:\n # crf\n output = self.crf.decode(output)\n return output\n\n def log_likelihood(self, source, target):\n '''\n :param source: [batch_size, src_len]\n :param target: [batch_size, src_len]\n :return:\n '''\n # token, position embedding\n tok_embedded = self.tok_embedding(source) # [batch_size, src_len, emb_dim]\n # 构建位置tensor -> [batch_size, src_len],位置序号从(0)开始到(src_len-1)\n position = torch.arange(0, source.shape[1]).unsqueeze(0).repeat(source.shape[0], 1).to(DEVICE)\n pos_embedded = self.pos_embedding(position.long()) # [batch_size, src_len, emb_dim]\n\n # token embedded + pos_embedded\n embedded = self.dropout(tok_embedded + pos_embedded) # [batch_size, src_len, emb_dim]\n encoder_output = embedded\n\n # encoder block\n for i, encoder in enumerate(self.encoder):\n # encoding\n conved, encoder_output = encoder(self.dropout(encoder_output)) # [batch_size, src_len, emb_dim]\n\n # pooling, predict class of the entire sentence\n # encoder_output = F.avg_pool1d(encoder_output.permute(0, 2, 1), encoder_output.shape[1]).squeeze(2) # [batch_size, emb_dim]\n # output = self.fc_out(encoder_output) # [batch_size, output_dim]\n\n # sequence labeling\n outputs = self.fc_out(encoder_output) # [batch_size, src_len, output_dim]\n\n return -self.crf(outputs, target)\n"
]
| [
[
"torch.nn.Linear",
"torch.nn.functional.glu",
"torch.nn.Dropout",
"torch.arange",
"torch.FloatTensor",
"torch.cuda.is_available",
"torch.nn.Embedding"
]
]
|
snasiriany/parasol | [
"88b99704676fb1253b8bc6402665a3174a00072d"
]
| [
"parasol/gym/mujoco/cartpole.py"
]
| [
"import os\n\nimport cv2\nimport numpy as np\nimport scipy.misc\n\nfrom deepx import T\nfrom gym import utils\nfrom gym.envs.mujoco import mujoco_env\n\nfrom ..gym_wrapper import GymWrapper\n\n\n__all__ = ['Cartpole']\n\n\nclass GymCartpole(mujoco_env.MujocoEnv, utils.EzPickle):\n\n def __init__(self, *args, **kwargs):\n self.__dict__.update(kwargs)\n utils.EzPickle.__init__(self)\n if self.image:\n self.prev_obs = None\n assets_dir = os.path.join(os.path.dirname(__file__), \"assets\", \"inverted_pendulum.xml\")\n mujoco_env.MujocoEnv.__init__(self, assets_dir, 2)\n\n def reward(self, ob, a):\n reward_dist = -(ob[1] ** 2)\n reward_ctrl = -1e-4 * np.square(a).sum()\n done = not (np.isfinite(ob).all() and (np.abs(ob[1]) <= 0.2))\n return reward_dist + reward_ctrl, {'done' : done}\n\n def step(self, a):\n self.do_simulation(a, self.frame_skip)\n ob = self._get_obs()\n reward, info = self.reward(self.sim.data.qpos, a)\n done = False\n return ob, reward, done, info\n\n def viewer_setup(self):\n v = self.viewer\n v.cam.trackbodyid = 0\n v.cam.distance = self.model.stat.extent\n\n def reset_model(self):\n qpos = self.init_qpos + self.np_random.uniform(size=self.model.nq, low=-0.01, high=0.01)\n qvel = self.init_qvel + self.np_random.uniform(size=self.model.nv, low=-0.01, high=0.01)\n if self.random_start:\n qpos[0] += self.np_random.uniform(low=-0.5, high=0.5)\n self.set_state(qpos, qvel)\n return self._get_obs()\n\n def _get_obs(self):\n if self.image:\n img = self.render(mode='rgb_array')\n return (cv2.resize(img, (self.image_dim, self.image_dim), interpolation=cv2.INTER_LINEAR) / 255).flatten()\n else:\n return np.concatenate([self.sim.data.qpos, self.sim.data.qvel]).ravel()\n\n\nclass Cartpole(GymWrapper):\n\n environment_name = 'Cartpole'\n entry_point = \"parasol.gym.mujoco.cartpole:GymCartpole\"\n max_episode_steps = 100\n reward_threshold = -3.75 # ignore\n\n def __init__(self, **kwargs):\n config = {\n 'image': kwargs.pop('image', False),\n 'sliding_window': kwargs.pop('sliding_window', 0),\n 'image_dim': kwargs.pop('image_dim', 32),\n 'random_start': kwargs.pop('random_start', False),\n }\n super(Cartpole, self).__init__(config)\n\n def torque_matrix(self):\n return 2e-4 * np.eye(self.get_action_dim())\n\n def make_summary(self, observations, name):\n if self.image:\n observations = T.reshape(observations, [-1] + self.image_size())\n T.core.summary.image(name, observations)\n\n def is_image(self):\n return self.image\n\n def image_size(self):\n if self.image:\n return [self.image_dim, self.image_dim, 3]\n return None\n"
]
| [
[
"numpy.square",
"numpy.isfinite",
"numpy.concatenate",
"numpy.abs"
]
]
|
emmazmi/research-template | [
"ec175fb580075de5e7673ba1114ec11d86b72dec"
]
| [
"analysis/report.py"
]
| [
"import pandas as pd\n\ndata = pd.read_csv(\"output/input.csv\")\n\ndata['covid_date'] = pd.to_datetime(data['covid_date'])\ndata['long_covid_date'] = pd.to_datetime(data['long_covid_date'])\n\ndata['time'] = data['long_covid_date'] - data['covid_date']\n\ndata.to_csv(\"output/times.csv\")\n\n#fig = data.time.plot.hist().get_figure()\n#fig.savefig(\"output/descriptive.png\")"
]
| [
[
"pandas.to_datetime",
"pandas.read_csv"
]
]
|
86sanj/datasetinsights | [
"892e2ed3a2facf97cfa3a883700830d959a0c49b"
]
| [
"datasetinsights/datasets/unity_perception/tables.py"
]
| [
"import json\nimport logging\nimport pathlib\nfrom collections import namedtuple\nfrom enum import Enum\n\nimport pandas as pd\n\nfrom .validation import verify_version\n\nlogger = logging.getLogger(__name__)\nSCHEMA_VERSION = \"0.0.1\" # Synthetic dataset schema version\n\n\nclass FileType(Enum):\n BINARY = \"binary\"\n REFERENCE = \"reference\"\n METRIC = \"metric\"\n CAPTURE = \"capture\"\n\n\nTable = namedtuple(\"Table\", \"file pattern filetype\")\nDATASET_TABLES = {\n \"annotation_definitions\": Table(\n \"**/annotation_definitions.json\",\n r\"(?:\\w|-|/)*annotation_definitions.json\",\n FileType.REFERENCE,\n ),\n \"captures\": Table(\n \"**/captures_*.json\",\n r\"(?:\\w|-|/)*captures_[0-9]+.json\",\n FileType.CAPTURE,\n ),\n \"egos\": Table(\"**/egos.json\", r\"(?:\\w|-|/)*egos.json\", FileType.REFERENCE),\n \"metric_definitions\": Table(\n \"**/metric_definitions.json\",\n r\"(?:\\w|-|/)*metric_definitions.json\",\n FileType.REFERENCE,\n ),\n \"metrics\": Table(\n \"**/metrics_*.json\", r\"(?:\\w|-|/)*metrics_[0-9]+.json\", FileType.METRIC\n ),\n \"sensors\": Table(\n \"**/sensors.json\", r\"(?:\\w|-|/)*sensors.json\", FileType.REFERENCE\n ),\n}\n\n\ndef glob(data_root, pattern):\n \"\"\"Find all matching files in a directory.\n\n Args:\n data_root (str): directory containing capture files\n pattern (str): Unix file pattern\n\n Yields:\n str: matched filenames in a directory\n \"\"\"\n path = pathlib.Path(data_root)\n for fp in path.glob(pattern):\n yield fp\n\n\ndef load_table(json_file, table_name, version, **kwargs):\n \"\"\"Load records from json files into a pandas table\n\n Args:\n json_file (str): filename to json.\n table_name (str): table name in the json file to be loaded\n version (str): requested version of this table\n **kwargs: arbitrary keyword arguments to be passed to pandas'\n json_normalize method.\n\n Returns:\n a pandas dataframe of the loaded table.\n\n Raises:\n VersionError: If the version in json file does not match the requested\n version.\n \"\"\"\n logger.debug(f\"Loading table {table_name} from {json_file}\")\n data = json.load(open(json_file, \"r\"))\n verify_version(data, version)\n table = pd.json_normalize(data[table_name], **kwargs)\n\n return table\n"
]
| [
[
"pandas.json_normalize"
]
]
|
ghostofsheep/asl-ml-immersion | [
"4ed74c9fb67d570a498219b347b905e82f525d6e"
]
| [
"notebooks/tfx_pipelines/guided_projects/guided_project_2_solution/models/preprocessing.py"
]
| [
"# Copyright 2021 Google LLC. 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\"\"\"Covertype preprocessing.\nThis file defines a template for TFX Transform component.\n\"\"\"\n\nimport tensorflow as tf\nimport tensorflow_transform as tft\n\nfrom models import features\n\ndef _fill_in_missing(x):\n \"\"\"Replace missing values in a SparseTensor.\n Fills in missing values of `x` with '' or 0, and converts to a dense tensor.\n Args:\n x: A `SparseTensor` of rank 2. Its dense shape should have size at most 1\n in the second dimension.\n Returns:\n A rank 1 tensor where missing values of `x` have been filled in.\n \"\"\"\n default_value = '' if x.dtype == tf.string else 0\n return tf.squeeze(\n tf.sparse.to_dense(\n tf.SparseTensor(x.indices, x.values, [x.dense_shape[0], 1]),\n default_value),\n axis=1)\n\ndef preprocessing_fn(inputs):\n \"\"\"Preprocesses Covertype Dataset.\"\"\"\n\n outputs = {}\n\n # Scale numerical features\n for key in features.NUMERIC_FEATURE_KEYS:\n outputs[features.transformed_name(key)] = tft.scale_to_z_score(\n _fill_in_missing(inputs[key]))\n\n # Generate vocabularies and maps categorical features\n for key in features.CATEGORICAL_FEATURE_KEYS:\n outputs[features.transformed_name(key)] = tft.compute_and_apply_vocabulary(\n x=_fill_in_missing(inputs[key]), num_oov_buckets=1, vocab_filename=key)\n\n # Convert Cover_Type to dense tensor\n outputs[features.transformed_name(features.LABEL_KEY)] = _fill_in_missing(\n inputs[features.LABEL_KEY])\n\n return outputs\n"
]
| [
[
"tensorflow.SparseTensor"
]
]
|
bmi-imaginelab/CD-Net-Histopathology-Representation-Learning-using-Pyramidal-Context-Detail-Network | [
"cc4dad85cdeea7295cb48f6f947fd1ac25d8862e"
]
| [
"vision_transformer.py"
]
| [
"# Copyright (c) Facebook, Inc. and its affiliates.\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\"\"\"\nMostly copy-paste from timm library.\nhttps://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py\n\"\"\"\nimport math\nfrom functools import partial\n\nimport torch\nimport torch.nn as nn\n\nfrom utils import trunc_normal_\n\n\ndef drop_path(x, drop_prob: float = 0., training: bool = False):\n if drop_prob == 0. or not training:\n return x\n keep_prob = 1 - drop_prob\n shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets\n random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)\n random_tensor.floor_() # binarize\n output = x.div(keep_prob) * random_tensor\n return output\n\n\nclass DropPath(nn.Module):\n \"\"\"Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).\n \"\"\"\n def __init__(self, drop_prob=None):\n super(DropPath, self).__init__()\n self.drop_prob = drop_prob\n\n def forward(self, x):\n return drop_path(x, self.drop_prob, self.training)\n\n\nclass Mlp(nn.Module):\n def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):\n super().__init__()\n out_features = out_features or in_features\n hidden_features = hidden_features or in_features\n self.fc1 = nn.Linear(in_features, hidden_features)\n self.act = act_layer()\n self.fc2 = nn.Linear(hidden_features, out_features)\n self.drop = nn.Dropout(drop)\n\n def forward(self, x):\n x = self.fc1(x)\n x = self.act(x)\n x = self.drop(x)\n x = self.fc2(x)\n x = self.drop(x)\n return x\n\n\nclass Attention(nn.Module):\n def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):\n super().__init__()\n self.num_heads = num_heads\n head_dim = dim // num_heads\n self.scale = qk_scale or head_dim ** -0.5\n\n self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)\n self.attn_drop = nn.Dropout(attn_drop)\n self.proj = nn.Linear(dim, dim)\n self.proj_drop = nn.Dropout(proj_drop)\n\n def forward(self, x):\n B, N, C = x.shape\n qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)\n q, k, v = qkv[0], qkv[1], qkv[2]\n\n attn = (q @ k.transpose(-2, -1)) * self.scale\n attn = attn.softmax(dim=-1)\n attn = self.attn_drop(attn)\n\n x = (attn @ v).transpose(1, 2).reshape(B, N, C)\n x = self.proj(x)\n x = self.proj_drop(x)\n return x, attn\n\n\nclass Block(nn.Module):\n def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,\n drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):\n super().__init__()\n self.norm1 = norm_layer(dim)\n self.attn = Attention(\n dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)\n self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()\n self.norm2 = norm_layer(dim)\n mlp_hidden_dim = int(dim * mlp_ratio)\n self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)\n\n def forward(self, x, return_attention=False):\n y, attn = self.attn(self.norm1(x))\n if return_attention:\n return attn\n x = x + self.drop_path(y)\n x = x + self.drop_path(self.mlp(self.norm2(x)))\n return x\n\n\nclass PatchEmbed(nn.Module):\n \"\"\" Image to Patch Embedding\n \"\"\"\n def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):\n super().__init__()\n num_patches = (img_size // patch_size) * (img_size // patch_size)\n self.img_size = img_size\n self.patch_size = patch_size\n self.num_patches = num_patches\n\n self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)\n\n def forward(self, x):\n B, C, H, W = x.shape\n x = self.proj(x).flatten(2).transpose(1, 2)\n return x\n\n\nclass VisionTransformer(nn.Module):\n \"\"\" Vision Transformer \"\"\"\n def __init__(self, img_size=[224], patch_size=16, in_chans=3, num_classes=0, embed_dim=768, depth=12,\n num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,\n drop_path_rate=0., norm_layer=nn.LayerNorm, **kwargs):\n super().__init__()\n self.num_features = self.embed_dim = embed_dim\n\n self.patch_embed = PatchEmbed(\n img_size=img_size[0], patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)\n num_patches = self.patch_embed.num_patches\n\n self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))\n self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))\n self.pos_drop = nn.Dropout(p=drop_rate)\n\n dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule\n self.blocks = nn.ModuleList([\n Block(\n dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,\n drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer)\n for i in range(depth)])\n self.norm = norm_layer(embed_dim)\n\n # Classifier head\n self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()\n\n trunc_normal_(self.pos_embed, std=.02)\n trunc_normal_(self.cls_token, std=.02)\n self.apply(self._init_weights)\n\n def _init_weights(self, m):\n if isinstance(m, nn.Linear):\n trunc_normal_(m.weight, std=.02)\n if isinstance(m, nn.Linear) and m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.LayerNorm):\n nn.init.constant_(m.bias, 0)\n nn.init.constant_(m.weight, 1.0)\n\n def interpolate_pos_encoding(self, x, w, h):\n npatch = x.shape[1] - 1\n N = self.pos_embed.shape[1] - 1\n if npatch == N and w == h:\n return self.pos_embed\n class_pos_embed = self.pos_embed[:, 0]\n patch_pos_embed = self.pos_embed[:, 1:]\n dim = x.shape[-1]\n w0 = w // self.patch_embed.patch_size\n h0 = h // self.patch_embed.patch_size\n # we add a small number to avoid floating point error in the interpolation\n # see discussion at https://github.com/facebookresearch/dino/issues/8\n w0, h0 = w0 + 0.1, h0 + 0.1\n patch_pos_embed = nn.functional.interpolate(\n patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2),\n scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)),\n mode='bicubic',\n )\n assert int(w0) == patch_pos_embed.shape[-2] and int(h0) == patch_pos_embed.shape[-1]\n patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)\n return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)\n\n def prepare_tokens(self, x):\n B, nc, w, h = x.shape\n x = self.patch_embed(x) # patch linear embedding\n\n # add the [CLS] token to the embed patch tokens\n cls_tokens = self.cls_token.expand(B, -1, -1)\n x = torch.cat((cls_tokens, x), dim=1)\n\n # add positional encoding to each token\n x = x + self.interpolate_pos_encoding(x, w, h)\n\n return self.pos_drop(x)\n\n def forward(self, x):\n x = self.prepare_tokens(x)\n for blk in self.blocks:\n x = blk(x)\n x = self.norm(x)\n return x[:, 0]\n\n def get_last_selfattention(self, x):\n x = self.prepare_tokens(x)\n for i, blk in enumerate(self.blocks):\n if i < len(self.blocks) - 1:\n x = blk(x)\n else:\n # return attention of the last block\n return blk(x, return_attention=True)\n\n def get_intermediate_layers(self, x, n=1):\n x = self.prepare_tokens(x)\n # we return the output tokens from the `n` last blocks\n output = []\n for i, blk in enumerate(self.blocks):\n x = blk(x)\n if len(self.blocks) - i <= n:\n output.append(self.norm(x))\n return output\n\n\ndef vit_tiny(patch_size=16, **kwargs):\n model = VisionTransformer(\n patch_size=patch_size, embed_dim=192, depth=12, num_heads=3, mlp_ratio=4,\n qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n return model\n\n\ndef vit_tiny_cam(patch_size=16, **kwargs):\n model = VisionTransformer(\n patch_size=patch_size, embed_dim=192, depth=12, num_heads=3, mlp_ratio=4,\n qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n return model\n\n\ndef vit_small(patch_size=16, **kwargs):\n model = VisionTransformer(\n patch_size=patch_size, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4,\n qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n return model\n\ndef vit_small_cam(patch_size=16, **kwargs):\n model = VisionTransformer(\n patch_size=patch_size, embed_dim=512, depth=12, num_heads=8, mlp_ratio=4,\n qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n return model\n\n\ndef vit_base(patch_size=16, **kwargs):\n model = VisionTransformer(\n patch_size=patch_size, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4,\n qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n return model\n\n\nclass DINOHead(nn.Module):\n def __init__(self, in_dim, out_dim, use_bn=False, norm_last_layer=True, nlayers=3, hidden_dim=2048, bottleneck_dim=256):\n super().__init__()\n nlayers = max(nlayers, 1)\n if nlayers == 1:\n self.mlp = nn.Linear(in_dim, bottleneck_dim)\n else:\n layers = [nn.Linear(in_dim, hidden_dim)]\n if use_bn:\n layers.append(nn.BatchNorm1d(hidden_dim))\n layers.append(nn.GELU())\n for _ in range(nlayers - 2):\n layers.append(nn.Linear(hidden_dim, hidden_dim))\n if use_bn:\n layers.append(nn.BatchNorm1d(hidden_dim))\n layers.append(nn.GELU())\n layers.append(nn.Linear(hidden_dim, bottleneck_dim))\n self.mlp = nn.Sequential(*layers)\n self.apply(self._init_weights)\n self.last_layer = nn.utils.weight_norm(nn.Linear(bottleneck_dim, out_dim, bias=False))\n self.last_layer.weight_g.data.fill_(1)\n if norm_last_layer:\n self.last_layer.weight_g.requires_grad = False\n\n def _init_weights(self, m):\n if isinstance(m, nn.Linear):\n trunc_normal_(m.weight, std=.02)\n if isinstance(m, nn.Linear) and m.bias is not None:\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x):\n x = self.mlp(x)\n x = nn.functional.normalize(x, dim=-1, p=2)\n x = self.last_layer(x)\n return x\n"
]
| [
[
"torch.nn.Linear",
"torch.rand",
"torch.nn.Dropout",
"torch.cat",
"torch.nn.functional.normalize",
"torch.nn.Identity",
"torch.zeros",
"torch.nn.init.constant_",
"torch.nn.Sequential",
"torch.linspace",
"torch.nn.Conv2d",
"torch.nn.BatchNorm1d",
"torch.nn.GELU"
]
]
|
xueeinstein/jax | [
"6388f7ef32659d8ab4ac5970a186cab23875c178"
]
| [
"jax/test_util.py"
]
| [
"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom contextlib import contextmanager\nimport functools\nimport re\nimport os\nfrom typing import Dict, Sequence, Union\nimport unittest\nimport warnings\nimport zlib\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n\nimport numpy as np\nimport numpy.random as npr\n\nfrom . import api\nfrom . import core\nfrom . import dtypes as _dtypes\nfrom . import lax\nfrom .config import flags, bool_env\nfrom .util import partial\nfrom .tree_util import tree_multimap, tree_all, tree_map, tree_reduce\nfrom .lib import xla_bridge\nfrom .interpreters import xla\n\n\nFLAGS = flags.FLAGS\nflags.DEFINE_enum(\n 'jax_test_dut', '',\n enum_values=['', 'cpu', 'gpu', 'tpu'],\n help=\n 'Describes the device under test in case special consideration is required.'\n)\n\nflags.DEFINE_integer(\n 'num_generated_cases',\n int(os.getenv('JAX_NUM_GENERATED_CASES', 10)),\n help='Number of generated cases to test')\n\nflags.DEFINE_bool(\n 'jax_skip_slow_tests',\n bool_env('JAX_SKIP_SLOW_TESTS', False),\n help='Skip tests marked as slow (> 5 sec).'\n)\n\nflags.DEFINE_string(\n 'test_targets', '',\n 'Regular expression specifying which tests to run, called via re.match on '\n 'the test name. If empty or unspecified, run all tests.'\n)\n\nEPS = 1e-4\n\ndef _dtype(x):\n return (getattr(x, 'dtype', None) or\n np.dtype(_dtypes.python_scalar_dtypes.get(type(x), None)) or\n np.asarray(x).dtype)\n\n\ndef num_float_bits(dtype):\n return _dtypes.finfo(_dtypes.canonicalize_dtype(dtype)).bits\n\n\ndef is_sequence(x):\n try:\n iter(x)\n except TypeError:\n return False\n else:\n return True\n\n_default_tolerance = {\n np.dtype(np.bool_): 0,\n np.dtype(np.int8): 0,\n np.dtype(np.int16): 0,\n np.dtype(np.int32): 0,\n np.dtype(np.int64): 0,\n np.dtype(np.uint8): 0,\n np.dtype(np.uint16): 0,\n np.dtype(np.uint32): 0,\n np.dtype(np.uint64): 0,\n np.dtype(_dtypes.bfloat16): 1e-2,\n np.dtype(np.float16): 1e-3,\n np.dtype(np.float32): 1e-6,\n np.dtype(np.float64): 1e-15,\n np.dtype(np.complex64): 1e-6,\n np.dtype(np.complex128): 1e-15,\n}\n\ndef default_tolerance():\n if device_under_test() != \"tpu\":\n return _default_tolerance\n tol = _default_tolerance.copy()\n tol[np.dtype(np.float32)] = 1e-3\n tol[np.dtype(np.complex64)] = 1e-3\n return tol\n\ndefault_gradient_tolerance = {\n np.dtype(_dtypes.bfloat16): 1e-1,\n np.dtype(np.float16): 1e-2,\n np.dtype(np.float32): 2e-3,\n np.dtype(np.float64): 1e-5,\n np.dtype(np.complex64): 1e-3,\n np.dtype(np.complex128): 1e-5,\n}\n\ndef _assert_numpy_allclose(a, b, atol=None, rtol=None):\n a = a.astype(np.float32) if a.dtype == _dtypes.bfloat16 else a\n b = b.astype(np.float32) if b.dtype == _dtypes.bfloat16 else b\n kw = {}\n if atol: kw[\"atol\"] = atol\n if rtol: kw[\"rtol\"] = rtol\n np.testing.assert_allclose(a, b, **kw)\n\ndef tolerance(dtype, tol=None):\n tol = {} if tol is None else tol\n if not isinstance(tol, dict):\n return tol\n tol = {np.dtype(key): value for key, value in tol.items()}\n dtype = _dtypes.canonicalize_dtype(np.dtype(dtype))\n return tol.get(dtype, default_tolerance()[dtype])\n\ndef _normalize_tolerance(tol):\n tol = tol or 0\n if isinstance(tol, dict):\n return {np.dtype(k): v for k, v in tol.items()}\n else:\n return {k: tol for k in _default_tolerance.keys()}\n\ndef join_tolerance(tol1, tol2):\n tol1 = _normalize_tolerance(tol1)\n tol2 = _normalize_tolerance(tol2)\n out = tol1\n for k, v in tol2.items():\n out[k] = max(v, tol1.get(k, 0))\n return out\n\ndef _assert_numpy_close(a, b, atol=None, rtol=None):\n assert a.shape == b.shape\n atol = max(tolerance(a.dtype, atol), tolerance(b.dtype, atol))\n rtol = max(tolerance(a.dtype, rtol), tolerance(b.dtype, rtol))\n _assert_numpy_allclose(a, b, atol=atol * a.size, rtol=rtol * b.size)\n\n\ndef check_eq(xs, ys):\n tree_all(tree_multimap(_assert_numpy_allclose, xs, ys))\n\n\ndef check_close(xs, ys, atol=None, rtol=None):\n assert_close = partial(_assert_numpy_close, atol=atol, rtol=rtol)\n tree_all(tree_multimap(assert_close, xs, ys))\n\ndef _check_dtypes_match(xs, ys):\n def _assert_dtypes_match(x, y):\n if FLAGS.jax_enable_x64:\n assert _dtype(x) == _dtype(y)\n else:\n assert (_dtypes.canonicalize_dtype(_dtype(x)) ==\n _dtypes.canonicalize_dtype(_dtype(y)))\n tree_all(tree_multimap(_assert_dtypes_match, xs, ys))\n\n\ndef inner_prod(xs, ys):\n def contract(x, y):\n return np.real(np.dot(np.conj(x).reshape(-1), y.reshape(-1)))\n return tree_reduce(np.add, tree_multimap(contract, xs, ys))\n\n\ndef _safe_subtract(x, y, *, dtype):\n \"\"\"Subtraction that with `inf - inf == 0` semantics.\"\"\"\n with np.errstate(invalid='ignore'):\n return np.where(np.equal(x, y), np.array(0, dtype),\n np.subtract(x, y, dtype=dtype))\n\nadd = partial(tree_multimap, lambda x, y: np.add(x, y, dtype=_dtype(x)))\nsub = partial(tree_multimap, lambda x, y: np.subtract(x, y, dtype=_dtype(x)))\nsafe_sub = partial(tree_multimap,\n lambda x, y: _safe_subtract(x, y, dtype=_dtype(x)))\nconj = partial(tree_map, lambda x: np.conj(x, dtype=_dtype(x)))\n\ndef scalar_mul(xs, a):\n return tree_map(lambda x: np.multiply(x, a, dtype=_dtype(x)), xs)\n\n\ndef rand_like(rng, x):\n shape = np.shape(x)\n dtype = _dtype(x)\n randn = lambda: np.asarray(rng.randn(*shape), dtype=dtype)\n if _dtypes.issubdtype(dtype, np.complexfloating):\n return randn() + dtype.type(1.0j) * randn()\n else:\n return randn()\n\n\ndef numerical_jvp(f, primals, tangents, eps=EPS):\n delta = scalar_mul(tangents, eps)\n f_pos = f(*add(primals, delta))\n f_neg = f(*sub(primals, delta))\n return scalar_mul(safe_sub(f_pos, f_neg), 0.5 / eps)\n\n\ndef _merge_tolerance(tol, default):\n if tol is None:\n return default\n if not isinstance(tol, dict):\n return tol\n out = default.copy()\n for k, v in tol.items():\n out[np.dtype(k)] = v\n return out\n\ndef check_jvp(f, f_jvp, args, atol=None, rtol=None, eps=EPS):\n atol = _merge_tolerance(atol, default_gradient_tolerance)\n rtol = _merge_tolerance(rtol, default_gradient_tolerance)\n rng = np.random.RandomState(0)\n tangent = tree_map(partial(rand_like, rng), args)\n v_out, t_out = f_jvp(args, tangent)\n _check_dtypes_match(v_out, t_out)\n v_out_expected = f(*args)\n _check_dtypes_match(v_out, v_out_expected)\n t_out_expected = numerical_jvp(f, args, tangent, eps=eps)\n # In principle we should expect exact equality of v_out and v_out_expected,\n # but due to nondeterminism especially on GPU (e.g., due to convolution\n # autotuning) we only require \"close\".\n check_close(v_out, v_out_expected, atol=atol, rtol=rtol)\n check_close(t_out, t_out_expected, atol=atol, rtol=rtol)\n\n\ndef check_vjp(f, f_vjp, args, atol=None, rtol=None, eps=EPS):\n atol = _merge_tolerance(atol, default_gradient_tolerance)\n rtol = _merge_tolerance(rtol, default_gradient_tolerance)\n _rand_like = partial(rand_like, np.random.RandomState(0))\n v_out, vjpfun = f_vjp(*args)\n v_out_expected = f(*args)\n check_close(v_out, v_out_expected, atol=atol, rtol=rtol)\n tangent = tree_map(_rand_like, args)\n tangent_out = numerical_jvp(f, args, tangent, eps=eps)\n cotangent = tree_map(_rand_like, v_out)\n cotangent_out = conj(vjpfun(conj(cotangent)))\n ip = inner_prod(tangent, cotangent_out)\n ip_expected = inner_prod(tangent_out, cotangent)\n check_close(ip, ip_expected, atol=atol, rtol=rtol)\n\n\ndef check_grads(f, args, order,\n modes=[\"fwd\", \"rev\"], atol=None, rtol=None, eps=None):\n \"\"\"Check gradients from automatic differentiation against finite differences.\n\n Gradients are only checked in a single randomly chosen direction, which\n ensures that the finite difference calculation does not become prohibitively\n expensive even for large input/output spaces.\n\n Args:\n f: function to check at ``f(*args)``.\n args: tuple of argument values.\n order: forward and backwards gradients up to this order are checked.\n modes: lists of gradient modes to check ('fwd' and/or 'rev').\n atol: absolute tolerance for gradient equality.\n rtol: relative tolerance for gradient equality.\n eps: step size used for finite differences.\n\n Raises:\n AssertionError: if gradients do not match.\n \"\"\"\n args = tuple(args)\n eps = eps or EPS\n\n _check_jvp = partial(check_jvp, atol=atol, rtol=rtol, eps=eps)\n _check_vjp = partial(check_vjp, atol=atol, rtol=rtol, eps=eps)\n\n def _check_grads(f, args, order):\n if \"fwd\" in modes:\n _check_jvp(f, partial(api.jvp, f), args)\n if order > 1:\n _check_grads(partial(api.jvp, f), (args, args), order - 1)\n\n if \"rev\" in modes:\n _check_vjp(f, partial(api.vjp, f), args)\n if order > 1:\n def f_vjp(*args):\n out_primal_py, vjp_py = api.vjp(f, *args)\n return vjp_py(out_primal_py)\n _check_grads(f_vjp, args, order - 1)\n\n _check_grads(f, args, order)\n\n\n@contextmanager\ndef count_primitive_compiles():\n xla.xla_primitive_callable.cache_clear()\n\n # We count how many times we call primitive_computation (which is called\n # inside xla_primitive_callable) instead of xla_primitive_callable so we don't\n # count cache hits.\n primitive_computation = xla.primitive_computation\n count = [0]\n\n def primitive_computation_and_count(*args, **kwargs):\n count[0] += 1\n return primitive_computation(*args, **kwargs)\n\n xla.primitive_computation = primitive_computation_and_count\n try:\n yield count\n finally:\n xla.primitive_computation = primitive_computation\n\n\n@contextmanager\ndef count_jit_and_pmap_compiles():\n # No need to clear any caches since we generally jit and pmap fresh callables\n # in tests.\n\n jaxpr_subcomp = xla.jaxpr_subcomp\n count = [0]\n\n def jaxpr_subcomp_and_count(*args, **kwargs):\n count[0] += 1\n return jaxpr_subcomp(*args, **kwargs)\n\n xla.jaxpr_subcomp = jaxpr_subcomp_and_count\n try:\n yield count\n finally:\n xla.jaxpr_subcomp = jaxpr_subcomp\n\n\ndef device_under_test():\n return FLAGS.jax_test_dut or xla_bridge.get_backend().platform\n\ndef if_device_under_test(device_type: Union[str, Sequence[str]],\n if_true, if_false):\n \"\"\"Chooses `if_true` of `if_false` based on device_under_test.\"\"\"\n if device_under_test() in ([device_type] if isinstance(device_type, str)\n else device_type):\n return if_true\n else:\n return if_false\n\ndef supported_dtypes():\n if device_under_test() == \"tpu\":\n types = {np.bool_, np.int32, np.uint32, _dtypes.bfloat16, np.float32,\n np.complex64}\n else:\n types = {np.bool_, np.int8, np.int16, np.int32, np.int64,\n np.uint8, np.uint16, np.uint32, np.uint64,\n _dtypes.bfloat16, np.float16, np.float32, np.float64,\n np.complex64, np.complex128}\n if not FLAGS.jax_enable_x64:\n types -= {np.uint64, np.int64, np.float64, np.complex128}\n return types\n\ndef skip_if_unsupported_type(dtype):\n if dtype not in supported_dtypes():\n raise unittest.SkipTest(\n f\"Type {dtype} not supported on {device_under_test()}\")\n\ndef skip_on_devices(*disabled_devices):\n \"\"\"A decorator for test methods to skip the test on certain devices.\"\"\"\n def skip(test_method):\n @functools.wraps(test_method)\n def test_method_wrapper(self, *args, **kwargs):\n device = device_under_test()\n if device in disabled_devices:\n test_name = getattr(test_method, '__name__', '[unknown test]')\n raise unittest.SkipTest(\n f\"{test_name} not supported on {device.upper()}.\")\n return test_method(self, *args, **kwargs)\n return test_method_wrapper\n return skip\n\n\ndef skip_on_flag(flag_name, skip_value):\n \"\"\"A decorator for test methods to skip the test when flags are set.\"\"\"\n def skip(test_method): # pylint: disable=missing-docstring\n @functools.wraps(test_method)\n def test_method_wrapper(self, *args, **kwargs):\n flag_value = getattr(FLAGS, flag_name)\n if flag_value == skip_value:\n test_name = getattr(test_method, '__name__', '[unknown test]')\n raise unittest.SkipTest(\n f\"{test_name} not supported when FLAGS.{flag_name} is {flag_value}\")\n return test_method(self, *args, **kwargs)\n return test_method_wrapper\n return skip\n\n\ndef format_test_name_suffix(opname, shapes, dtypes):\n arg_descriptions = (format_shape_dtype_string(shape, dtype)\n for shape, dtype in zip(shapes, dtypes))\n return '{}_{}'.format(opname.capitalize(), '_'.join(arg_descriptions))\n\n\n# We use special symbols, represented as singleton objects, to distinguish\n# between NumPy scalars, Python scalars, and 0-D arrays.\nclass ScalarShape(object):\n def __len__(self): return 0\nclass _NumpyScalar(ScalarShape): pass\nclass _PythonScalar(ScalarShape): pass\nNUMPY_SCALAR_SHAPE = _NumpyScalar()\nPYTHON_SCALAR_SHAPE = _PythonScalar()\n\n\ndef _dims_of_shape(shape):\n \"\"\"Converts `shape` to a tuple of dimensions.\"\"\"\n if type(shape) in (list, tuple):\n return shape\n elif isinstance(shape, ScalarShape):\n return ()\n else:\n raise TypeError(type(shape))\n\n\ndef _cast_to_shape(value, shape, dtype):\n \"\"\"Casts `value` to the correct Python type for `shape` and `dtype`.\"\"\"\n if shape is NUMPY_SCALAR_SHAPE:\n # explicitly cast to NumPy scalar in case `value` is a Python scalar.\n return np.dtype(dtype).type(value)\n elif shape is PYTHON_SCALAR_SHAPE:\n # explicitly cast to Python scalar via https://stackoverflow.com/a/11389998\n return np.asarray(value).item()\n elif type(shape) in (list, tuple):\n assert np.shape(value) == tuple(shape)\n return value\n else:\n raise TypeError(type(shape))\n\n\ndef dtype_str(dtype):\n return np.dtype(dtype).name\n\n\ndef format_shape_dtype_string(shape, dtype):\n if isinstance(shape, np.ndarray):\n return f'{dtype_str(dtype)}[{shape}]'\n elif isinstance(shape, list):\n shape = tuple(shape)\n return _format_shape_dtype_string(shape, dtype)\n\[email protected]_cache(maxsize=64)\ndef _format_shape_dtype_string(shape, dtype):\n if shape is NUMPY_SCALAR_SHAPE:\n return dtype_str(dtype)\n elif shape is PYTHON_SCALAR_SHAPE:\n return 'py' + dtype_str(dtype)\n elif type(shape) is tuple:\n shapestr = ','.join(str(dim) for dim in shape)\n return '{}[{}]'.format(dtype_str(dtype), shapestr)\n elif type(shape) is int:\n return '{}[{},]'.format(dtype_str(dtype), shape)\n else:\n raise TypeError(type(shape))\n\n\ndef _rand_dtype(rand, shape, dtype, scale=1., post=lambda x: x):\n \"\"\"Produce random values given shape, dtype, scale, and post-processor.\n\n Args:\n rand: a function for producing random values of a given shape, e.g. a\n bound version of either np.RandomState.randn or np.RandomState.rand.\n shape: a shape value as a tuple of positive integers.\n dtype: a numpy dtype.\n scale: optional, a multiplicative scale for the random values (default 1).\n post: optional, a callable for post-processing the random values (default\n identity).\n\n Returns:\n An ndarray of the given shape and dtype using random values based on a call\n to rand but scaled, converted to the appropriate dtype, and post-processed.\n \"\"\"\n r = lambda: np.asarray(scale * rand(*_dims_of_shape(shape)), dtype)\n if _dtypes.issubdtype(dtype, np.complexfloating):\n vals = r() + 1.0j * r()\n else:\n vals = r()\n return _cast_to_shape(np.asarray(post(vals), dtype), shape, dtype)\n\n\ndef rand_fullrange(rng, standardize_nans=False):\n \"\"\"Random numbers that span the full range of available bits.\"\"\"\n def gen(shape, dtype, post=lambda x: x):\n dtype = np.dtype(dtype)\n size = dtype.itemsize * np.prod(_dims_of_shape(shape))\n vals = rng.randint(0, np.iinfo(np.uint8).max, size=size, dtype=np.uint8)\n vals = post(vals).view(dtype).reshape(shape)\n # Non-standard NaNs cause errors in numpy equality assertions.\n if standardize_nans and np.issubdtype(dtype, np.floating):\n vals[np.isnan(vals)] = np.nan\n return _cast_to_shape(vals, shape, dtype)\n return gen\n\n\ndef rand_default(rng, scale=3):\n return partial(_rand_dtype, rng.randn, scale=scale)\n\n\ndef rand_nonzero(rng):\n post = lambda x: np.where(x == 0, np.array(1, dtype=x.dtype), x)\n return partial(_rand_dtype, rng.randn, scale=3, post=post)\n\n\ndef rand_positive(rng):\n post = lambda x: x + 1\n return partial(_rand_dtype, rng.rand, scale=2, post=post)\n\n\ndef rand_small(rng):\n return partial(_rand_dtype, rng.randn, scale=1e-3)\n\n\ndef rand_not_small(rng, offset=10.):\n post = lambda x: x + np.where(x > 0, offset, -offset)\n return partial(_rand_dtype, rng.randn, scale=3., post=post)\n\n\ndef rand_small_positive(rng):\n return partial(_rand_dtype, rng.rand, scale=2e-5)\n\ndef rand_uniform(rng, low=0.0, high=1.0):\n assert low < high\n post = lambda x: x * (high - low) + low\n return partial(_rand_dtype, rng.rand, post=post)\n\n\ndef rand_some_equal(rng):\n\n def post(x):\n x_ravel = x.ravel()\n if len(x_ravel) == 0:\n return x\n flips = rng.rand(*np.shape(x)) < 0.5\n return np.where(flips, x_ravel[0], x)\n\n return partial(_rand_dtype, rng.randn, scale=100., post=post)\n\n\ndef rand_some_inf(rng):\n \"\"\"Return a random sampler that produces infinities in floating types.\"\"\"\n base_rand = rand_default(rng)\n\n \"\"\"\n TODO: Complex numbers are not correctly tested\n If blocks should be switched in order, and relevant tests should be fixed\n \"\"\"\n def rand(shape, dtype):\n \"\"\"The random sampler function.\"\"\"\n if not _dtypes.issubdtype(dtype, np.floating):\n # only float types have inf\n return base_rand(shape, dtype)\n\n if _dtypes.issubdtype(dtype, np.complexfloating):\n base_dtype = np.real(np.array(0, dtype=dtype)).dtype\n out = (rand(shape, base_dtype) +\n np.array(1j, dtype) * rand(shape, base_dtype))\n return _cast_to_shape(out, shape, dtype)\n\n dims = _dims_of_shape(shape)\n posinf_flips = rng.rand(*dims) < 0.1\n neginf_flips = rng.rand(*dims) < 0.1\n\n vals = base_rand(shape, dtype)\n vals = np.where(posinf_flips, np.array(np.inf, dtype=dtype), vals)\n vals = np.where(neginf_flips, np.array(-np.inf, dtype=dtype), vals)\n\n return _cast_to_shape(np.asarray(vals, dtype=dtype), shape, dtype)\n\n return rand\n\ndef rand_some_nan(rng):\n \"\"\"Return a random sampler that produces nans in floating types.\"\"\"\n base_rand = rand_default(rng)\n\n def rand(shape, dtype):\n \"\"\"The random sampler function.\"\"\"\n if _dtypes.issubdtype(dtype, np.complexfloating):\n base_dtype = np.real(np.array(0, dtype=dtype)).dtype\n out = (rand(shape, base_dtype) +\n np.array(1j, dtype) * rand(shape, base_dtype))\n return _cast_to_shape(out, shape, dtype)\n\n if not _dtypes.issubdtype(dtype, np.floating):\n # only float types have inf\n return base_rand(shape, dtype)\n\n dims = _dims_of_shape(shape)\n nan_flips = rng.rand(*dims) < 0.1\n\n vals = base_rand(shape, dtype)\n vals = np.where(nan_flips, np.array(np.nan, dtype=dtype), vals)\n\n return _cast_to_shape(np.asarray(vals, dtype=dtype), shape, dtype)\n\n return rand\n\ndef rand_some_inf_and_nan(rng):\n \"\"\"Return a random sampler that produces infinities in floating types.\"\"\"\n base_rand = rand_default(rng)\n\n \"\"\"\n TODO: Complex numbers are not correctly tested\n If blocks should be switched in order, and relevant tests should be fixed\n \"\"\"\n def rand(shape, dtype):\n \"\"\"The random sampler function.\"\"\"\n if not _dtypes.issubdtype(dtype, np.floating):\n # only float types have inf\n return base_rand(shape, dtype)\n\n if _dtypes.issubdtype(dtype, np.complexfloating):\n base_dtype = np.real(np.array(0, dtype=dtype)).dtype\n out = (rand(shape, base_dtype) +\n np.array(1j, dtype) * rand(shape, base_dtype))\n return _cast_to_shape(out, shape, dtype)\n\n dims = _dims_of_shape(shape)\n posinf_flips = rng.rand(*dims) < 0.1\n neginf_flips = rng.rand(*dims) < 0.1\n nan_flips = rng.rand(*dims) < 0.1\n\n vals = base_rand(shape, dtype)\n vals = np.where(posinf_flips, np.array(np.inf, dtype=dtype), vals)\n vals = np.where(neginf_flips, np.array(-np.inf, dtype=dtype), vals)\n vals = np.where(nan_flips, np.array(np.nan, dtype=dtype), vals)\n\n return _cast_to_shape(np.asarray(vals, dtype=dtype), shape, dtype)\n\n return rand\n\n# TODO(mattjj): doesn't handle complex types\ndef rand_some_zero(rng):\n \"\"\"Return a random sampler that produces some zeros.\"\"\"\n base_rand = rand_default(rng)\n\n def rand(shape, dtype):\n \"\"\"The random sampler function.\"\"\"\n dims = _dims_of_shape(shape)\n zeros = rng.rand(*dims) < 0.5\n\n vals = base_rand(shape, dtype)\n vals = np.where(zeros, np.array(0, dtype=dtype), vals)\n\n return _cast_to_shape(np.asarray(vals, dtype=dtype), shape, dtype)\n\n return rand\n\n\ndef rand_int(rng, low=0, high=None):\n def fn(shape, dtype):\n return rng.randint(low, high=high, size=shape, dtype=dtype)\n return fn\n\ndef rand_unique_int(rng, high=None):\n def fn(shape, dtype):\n return rng.choice(np.arange(high or np.prod(shape), dtype=dtype),\n size=shape, replace=False)\n return fn\n\ndef rand_bool(rng):\n def generator(shape, dtype):\n return _cast_to_shape(rng.rand(*_dims_of_shape(shape)) < 0.5, shape, dtype)\n return generator\n\ndef check_raises(thunk, err_type, msg):\n try:\n thunk()\n assert False\n except err_type as e:\n assert str(e).startswith(msg), \"\\n{}\\n\\n{}\\n\".format(e, msg)\n\ndef check_raises_regexp(thunk, err_type, pattern):\n try:\n thunk()\n assert False\n except err_type as e:\n assert re.match(pattern, str(e)), \"{}\\n\\n{}\\n\".format(e, pattern)\n\n\ndef iter_eqns(jaxpr):\n # TODO(necula): why doesn't this search in params?\n for eqn in jaxpr.eqns:\n yield eqn\n for subjaxpr in core.subjaxprs(jaxpr):\n yield from iter_eqns(subjaxpr)\n\ndef assert_dot_precision(expected_precision, fun, *args):\n jaxpr = api.make_jaxpr(fun)(*args)\n precisions = [eqn.params['precision'] for eqn in iter_eqns(jaxpr.jaxpr)\n if eqn.primitive == lax.dot_general_p]\n for precision in precisions:\n msg = \"Unexpected precision: {} != {}\".format(expected_precision, precision)\n assert precision == expected_precision, msg\n\n\n_CACHED_INDICES: Dict[int, Sequence[int]] = {}\n\ndef cases_from_list(xs):\n xs = list(xs)\n n = len(xs)\n k = min(n, FLAGS.num_generated_cases)\n # Random sampling for every parameterized test is expensive. Do it once and\n # cache the result.\n indices = _CACHED_INDICES.get(n)\n if indices is None:\n rng = npr.RandomState(42)\n _CACHED_INDICES[n] = indices = rng.permutation(n)\n return [xs[i] for i in indices[:k]]\n\ndef cases_from_gens(*gens):\n sizes = [1, 3, 10]\n cases_per_size = int(FLAGS.num_generated_cases / len(sizes)) + 1\n for size in sizes:\n for i in range(cases_per_size):\n yield ('_{}_{}'.format(size, i),) + tuple(gen(size) for gen in gens)\n\n\nclass JaxTestLoader(absltest.TestLoader):\n def getTestCaseNames(self, testCaseClass):\n names = super().getTestCaseNames(testCaseClass)\n if FLAGS.test_targets:\n pattern = re.compile(FLAGS.test_targets)\n names = [name for name in names\n if pattern.search(f\"{testCaseClass.__name__}.{name}\")]\n return names\n\n\nclass JaxTestCase(parameterized.TestCase):\n \"\"\"Base class for JAX tests including numerical checks and boilerplate.\"\"\"\n\n # TODO(mattjj): this obscures the error messages from failures, figure out how\n # to re-enable it\n # def tearDown(self) -> None:\n # assert core.reset_trace_state()\n\n def setUp(self):\n super(JaxTestCase, self).setUp()\n core.skip_checks = False\n # We use the adler32 hash for two reasons.\n # a) it is deterministic run to run, unlike hash() which is randomized.\n # b) it returns values in int32 range, which RandomState requires.\n self._rng = npr.RandomState(zlib.adler32(self._testMethodName.encode()))\n\n def rng(self):\n return self._rng\n\n def assertArraysEqual(self, x, y, *, check_dtypes=True):\n \"\"\"Assert that x and y arrays are exactly equal.\"\"\"\n if check_dtypes:\n self.assertDtypesMatch(x, y)\n np.testing.assert_equal(x, y)\n\n def assertArraysAllClose(self, x, y, *, check_dtypes=True, atol=None,\n rtol=None):\n \"\"\"Assert that x and y are close (up to numerical tolerances).\"\"\"\n self.assertEqual(x.shape, y.shape)\n atol = max(tolerance(_dtype(x), atol), tolerance(_dtype(y), atol))\n rtol = max(tolerance(_dtype(x), rtol), tolerance(_dtype(y), rtol))\n\n _assert_numpy_allclose(x, y, atol=atol, rtol=rtol)\n\n if check_dtypes:\n self.assertDtypesMatch(x, y)\n\n def assertDtypesMatch(self, x, y, *, canonicalize_dtypes=True):\n if not FLAGS.jax_enable_x64 and canonicalize_dtypes:\n self.assertEqual(_dtypes.canonicalize_dtype(_dtype(x)),\n _dtypes.canonicalize_dtype(_dtype(y)))\n else:\n self.assertEqual(_dtype(x), _dtype(y))\n\n def assertAllClose(self, x, y, *, check_dtypes=True, atol=None, rtol=None,\n canonicalize_dtypes=True):\n \"\"\"Assert that x and y, either arrays or nested tuples/lists, are close.\"\"\"\n if isinstance(x, dict):\n self.assertIsInstance(y, dict)\n self.assertEqual(set(x.keys()), set(y.keys()))\n for k in x.keys():\n self.assertAllClose(x[k], y[k], check_dtypes=check_dtypes, atol=atol,\n rtol=rtol, canonicalize_dtypes=canonicalize_dtypes)\n elif is_sequence(x) and not hasattr(x, '__array__'):\n self.assertTrue(is_sequence(y) and not hasattr(y, '__array__'))\n self.assertEqual(len(x), len(y))\n for x_elt, y_elt in zip(x, y):\n self.assertAllClose(x_elt, y_elt, check_dtypes=check_dtypes, atol=atol,\n rtol=rtol, canonicalize_dtypes=canonicalize_dtypes)\n elif hasattr(x, '__array__') or np.isscalar(x):\n self.assertTrue(hasattr(y, '__array__') or np.isscalar(y))\n if check_dtypes:\n self.assertDtypesMatch(x, y, canonicalize_dtypes=canonicalize_dtypes)\n x = np.asarray(x)\n y = np.asarray(y)\n self.assertArraysAllClose(x, y, check_dtypes=False, atol=atol, rtol=rtol)\n elif x == y:\n return\n else:\n raise TypeError((type(x), type(y)))\n\n def assertMultiLineStrippedEqual(self, expected, what):\n \"\"\"Asserts two strings are equal, after stripping each line.\"\"\"\n ignore_space_re = re.compile(r'\\s*\\n\\s*')\n expected_clean = re.sub(ignore_space_re, '\\n', expected.strip())\n what_clean = re.sub(ignore_space_re, '\\n', what.strip())\n self.assertMultiLineEqual(expected_clean, what_clean,\n msg=\"Found\\n{}\\nExpecting\\n{}\".format(what, expected))\n\n def _CompileAndCheck(self, fun, args_maker, *, check_dtypes=True,\n rtol=None, atol=None):\n \"\"\"Helper method for running JAX compilation and allclose assertions.\"\"\"\n args = args_maker()\n\n def wrapped_fun(*args):\n self.assertTrue(python_should_be_executing)\n return fun(*args)\n\n python_should_be_executing = True\n python_ans = fun(*args)\n\n python_shapes = tree_map(lambda x: np.shape(x), python_ans)\n np_shapes = tree_map(lambda x: np.shape(np.asarray(x)), python_ans)\n self.assertEqual(python_shapes, np_shapes)\n\n cache_misses = xla.xla_primitive_callable.cache_info().misses\n python_ans = fun(*args)\n self.assertEqual(\n cache_misses, xla.xla_primitive_callable.cache_info().misses,\n \"Compilation detected during second call of {} in op-by-op \"\n \"mode.\".format(fun))\n\n cfun = api.jit(wrapped_fun)\n python_should_be_executing = True\n monitored_ans = cfun(*args)\n\n python_should_be_executing = False\n compiled_ans = cfun(*args)\n\n self.assertAllClose(python_ans, monitored_ans, check_dtypes=check_dtypes,\n atol=atol, rtol=rtol)\n self.assertAllClose(python_ans, compiled_ans, check_dtypes=check_dtypes,\n atol=atol, rtol=rtol)\n\n args = args_maker()\n\n python_should_be_executing = True\n python_ans = fun(*args)\n\n python_should_be_executing = False\n compiled_ans = cfun(*args)\n\n self.assertAllClose(python_ans, compiled_ans, check_dtypes=check_dtypes,\n atol=atol, rtol=rtol)\n\n def _CheckAgainstNumpy(self, numpy_reference_op, lax_op, args_maker,\n check_dtypes=True, tol=None,\n canonicalize_dtypes=True):\n args = args_maker()\n lax_ans = lax_op(*args)\n numpy_ans = numpy_reference_op(*args)\n self.assertAllClose(numpy_ans, lax_ans, check_dtypes=check_dtypes,\n atol=tol, rtol=tol,\n canonicalize_dtypes=canonicalize_dtypes)\n\n\n@contextmanager\ndef ignore_warning(**kw):\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", **kw)\n yield\n\n\nclass _cached_property:\n null = object()\n\n def __init__(self, method):\n self._method = method\n self._value = self.null\n\n def __get__(self, obj, cls):\n if self._value is self.null:\n self._value = self._method(obj)\n return self._value\n\n\nclass _LazyDtypes:\n \"\"\"A class that unifies lists of supported dtypes.\n\n These could be module-level constants, but device_under_test() is not always\n known at import time, so we need to define these lists lazily.\n \"\"\"\n def supported(self, dtypes):\n supported = supported_dtypes()\n return type(dtypes)(d for d in dtypes if d in supported)\n\n @_cached_property\n def floating(self):\n return self.supported([np.float32, np.float64])\n\n @_cached_property\n def all_floating(self):\n return self.supported([_dtypes.bfloat16, np.float16, np.float32, np.float64])\n\n @_cached_property\n def integer(self):\n return self.supported([np.int32, np.int64])\n\n @_cached_property\n def all_integer(self):\n return self.supported([np.int8, np.int16, np.int32, np.int64])\n\n @_cached_property\n def unsigned(self):\n return self.supported([np.uint32, np.uint64])\n\n @_cached_property\n def all_unsigned(self):\n return self.supported([np.uint8, np.uint16, np.uint32, np.uint64])\n\n @_cached_property\n def complex(self):\n return self.supported([np.complex64, np.complex128])\n\n @_cached_property\n def boolean(self):\n return self.supported([np.bool_])\n\n @_cached_property\n def inexact(self):\n return self.floating + self.complex\n\n @_cached_property\n def all_inexact(self):\n return self.all_floating + self.complex\n\n @_cached_property\n def numeric(self):\n return self.floating + self.integer + self.unsigned + self.complex\n\n @_cached_property\n def all(self):\n return (self.all_floating + self.all_integer + self.all_unsigned +\n self.complex + self.boolean)\n\n\ndtypes = _LazyDtypes()\n"
]
| [
[
"numpy.testing.assert_allclose",
"numpy.equal",
"numpy.array",
"numpy.isnan",
"numpy.asarray",
"numpy.errstate",
"numpy.random.RandomState",
"numpy.testing.assert_equal",
"numpy.shape",
"numpy.where",
"numpy.subtract",
"numpy.prod",
"numpy.isscalar",
"numpy.conj",
"numpy.issubdtype",
"numpy.iinfo",
"numpy.dtype"
]
]
|
bobhonores/aipnd-image-classifier | [
"5c012626250088b1d958fdb8aaddf2145db23cbe"
]
| [
"imagedataloader.py"
]
| [
"import torch\nfrom torchvision import datasets, transforms\n\n\ndef create_dataloaders(image_data_directory):\n data_transforms = {'train': transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(\n 224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])]),\n 'valid': transforms.Compose([transforms.Resize(224),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])}\n image_datasets = {\n 'train': datasets.ImageFolder(image_data_directory + '/train', transform=data_transforms['train']),\n 'valid': datasets.ImageFolder(image_data_directory + '/valid', transform=data_transforms['valid'])}\n image_dataloders = {'train': torch.utils.data.DataLoader(image_datasets['train'], batch_size=32, shuffle=True),\n 'valid': torch.utils.data.DataLoader(image_datasets['valid'], batch_size=32)}\n\n return image_datasets, image_dataloders\n"
]
| [
[
"torch.utils.data.DataLoader"
]
]
|
shivam-raj/EfficientDet | [
"37fa8dfeb1573129f498e1b431bf0780654faed7"
]
| [
"model.py"
]
| [
"from functools import reduce\n\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import initializers\nfrom tensorflow.keras import models\nfrom tfkeras import EfficientNetB0, EfficientNetB1, EfficientNetB2\nfrom tfkeras import EfficientNetB3, EfficientNetB4, EfficientNetB5, EfficientNetB6\nfrom custom.BFPN import BiFPN\nfrom layers import ClipBoxes, RegressBoxes, FilterDetections, wBiFPNAdd, BatchNormalization\nfrom initializers import PriorProbability\nfrom utils.anchors import anchors_for_shape\nimport numpy as np\n\nw_bifpns = [64, 88, 112, 160, 224, 288, 384]\nd_bifpns = [3, 4, 5, 6, 7, 7, 8]\nd_heads = [3, 3, 3, 4, 4, 4, 5]\nimage_sizes = [512, 640, 768, 896, 1024, 1280, 1408]\nbackbones = [EfficientNetB0, EfficientNetB1, EfficientNetB2,\n EfficientNetB3, EfficientNetB4, EfficientNetB5, EfficientNetB6]\n\nMOMENTUM = 0.997\nEPSILON = 1e-4\n\n\n\nclass BoxNet(models.Model):\n def __init__(self, width, depth, num_anchors=9, separable_conv=True, freeze_bn=False, **kwargs):\n super(BoxNet, self).__init__(**kwargs)\n self.width = width\n self.depth = depth\n self.num_anchors = num_anchors\n self.separable_conv = separable_conv\n options = {\n 'kernel_size': 3,\n 'strides': 1,\n 'padding': 'same',\n 'bias_initializer': 'zeros',\n }\n if separable_conv:\n kernel_initializer = {\n 'depthwise_initializer': initializers.VarianceScaling(),\n 'pointwise_initializer': initializers.VarianceScaling(),\n }\n options.update(kernel_initializer)\n self.convs = [layers.SeparableConv2D(filters=width, name=f'{self.name}/box-{i}', **options) for i in\n range(depth)]\n self.head = layers.SeparableConv2D(filters=num_anchors * 4, name=f'{self.name}/box-predict', **options)\n else:\n kernel_initializer = {\n 'kernel_initializer': initializers.RandomNormal(mean=0.0, stddev=0.01, seed=None)\n }\n options.update(kernel_initializer)\n self.convs = [layers.Conv2D(filters=width, name=f'{self.name}/box-{i}', **options) for i in range(depth)]\n self.head = layers.Conv2D(filters=num_anchors * 4, name=f'{self.name}/box-predict', **options)\n self.bns = [\n [layers.BatchNormalization(momentum=MOMENTUM, epsilon=EPSILON, name=f'{self.name}/box-{i}-bn-{j}') for j in\n range(3, 8)]\n for i in range(depth)]\n # self.bns = [[BatchNormalization(freeze=freeze_bn, name=f'{self.name}/box-{i}-bn-{j}') for j in range(3, 8)]\n # for i in range(depth)]\n self.relu = layers.Lambda(lambda x: tf.nn.swish(x))\n self.reshape = layers.Reshape((-1, 4))\n self.level = 0\n\n def call(self, inputs, **kwargs):\n feature, level = inputs\n for i in range(self.depth):\n feature = self.convs[i](feature)\n feature = self.bns[i][self.level](feature)\n feature = self.relu(feature)\n outputs = self.head(feature)\n outputs = self.reshape(outputs)\n self.level += 1\n return outputs\n\n\nclass ClassNet(models.Model):\n def __init__(self, width, depth, num_classes=20, num_anchors=9, separable_conv=True, freeze_bn=False, **kwargs):\n super(ClassNet, self).__init__(**kwargs)\n self.width = width\n self.depth = depth\n self.num_classes = num_classes\n self.num_anchors = num_anchors\n self.separable_conv = separable_conv\n options = {\n 'kernel_size': 3,\n 'strides': 1,\n 'padding': 'same',\n }\n if self.separable_conv:\n kernel_initializer = {\n 'depthwise_initializer': initializers.VarianceScaling(),\n 'pointwise_initializer': initializers.VarianceScaling(),\n }\n options.update(kernel_initializer)\n self.convs = [layers.SeparableConv2D(filters=width, bias_initializer='zeros', name=f'{self.name}/class-{i}',\n **options)\n for i in range(depth)]\n self.head = layers.SeparableConv2D(filters=num_classes * num_anchors,\n bias_initializer=PriorProbability(probability=0.01),\n name=f'{self.name}/class-predict', **options)\n else:\n kernel_initializer = {\n 'kernel_initializer': initializers.RandomNormal(mean=0.0, stddev=0.01, seed=None)\n }\n options.update(kernel_initializer)\n self.convs = [layers.Conv2D(filters=width, bias_initializer='zeros', name=f'{self.name}/class-{i}',\n **options)\n for i in range(depth)]\n self.head = layers.Conv2D(filters=num_classes * num_anchors,\n bias_initializer=PriorProbability(probability=0.01),\n name='class-predict', **options)\n self.bns = [\n [layers.BatchNormalization(momentum=MOMENTUM, epsilon=EPSILON, name=f'{self.name}/class-{i}-bn-{j}') for j\n in range(3, 8)]\n for i in range(depth)]\n # self.bns = [[BatchNormalization(freeze=freeze_bn, name=f'{self.name}/class-{i}-bn-{j}') for j in range(3, 8)]\n # for i in range(depth)]\n self.relu = layers.Lambda(lambda x: tf.nn.swish(x))\n self.reshape = layers.Reshape((-1, num_classes))\n self.activation = layers.Activation('sigmoid')\n self.level = 0\n\n def call(self, inputs, **kwargs):\n feature, level = inputs\n for i in range(self.depth):\n feature = self.convs[i](feature)\n feature = self.bns[i][self.level](feature)\n feature = self.relu(feature)\n outputs = self.head(feature)\n outputs = self.reshape(outputs)\n outputs = self.activation(outputs)\n self.level += 1\n return outputs\n\n\ndef efficientdet(phi, num_classes=20, num_anchors=9, weighted_bifpn=True, freeze_bn=False,\n score_threshold=0.01, detect_quadrangle=False, anchor_parameters=None, separable_conv=True):\n assert phi in range(7)\n input_size = image_sizes[phi]\n input_shape = (input_size, input_size, 3)\n image_input = layers.Input(input_shape)\n w_bifpn = w_bifpns[phi]\n d_bifpn = d_bifpns[phi]\n w_head = w_bifpn\n d_head = d_heads[phi]\n backbone_cls = backbones[phi]\n features = backbone_cls(input_tensor=image_input, freeze_bn=freeze_bn)\n if weighted_bifpn:\n fpn_features = features\n for i in range(d_bifpn):\n fpn_features=BiFPN(fpn_features,w_bifpn,index=i)\n else:\n raise ValueError('Only Weighted Network Supported')\n box_net = BoxNet(w_head, d_head, num_anchors=num_anchors, separable_conv=separable_conv, freeze_bn=freeze_bn,\n name='box_net')\n class_net = ClassNet(w_head, d_head, num_classes=num_classes, num_anchors=num_anchors,\n separable_conv=separable_conv, freeze_bn=freeze_bn, name='class_net')\n classification = [class_net([feature, i]) for i, feature in enumerate(fpn_features)]\n classification = layers.Concatenate(axis=1, name='classification')(classification)\n regression = [box_net([feature, i]) for i, feature in enumerate(fpn_features)]\n regression = layers.Concatenate(axis=1, name='regression')(regression)\n\n model = models.Model(inputs=[image_input], outputs=[classification, regression], name='efficientdet')\n\n # apply predicted regression to anchors\n anchors = anchors_for_shape((input_size, input_size), anchor_params=anchor_parameters)\n anchors_input = np.expand_dims(anchors, axis=0)\n boxes = RegressBoxes(name='boxes')([anchors_input, regression[..., :4]])\n boxes = ClipBoxes(name='clipped_boxes')([image_input, boxes])\n\n # filter detections (apply NMS / score threshold / select top-k)\n if detect_quadrangle:\n detections = FilterDetections(\n name='filtered_detections',\n score_threshold=score_threshold,\n detect_quadrangle=True\n )([boxes, classification, regression[..., 4:8], regression[..., 8]])\n else:\n detections = FilterDetections(\n name='filtered_detections',\n score_threshold=score_threshold\n )([boxes, classification])\n\n prediction_model = models.Model(inputs=[image_input], outputs=detections, name='efficientdet_p')\n return model, prediction_model\n"
]
| [
[
"tensorflow.nn.swish",
"tensorflow.keras.initializers.VarianceScaling",
"tensorflow.keras.layers.SeparableConv2D",
"tensorflow.keras.layers.Input",
"tensorflow.keras.layers.Activation",
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.models.Model",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.initializers.RandomNormal",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.layers.Concatenate",
"numpy.expand_dims"
]
]
|
shijieS/simple-faster-rcnn-pytorch | [
"a6abad5f2882d68ed1c52f4d0817411d37495d7e"
]
| [
"utils/array_tool.py"
]
| [
"\"\"\"\ntools to convert specified type\n\"\"\"\nimport torch as t\nimport numpy as np\n\n\ndef tonumpy(data):\n if isinstance(data, np.ndarray):\n return data\n if isinstance(data, t._C._TensorBase):\n return data.cpu().numpy()\n if isinstance(data, t.autograd.Variable):\n return tonumpy(data.data)\n\n\ndef totensor(data, cuda=True):\n if isinstance(data, np.ndarray):\n tensor = t.from_numpy(data)\n if isinstance(data, t._C._TensorBase):\n tensor = data\n if isinstance(data, t.autograd.Variable):\n tensor = data.data\n if cuda:\n tensor = tensor.cuda()\n return tensor\n\n\ndef tovariable(data):\n if isinstance(data, np.ndarray):\n return tovariable(totensor(data))\n if isinstance(data, t._C._TensorBase):\n return t.autograd.Variable(data)\n if isinstance(data, t.autograd.Variable):\n return data\n else:\n raise ValueError(\"UnKnow data type: %s, input should be {np.ndarray,Tensor,Variable}\" %type(data))\n\n\ndef scalar(data):\n if isinstance(data, np.ndarray):\n return data.reshape(1)[0]\n if isinstance(data, t._C._TensorBase):\n return data.view(1)[0]\n if isinstance(data, t.autograd.Variable):\n return data.data.view(1)[0]\n"
]
| [
[
"torch.autograd.Variable",
"torch.from_numpy"
]
]
|
jerabaul29/python_script_debugger | [
"eb6368a41e4f7bb1f8a255705a0274d9dd712607"
]
| [
"example/matplotlib_bugged.py"
]
| [
"import matplotlib.pyplot as plt\nimport numpy as np\n\na = np.array([1, 2, 3])\nb = np.array([2, 4, 7, 9, 9])\n\nplt.figure()\nplt.plot(a, b)\nplt.show()\n\n"
]
| [
[
"matplotlib.pyplot.show",
"numpy.array",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.figure"
]
]
|
akalia77/Grid_Surppresion | [
"c9b97c660cf62f448448f88643cc1884a1556c8e"
]
| [
"keras_test.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 7 15:17:41 2020\n\n@author: dhkim\n\"\"\"\n\nimport tensorflow as tf\n\ngpus = tf.config.experimental.list_physical_devices('GPU')\nif gpus:\n try:\n tf.config.experimental.set_memory_growth(gpus[0], True)\n except RuntimeError as e:\n # 프로그램 시작시에 메모리 증가가 설정되어야만 합니다\n print(e)\n\ntf.debugging.set_log_device_placement(True)\n\n# 텐서 생성\na = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\nb = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])\nc = tf.matmul(a, b)\n\nprint(c)\n"
]
| [
[
"tensorflow.matmul",
"tensorflow.config.experimental.set_memory_growth",
"tensorflow.debugging.set_log_device_placement",
"tensorflow.constant",
"tensorflow.config.experimental.list_physical_devices"
]
]
|
utiasSTARS/graphIK | [
"df5ca000485593540113dad42940680919dc4eb9"
]
| [
"experiments/tro2020/planar_chain.py"
]
| [
"import numpy as np\nimport networkx as nx\nimport pickle\n\nfrom graphik.graphs.graph_base import RobotPlanarGraph\nfrom graphik.robots.robot_base import RobotPlanar\nfrom graphik.utils.utils import list_to_variable_dict, make_save_string\nfrom graphik.utils.experiments import (\n run_multiple_experiments,\n process_experiment,\n scatter_error_between_solvers,\n)\n\n\nif __name__ == \"__main__\":\n # Experiment params\n dim = 2\n dof = 10\n n = dof\n seed = 8675309\n np.random.seed(seed)\n\n # Keep whichever algorithms you want to run ('trust-exact', 'Newton-CG', and 'trust-constr' are the best)\n # local_algorithms_unbounded = [\n # \"BFGS\",\n # \"CG\",\n # \"Newton-CG\",\n # \"trust-exact\"\n # ]\n # local_algorithms_bounded = [\n # \"L-BFGS-B\",\n # \"TNC\",\n # \"SLSQP\",\n # \"trust-constr\"\n # ]\n local_algorithms_unbounded = [\"trust-exact\"]\n local_algorithms_bounded = [\"trust-constr\"]\n n_goals = 10 # Number of goals\n n_init = 1 # Number of initializations to try (should be 1 for zero_init = True and for bound_smoothing = True)\n zero_init = True # True makes the angular solvers MUCH better w\n use_limits = False # Whether to use angular limits for all the solvers\n do_jacobian = False # Jacobian doesn't work well for zero_init (need a more local starting point)\n fabrik_only = (\n False # Only run the FABRIK solver (messy utility for re-running after the bug)\n )\n pose_goals = True\n symbolic = False\n if fabrik_only:\n do_jacobian = False\n if fabrik_only:\n local_algorithms = []\n else:\n local_algorithms = (\n local_algorithms_bounded if use_limits else local_algorithms_unbounded\n )\n # Solver params\n verbosity = (\n 2 # Needs to be 2 for Riemannian solver at the moment TODO: make it smarter!!\n )\n maxiter = 2000 # Most algs never max it (Riemannian ConjugateGradient often does)\n tol = 1e-9 # This is the key parameter, will be worth playing with (used for gtol except for SLSQP)\n initial_tr_radius = 1.0 # This is a key parameter for trust-constr and trust-exact.\n trigsimp = False # Not worth setting to True for n_init = 1\n if fabrik_only:\n riemannian_algorithms = []\n else:\n # riemannian_algorithms = [\"TrustRegions\", \"ConjugateGradient\"]\n riemannian_algorithms = [\"TrustRegions\"]\n solver_params = {\n \"solver\": \"BFGS\",\n \"maxiter\": maxiter,\n \"tol\": tol,\n \"initial_tr_radius\": initial_tr_radius,\n }\n bound_smoothing = True # Riemannian algs will do with and without bound smoothing when this is True\n riemannian_alg1 = riemannian_algorithms[0] if not fabrik_only else \"TrustRegions\"\n riemann_params = {\n \"solver\": riemannian_alg1,\n \"logverbosity\": verbosity,\n \"mingradnorm\": tol,\n \"maxiter\": maxiter,\n }\n jacobian_params = {\n \"tol\": tol,\n \"maxiter\": maxiter,\n \"dt\": 1e-3,\n \"method\": \"dls_inverse\",\n }\n fabrik_tol = 1e-9\n fabrik_max_iter = (\n maxiter # FABRIK is faster per iteration, might be worth changing this around\n )\n\n # Save string setup\n save_string_properties = [\n (\"dof\", dof),\n (\"bounded\", use_limits),\n (\"tol\", tol),\n (\"maxiter\", maxiter),\n (\"n_goals\", n_goals),\n (\"n_init\", n_init),\n (\"zero_init\", zero_init),\n ]\n\n if fabrik_only:\n save_string = \"results/FABRIK_only_planar_chain_\" + make_save_string(\n save_string_properties\n )\n else:\n save_string = \"results/planar_chain_\" + make_save_string(save_string_properties)\n\n # Robot params\n # link_lengths = list_to_variable_dict(np.random.rand(dof) * 2.0 + 1.0)\n link_lengths = list_to_variable_dict(np.ones(dof))\n if use_limits:\n lim = np.minimum(np.random.rand(n) * np.pi + 0.2, np.pi)\n else:\n # Try to keep the seed the same\n # _ = np.minimum(np.random.rand(n) * np.pi + 0.2, np.pi)\n lim = np.pi * np.ones(n)\n lim_u = list_to_variable_dict(lim)\n lim_l = list_to_variable_dict(-lim)\n params = {\n \"a\": link_lengths,\n \"theta\": list_to_variable_dict(len(link_lengths) * [0.0]),\n \"joint_limits_upper\": lim_u,\n \"joint_limits_lower\": lim_l,\n }\n robot = RobotPlanar(params)\n graph = RobotPlanarGraph(robot)\n\n results = run_multiple_experiments(\n graph,\n n_goals,\n n_init,\n zero_init,\n solver_params,\n riemann_params,\n jacobian_params,\n use_limits,\n verbosity,\n bound_smoothing,\n local_algorithms,\n riemannian_algorithms,\n fabrik_max_iter,\n use_symbolic=symbolic,\n trigsimp=trigsimp,\n do_jacobian=do_jacobian,\n pose_goals=True,\n )\n # results.robot = robot\n # results.seed = seed\n # pickle.dump(results, open(save_string + \"full_results.p\", \"wb\"))\n process_experiment(results)\n"
]
| [
[
"numpy.random.seed",
"numpy.ones",
"numpy.random.rand"
]
]
|
Ouranosinc/dcvar | [
"494c850164a9f553eeeba66c6cc90fe398eb2094"
]
| [
"xclim/sdba/properties.py"
]
| [
"# noqa: D205,D400\n\"\"\"\nProperties Submodule\n====================\nSDBA diagnostic tests are made up of statistical properties and measures. Properties are calculated on both simulation\nand reference datasets. They collapse the time dimension to one value.\n\nThis framework for the diagnostic tests was inspired by the [VALUE]_ project.\nStatistical Properties is the xclim term for 'indices' in the VALUE project.\n\n.. [VALUE] http://www.value-cost.eu/\n\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Callable\n\nimport numpy as np\nimport xarray as xr\nfrom boltons.funcutils import wraps\nfrom scipy import stats\nfrom statsmodels.tsa import stattools\n\nimport xclim as xc\nfrom xclim.core.formatting import update_xclim_history\nfrom xclim.core.units import convert_units_to\nfrom xclim.core.utils import uses_dask\nfrom xclim.indices import run_length as rl\nfrom xclim.indices.generic import select_resample_op\nfrom xclim.indices.stats import fit, parametric_quantile\n\nfrom .base import Grouper, map_groups, parse_group\n\nSTATISTICAL_PROPERTIES: dict[str, Callable] = {}\n\"\"\" Dictionary of all the statistical properties available.\"\"\"\n\n\ndef register_statistical_properties(\n aspect: str, seasonal: bool, annual: bool\n) -> Callable:\n \"\"\"Register statistical properties in the STATISTICAL_PROPERTIES dictionary with its aspect and time resolutions.\"\"\"\n\n def _register_statistical_properties(func):\n func.aspect = aspect\n func.seasonal = seasonal\n func.annual = annual\n allowed = []\n if annual:\n allowed.append(\"group\")\n if seasonal:\n allowed.extend([\"season\", \"month\"])\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n kwargs = parse_group(func, kwargs=kwargs, allow_only=allowed)\n out = func(*args, **kwargs)\n if \"group\" in out.dims:\n out = out.squeeze(\"group\", drop=True)\n return out\n\n STATISTICAL_PROPERTIES[func.__name__] = wrapper\n return wrapper\n\n return _register_statistical_properties\n\n\n@update_xclim_history\n@register_statistical_properties(aspect=\"marginal\", seasonal=True, annual=True)\ndef mean(da: xr.DataArray, *, group: str | Grouper = \"time\") -> xr.DataArray:\n \"\"\"Mean.\n\n Mean over all years at the time resolution.\n\n Parameters\n ----------\n da : xr.DataArray\n Variable on which to calculate the diagnostic.\n group : {'time', 'time.season', 'time.month'}\n Grouping of the output.\n E.g. If 'time.month', the temporal average is performed separately for each month.\n\n Returns\n -------\n xr.DataArray,\n Mean of the variable.\n\n Examples\n --------\n >>> pr = open_dataset(path_to_pr_file).pr\n >>> mean(da=pr, group=\"time.season\")\n \"\"\"\n attrs = da.attrs\n if group.prop != \"group\":\n da = da.groupby(group.name)\n out = da.mean(dim=group.dim)\n out.attrs.update(attrs)\n out.attrs[\"long_name\"] = \"Mean\"\n out.name = \"mean\"\n return out\n\n\n@update_xclim_history\n@register_statistical_properties(aspect=\"marginal\", seasonal=True, annual=True)\ndef var(da: xr.DataArray, *, group: str | Grouper = \"time\") -> xr.DataArray:\n \"\"\"Variance.\n\n Variance of the variable over all years at the time resolution.\n\n Parameters\n ----------\n da : xr.DataArray\n Variable on which to calculate the diagnostic.\n group : {'time', 'time.season', 'time.month'}\n Grouping of the output.\n E.g. If 'time.month', the variance is performed separately for each month.\n\n Returns\n -------\n xr.DataArray\n Variance of the variable.\n\n Examples\n --------\n >>> pr = open_dataset(path_to_pr_file).pr\n >>> var(da=pr, group=\"time.season\")\n \"\"\"\n attrs = da.attrs\n if group.prop != \"group\":\n da = da.groupby(group.name)\n out = da.var(dim=group.dim)\n out.attrs.update(attrs)\n out.attrs[\"long_name\"] = \"Variance\"\n u = xc.core.units.units2pint(attrs[\"units\"])\n u2 = u**2\n out.attrs[\"units\"] = xc.core.units.pint2cfunits(u2)\n out.name = \"variance\"\n return out\n\n\n@update_xclim_history\n@register_statistical_properties(aspect=\"marginal\", seasonal=True, annual=True)\ndef skewness(da: xr.DataArray, *, group: str | Grouper = \"time\") -> xr.DataArray:\n \"\"\"Skewness.\n\n Skewness of the distribution of the variable over all years at the time resolution.\n\n Parameters\n ----------\n da : xr.DataArray\n Variable on which to calculate the diagnostic.\n group : {'time', 'time.season', 'time.month'}\n Grouping of the output.\n E.g. If 'time.month', the skewness is performed separately for each month.\n\n Returns\n -------\n xr.DataArray\n Skewness of the variable.\n\n Examples\n --------\n >>> pr = open_dataset(path_to_pr_file).pr\n >>> skewness(da=pr, group=\"time.season\")\n\n See Also\n --------\n scipy.stats.skew\n \"\"\"\n attrs = da.attrs\n if group.prop != \"group\":\n da = da.groupby(group.name)\n out = xr.apply_ufunc(\n stats.skew,\n da,\n input_core_dims=[[group.dim]],\n vectorize=True,\n dask=\"parallelized\",\n )\n out.attrs.update(attrs)\n out.attrs[\"long_name\"] = \"Skewness\"\n out.attrs[\"units\"] = \"\"\n out.name = \"skewness\"\n return out\n\n\n@update_xclim_history\n@register_statistical_properties(aspect=\"marginal\", seasonal=True, annual=True)\ndef quantile(\n da: xr.DataArray, *, q: float = 0.98, group: str | Grouper = \"time\"\n) -> xr.DataArray:\n \"\"\"Quantile.\n\n Returns the quantile q of the distribution of the variable over all years at the time resolution.\n\n Parameters\n ----------\n da : xr.DataArray\n Variable on which to calculate the diagnostic.\n q: float\n Quantile to be calculated. Should be between 0 and 1.\n group : {'time', 'time.season', 'time.month'}\n Grouping of the output.\n E.g. If 'time.month', the quantile is computed separately for each month.\n\n Returns\n -------\n xr.DataArray\n Quantile {q} of the variable.\n\n Examples\n --------\n >>> pr = open_dataset(path_to_pr_file).pr\n >>> quantile(da=pr, q=0.9, group=\"time.season\")\n \"\"\"\n attrs = da.attrs\n if group.prop != \"group\":\n da = da.groupby(group.name)\n out = da.quantile(q, dim=group.dim, keep_attrs=True).drop_vars(\"quantile\")\n out.attrs.update(attrs)\n out.attrs[\"long_name\"] = f\"Quantile {q}\"\n out.name = \"quantile\"\n return out\n\n\n@update_xclim_history\n@register_statistical_properties(aspect=\"temporal\", seasonal=True, annual=True)\ndef spell_length_distribution(\n da: xr.DataArray,\n *,\n method: str = \"amount\",\n op: str = \">=\",\n thresh: str | float = \"1 mm d-1\",\n stat: str = \"mean\",\n group: str | Grouper = \"time\",\n) -> xr.DataArray:\n \"\"\"Spell length distribution.\n\n Statistic of spell length distribution when the variable respects a condition (defined by an operation, a method and\n a threshold).\n\n Parameters\n ----------\n da : xr.DataArray\n Variable on which to calculate the diagnostic.\n method: {'amount', 'quantile'}\n Method to choose the threshold.\n 'amount': The threshold is directly the quantity in {thresh}. It needs to have the same units as {da}.\n 'quantile': The threshold is calculated as the quantile {thresh} of the distribution.\n op: {\">\", \"<\", \">=\", \"<=\"}\n Operation to verify the condition for a spell.\n The condition for a spell is variable {op} threshold.\n thresh: str or float\n Threshold on which to evaluate the condition to have a spell.\n Str with units if the method is \"amount\".\n Float of the quantile if the method is \"quantile\".\n stat: {'mean','max','min'}\n Statistics to apply to the resampled input at the {group} (e.g. 1-31 Jan 1980)\n and then over all years (e.g. Jan 1980-2010)\n group : {'time', 'time.season', 'time.month'}\n Grouping of the output.\n E.g. If 'time.month', the spell lengths are coputed separately for each month.\n\n Returns\n -------\n xr.DataArray\n {stat} of spell length distribution when the variable is {op} the {method} {thresh}.\n\n Examples\n --------\n >>> pr = open_dataset(path_to_pr_file).pr\n >>> spell_length_distribution(da=pr, op=\"<\", thresh=\"1mm d-1\", group=\"time.season\")\n \"\"\"\n attrs = da.attrs\n ops = {\">\": np.greater, \"<\": np.less, \">=\": np.greater_equal, \"<=\": np.less_equal}\n\n @map_groups(out=[Grouper.PROP], main_only=True)\n def _spell_stats(ds, *, dim, method, thresh, op, freq, stat):\n # PB: This prevents an import error in the distributed dask scheduler, but I don't know why.\n import xarray.core.resample_cftime # noqa\n\n da = ds.data\n mask = ~(da.isel({dim: 0}).isnull()).drop_vars(\n dim\n ) # mask of the ocean with NaNs\n if method == \"quantile\":\n thresh = da.quantile(thresh, dim=dim).drop_vars(\"quantile\")\n\n cond = op(da, thresh)\n out = cond.resample(time=freq).map(rl.rle_statistics, dim=dim, reducer=stat)\n out = getattr(out, stat)(dim=dim)\n out = out.where(mask)\n return out.rename(\"out\").to_dataset()\n\n # threshold is an amount that will be converted to the right units\n if method == \"amount\":\n thresh = convert_units_to(thresh, da)\n elif method != \"quantile\":\n raise ValueError(\n f\"{method} is not a valid method. Choose 'amount' or 'quantile'.\"\n )\n\n out = _spell_stats(\n da.rename(\"data\").to_dataset(),\n group=group,\n method=method,\n thresh=thresh,\n op=ops[op],\n freq=group.freq,\n stat=stat,\n ).out\n out.attrs.update(attrs)\n out.attrs[\n \"long_name\"\n ] = f\"{stat} of spell length when input variable {op} {method} {thresh}\"\n out.name = \"spell_length_distribution\"\n out.attrs[\"units\"] = \"day\"\n return out\n\n\n@update_xclim_history\n@register_statistical_properties(aspect=\"temporal\", seasonal=True, annual=False)\ndef acf(\n da: xr.DataArray, *, lag: int = 1, group: str | Grouper = \"time.season\"\n) -> xr.DataArray:\n \"\"\"Autocorrelation function.\n\n Autocorrelation with a lag over a time resolution and averaged over all years.\n\n Parameters\n ----------\n da : xr.DataArray\n Variable on which to calculate the diagnostic.\n lag: int\n Lag.\n group : {'time.season', 'time.month'}\n Grouping of the output.\n E.g. If 'time.month', the autocorrelation is calculated over each month separately for all years.\n Then, the autocorrelation for all Jan/Feb/... is averaged over all years, giving 12 outputs for each grid point.\n\n Returns\n -------\n xr.DataArray\n lag-{lag} autocorrelation of the variable over a {group.prop} and averaged over all years.\n\n See Also\n --------\n statsmodels.tsa.stattools.acf\n\n References\n ----------\n Alavoine M., and Grenier P. (under review) The distinct problems of physical inconsistency and of multivariate bias potentially involved in the statistical adjustment of climate simulations. International Journal of Climatology, submitted on September 19th 2021. (Preprint: https://doi.org/10.31223/X5C34C)\n\n Examples\n --------\n >>> from xclim.testing import open_dataset\n >>> pr = open_dataset(path_to_pr_file).pr\n >>> acf(da=pr, lag=3, group=\"time.season\")\n \"\"\"\n attrs = da.attrs\n\n def acf_last(x, nlags):\n # noqa: D403\n \"\"\"statsmodels acf calculates acf for lag 0 to nlags, this return only the last one.\"\"\"\n # As we resample + group, timeseries are quite short and fft=False seems more performant\n out_last = stattools.acf(x, nlags=nlags, fft=False)\n return out_last[-1]\n\n @map_groups(out=[Grouper.PROP], main_only=True)\n def _acf(ds, *, dim, lag, freq):\n out = xr.apply_ufunc(\n acf_last,\n ds.dat.resample({dim: freq}),\n input_core_dims=[[dim]],\n vectorize=True,\n kwargs={\"nlags\": lag},\n )\n out = out.mean(\"__resample_dim__\")\n return out.rename(\"out\").to_dataset()\n\n out = _acf(da.rename(\"dat\").to_dataset(), group=group, lag=lag, freq=group.freq).out\n out.attrs.update(attrs)\n out.attrs[\"long_name\"] = f\"lag-{lag} autocorrelation\"\n out.attrs[\"units\"] = \"\"\n out.name = \"acf\"\n return out\n\n\n# group was kept even though \"time\" is the only acceptable arg to keep the signature similar to other properties\n@update_xclim_history\n@register_statistical_properties(aspect=\"temporal\", seasonal=False, annual=True)\ndef annual_cycle_amplitude(\n da: xr.DataArray,\n *,\n amplitude_type: str = \"absolute\",\n group: str | Grouper = \"time\",\n) -> xr.DataArray:\n r\"\"\"Annual cycle amplitude.\n\n The amplitudes of the annual cycle are calculated for each year, then averaged over the all years.\n\n Parameters\n ----------\n da : xr.DataArray\n Variable on which to calculate the diagnostic.\n amplitude_type: {'absolute','relative'}\n Type of amplitude.\n 'absolute' is the peak-to-peak amplitude. (max - min).\n 'relative' is a relative percentage. 100 * (max - min) / mean (Recommended for precipitation).\n\n Returns\n -------\n xr.DataArray\n {amplitude_type} amplitude of the annual cycle.\n\n Examples\n --------\n >>> pr = open_dataset(path_to_pr_file).pr\n >>> annual_cycle_amplitude(da=pr, amplitude_type=\"relative\")\n \"\"\"\n attrs = da.attrs\n da = da.resample({group.dim: group.freq})\n # amplitude\n amp = da.max(dim=group.dim) - da.min(dim=group.dim)\n amp.attrs.update(attrs)\n amp.attrs[\"units\"] = xc.core.units.ensure_delta(attrs[\"units\"])\n if amplitude_type == \"relative\":\n amp = amp * 100 / da.mean(dim=group.dim, keep_attrs=True)\n amp.attrs[\"units\"] = \"%\"\n amp = amp.mean(dim=group.dim, keep_attrs=True)\n amp.attrs[\"long_name\"] = f\"{amplitude_type} amplitude of the annual cycle\"\n amp.name = \"annual_cycle_amplitude\"\n return amp\n\n\n# group was kept even though \"time\" is the only acceptable arg to keep the signature similar to other properties\n@update_xclim_history\n@register_statistical_properties(aspect=\"temporal\", seasonal=False, annual=True)\ndef annual_cycle_phase(\n da: xr.DataArray, *, group: str | Grouper = \"time\"\n) -> xr.DataArray:\n \"\"\"Annual cycle phase.\n\n The phases of the annual cycle are calculated for each year, then averaged over the all years.\n\n Parameters\n ----------\n da : xr.DataArray\n Variable on which to calculate the diagnostic.\n group : {\"time\", 'time.season', 'time.month'}\n Grouping of the output. Default: \"time\".\n\n Returns\n -------\n xr.DataArray\n Phase of the annual cycle. The position (day-of-year) of the maximal value.\n\n Examples\n --------\n >>> pr = open_dataset(path_to_pr_file).pr\n >>> annual_cycle_phase(da=pr)\n \"\"\"\n attrs = da.attrs\n mask = ~(da.isel({group.dim: 0}).isnull()).drop_vars(\n group.dim\n ) # mask of the ocean with NaNs\n da = da.resample({group.dim: group.freq})\n\n # +1 at the end to go from index to doy\n phase = (\n xr.apply_ufunc(\n np.argmax,\n da,\n input_core_dims=[[group.dim]],\n vectorize=True,\n dask=\"parallelized\",\n )\n + 1\n )\n phase = phase.mean(dim=\"__resample_dim__\")\n # put nan where there was nan in the input, if not phase = 0 + 1\n phase = phase.where(mask, np.nan)\n phase.attrs.update(attrs)\n phase.attrs[\"long_name\"] = \"Phase of the annual cycle\"\n phase.attrs.update(units=\"\", is_dayofyear=1)\n phase.name = \"annual_cycle_phase\"\n return phase\n\n\n@update_xclim_history\n@register_statistical_properties(aspect=\"multivariate\", seasonal=True, annual=True)\ndef corr_btw_var(\n da1: xr.DataArray,\n da2: xr.DataArray,\n *,\n corr_type: str = \"Spearman\",\n group: str | Grouper = \"time\",\n output: str = \"correlation\",\n) -> xr.DataArray:\n r\"\"\"Correlation between two variables.\n\n Spearman or Pearson correlation coefficient between two variables at the time resolution.\n\n Parameters\n ----------\n da1 : xr.DataArray\n First variable on which to calculate the diagnostic.\n da2 : xr.DataArray\n Second variable on which to calculate the diagnostic.\n corr_type: {'Pearson','Spearman'}\n Type of correlation to calculate.\n output: {'correlation', 'pvalue'}\n Wheter to return the correlation coefficient or the p-value.\n group : {'time', 'time.season', 'time.month'}\n Grouping of the output.\n Eg. For 'time.month', the correlation would be calculated on each month separately,\n but with all the years together.\n\n Returns\n -------\n xr.DataArray\n {corr_type} correlation coefficient\n\n Examples\n --------\n >>> pr = open_dataset(path_to_pr_file).pr\n >>> tasmax = open_dataset(\"NRCANdaily/nrcan_canada_daily_tasmax_1990.nc\").tasmax\n >>> corr_btw_var(da1=pr, da2=tasmax, group=\"time.season\")\n \"\"\"\n attrs1 = da1.attrs\n\n if corr_type.lower() not in {\"pearson\", \"spearman\"}:\n raise ValueError(\n f\"{corr_type} is not a valid type. Choose 'Pearson' or 'Spearman'.\"\n )\n\n index = {\"correlation\": 0, \"pvalue\": 1}[output]\n\n def _first_output_1d(a, b, index, corr_type):\n \"\"\"Only keep the correlation (first output) from the scipy function.\"\"\"\n if corr_type == \"Pearson\":\n # for points in the water with NaNs\n if np.isnan(a).any():\n return np.nan\n return stats.pearsonr(a, b)[index]\n return stats.spearmanr(a, b, nan_policy=\"propagate\")[index]\n\n @map_groups(out=[Grouper.PROP], main_only=True)\n def _first_output(ds, *, dim, index, corr_type):\n out = xr.apply_ufunc(\n _first_output_1d,\n ds.a,\n ds.b,\n input_core_dims=[[dim], [dim]],\n vectorize=True,\n dask=\"parallelized\",\n kwargs={\"index\": index, \"corr_type\": corr_type},\n )\n return out.rename(\"out\").to_dataset()\n\n out = _first_output(\n xr.Dataset({\"a\": da1, \"b\": da2}), group=group, index=index, corr_type=corr_type\n ).out\n out.attrs.update(attrs1)\n out.attrs[\"long_name\"] = f\"{corr_type} correlation coefficient\"\n out.attrs[\"units\"] = \"\"\n out.name = \"corr_btw_varr\"\n return out\n\n\n@update_xclim_history\n@register_statistical_properties(aspect=\"temporal\", seasonal=True, annual=True)\ndef relative_frequency(\n da: xr.DataArray,\n *,\n op: str = \">=\",\n thresh: str = \"1mm d-1\",\n group: str | Grouper = \"time\",\n) -> xr.DataArray:\n \"\"\"Relative Frequency.\n\n Relative Frequency of days with variable respecting a condition (defined by an operation and a threshold) at the\n time resolution. The relative freqency is the number of days that satisfy the condition divided by the total number\n of days.\n\n Parameters\n ----------\n da : xr.DataArray\n Variable on which to calculate the diagnostic.\n op: {\">\", \"<\", \">=\", \"<=\"}\n Operation to verify the condition.\n The condition is variable {op} threshold.\n thresh: str\n Threshold on which to evaluate the condition.\n group : {'time', 'time.season', 'time.month'}\n Grouping on the output.\n Eg. For 'time.month', the relative frequency would be calculated on each month,\n with all years included.\n\n Returns\n -------\n xr.DataArray\n Relative frequency of the variable.\n\n Examples\n --------\n >>> tasmax = open_dataset(path_to_tasmax_file).tasmax\n >>> relative_frequency(da=tasmax, op=\"<\", thresh=\"0 degC\", group=\"time.season\")\n \"\"\"\n attrs = da.attrs\n mask = ~(da.isel({group.dim: 0}).isnull()).drop_vars(\n group.dim\n ) # mask of the ocean with NaNs\n ops = {\">\": np.greater, \"<\": np.less, \">=\": np.greater_equal, \"<=\": np.less_equal}\n t = convert_units_to(thresh, da)\n length = da.sizes[group.dim]\n cond = ops[op](da, t)\n if group.prop != \"group\": # change the time resolution if necessary\n cond = cond.groupby(group.name)\n # length of the groupBy groups\n length = np.array([len(v) for k, v in cond.groups.items()])\n for i in range(da.ndim - 1): # add empty dimension(s) to match input\n length = np.expand_dims(length, axis=-1)\n # count days with the condition and divide by total nb of days\n out = cond.sum(dim=group.dim, skipna=False) / length\n out = out.where(mask, np.nan)\n out.attrs.update(attrs)\n out.attrs[\n \"long_name\"\n ] = f\"Relative frequency of days with input variable {op} {thresh}\"\n out.attrs[\"units\"] = \"\"\n out.name = \"relative frequency\"\n return out\n\n\n@update_xclim_history\n@register_statistical_properties(aspect=\"temporal\", seasonal=True, annual=True)\ndef trend(\n da: xr.DataArray,\n *,\n group: str | Grouper = \"time\",\n output: str = \"slope\",\n) -> xr.DataArray:\n \"\"\"Linear Trend.\n\n The data is averaged over each time resolution and the interannual trend is returned.\n\n Parameters\n ----------\n da : xr.DataArray\n Variable on which to calculate the diagnostic.\n output: {'slope', 'pvalue'}\n Attributes of the linear regression to return.\n 'slope' is the slope of the regression line.\n 'pvalue' is for a hypothesis test whose null hypothesis is that the slope is zero,\n using Wald Test with t-distribution of the test statistic.\n group : {'time', 'time.season', 'time.month'}\n Grouping on the output.\n\n Returns\n -------\n xr.DataArray\n Trend of the variable.\n\n See Also\n --------\n scipy.stats.linregress\n\n numpy.polyfit\n\n Examples\n --------\n >>> tas = open_dataset(path_to_tas_file).tas\n >>> trend(da=tas, group=\"time.season\")\n \"\"\"\n attrs = da.attrs\n da = da.resample({group.dim: group.freq}) # separate all the {group}\n da_mean = da.mean(dim=group.dim) # avg over all {group}\n if uses_dask(da_mean):\n da_mean = da_mean.chunk({group.dim: -1})\n if group.prop != \"group\":\n da_mean = da_mean.groupby(group.name) # group all month/season together\n\n def modified_lr(\n x,\n ): # modify linregress to fit into apply_ufunc and only return slope\n return getattr(stats.linregress(list(range(len(x))), x), output)\n\n out = xr.apply_ufunc(\n modified_lr,\n da_mean,\n input_core_dims=[[group.dim]],\n vectorize=True,\n dask=\"parallelized\",\n )\n out.attrs.update(attrs)\n out.attrs[\"long_name\"] = f\"{output} of the interannual linear trend\"\n out.attrs[\"units\"] = f\"{attrs['units']}/year\"\n out.name = \"trend\"\n return out\n\n\n@update_xclim_history\n@register_statistical_properties(aspect=\"marginal\", seasonal=True, annual=True)\ndef return_value(\n da: xr.DataArray,\n *,\n period: int = 20,\n op: str = \"max\",\n method: str = \"ML\",\n group: str | Grouper = \"time\",\n) -> xr.DataArray:\n r\"\"\"Return value.\n\n Return the value corresponding to a return period.\n On average, the return value will be exceeded (or not exceed for op='min') every return period (eg. 20 years).\n The return value is computed by first extracting the variable annual maxima/minima,\n fitting a statistical distribution to the maxima/minima,\n then estimating the percentile associated with the return period (eg. 95th percentile (1/20) for 20 years)\n\n Parameters\n ----------\n da : xr.DataArray\n Variable on which to calculate the diagnostic.\n period: int\n Return period. Number of years over which to check if the value is exceeded (or not for op='min').\n op: {'max','min'}\n Whether we are looking for a probability of exceedance ('max', right side of the distribution)\n or a probability of non-exceedance (min, left side of the distribution).\n method : {\"ML\", \"PWM\"}\n Fitting method, either maximum likelihood (ML) or probability weighted moments (PWM), also called L-Moments.\n The PWM method is usually more robust to outliers. However, it requires the lmoments3 libraryto be installed\n from the `develop` branch.\n ``pip install git+https://github.com/OpenHydrology/lmoments3.git@develop#egg=lmoments3``\n group : {'time', 'time.season', 'time.month'}\n Grouping of the output. A distribution of the extremums is done for each group.\n\n Returns\n -------\n xr.DataArray\n {period}-{group} {op} return level of the variable.\n\n Examples\n --------\n >>> tas = open_dataset(path_to_tas_file).tas\n >>> return_value(da=tas, group=\"time.season\")\n \"\"\"\n\n @map_groups(out=[Grouper.PROP], main_only=True)\n def frequency_analysis_method(ds, *, dim, method):\n sub = select_resample_op(ds.x, op=op)\n params = fit(sub, dist=\"genextreme\", method=method)\n out = parametric_quantile(params, q=1 - 1.0 / period)\n return out.isel(quantile=0, drop=True).rename(\"out\").to_dataset()\n\n out = frequency_analysis_method(\n da.rename(\"x\").to_dataset(), method=method, group=group\n ).out\n out.attrs.update(da.attrs)\n out.attrs[\"long_name\"] = f\"{period}-{group.prop_name} {op} return level\"\n out.name = \"return_value\"\n return out\n"
]
| [
[
"scipy.stats.spearmanr",
"numpy.isnan",
"numpy.expand_dims",
"scipy.stats.pearsonr"
]
]
|
Hcnaeg/DI-engine | [
"aba0c629f87649854091e9e59d948f83962e3e1e"
]
| [
"ding/entry/serial_entry_guided_cost.py"
]
| [
"from ding.policy.base_policy import Policy\nfrom typing import Union, Optional, List, Any, Tuple\nimport os\nimport copy\nimport torch\nimport logging\nfrom functools import partial\nfrom tensorboardX import SummaryWriter\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom ding.envs import get_vec_env_setting, create_env_manager\nfrom ding.worker import BaseLearner, InteractionSerialEvaluator, BaseSerialCommander, create_buffer, \\\n create_serial_collector\nfrom ding.config import read_config, compile_config\nfrom ding.policy import create_policy\nfrom ding.utils import set_pkg_seed, save_file\nfrom ding.reward_model import create_reward_model\nfrom .utils import random_collect\n\n\ndef serial_pipeline_guided_cost(\n input_cfg: Union[str, Tuple[dict, dict]],\n seed: int = 0,\n env_setting: Optional[List[Any]] = None,\n model: Optional[torch.nn.Module] = None,\n expert_model: Optional[torch.nn.Module] = None,\n max_iterations: Optional[int] = int(1e10),\n) -> 'Policy': # noqa\n \"\"\"\n Overview:\n Serial pipeline guided cost: we create this serial pipeline in order to\\\n implement guided cost learning in DI-engine. For now, we support the following envs\\\n Cartpole, Lunarlander, Hopper, Halfcheetah, Walker2d. The demonstration\\\n data come from the expert model. We use a well-trained model to \\\n generate demonstration data online\n Arguments:\n - input_cfg (:obj:`Union[str, Tuple[dict, dict]]`): Config in dict type. \\\n ``str`` type means config file path. \\\n ``Tuple[dict, dict]`` type means [user_config, create_cfg].\n - seed (:obj:`int`): Random seed.\n - env_setting (:obj:`Optional[List[Any]]`): A list with 3 elements: \\\n ``BaseEnv`` subclass, collector env config, and evaluator env config.\n - model (:obj:`Optional[torch.nn.Module]`): Instance of torch.nn.Module.\n - expert_model (:obj:`Optional[torch.nn.Module]`): Instance of torch.nn.Module.\\\n The default model is DQN(**cfg.policy.model)\n - max_iterations (:obj:`Optional[torch.nn.Module]`): Learner's max iteration. Pipeline will stop \\\n when reaching this iteration.\n Returns:\n - policy (:obj:`Policy`): Converged policy.\n \"\"\"\n if isinstance(input_cfg, str):\n cfg, create_cfg = read_config(input_cfg)\n else:\n cfg, create_cfg = input_cfg\n create_cfg.policy.type = create_cfg.policy.type + '_command'\n env_fn = None if env_setting is None else env_setting[0]\n cfg = compile_config(cfg, seed=seed, env=env_fn, auto=True, create_cfg=create_cfg, save_cfg=True)\n # Create main components: env, policy\n if env_setting is None:\n env_fn, collector_env_cfg, evaluator_env_cfg = get_vec_env_setting(cfg.env)\n else:\n env_fn, collector_env_cfg, evaluator_env_cfg = env_setting\n collector_env = create_env_manager(cfg.env.manager, [partial(env_fn, cfg=c) for c in collector_env_cfg])\n expert_collector_env = create_env_manager(cfg.env.manager, [partial(env_fn, cfg=c) for c in collector_env_cfg])\n evaluator_env = create_env_manager(cfg.env.manager, [partial(env_fn, cfg=c) for c in evaluator_env_cfg])\n expert_collector_env.seed(cfg.seed)\n collector_env.seed(cfg.seed)\n evaluator_env.seed(cfg.seed, dynamic_seed=False)\n expert_policy = create_policy(cfg.policy, model=expert_model, enable_field=['learn', 'collect'])\n set_pkg_seed(cfg.seed, use_cuda=cfg.policy.cuda)\n policy = create_policy(cfg.policy, model=model, enable_field=['learn', 'collect', 'eval', 'command'])\n expert_policy.collect_mode.load_state_dict(\n torch.load(cfg.policy.collect.demonstration_info_path, map_location='cpu')\n )\n # Create worker components: learner, collector, evaluator, replay buffer, commander.\n tb_logger = SummaryWriter(os.path.join('./{}/log/'.format(cfg.exp_name), 'serial'))\n learner = BaseLearner(cfg.policy.learn.learner, policy.learn_mode, tb_logger, exp_name=cfg.exp_name)\n collector = create_serial_collector(\n cfg.policy.collect.collector,\n env=collector_env,\n policy=policy.collect_mode,\n tb_logger=tb_logger,\n exp_name=cfg.exp_name\n )\n expert_collector = create_serial_collector(\n cfg.policy.collect.collector,\n env=expert_collector_env,\n policy=expert_policy.collect_mode,\n tb_logger=tb_logger,\n exp_name=cfg.exp_name\n )\n evaluator = InteractionSerialEvaluator(\n cfg.policy.eval.evaluator, evaluator_env, policy.eval_mode, tb_logger, exp_name=cfg.exp_name\n )\n replay_buffer = create_buffer(cfg.policy.other.replay_buffer, tb_logger=tb_logger, exp_name=cfg.exp_name)\n expert_buffer = create_buffer(cfg.policy.other.replay_buffer, tb_logger=tb_logger, exp_name=cfg.exp_name)\n commander = BaseSerialCommander(\n cfg.policy.other.commander, learner, collector, evaluator, replay_buffer, policy.command_mode\n )\n\n reward_model = create_reward_model(cfg.reward_model, policy.collect_mode.get_attribute('device'), tb_logger)\n # ==========\n # Main loop\n # ==========\n # Learner's before_run hook.\n learner.call_hook('before_run')\n\n # Accumulate plenty of data at the beginning of training.\n if cfg.policy.get('random_collect_size', 0) > 0:\n random_collect(cfg.policy, policy, collector, collector_env, commander, replay_buffer)\n for _ in range(max_iterations):\n collect_kwargs = commander.step()\n # Evaluate policy performance\n if evaluator.should_eval(learner.train_iter):\n stop, reward = evaluator.eval(learner.save_checkpoint, learner.train_iter, collector.envstep)\n if stop:\n break\n # Collect data by default config n_sample/n_episode\n new_data = collector.collect(train_iter=learner.train_iter, policy_kwargs=collect_kwargs)\n train_data = copy.deepcopy(new_data)\n expert_data = expert_collector.collect(train_iter=learner.train_iter, policy_kwargs=collect_kwargs)\n replay_buffer.push(new_data, cur_collector_envstep=collector.envstep)\n expert_buffer.push(expert_data, cur_collector_envstep=expert_collector.envstep)\n # Learn policy from collected data\n for i in range(cfg.reward_model.update_per_collect):\n expert_demo = expert_buffer.sample(cfg.reward_model.batch_size, learner.train_iter)\n samp = replay_buffer.sample(cfg.reward_model.batch_size, learner.train_iter)\n reward_model.train(expert_demo, samp, learner.train_iter, collector.envstep)\n for i in range(cfg.policy.learn.update_per_collect):\n # Learner will train ``update_per_collect`` times in one iteration.\n #train_data = replay_buffer.sample(learner.policy.get_attribute('batch_size'), learner.train_iter)\n train_data = train_data\n reward_model.estimate(train_data)\n if train_data is None:\n # It is possible that replay buffer's data count is too few to train ``update_per_collect`` times\n logging.warning(\n \"Replay buffer's data can only train for {} steps. \".format(i) +\n \"You can modify data collect config, e.g. increasing n_sample, n_episode.\"\n )\n break\n learner.train(train_data, collector.envstep)\n if learner.policy.get_attribute('priority'):\n replay_buffer.update(learner.priority_info)\n if cfg.policy.on_policy:\n # On-policy algorithm must clear the replay buffer.\n replay_buffer.clear()\n dirname = cfg.exp_name + '/reward_model'\n if not os.path.exists(dirname):\n try:\n os.mkdir(dirname)\n except FileExistsError:\n pass\n if learner.train_iter % cfg.reward_model.store_model_every_n_train == 0:\n #if learner.train_iter%5000 == 0:\n path = os.path.join(dirname, 'iteration_{}.pth.tar'.format(learner.train_iter))\n state_dict = reward_model.state_dict_reward_model()\n save_file(path, state_dict)\n path = os.path.join(dirname, 'final_model.pth.tar')\n state_dict = reward_model.state_dict_reward_model()\n save_file(path, state_dict)\n # Learner's after_run hook.\n learner.call_hook('after_run')\n return policy\n"
]
| [
[
"torch.load"
]
]
|
mpia3/SysAg | [
"ba2a95d401f86d2db82a2f97e44c2bcd778adadf"
]
| [
"MaskDetection/utils/anchor_decode.py"
]
| [
"# -*- coding:utf-8 -*-\nimport numpy as np\n\n\ndef decode_bbox(anchors, raw_outputs, variances=[0.1, 0.1, 0.2, 0.2]):\n '''\n Decode the actual bbox according to the anchors.\n the anchor value order is:[xmin,ymin, xmax, ymax]\n :param anchors: numpy array with shape [batch, num_anchors, 4]\n :param raw_outputs: numpy array with the same shape with anchors\n :param variances: list of float, default=[0.1, 0.1, 0.2, 0.2]\n :return:\n '''\n anchor_centers_x = (anchors[:, :, 0:1] + anchors[:, :, 2:3]) / 2\n anchor_centers_y = (anchors[:, :, 1:2] + anchors[:, :, 3:]) / 2\n anchors_w = anchors[:, :, 2:3] - anchors[:, :, 0:1]\n anchors_h = anchors[:, :, 3:] - anchors[:, :, 1:2]\n raw_outputs_rescale = raw_outputs * np.array(variances)\n predict_center_x = raw_outputs_rescale[:, :, 0:1] * anchors_w + anchor_centers_x\n predict_center_y = raw_outputs_rescale[:, :, 1:2] * anchors_h + anchor_centers_y\n predict_w = np.exp(raw_outputs_rescale[:, :, 2:3]) * anchors_w\n predict_h = np.exp(raw_outputs_rescale[:, :, 3:]) * anchors_h\n predict_xmin = predict_center_x - predict_w / 2\n predict_ymin = predict_center_y - predict_h / 2\n predict_xmax = predict_center_x + predict_w / 2\n predict_ymax = predict_center_y + predict_h / 2\n predict_bbox = np.concatenate([predict_xmin, predict_ymin, predict_xmax, predict_ymax], axis=-1)\n return predict_bbox\n"
]
| [
[
"numpy.concatenate",
"numpy.array",
"numpy.exp"
]
]
|
PlainConcepts/ARLIE | [
"10b8992b0820e08fb649805e8bc12ff0509d78d9"
]
| [
"arlie/arlie/envs/lunar_lander/env.py"
]
| [
"import os\nimport subprocess\nimport time\n\nimport grpc\nimport gym\nimport numpy as np\nfrom arlie.envs.base_reward import BaseReward\nfrom arlie.envs.lunar_lander.python_protos import Lunar3D_pb2, Lunar3D_pb2_grpc\nfrom gym import spaces\n\n\nclass LunarLander(gym.Env):\n\n metadata = {\"render.modes\": [\"human\"]}\n # reward_range = (-100.0, 100.0)\n # spec = None\n\n # keys map for Human model\n keyboard_map = {\n \"space\": 7,\n \"down\": 4,\n \"up\": 3,\n \"left\": 6,\n \"right\": 5,\n \"z\": 2,\n \"x\": 1,\n }\n\n def __init__(self):\n self.channel = None\n self.stub = None\n\n self._seed = 0\n\n # elapsed_t = 0.0\n # count = 0.0\n\n def step(self, action):\n # self.count += 1.0\n # _t = time.time()\n request = Lunar3D_pb2.Action(EngineAction=action)\n result = self.stub.PerformAction(request)\n # self.elapsed_t += time.time() - _t\n\n # if self.count % 1000 == 0:\n # print(\"Elapsed time: {} ms\".format(self.elapsed_t / self.count))\n\n observation = [\n getattr(result.observation, field.name)\n for field in result.observation.DESCRIPTOR.fields\n ]\n reward, done = self.reward.evaluate(observation, action, result.done)\n return (\n np.array(observation, dtype=np.float32),\n reward,\n done,\n {\"failed_landing\": result.done},\n )\n\n def reset(self):\n result = self.stub.Reset(Lunar3D_pb2.ServiceMessage())\n state = [getattr(result, field.name) for field in result.DESCRIPTOR.fields]\n self.reward.reset()\n return np.array(state, dtype=np.float32)\n\n def render(self, mode=\"human\"):\n self.stub.Render(Lunar3D_pb2.ServiceMessage())\n\n def close(self):\n self.process.terminate()\n\n def seed(self, seed):\n self._seed = seed\n\n def launch(\n self,\n reward=None,\n seed=0,\n host=\"localhost\",\n port=3000,\n render_mode=True,\n reset_mode=\"center\",\n ):\n if reward is None:\n from arlie.envs.lunar_lander.reward import LunarLanderReward\n\n self.reward = LunarLanderReward()\n elif not isinstance(reward, BaseReward):\n print(\"Reward must inheritate from 'BaseReward'\")\n exit(-1)\n else:\n self.reward = reward\n\n self.host = host\n self.port = port\n self.render_mode = render_mode\n self.reset_mode = reset_mode\n self.seed(seed)\n\n self.__init_connection()\n self.channel = grpc.insecure_channel(\"{}:{}\".format(self.host, self.port))\n self.stub = Lunar3D_pb2_grpc.Lunar3DServiceStub(self.channel)\n\n act_size = self.stub.GetActionDim(Lunar3D_pb2.ServiceMessage()).value # 8\n obs_size = self.stub.GetObservationDim(Lunar3D_pb2.ServiceMessage()).value # 16\n\n self.action_space = spaces.Discrete(act_size)\n # useful range is -1 .. +1, but spikes can be higher\n self.observation_space = spaces.Box(\n -np.inf, np.inf, shape=(obs_size,), dtype=np.float32\n )\n\n def __init_connection(self):\n path = os.path.dirname(os.path.abspath(__file__))\n cmd = os.path.join(path, \"LunarLander\", \"RLEnvs.exe\")\n self.process = subprocess.Popen(\n [\n cmd,\n \"server\",\n \"{}\".format(self.port),\n \"{}\".format(self.render_mode),\n \"{}\".format(self.reset_mode),\n \"{}\".format(self._seed),\n ],\n stdout=subprocess.PIPE,\n )\n time.sleep(5)\n\n @staticmethod\n def parse_observation(observation):\n return {\n \"position\": observation[0:3], # [X, Y, Z]\n \"velocity\": observation[3:6], # [X, Y, Z]\n \"angle\": observation[6:9], # [X, Y, Z]\n \"angular_velocity\": observation[9:12], # [X, Y, Z]\n \"leg_contact\": observation[12:16], # [Front, Back, Left, Right]\n }\n"
]
| [
[
"numpy.array"
]
]
|
CJCascalheira/ml-gender-dysphoria | [
"2b20c19020342bd5b3c09aa0c107f26770aa541c"
]
| [
"src/dass/classifier_depression.py"
]
| [
"\"\"\"\nSVM classifier for the DASS labels.\n\nTrains a depression classifier.\n\"\"\"\n\n# region PREPARE WORKSPACE\n\n# Load dependencies\nimport os\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_validate\nfrom datetime import datetime\nfrom sklearn import metrics\nfrom joblib import dump\n\n# Get current working directory\nmy_path = os.getcwd()\n\n# Start file output\nwith open(my_path + '/doc/dass_output.txt', 'a') as f:\n print('\\n', file=f)\n print('##############################################################', file=f)\n print('DEPRESSION OUTPUT ############################################', file=f)\n print('\\n', file=f)\n\n# endregion\n\n# region PREPARE DATA\n\n# Load the data\nraw_data = pd.read_csv(my_path + '/data/cleaned/dass/with_features/depression.csv')\n\n# Get features and label\nX = raw_data.drop(['id', 'text', 'label', 'dysphoria'], axis=1)\nY = raw_data['label']\n\n# No standardization needed because features are dichotomous\n\n# Split into 80% train, 20% test\nx_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.20, random_state=1, stratify=Y)\n\n# endregion\n\n# region SVM CLASSIFIER\n\n# Instantiate the class\nsvm = SVC(kernel='linear', C=1.0, random_state=1)\n\n# Prepare the K-fold\nkfold = KFold(n_splits=10, random_state=1, shuffle=True)\n\n# Set the metrics\nmy_metrics = ['accuracy', 'precision', 'recall', 'f1']\n\n# Perform k-fold cross-validation\nscores = cross_validate(estimator=svm, X=x_train, y=y_train, scoring=my_metrics, cv=kfold, n_jobs=-1,\n error_score='raise')\n\n# Print the average scores during training\nwith open(my_path + '/doc/dass_output.txt', 'a') as f:\n print('TRAINING METRICS', file=f)\n print('Average runtime: %.3f' % np.mean(scores['fit_time'] + scores['score_time']), file=f)\n print('Average accuracy: %.3f (%.3f)' % (np.mean(scores['test_accuracy']), np.std(scores['test_accuracy'])),\n file=f)\n print('Average precision: %.3f (%.3f)' % (np.mean(scores['test_precision']), np.std(scores['test_precision'])),\n file=f)\n print('Average recall: %.3f (%.3f)' % (np.mean(scores['test_recall']), np.std(scores['test_recall'])), file=f)\n print('Average F1: %.3f (%.3f)' % (np.mean(scores['test_f1']), np.std(scores['test_f1'])), file=f)\n print('\\n', file=f)\n\n# Fit the data\nstart_time = datetime.now()\nsvm.fit(x_train, y_train)\nend_time = datetime.now()\n\n# Save results to file\nwith open(my_path + '/doc/dass_output.txt', 'a') as f:\n print('Runtime to fit SVM model: ' + str(end_time - start_time), file=f)\n print('\\n', file=f)\n\n# Get the predicted class labels\nstart_time = datetime.now()\ny_pred = svm.predict(x_test)\nend_time = datetime.now()\n\n# Save results to file\nwith open(my_path + '/doc/dass_output.txt', 'a') as f:\n print('Runtime to predict class labels: ' + str(end_time - start_time), file=f)\n print('\\n', file=f)\n\n# Print the metrics of the test results\nwith open(my_path + '/doc/dass_output.txt', 'a') as f:\n print('TEST METRICS', file=f)\n print('Accuracy: %.3f' % metrics.accuracy_score(y_true=y_test, y_pred=y_pred), file=f)\n print('Precision: %.3f' % metrics.precision_score(y_true=y_test, y_pred=y_pred), file=f)\n print('Recall: %.3f' % metrics.recall_score(y_true=y_test, y_pred=y_pred), file=f)\n print('F1: %.3f' % metrics.f1_score(y_true=y_test, y_pred=y_pred), file=f)\n print('\\n', file=f)\n\n# endregion\n\n# Save the SVM model to a file\ndump(svm, my_path + '/models/dass_depression.joblib')\n"
]
| [
[
"sklearn.model_selection.cross_validate",
"sklearn.metrics.precision_score",
"numpy.mean",
"sklearn.model_selection.KFold",
"sklearn.svm.SVC",
"sklearn.metrics.accuracy_score",
"numpy.std",
"sklearn.model_selection.train_test_split",
"pandas.read_csv",
"sklearn.metrics.f1_score",
"sklearn.metrics.recall_score"
]
]
|
MKrinitskiy/Antarctic-mesocyclones-detection-Retinanet | [
"8da29c8ceb639c140c2bc6b264d21b638b9b806c"
]
| [
"utils/scaling.py"
]
| [
"import numpy as np\n\ndef scale_btd(data):\n data_scaled_01 = (data+80.)/(5.5+80.)\n data_scaled01_inv = 1.001-data_scaled_01\n data_scaled01_inv_log = np.log(data_scaled01_inv)\n data_scaled2 = 1. - (data_scaled01_inv_log - np.log(0.001))/(-np.log(0.001))\n return data_scaled2\n\ndef scale_btd_back(data):\n data_scaled01_inv_log = (1. - data)*(-np.log(0.001)) + np.log(0.001)\n data_exp = np.exp(data_scaled01_inv_log)\n data_exp_inv = 1.001-data_exp\n data_descaled = data_exp_inv*(5.5+80.) - 80.\n return data_descaled\n\n\ndef scale_ch5(data):\n ch5_vmin = 205.\n ch5_vmax = 260.\n return 1 + (ch5_vmin - data)/(ch5_vmax-ch5_vmin)\n\ndef scale_ch5_back(data):\n ch5_vmin = 205.\n ch5_vmax = 260.\n return ch5_vmin - (data-1.)*(ch5_vmax-ch5_vmin)\n\n\ndef scale_ch9(data):\n return np.minimum(1. + (200. - data)/(320.-200.), 1.)\n\ndef scale_ch9_back(data):\n return 200. - (data-1.)*(320.-200.)\n"
]
| [
[
"numpy.exp",
"numpy.log",
"numpy.minimum"
]
]
|
shuxinyin/Loss-Set-Pytorch | [
"0dc125a2c245f589e346d2d9a4c94aaad08f0667",
"0dc125a2c245f589e346d2d9a4c94aaad08f0667"
]
| [
"unbalanced_loss/dice_loss.py",
"unbalanced_loss/GHM_loss.py"
]
| [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\n\nclass BinaryDiceLoss(nn.Module):\n \"\"\"\n Args:\n ignore_index: Specifies a target value that is ignored and does not contribute to the input gradient\n reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'\n Shapes:\n output: A tensor of shape [N, *] without sigmoid activation function applied\n target: A tensor of shape same with output\n Returns:\n Loss tensor according to arg reduction\n Raise:\n Exception if unexpected reduction\n \"\"\"\n\n def __init__(self, ignore_index=None, reduction='mean', **kwargs):\n super(BinaryDiceLoss, self).__init__()\n self.smooth = 1 # suggest set a large number when target area is large,like '10|100'\n self.ignore_index = ignore_index\n self.reduction = reduction\n self.batch_dice = False # treat a large map when True\n if 'batch_loss' in kwargs.keys():\n self.batch_dice = kwargs['batch_loss']\n\n def forward(self, output, target, use_sigmoid=True):\n assert output.shape[0] == target.shape[0], \"output & target batch size don't match\"\n if use_sigmoid:\n output = torch.sigmoid(output)\n\n if self.ignore_index is not None:\n validmask = (target != self.ignore_index).float()\n output = output.mul(validmask) # can not use inplace for bp\n target = target.float().mul(validmask)\n\n dim0 = output.shape[0]\n if self.batch_dice:\n dim0 = 1\n\n output = output.contiguous().view(dim0, -1)\n target = target.contiguous().view(dim0, -1).float()\n\n num = 2 * torch.sum(torch.mul(output, target), dim=1) + self.smooth\n den = torch.sum(output.abs() + target.abs(), dim=1) + self.smooth\n\n loss = 1 - (num / den)\n\n if self.reduction == 'mean':\n return loss.mean()\n elif self.reduction == 'sum':\n return loss.sum()\n elif self.reduction == 'none':\n return loss\n else:\n raise Exception('Unexpected reduction {}'.format(self.reduction))\n\n\nclass DiceLoss(nn.Module):\n \"\"\"\n Args:\n weight: An array of shape [num_classes,]\n ignore_index: Specifies a target value that is ignored and does not contribute to the input gradient\n output: A tensor of shape [N, C, *]\n target: A tensor of same shape with output\n other args pass to BinaryDiceLoss\n Return:\n same as BinaryDiceLoss\n \"\"\"\n\n def __init__(self, weight=None, ignore_index=None, **kwargs):\n super(DiceLoss, self).__init__()\n self.kwargs = kwargs\n self.weight = weight\n if isinstance(ignore_index, (int, float)):\n self.ignore_index = [int(ignore_index)]\n elif ignore_index is None:\n self.ignore_index = []\n elif isinstance(ignore_index, (list, tuple)):\n self.ignore_index = ignore_index\n else:\n raise TypeError(\"Expect 'int|float|list|tuple', while get '{}'\".format(type(ignore_index)))\n\n def forward(self, output, target):\n assert output.shape == target.shape, 'output & target shape do not match'\n dice = BinaryDiceLoss(**self.kwargs)\n total_loss = 0\n output = F.softmax(output, dim=1)\n for i in range(target.shape[1]):\n if i not in self.ignore_index:\n dice_loss = dice(output[:, i], target[:, i], use_sigmoid=False)\n if self.weight is not None:\n assert self.weight.shape[0] == target.shape[1], \\\n 'Expect weight shape [{}], get[{}]'.format(target.shape[1], self.weight.shape[0])\n dice_loss *= self.weights[i]\n total_loss += (dice_loss)\n loss = total_loss / (target.size(1) - len(self.ignore_index))\n return loss\n\n\ndef test():\n input = torch.rand((3, 1, 32, 32, 32))\n model = nn.Conv3d(1, 4, 3, padding=1)\n target = torch.randint(0, 4, (3, 1, 32, 32, 32)).float()\n target = make_one_hot(target, num_classes=4)\n criterion = DiceLoss(ignore_index=[2, 3], reduction='mean')\n loss = criterion(model(input), target)\n loss.backward()\n print(loss.item())\n\n\ndef make_one_hot(input, num_classes=None):\n \"\"\"Convert class index tensor to one hot encoding tensor.\n\n Args:\n input: A tensor of shape [N, 1, *]\n num_classes: An int of number of class\n Shapes:\n predict: A tensor of shape [N, *] without sigmoid activation function applied\n target: A tensor of shape same with predict\n Returns:\n A tensor of shape [N, num_classes, *]\n \"\"\"\n if num_classes is None:\n num_classes = input.max() + 1\n shape = np.array(input.shape)\n shape[1] = num_classes\n shape = tuple(shape)\n result = torch.zeros(shape)\n result = result.scatter_(1, input.cpu().long(), 1)\n return result\n\n\nif __name__ == '__main__':\n test()\n",
"# some code reforenced from https://github.com/DHPO/GHM_Loss.pytorch\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\n\nclass GHM_Loss(nn.Module):\n def __init__(self, bins=10, alpha=0.5):\n '''\n bins: split to n bins\n alpha: hyper-parameter\n '''\n super(GHM_Loss, self).__init__()\n self._bins = bins\n self._alpha = alpha\n self._last_bin_count = None\n\n def _g2bin(self, g):\n return torch.floor(g * (self._bins - 0.0001)).long()\n\n def _custom_loss(self, x, target, weight):\n raise NotImplementedError\n\n def _custom_loss_grad(self, x, target):\n raise NotImplementedError\n\n def forward(self, x, target):\n g = torch.abs(self._custom_loss_grad(x, target)).detach()\n\n bin_idx = self._g2bin(g)\n\n bin_count = torch.zeros((self._bins))\n for i in range(self._bins):\n bin_count[i] = (bin_idx == i).sum().item()\n\n N = (x.size(0) * x.size(1))\n\n if self._last_bin_count is None:\n self._last_bin_count = bin_count\n else:\n bin_count = self._alpha * self._last_bin_count + (1 - self._alpha) * bin_count\n self._last_bin_count = bin_count\n\n nonempty_bins = (bin_count > 0).sum().item()\n\n gd = bin_count * nonempty_bins\n gd = torch.clamp(gd, min=0.0001)\n beta = N / gd\n\n return self._custom_loss(x, target, beta[bin_idx])\n\n\nclass GHMC_Loss(GHM_Loss):\n '''\n GHM_Loss for classification\n '''\n\n def __init__(self, bins, alpha):\n super(GHMC_Loss, self).__init__(bins, alpha)\n\n def _custom_loss(self, x, target, weight):\n return F.binary_cross_entropy_with_logits(x, target, weight=weight)\n\n def _custom_loss_grad(self, x, target):\n return torch.sigmoid(x).detach() - target\n\n\nclass GHMR_Loss(GHM_Loss):\n '''\n GHM_Loss for regression\n '''\n\n def __init__(self, bins, alpha, mu):\n super(GHMR_Loss, self).__init__(bins, alpha)\n self._mu = mu\n\n def _custom_loss(self, x, target, weight):\n d = x - target\n mu = self._mu\n loss = torch.sqrt(d * d + mu * mu) - mu\n N = x.size(0) * x.size(1)\n return (loss * weight).sum() / N\n\n def _custom_loss_grad(self, x, target):\n d = x - target\n mu = self._mu\n return d / torch.sqrt(d * d + mu * mu)\n"
]
| [
[
"torch.zeros",
"torch.rand",
"numpy.array",
"torch.sigmoid",
"torch.mul",
"torch.randint",
"torch.nn.Conv3d",
"torch.nn.functional.softmax"
],
[
"torch.zeros",
"torch.nn.functional.binary_cross_entropy_with_logits",
"torch.sigmoid",
"torch.sqrt",
"torch.clamp",
"torch.floor"
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.