repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
alexcercos/ML-Agents
[ "c096c36b0348e3673b687499e17891cd35168939" ]
[ "ml-agents-envs/mlagents/envs/brain.py" ]
[ "import logging\nimport numpy as np\nimport io\n\nfrom mlagents.envs.communicator_objects.agent_info_pb2 import AgentInfoProto\nfrom mlagents.envs.communicator_objects.brain_parameters_pb2 import BrainParametersProto\nfrom mlagents.envs.timers import hierarchical_timer, timed\nfrom typing import Dict, List, NamedTuple, Optional\nfrom PIL import Image\n\nlogger = logging.getLogger(\"mlagents.envs\")\n\n\nclass CameraResolution(NamedTuple):\n height: int\n width: int\n num_channels: int\n\n @property\n def gray_scale(self) -> bool:\n return self.num_channels == 1\n\n\nclass BrainParameters:\n def __init__(\n self,\n brain_name: str,\n vector_observation_space_size: int,\n num_stacked_vector_observations: int,\n camera_resolutions: List[CameraResolution],\n vector_action_space_size: List[int],\n vector_action_descriptions: List[str],\n vector_action_space_type: int,\n ):\n \"\"\"\n Contains all brain-specific parameters.\n \"\"\"\n self.brain_name = brain_name\n self.vector_observation_space_size = vector_observation_space_size\n self.num_stacked_vector_observations = num_stacked_vector_observations\n self.number_visual_observations = len(camera_resolutions)\n self.camera_resolutions = camera_resolutions\n self.vector_action_space_size = vector_action_space_size\n self.vector_action_descriptions = vector_action_descriptions\n self.vector_action_space_type = [\"discrete\", \"continuous\"][\n vector_action_space_type\n ]\n\n def __str__(self):\n return \"\"\"Unity brain name: {}\n Number of Visual Observations (per agent): {}\n Vector Observation space size (per agent): {}\n Number of stacked Vector Observation: {}\n Vector Action space type: {}\n Vector Action space size (per agent): {}\n Vector Action descriptions: {}\"\"\".format(\n self.brain_name,\n str(self.number_visual_observations),\n str(self.vector_observation_space_size),\n str(self.num_stacked_vector_observations),\n self.vector_action_space_type,\n str(self.vector_action_space_size),\n \", \".join(self.vector_action_descriptions),\n )\n\n @staticmethod\n def from_proto(\n brain_param_proto: BrainParametersProto, agent_info: AgentInfoProto\n ) -> \"BrainParameters\":\n \"\"\"\n Converts brain parameter proto to BrainParameter object.\n :param brain_param_proto: protobuf object.\n :return: BrainParameter object.\n \"\"\"\n resolutions = [\n CameraResolution(x.shape[0], x.shape[1], x.shape[2])\n for x in agent_info.compressed_observations\n ]\n\n brain_params = BrainParameters(\n brain_param_proto.brain_name,\n brain_param_proto.vector_observation_size,\n brain_param_proto.num_stacked_vector_observations,\n resolutions,\n list(brain_param_proto.vector_action_size),\n list(brain_param_proto.vector_action_descriptions),\n brain_param_proto.vector_action_space_type,\n )\n return brain_params\n\n\nclass BrainInfo:\n def __init__(\n self,\n visual_observation,\n vector_observation,\n text_observations,\n memory=None,\n reward=None,\n agents=None,\n local_done=None,\n vector_action=None,\n text_action=None,\n max_reached=None,\n action_mask=None,\n custom_observations=None,\n ):\n \"\"\"\n Describes experience at current step of all agents linked to a brain.\n \"\"\"\n self.visual_observations = visual_observation\n self.vector_observations = vector_observation\n self.text_observations = text_observations\n self.memories = memory\n self.rewards = reward\n self.local_done = local_done\n self.max_reached = max_reached\n self.agents = agents\n self.previous_vector_actions = vector_action\n self.previous_text_actions = text_action\n self.action_masks = action_mask\n self.custom_observations = custom_observations\n\n def merge(self, other):\n for i in range(len(self.visual_observations)):\n self.visual_observations[i].extend(other.visual_observations[i])\n self.vector_observations = np.append(\n self.vector_observations, other.vector_observations, axis=0\n )\n self.text_observations.extend(other.text_observations)\n self.memories = self.merge_memories(\n self.memories, other.memories, self.agents, other.agents\n )\n self.rewards = safe_concat_lists(self.rewards, other.rewards)\n self.local_done = safe_concat_lists(self.local_done, other.local_done)\n self.max_reached = safe_concat_lists(self.max_reached, other.max_reached)\n self.agents = safe_concat_lists(self.agents, other.agents)\n self.previous_vector_actions = safe_concat_np_ndarray(\n self.previous_vector_actions, other.previous_vector_actions\n )\n self.previous_text_actions = safe_concat_lists(\n self.previous_text_actions, other.previous_text_actions\n )\n self.action_masks = safe_concat_np_ndarray(\n self.action_masks, other.action_masks\n )\n self.custom_observations = safe_concat_lists(\n self.custom_observations, other.custom_observations\n )\n\n @staticmethod\n def merge_memories(m1, m2, agents1, agents2):\n if len(m1) == 0 and len(m2) != 0:\n m1 = np.zeros((len(agents1), m2.shape[1]))\n elif len(m2) == 0 and len(m1) != 0:\n m2 = np.zeros((len(agents2), m1.shape[1]))\n elif m2.shape[1] > m1.shape[1]:\n new_m1 = np.zeros((m1.shape[0], m2.shape[1]))\n new_m1[0 : m1.shape[0], 0 : m1.shape[1]] = m1\n return np.append(new_m1, m2, axis=0)\n elif m1.shape[1] > m2.shape[1]:\n new_m2 = np.zeros((m2.shape[0], m1.shape[1]))\n new_m2[0 : m2.shape[0], 0 : m2.shape[1]] = m2\n return np.append(m1, new_m2, axis=0)\n return np.append(m1, m2, axis=0)\n\n @staticmethod\n @timed\n def process_pixels(image_bytes: bytes, gray_scale: bool) -> np.ndarray:\n \"\"\"\n Converts byte array observation image into numpy array, re-sizes it,\n and optionally converts it to grey scale\n :param gray_scale: Whether to convert the image to grayscale.\n :param image_bytes: input byte array corresponding to image\n :return: processed numpy array of observation from environment\n \"\"\"\n with hierarchical_timer(\"image_decompress\"):\n image_bytearray = bytearray(image_bytes)\n image = Image.open(io.BytesIO(image_bytearray))\n # Normally Image loads lazily, this forces it to do loading in the timer scope.\n image.load()\n s = np.array(image) / 255.0\n if gray_scale:\n s = np.mean(s, axis=2)\n s = np.reshape(s, [s.shape[0], s.shape[1], 1])\n return s\n\n @staticmethod\n def from_agent_proto(\n worker_id: int,\n agent_info_list: List[AgentInfoProto],\n brain_params: BrainParameters,\n ) -> \"BrainInfo\":\n \"\"\"\n Converts list of agent infos to BrainInfo.\n \"\"\"\n vis_obs: List[np.ndarray] = []\n for i in range(brain_params.number_visual_observations):\n obs = [\n BrainInfo.process_pixels(\n x.compressed_observations[i].data,\n brain_params.camera_resolutions[i].gray_scale,\n )\n for x in agent_info_list\n ]\n vis_obs += [obs]\n if len(agent_info_list) == 0:\n memory_size = 0\n else:\n memory_size = max(len(x.memories) for x in agent_info_list)\n if memory_size == 0:\n memory = np.zeros((0, 0))\n else:\n [\n x.memories.extend([0] * (memory_size - len(x.memories)))\n for x in agent_info_list\n ]\n memory = np.array([list(x.memories) for x in agent_info_list])\n total_num_actions = sum(brain_params.vector_action_space_size)\n mask_actions = np.ones((len(agent_info_list), total_num_actions))\n for agent_index, agent_info in enumerate(agent_info_list):\n if agent_info.action_mask is not None:\n if len(agent_info.action_mask) == total_num_actions:\n mask_actions[agent_index, :] = [\n 0 if agent_info.action_mask[k] else 1\n for k in range(total_num_actions)\n ]\n if any(np.isnan(x.reward) for x in agent_info_list):\n logger.warning(\n \"An agent had a NaN reward for brain \" + brain_params.brain_name\n )\n\n if len(agent_info_list) == 0:\n vector_obs = np.zeros(\n (\n 0,\n brain_params.vector_observation_space_size\n * brain_params.num_stacked_vector_observations,\n )\n )\n else:\n stacked_obs = []\n has_nan = False\n has_inf = False\n for x in agent_info_list:\n np_obs = np.array(x.stacked_vector_observation)\n # Check for NaNs or infs in the observations\n # If there's a NaN in the observations, the dot() result will be NaN\n # If there's an Inf (either sign) then the result will be Inf\n # See https://stackoverflow.com/questions/6736590/fast-check-for-nan-in-numpy for background\n # Note that a very large values (larger than sqrt(float_max)) will result in an Inf value here\n # This is OK though, worst case it results in an unnecessary (but harmless) nan_to_num call.\n d = np.dot(np_obs, np_obs)\n has_nan = has_nan or np.isnan(d)\n has_inf = has_inf or not np.isfinite(d)\n stacked_obs.append(np_obs)\n vector_obs = np.array(stacked_obs)\n\n # In we have any NaN or Infs, use np.nan_to_num to replace these with finite values\n if has_nan or has_inf:\n vector_obs = np.nan_to_num(vector_obs)\n\n if has_nan:\n logger.warning(\n f\"An agent had a NaN observation for brain {brain_params.brain_name}\"\n )\n\n agents = [f\"${worker_id}-{x.id}\" for x in agent_info_list]\n brain_info = BrainInfo(\n visual_observation=vis_obs,\n vector_observation=vector_obs,\n text_observations=[x.text_observation for x in agent_info_list],\n memory=memory,\n reward=[x.reward if not np.isnan(x.reward) else 0 for x in agent_info_list],\n agents=agents,\n local_done=[x.done for x in agent_info_list],\n vector_action=np.array([x.stored_vector_actions for x in agent_info_list]),\n text_action=[list(x.stored_text_actions) for x in agent_info_list],\n max_reached=[x.max_step_reached for x in agent_info_list],\n custom_observations=[x.custom_observation for x in agent_info_list],\n action_mask=mask_actions,\n )\n return brain_info\n\n\ndef safe_concat_lists(l1: Optional[List], l2: Optional[List]) -> Optional[List]:\n if l1 is None:\n if l2 is None:\n return None\n else:\n return l2.copy()\n else:\n if l2 is None:\n return l1.copy()\n else:\n copy = l1.copy()\n copy.extend(l2)\n return copy\n\n\ndef safe_concat_np_ndarray(\n a1: Optional[np.ndarray], a2: Optional[np.ndarray]\n) -> Optional[np.ndarray]:\n if a1 is not None and a1.size != 0:\n if a2 is not None and a2.size != 0:\n return np.append(a1, a2, axis=0)\n else:\n return a1.copy()\n elif a2 is not None and a2.size != 0:\n return a2.copy()\n return None\n\n\n# Renaming of dictionary of brain name to BrainInfo for clarity\nAllBrainInfo = Dict[str, BrainInfo]\n" ]
[ [ "numpy.dot", "numpy.isfinite", "numpy.reshape", "numpy.isnan", "numpy.nan_to_num", "numpy.append", "numpy.mean", "numpy.array", "numpy.zeros" ] ]
hvkwak/simple-faster-rcnn-pytorch
[ "3ea84a789c91ea8d403637026b4a5add19e5343a" ]
[ "models/faster_rcnn.py" ]
[ "import os\nimport sys\nimport torch\nimport torchvision\nimport numpy as np\nfrom torch import nn\nfrom torch.nn import functional as F\n# from models.utils.nms import non_maximum_suppression\nfrom models.utils.bbox_tools import loc2bbox\nfrom utils.array_tool import tonumpy, totensor\nfrom data.dataset import preprocess\nfrom utils.util import read_image\nfrom utils.config import opt\n\nclass FasterRCNN(nn.Module):\n \"\"\"Base class for Faster R-CNN.\n\n This is a base class for Faster R-CNN links supporting object detection\n API [#]_. The following three stages constitute Faster R-CNN.\n\n 1. **Feature extraction**: Images are taken and their \\\n feature maps are calculated.\n 2. **Region Proposal Networks**: Given the feature maps calculated in \\\n the previous stage, produce set of RoIs around objects.\n 3. **Localization and Classification Heads**: Using feature maps that \\\n belong to the proposed RoIs, classify the categories of the objects \\\n in the RoIs and improve localizations.\n\n Each stage is carried out by one of the callable\n :class:`torch.nn.Module` objects :obj:`feature`, :obj:`rpn` and :obj:`head`.\n\n There are two functions :meth:`predict` and :meth:`__call__` to conduct\n object detection.\n :meth:`predict` takes images and returns bounding boxes that are converted\n to image coordinates. This will be useful for a scenario when\n Faster R-CNN is treated as a black box function, for instance.\n :meth:`__call__` is provided for a scnerario when intermediate outputs\n are needed, for instance, for training and debugging.\n\n Links that support obejct detection API have method :meth:`predict` with\n the same interface. Please refer to :meth:`predict` for\n further details.\n\n .. [#] Shaoqing Ren, Kaiming He, Ross Girshick, Jian Sun. \\\n Faster R-CNN: Towards Real-Time Object Detection with \\\n Region Proposal Networks. NIPS 2015.\n\n Args:\n extractor (nn.Module): A module that takes a BCHW image\n array and returns feature maps.\n rpn (nn.Module): A module that has the same interface as\n :class:`model.region_proposal_network.RegionProposalNetwork`.\n Please refer to the documentation found there.\n head (nn.Module): A module that takes\n a BCHW variable, RoIs and batch indices for RoIs. This returns class\n dependent localization paramters and class scores.\n loc_normalize_mean (tuple of four floats): Mean values of\n localization estimates.\n loc_normalize_std (tupler of four floats): Standard deviation\n of localization estimates.\n \"\"\"\n\n def __init__(self, extractor, rpn, head, \n loc_normalize_mean = (0., 0., 0., 0.),\n loc_normalize_std = (0.1, 0.1, 0.2, 0.2)):\n # in Python3, inheritance and initialize like this:\n super().__init__()\n self.extractor = extractor\n self.rpn = rpn\n self.head = head\n\n # mean and std\n self.loc_normalize_mean = loc_normalize_mean\n self.loc_normalize_std = loc_normalize_std\n self.use_preset('evaluate')\n\n # demo_image\n self.demo_image = \"\" \n\n @property\n def n_class(self):\n # Total number of classes including the background.\n return self.head.n_class\n \n\n def forward(self, x, scale=1.):\n \"\"\"Forward Faster R-CNN.\n\n Scaling paramter :obj:`scale` is used by RPN to determine the\n threshold to select small objects, which are going to be\n rejected irrespective of their confidence scores.\n\n Here are notations used.\n\n * :math:`N` is the number of batch size\n * :math:`R'` is the total number of RoIs produced across batches. \\\n Given :math:`R_i` proposed RoIs from the :math:`i` th image, \\\n :math:`R' = \\\\sum _{i=1} ^ N R_i`.\n * :math:`L` is the number of classes excluding the background.\n\n Classes are ordered by the background, the first class, ..., and\n the :math:`L` th class.\n\n Args:\n x (autograd.Variable): 4D image variable.\n scale (float): Amount of scaling applied to the raw image\n during preprocessing.\n\n Returns:\n Variable, Variable, array, array:\n Returns tuple of four values listed below.\n\n * **roi_cls_locs**: Offsets and scalings for the proposed RoIs. \\\n Its shape is :math:`(R', (L + 1) \\\\times 4)`.\n * **roi_scores**: Class predictions for the proposed RoIs. \\\n Its shape is :math:`(R', L + 1)`.\n * **rois**: RoIs proposed by RPN. Its shape is \\\n :math:`(R', 4)`.\n * **roi_indices**: Batch indices of RoIs. Its shape is \\\n :math:`(R',)`.\n\n \"\"\"\n img_size = x.shape[2:]\n h = self.extractor(x)\n\n # rpn_locs, rpn_scores, rois, roi_indices, anchor = self.rpn(h, img_size, scale)\n # rpn_locs, rpn_scores, anchors are obsolete\n _, _, rois, roi_indices, _ = self.rpn(h, img_size, scale)\n\n # visualize RPN results to see if they are working correctly:\n # visualize_RPN(rois, self.scale, self.demo_image)\n\n # feed forward weiter:\n roi_cls_locs, roi_scores = self.head(h, rois, roi_indices)\n return roi_cls_locs, roi_scores, rois, roi_indices\n\n def use_preset(self, preset):\n \"\"\"Use the given preset during prediction.\n\n This method changes values of :obj:`self.nms_thresh` and\n :obj:`self.score_thresh`. These values are a threshold value\n used for non maximum suppression and a threshold value\n to discard low confidence proposals in :meth:`predict`,\n respectively.\n\n If the attributes need to be changed to something\n other than the values provided in the presets, please modify\n them by directly accessing the public attributes.\n\n Args:\n preset ({'visualize', 'evaluate'): A string to determine the\n preset to use.\n\n \"\"\"\n if preset == 'visualize':\n self.nms_thresh = 0.3\n self.score_thresh = 0.9\n elif preset == 'evaluate':\n self.nms_thresh = 0.1 # 0.2\n self.score_thresh = 0.9 # 0.05\n else:\n raise ValueError('preset must be visualize or evaluate')\n\n def _suppress(self, raw_cls_bbox, raw_prob):\n # non maximum suppresion before final predictions\n bbox = list()\n label = list()\n score = list()\n # masks = list()\n\n # skip cls_id = 0 because it is the background class\n for l in range(1, self.n_class):\n cls_bbox_l = raw_cls_bbox.reshape((-1, self.n_class, 4))[:, l, :]\n prob_l = raw_prob[:, l]\n mask = prob_l > self.score_thresh\n cls_bbox_l = cls_bbox_l[mask]\n prob_l = prob_l[mask]\n \n keep = torchvision.ops.nms(torch.from_numpy(cls_bbox_l), torch.from_numpy(prob_l), self.nms_thresh)\n # mask = np.where(mask)[0]\n \n # import ipdb;ipdb.set_trace()\n keep = keep.numpy()\n bbox.append(cls_bbox_l[keep])\n # The labels are in [0, self.n_class - 2].\n label.append((l - 1) * np.ones((len(keep),)))\n score.append(prob_l[keep])\n # masks.append(mask[keep])\n bbox = np.concatenate(bbox, axis=0).astype(np.float32)\n label = np.concatenate(label, axis=0).astype(np.int32)\n score = np.concatenate(score, axis=0).astype(np.float32)\n # masks = np.concatenate(masks, axis = 0)\n return bbox, label, score\n\n @torch.no_grad()\n def predict(self, imgs, sizes=None, visualize=False):\n \"\"\"Detect objects from images.\n\n This method predicts objects for each image.\n\n Args:\n imgs (iterable of numpy.ndarray): Arrays holding images.\n All images are in CHW and RGB format\n and the range of their value is :math:`[0, 255]`.\n\n Returns:\n tuple of lists:\n This method returns a tuple of three lists,\n :obj:`(bboxes, labels, scores)`.\n\n * **bboxes**: A list of float arrays of shape :math:`(R, 4)`, \\\n where :math:`R` is the number of bounding boxes in a image. \\\n Each bouding box is organized by \\\n :math:`(y_{min}, x_{min}, y_{max}, x_{max})` \\\n in the second axis.\n * **labels** : A list of integer arrays of shape :math:`(R,)`. \\\n Each value indicates the class of the bounding box. \\\n Values are in range :math:`[0, L - 1]`, where :math:`L` is the \\\n number of the foreground classes.\n * **scores** : A list of float arrays of shape :math:`(R,)`. \\\n Each value indicates how confident the prediction is.\n\n \"\"\"\n self.eval()\n if visualize:\n self.use_preset('visualize') # Visualize mode\n prepared_imgs = list()\n sizes = list()\n for img in imgs:\n size = img.shape[1:]\n img, scale = preprocess(tonumpy(img))\n self.scale = scale\n prepared_imgs.append(img)\n sizes.append(size)\n else:\n prepared_imgs = imgs\n \n # create output lists\n bboxes = list()\n labels = list()\n scores = list()\n masks = list()\n for img, size in zip(prepared_imgs, sizes):\n # change it to tensor\n # [None] addes up one more dimension\n img = totensor(img[None]).float()\n\n # scale factor\n scale = img.shape[3] / size[1]\n\n # fast forward the image\n # img -> (extractor+rpn+head) -> roi_cls_loc, roi_scores, rois\n roi_cls_loc, roi_scores, rois, roi_indices = self(img, scale=scale)\n\n # NOTE:\n # rois.shape = (300, 4)\n # where 4 corresponds to (y1, x1, y2, x2)\n # x in [0, 600], y in [0, 800]\n\n # We are assuming that batch size is 1.\n roi_score = roi_scores.data\n roi_cls_loc = roi_cls_loc.data\n\n # change rois to tensor\n roi = totensor(rois) / scale\n\n # check the codes below.\n # Convert predictions to bounding boxes in image coordinates.\n # Bounding boxes are scaled to the scale of the input images.\n mean = torch.Tensor(self.loc_normalize_mean). \\\n repeat(self.n_class)[None]\n std = torch.Tensor(self.loc_normalize_std). \\\n repeat(self.n_class)[None]\n\n roi_cls_loc = (roi_cls_loc * std + mean)\n roi_cls_loc = roi_cls_loc.view(-1, self.n_class, 4)\n roi = roi.view(-1, 1, 4).expand_as(roi_cls_loc)\n cls_bbox = loc2bbox(tonumpy(roi).reshape((-1, 4)),\n tonumpy(roi_cls_loc).reshape((-1, 4)))\n cls_bbox = totensor(cls_bbox)\n # change the form (N, 4) \n cls_bbox = cls_bbox.view(-1, self.n_class * 4)\n\n # clamp in range of [0, size[0]]\n cls_bbox[:, 0::2] = (cls_bbox[:, 0::2]).clamp(min=0, max=size[0])\n cls_bbox[:, 1::2] = (cls_bbox[:, 1::2]).clamp(min=0, max=size[1])\n\n prob = tonumpy(F.softmax(totensor(roi_score), dim=1))\n\n # change tensors to numpy\n raw_cls_bbox = tonumpy(cls_bbox)\n raw_prob = tonumpy(prob)\n\n # non maximum suppression\n bbox, label, score = self._suppress(raw_cls_bbox, raw_prob)\n bboxes.append(bbox)\n labels.append(label)\n scores.append(score)\n # masks.append(mask)\n\n self.use_preset('evaluate')\n self.train() # change it back to train mode.\n return bboxes, labels, scores\n \n\ndef visualize_RPN(rois, scale, image):\n # Visualize RPN results\n import matplotlib.pyplot as plt\n import matplotlib.patches as patches\n from PIL import Image\n ## load image\n image_name = image\n img1 = Image.open('/home/hyobin/Documents/in-facedemo/facerecognition/PyFaceRecClient/simple-faster-rcnn-pytorch/'+image_name)\n # img1 = read_image(os.path.dirname(os.path.abspath(__file__))+'/demo.jpg')\n fig, ax = plt.subplots(1)\n ax.imshow(img1)\n # visualize top images\n for i in range(10):\n y1, x1, y2, x2 = rois[i, :]\n y1, x1, y2, x2 = y1/scale, x1/scale, y2/scale, x2/scale\n h = y2 - y1\n w = x2 - x1\n rect = patches.Rectangle((x1,y1),w,h,linewidth=1,edgecolor='r',facecolor='none')\n ax.add_patch(rect)\n plt.show()" ]
[ [ "torch.Tensor", "matplotlib.patches.Rectangle", "torch.from_numpy", "matplotlib.pyplot.subplots", "numpy.concatenate", "torch.no_grad", "matplotlib.pyplot.show" ] ]
apl-ocean-engineering/visual_odom
[ "6e88c8d5a098585f7b12e4934f47494414824b4d" ]
[ "helper_nodes/display_poses.py" ]
[ "import matplotlib.pyplot as plt\nimport copy\nimport numpy as np\n\nimport argparse\n\n\ndef get_eucld_error(x1, x2, y1, y2, z1, z2):\n error = []\n for i in range(len(x1)):\n p1 = np.array([x1[i], y1[i], z1[i]])\n p2 = np.array([x2[i], y2[i], z2[i]])\n\n error.append(float(np.sum(np.subtract(p1, p2))))\n\n return error\n\n\ndef get_data(f, ignore_count=[]):\n count = 0\n idx = []\n time = []\n x = []\n y = []\n z = []\n roll = []\n pitch = []\n yaw = []\n for line in f:\n idx.append(count)\n count += 1\n time.append(line.split(',')[0])\n x.append(float(line.split(',')[1]))\n y.append(float(line.split(',')[2]))\n z.append(float(line.split(',')[3]))\n roll.append(float(line.split(',')[4]))\n pitch.append(float(line.split(',')[5]))\n yaw.append(float(line.split(',')[6]))\n\n return idx, time, x, y, z, roll, pitch, yaw\n\n\ndef check_val(l1, l2, idx, ind, max_val, min_val):\n if l1[ind] > max_val or l2[ind] > max_val:\n l1.pop(ind)\n l2.pop(ind)\n idx.pop(ind)\n elif l1[ind] < min_val or l2[ind] < min_val:\n l1.pop(ind)\n l2.pop(ind)\n idx.pop(ind)\n else:\n ind += 1\n\n return l1, l2, idx, ind\n\n\ndef check_error_val(error, idx, ind, max_val, min_val):\n if error[ind] > max_val:\n error.pop(ind)\n idx.pop(ind)\n elif error[ind] < min_val:\n error.pop(ind)\n idx.pop(ind)\n else:\n ind += 1\n\n return error, idx, ind\n\n\ndef plot(idx_list, v1, v2, v3=None, title=\" \",\n label1=\"1\", label2=\"2\", label3=\"3\", dump=False, y_min=None,\n y_max=None):\n fig1, ax1 = plt.subplots()\n ax1.scatter(idx_list, v1, c='k', label=label1)\n ax1.scatter(idx_list, v2, c='g', label=label2)\n if v3 is not None:\n ax1.scatter(idx_list, v3, c='b', label=label3)\n ax1.set_title(title)\n if y_min is not None and y_max is not None:\n ax1.set_ylim((y_min, y_max))\n ax1.legend()\n if dump:\n fig1.savefig(title + \".png\")\n\n\ndef plot_error(idx_list, error, title=\" \",\n dump=False, y_min=None, y_max=None):\n fig1, ax1 = plt.subplots()\n ax1.scatter(idx_list, error, c='k')\n ax1.set_title(title)\n if y_min is not None and y_max is not None:\n ax1.set_ylim((y_min, y_max))\n if dump:\n fig1.savefig(title + \".png\")\n\ndef integrate(lst):\n total = 0\n for v in lst:\n total += v\n\n return total\n\n\ndef main(fname1, fname2, display_integration=False, fname3 = None):\n print(fname1, fname2, fname3)\n f1 = open(fname1, 'r')\n f2 = open(fname2, 'r')\n if fname3 is not None:\n f3 = open(fname3, 'r')\n idx1, time1, x1, y1, z1, roll1, pitch1, yaw1 = get_data(f1)\n idx2, time2, x2, y2, z2, roll2, pitch2, yaw2 = get_data(f2)\n if fname3 is not None:\n idx3, time3, x3, y3, z3, roll3, pitch3, yaw3 = get_data(f3)\n error = get_eucld_error(x1, x2, y1, y2, z1, z2)\n\n idx_x = copy.deepcopy(idx1)\n idx_y = copy.deepcopy(idx1)\n idx_z = copy.deepcopy(idx1)\n idx_error = copy.deepcopy(idx1)\n\n # i = 0\n # while i < len(x1):\n # x1, x2, idx_x, i = check_val(x1, x2, idx_x, i, 100.0, -100.0)\n # i = 0\n # while i < len(y1):\n # y1, y2, idx_y, i = check_val(y1, y2, idx_y, i, 100.0, -100.0)\n # i = 0\n # while i < len(z1):\n # z1, z2, idx_z, i = check_val(z1, z2, idx_z, i, 100.0, -100.0)\n # i = 0\n # while i < len(error):\n # error, idx_error, i = check_error_val(error,\n # idx_error, i, 100.0, -100.0)\n\n if display_integration:\n print('X')\n print(integrate(x1), integrate(x2))\n print('Y')\n print(integrate(y1), integrate(y2))\n print('Z')\n print(integrate(z1), integrate(z2))\n print('Error')\n print(integrate(error)/len(error))\n\n\n plot(idx_x, x1, x2, v3=x3, title=\"x\",\n label1=fname1.split('/')[-1].replace('.txt', ''),\n label2=fname2.split('/')[-1].replace('.txt', ''),\n label3=fname3.split('/')[-1].replace('.txt', ''),\n dump=True)\n plot(idx_y, y1, y2, v3=y3, title=\"y\",\n label1=fname1.split('/')[-1].replace('.txt', ''),\n label2=fname2.split('/')[-1].replace('.txt', ''),\n label3=fname3.split('/')[-1].replace('.txt', ''),\n dump=True)\n plot(idx_z, z1, z2, v3=z3, title=\"z\",\n label1=fname1.split('/')[-1].replace('.txt', ''),\n label2=fname2.split('/')[-1].replace('.txt', ''),\n label3=fname3.split('/')[-1].replace('.txt', ''),\n dump=True)\n plot_error(idx_error, error)\n\n plt.show()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser('Display twist')\n parser.add_argument('file1')\n parser.add_argument('file2')\n parser.add_argument('--file3')\n parser.add_argument('--show_final_pose', type=bool, default=False)\n\n args = parser.parse_args()\n\n main(args.file1, args.file2, args.show_final_pose, fname3=args.file3)\n" ]
[ [ "numpy.array", "matplotlib.pyplot.show", "numpy.subtract", "matplotlib.pyplot.subplots" ] ]
TalkToTheGAN/RelaxTextGAN
[ "6d0846392c8a1267eaa103dd70492cb80024079e" ]
[ "models/plain_lstm.py" ]
[ "import os\nimport random\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\n\nclass PlainLSTM(nn.Module):\n \"\"\"PlainLSTM \"\"\"\n def __init__(self, vocab_size, emb_dim, hidden_dim, use_cuda=False):\n super(PlainLSTM, self).__init__()\n self.vocab_size = vocab_size\n self.emb_dim = emb_dim\n self.hidden_dim = hidden_dim\n self.use_cuda = use_cuda\n self.emb = nn.Embedding(vocab_size, emb_dim)\n self.lstm = nn.LSTM(emb_dim, hidden_dim, batch_first=True)\n self.lin = nn.Linear(hidden_dim, vocab_size)\n self.log_softmax = nn.LogSoftmax(dim=1)\n self.init_params()\n\n def forward(self, x):\n\n emb = self.emb(x) # emb dim: (batch_size, seq_len, emb_dim)\n h0, c0 = self.init_hidden(x.size(0))\n\n # input to lstm dimensions: (batch, seq_len, input_size)\n output, (h, c) = self.lstm(emb, (h0, c0)) # output dim = (batch_size x seq_len, x hidden_dim)\n \n seq_len = output.size()[1]\n batch_size = output.size()[0]\n\n pred = self.log_softmax(self.lin(output.contiguous().view(-1, self.hidden_dim)))\n pred = pred.view(batch_size, seq_len, self.vocab_size)\n return pred\n\n def step(self, x, h, c):\n \"\"\"\n Args:\n x: (batch_size, 1), sequence of tokens generated by lstm\n h: (1, batch_size, hidden_dim), lstm hidden state\n c: (1, batch_size, hidden_dim), lstm cell state\n \"\"\"\n emb = self.emb(x)\n output, (h, c) = self.lstm(emb, (h, c))\n pred = F.softmax(self.lin(output.view(-1, self.hidden_dim)), dim=1)\n return pred, h, c\n\n\n def init_hidden(self, batch_size):\n\n h = Variable(torch.zeros((1, batch_size, self.hidden_dim)))\n c = Variable(torch.zeros((1, batch_size, self.hidden_dim)))\n if self.use_cuda:\n h, c = h.cuda(), c.cuda()\n return h, c\n \n def init_params(self):\n for param in self.parameters():\n param.data.uniform_(-0.05, 0.05)\n\n def sample(self, batch_size, seq_len, x=None):\n res = []\n flag = False # whether sample from zero\n if x is None:\n flag = True\n if flag:\n x = Variable(torch.zeros((batch_size, 1)).long())\n if self.use_cuda:\n x = x.cuda()\n h, c = self.init_hidden(batch_size)\n samples = []\n if flag:\n for i in range(seq_len):\n output, h, c = self.step(x, h, c)\n x = output.multinomial(1)\n samples.append(x)\n else:\n given_len = x.size(1)\n lis = x.chunk(x.size(1), dim=1)\n for i in range(given_len):\n output, h, c = self.step(lis[i], h, c)\n samples.append(lis[i])\n x = output.multinomial(1)\n for i in range(given_len, seq_len):\n samples.append(x)\n output, h, c = self.step(x, h, c)\n x = output.multinomial(1)\n output = torch.cat(samples, dim=1)\n return output\n\n\n def test_sample(self, batch_size, seq_len, vocab_size):\n\n big_list = []\n x = Variable(torch.zeros((batch_size, 1)).long())\n h, c = self.init_hidden(batch_size)\n\n for i in range(seq_len):\n output, h, c = self.step(x, h, c)\n g = Variable(torch.zeros(output.size()))\n # print(g.size())\n g.data[:,0] = 1 # R*pij\n # output.backward(g)\n big_list.append((output, g))\n\n \n\n for p, g in big_list:\n p.backward(g)\n return output\n " ]
[ [ "torch.nn.LogSoftmax", "torch.cat", "torch.nn.LSTM", "torch.zeros", "torch.nn.Embedding", "torch.nn.Linear" ] ]
ebadkamil/EXtra-foam
[ "8e58143040c788dc70ea98ea5adc1fb63b7cfe0d" ]
[ "extra_foam/special_suite/tests/test_gotthard.py" ]
[ "import unittest\nfrom unittest.mock import MagicMock, patch, PropertyMock\nfrom collections import Counter\n\nimport pytest\nimport numpy as np\nfrom xarray import DataArray\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtTest import QSignalSpy, QTest\n\nfrom extra_foam.pipeline.tests import _RawDataMixin\n\nfrom extra_foam.special_suite import logger, mkQApp\nfrom extra_foam.special_suite.gotthard_proc import GotthardProcessor\nfrom extra_foam.special_suite.gotthard_w import (\n GotthardWindow, GotthardImageView, GotthardAvgPlot, GotthardPulsePlot,\n GotthardHist\n)\nfrom extra_foam.special_suite.special_analysis_base import (\n ProcessingError\n)\n\nfrom . import _SpecialSuiteWindowTestBase, _SpecialSuiteProcessorTestBase\n\napp = mkQApp()\n\nlogger.setLevel('INFO')\n\n\nclass TestGotthardWindow(_SpecialSuiteWindowTestBase):\n _window_type = GotthardWindow\n\n @staticmethod\n def data4visualization(n_pulses=4):\n \"\"\"Override.\"\"\"\n return {\n \"x\": None,\n \"spectrum\": np.arange(10 * n_pulses).reshape(n_pulses, 10),\n \"spectrum_ma\": np.arange(10 * n_pulses).reshape(n_pulses, 10),\n \"spectrum_mean\": np.arange(10),\n \"spectrum_ma_mean\": np.arange(10),\n \"poi_index\": 0,\n \"hist\": (np.arange(5), np.arange(5), 1, 1, 1),\n }\n\n def testWindow(self):\n win = self._win\n\n self.assertEqual(4, len(win._plot_widgets_st))\n counter = Counter()\n for key in win._plot_widgets_st:\n counter[key.__class__] += 1\n\n self.assertEqual(1, counter[GotthardImageView])\n self.assertEqual(1, counter[GotthardAvgPlot])\n self.assertEqual(1, counter[GotthardPulsePlot])\n self.assertEqual(1, counter[GotthardHist])\n\n self._check_update_plots()\n\n def testCtrl(self):\n from extra_foam.special_suite.gotthard_w import _DEFAULT_N_BINS, _DEFAULT_BIN_RANGE\n\n win = self._win\n ctrl_widget = win._ctrl_widget_st\n proc = win._worker_st\n\n # test default values\n self.assertTrue(proc._output_channel)\n self.assertEqual(slice(None, None), proc._pulse_slicer)\n self.assertEqual(0, proc._poi_index)\n self.assertEqual(1, proc.__class__._raw_ma.window)\n self.assertEqual(0, proc._scale)\n self.assertEqual(0, proc._offset)\n self.assertTupleEqual(tuple(float(v) for v in _DEFAULT_BIN_RANGE.split(',')),\n proc._bin_range)\n self.assertEqual(int(_DEFAULT_N_BINS), proc._n_bins)\n self.assertFalse(proc._hist_over_ma)\n\n # test set new values\n widget = ctrl_widget.output_ch_le\n widget.clear()\n QTest.keyClicks(widget, \"new/output/channel\")\n QTest.keyPress(widget, Qt.Key_Enter)\n self.assertEqual(\"new/output/channel\", proc._output_channel)\n\n widget = ctrl_widget.pulse_slicer_le\n widget.clear()\n QTest.keyClicks(widget, \"::2\")\n QTest.keyPress(widget, Qt.Key_Enter)\n self.assertEqual(slice(None, None, 2), proc._pulse_slicer)\n\n widget = ctrl_widget.poi_index_le\n widget.clear()\n QTest.keyClicks(widget, \"120\")\n QTest.keyPress(widget, Qt.Key_Enter)\n self.assertEqual(0, proc._poi_index) # maximum is 119 and one can still type \"120\"\n widget.clear()\n QTest.keyClicks(widget, \"119\")\n QTest.keyPress(widget, Qt.Key_Enter)\n self.assertEqual(119, proc._poi_index)\n\n widget = ctrl_widget.ma_window_le\n widget.clear()\n QTest.keyClicks(widget, \"9\")\n QTest.keyPress(widget, Qt.Key_Enter)\n self.assertEqual(9, proc.__class__._raw_ma.window)\n\n widget = ctrl_widget.scale_le\n widget.clear()\n QTest.keyClicks(widget, \"0.002\")\n QTest.keyPress(widget, Qt.Key_Enter)\n self.assertEqual(0.002, proc._scale)\n widget.clear()\n QTest.keyClicks(widget, \"-1\")\n QTest.keyPress(widget, Qt.Key_Enter)\n self.assertEqual(1, proc._scale) # cannot enter '-'\n\n widget = ctrl_widget.offset_le\n widget.clear()\n QTest.keyClicks(widget, \"-0.18\")\n QTest.keyPress(widget, Qt.Key_Enter)\n self.assertEqual(-0.18, proc._offset)\n\n widget = ctrl_widget.bin_range_le\n widget.clear()\n QTest.keyClicks(widget, \"-1.0, 1.0\")\n QTest.keyPress(widget, Qt.Key_Enter)\n self.assertTupleEqual((-1.0, 1.0), proc._bin_range)\n\n widget = ctrl_widget.n_bins_le\n widget.clear()\n QTest.keyClicks(widget, \"1000\")\n QTest.keyPress(widget, Qt.Key_Enter)\n self.assertEqual(100, proc._n_bins) # maximum is 999 and one can not put the 3rd 0 in\n widget.clear()\n QTest.keyClicks(widget, \"999\")\n QTest.keyPress(widget, Qt.Key_Enter)\n self.assertEqual(999, proc._n_bins)\n\n ctrl_widget.hist_over_ma_cb.setChecked(True)\n self.assertTrue(proc._hist_over_ma)\n\n\nclass TestGotthardProcessor(_RawDataMixin, _SpecialSuiteProcessorTestBase):\n @pytest.fixture(autouse=True)\n def setUp(self):\n self._proc = GotthardProcessor(object(), object())\n\n self._proc._output_channel = \"gotthard:output\"\n self._adc = np.random.randint(0, 100, size=(4, 4), dtype=np.uint16)\n\n def _get_data(self, tid, times=1):\n # data, meta\n return self._gen_data(tid, {\n \"gotthard:output\": [\n (\"data.adc\", times * self._adc),\n (\"data.3d\", np.ones((4, 2, 2)))\n ]})\n\n def testPreProcessing(self):\n proc = self._proc\n data = self._get_data(12345)\n\n with pytest.raises(ProcessingError, match=\"actual 3D\"):\n with patch.object(GotthardProcessor, \"_ppt\",\n new_callable=PropertyMock, create=True, return_value=\"data.3d\"):\n proc.process(data)\n\n with pytest.raises(ProcessingError, match=\"out of boundary\"):\n proc._poi_index = 100\n processed = proc.process(data)\n assert processed is None\n # test not raise\n proc._poi_index = 3\n proc.process(data)\n with pytest.raises(ProcessingError, match=\"out of boundary\"):\n # test with slicer\n proc._pulse_slicer = slice(None, None, 2)\n proc.process(data)\n\n @patch(\"extra_foam.special_suite.special_analysis_base.QThreadWorker._loadRunDirectoryST\")\n def testLoadDarkRun(self, load_run):\n proc = self._proc\n\n load_run.return_value = None\n # nothing should happen\n proc.onLoadDarkRun(\"run/path\")\n\n data_collection = MagicMock()\n load_run.return_value = data_collection\n with patch.object(proc.log, \"error\") as error:\n # get_array returns a wrong shape\n data_collection.get_array.return_value = DataArray(np.random.randn(4, 3))\n proc.onLoadDarkRun(\"run/path\")\n error.assert_called_once()\n assert \"Data must be a 3D array\" in error.call_args[0][0]\n error.reset_mock()\n\n # get_array returns a correct shape\n data_collection.get_array.return_value = DataArray(np.random.randn(4, 3, 2))\n with patch.object(proc.log, \"info\") as info:\n proc.onLoadDarkRun(\"run/path\")\n info.assert_called_once()\n assert \"Found dark data with shape\" in info.call_args[0][0]\n error.assert_not_called()\n\n def testProcessingWhenRecordingDark(self):\n from extra_foam.special_suite.gotthard_proc import _PIXEL_DTYPE\n\n proc = self._proc\n assert 2147483647 == proc.__class__._dark_ma.window\n proc._recording_dark_st = True\n proc._subtract_dark_st = True # take no effect\n proc._poi_index = 0\n\n adc_gt = self._adc.astype(_PIXEL_DTYPE)\n adc_gt2 = 2.0 * self._adc\n adc_gt_avg = 1.5 * self._adc\n\n # 1st train\n processed = proc.process(self._get_data(12345))\n np.testing.assert_array_almost_equal(adc_gt, proc._dark_ma)\n np.testing.assert_array_almost_equal(np.mean(adc_gt, axis=0), proc._dark_mean_ma)\n assert 0 == processed[\"poi_index\"]\n np.testing.assert_array_almost_equal(adc_gt, processed[\"spectrum\"])\n np.testing.assert_array_almost_equal(adc_gt, processed[\"spectrum_ma\"])\n np.testing.assert_array_almost_equal(np.mean(adc_gt, axis=0), processed[\"spectrum_mean\"])\n np.testing.assert_array_almost_equal(np.mean(adc_gt, axis=0), processed[\"spectrum_ma_mean\"])\n assert np.mean(adc_gt) == processed[\"hist\"][2]\n\n # 2nd train\n processed = proc.process(self._get_data(12346, 2))\n np.testing.assert_array_almost_equal(adc_gt_avg, proc._dark_ma)\n np.testing.assert_array_almost_equal(np.mean(adc_gt_avg, axis=0), proc._dark_mean_ma)\n assert 0 == processed[\"poi_index\"]\n np.testing.assert_array_almost_equal(adc_gt2, processed[\"spectrum\"])\n np.testing.assert_array_almost_equal(adc_gt_avg, processed[\"spectrum_ma\"])\n np.testing.assert_array_almost_equal(np.mean(adc_gt2, axis=0), processed[\"spectrum_mean\"])\n np.testing.assert_array_almost_equal(np.mean(adc_gt_avg, axis=0), processed[\"spectrum_ma_mean\"])\n assert np.mean(adc_gt2) == processed[\"hist\"][2]\n\n # 3nd train\n proc._hist_over_ma = True\n processed = proc.process(self._get_data(12347, 3))\n np.testing.assert_array_almost_equal(adc_gt2, proc._dark_ma)\n np.testing.assert_array_almost_equal(np.mean(adc_gt2, axis=0), proc._dark_mean_ma)\n assert np.mean(adc_gt2) == processed[\"hist\"][2]\n\n # reset\n proc.reset()\n assert proc._dark_ma is None\n\n @pytest.mark.parametrize(\"subtract_dark\", [(True, ), (False,)])\n def testProcessing(self, subtract_dark):\n from extra_foam.special_suite.gotthard_proc import _PIXEL_DTYPE\n\n proc = self._proc\n proc._recording_dark = False\n proc._poi_index = 1\n proc._scale = 0.1\n proc._offset = 0.2\n\n proc._subtract_dark = subtract_dark\n offset = np.ones(self._adc.shape[1]).astype(np.float32)\n proc._dark_mean_ma = offset\n proc._hist_over_ma = False\n\n adc_gt = self._adc.astype(_PIXEL_DTYPE)\n adc_gt2 = 2.0 * self._adc\n adc_gt_avg = 1.5 * self._adc\n if subtract_dark:\n adc_gt -= offset\n adc_gt2 -= offset\n adc_gt_avg -= offset\n\n # 1st train\n processed = proc.process(self._get_data(12345))\n self._check_processed_data_structure(processed)\n assert 1 == processed[\"poi_index\"]\n np.testing.assert_array_almost_equal(adc_gt, processed[\"spectrum\"])\n np.testing.assert_array_almost_equal(adc_gt, processed[\"spectrum_ma\"])\n np.testing.assert_array_almost_equal(np.mean(adc_gt, axis=0), processed[\"spectrum_mean\"])\n np.testing.assert_array_almost_equal(np.mean(adc_gt, axis=0), processed[\"spectrum_ma_mean\"])\n assert np.mean(adc_gt) == processed[\"hist\"][2]\n\n # 2nd train\n proc.__class__._raw_ma.window = 3\n processed = proc.process(self._get_data(12346, 2))\n assert 1 == processed[\"poi_index\"]\n np.testing.assert_array_almost_equal(adc_gt2, processed[\"spectrum\"])\n np.testing.assert_array_almost_equal(adc_gt_avg, processed[\"spectrum_ma\"])\n np.testing.assert_array_almost_equal(np.mean(adc_gt2, axis=0), processed[\"spectrum_mean\"])\n np.testing.assert_array_almost_equal(np.mean(adc_gt_avg, axis=0), processed[\"spectrum_ma_mean\"])\n assert np.mean(adc_gt2) == processed[\"hist\"][2]\n\n # 3nd train\n proc._hist_over_ma = True\n processed = proc.process(self._get_data(12347, 3))\n assert np.mean(adc_gt2) == processed[\"hist\"][2]\n\n # reset\n proc.reset()\n assert proc._raw_ma is None\n\n def testCalibration(self):\n proc = self._proc\n\n processed = proc.process(self._get_data(12345))\n assert processed[\"x\"] is None\n\n proc._scale = 0.1\n proc._offset = 0.2\n processed = proc.process(self._get_data(12345))\n np.testing.assert_array_almost_equal(np.arange(len(self._adc)) * 0.1 - 0.2, processed['x'])\n\n def testPulseSlicerChange(self):\n proc = self._proc\n\n del proc._dark_ma\n proc._dark_mean_ma = None\n proc._pulse_slicer = slice(None, None)\n\n proc.onPulseSlicerChanged([None, 4])\n assert proc._dark_mean_ma is None\n\n proc._dark_ma = np.random.randn(4, 2)\n proc.onPulseSlicerChanged([None, None, 2])\n # test _dark_mean_ma was re-calculated\n np.testing.assert_array_almost_equal(np.mean(proc._dark_ma[::2], axis=0), proc._dark_mean_ma)\n\n def testRemoveDark(self):\n proc = self._proc\n proc._dark_ma = np.ones((2, 2))\n proc._dark_mean_ma = np.ones((2, 2))\n\n proc.onRemoveDark()\n assert proc._dark_ma is None\n assert proc._dark_mean_ma is None\n\n def _check_processed_data_structure(self, ret):\n \"\"\"Override.\"\"\"\n data_gt = TestGotthardWindow.data4visualization().keys()\n assert set(ret.keys()) == set(data_gt)\n" ]
[ [ "numpy.arange", "numpy.ones", "numpy.random.randn", "numpy.random.randint", "numpy.mean", "numpy.testing.assert_array_almost_equal" ] ]
gdalle/PartiallyObservedVectorAutoRegressions
[ "28c9d34d7b6e45679e442721daf4946867fd5fb0" ]
[ "src/read_actual_data.py" ]
[ "import itertools\nimport os\nimport zipfile\nfrom joblib import Parallel, delayed\nimport pandas as pd\nfrom tqdm.notebook import tqdm\n\n# Constants\n\nYEARS = [\"2018\", \"2019\", \"2020\", \"2021\"]\nMONTHS = [\"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"10\", \"11\", \"12\"]\n\nDATA_COLUMNS = {\n \"BETRIEBSTAG\": (\"date\", \"string\"),\n \"FAHRT_BEZEICHNER\": (\"trip_id\", \"category\"),\n \"BETREIBER_ID\": (\"agency_id\", \"category\"),\n \"BETREIBER_ABK\": (\"agency_short_name\", \"category\"),\n \"BETREIBER_NAME\": (\"agency_name\", \"category\"),\n \"PRODUKT_ID\": (\"transportation_type\", \"category\"),\n \"LINIEN_ID\": (\"line_id\", \"category\"),\n \"LINIEN_TEXT\": (\"line_name\", \"category\"),\n \"UMLAUF_ID\": (\"circuit_transfer\", \"category\"),\n \"VERKEHRSMITTEL_TEXT\": (\"transportation_subtype\", \"category\"),\n \"ZUSATZFAHRT_TF\": (\"unplanned_trip\", \"category\"),\n \"FAELLT_AUS_TF\": (\"cancelled_trip\", \"category\"),\n \"BPUIC\": (\"stop_id\", \"category\"),\n \"HALTESTELLEN_NAME\": (\"stop_name_unofficial\", \"category\"),\n \"ANKUNFTSZEIT\": (\"arrival_time_planned\", \"string\"),\n \"AN_PROGNOSE\": (\"arrival_time_real\", \"string\"),\n \"AN_PROGNOSE_STATUS\": (\"arrival_time_status\", \"category\"),\n \"ABFAHRTSZEIT\": (\"departure_time_planned\", \"string\"),\n \"AB_PROGNOSE\": (\"departure_time_real\", \"string\"),\n \"AB_PROGNOSE_STATUS\": (\"departure_time_status\", \"category\"),\n \"DURCHFAHRT_TF\": (\"skipped_stop\", \"category\"),\n}\n\nAGENCY_NAMES = [\"Verkehrsbetriebe Zürich\", \"Verkehrsbetriebe Zürich INFO+\"]\nTRANSPORTATION_TYPES = [\"Tram\"]\n\n# Utils\n\n\ndef concat_preserving_categorical(dfs):\n \"\"\"Concatenate while preserving categorical columns.\"\"\"\n columns, dtypes = dfs[0].columns, dfs[0].dtypes\n res = pd.DataFrame()\n for c in tqdm(columns, desc=\"Concatenation \"):\n if str(dtypes[c]) == \"category\":\n res[c] = pd.api.types.union_categoricals(\n [df[c].astype(\"category\") for df in dfs]\n )\n else:\n res[c] = pd.concat([df[c] for df in dfs])\n return res\n\n\n# Read CSV files\n\n\ndef read_day_csv(daily_csv_path):\n \"\"\"Read daily csv in the right format.\"\"\"\n try:\n data = pd.read_csv(\n daily_csv_path,\n sep=\";\",\n dtype={c: DATA_COLUMNS[c][1] for c in DATA_COLUMNS.keys()},\n )\n except UnicodeDecodeError:\n print(\"Skipped (UTF-8 error): \", daily_csv_path)\n return None\n # Rename columns\n data = data.rename(\n mapper={c: DATA_COLUMNS[c][0] for c in DATA_COLUMNS.keys()}, axis=1\n )\n # Convert datetime columns\n for timecol in [\"date\"]:\n data[timecol] = pd.to_datetime(\n data[timecol], format=\"%d.%m.%Y\", errors=\"coerce\"\n )\n for timecol in [\"arrival_time_planned\", \"departure_time_planned\"]:\n data[timecol] = pd.to_datetime(\n data[timecol], format=\"%d.%m.%Y %H:%M\", errors=\"coerce\"\n )\n for timecol in [\"arrival_time_real\", \"departure_time_real\"]:\n data[timecol] = pd.to_datetime(\n data[timecol], format=\"%d.%m.%Y %H:%M:%S\", errors=\"coerce\"\n )\n # Translate columns in German\n for status_col in [\"arrival_time_status\", \"departure_time_status\"]:\n data[status_col] = (\n data[status_col]\n .replace(\n {\n \"PROGNOSE\": \"Forecast\",\n \"GESCHAETZT\": \"Estimated\",\n \"UNBEKANNT\": \"Unknown\",\n \"REAL\": \"Real\",\n }\n )\n .fillna(\"Forecast\")\n .astype(\"category\")\n )\n data[\"transportation_type\"] = (\n data[\"transportation_type\"]\n .replace(\n {\n \"Zug\": \"Train\",\n \"Bus\": \"Bus\",\n \"BUS\": \"Bus\",\n \"Schiff\": \"Boat\",\n \"Tram\": \"Tram\",\n }\n )\n .fillna(\"Unknown\")\n .astype(\"category\")\n )\n return data\n\n\n# A pyramid of decompression and recompression\n\n\ndef unzip_single_month_store_days(\n monthly_zip_dir_path, monthly_zip_name, daily_parquet_dir_path\n):\n \"\"\"Read a single zipped month full of csv and split it into parquet days.\"\"\"\n monthly_zip_path = os.path.join(monthly_zip_dir_path, monthly_zip_name)\n with zipfile.ZipFile(monthly_zip_path) as monthly_zip_file:\n # Loop over all days of the month\n for daily_csv_name in monthly_zip_file.namelist():\n # Skip additional files\n if \".csv\" not in daily_csv_name:\n continue\n # Open and parse csv\n with monthly_zip_file.open(daily_csv_name, \"r\") as daily_csv_file:\n daily_data = read_day_csv(daily_csv_file)\n # Filter\n if daily_data is not None:\n daily_data = daily_data[\n daily_data[\"agency_name\"].isin(AGENCY_NAMES)\n & daily_data[\"transportation_type\"].isin(TRANSPORTATION_TYPES)\n ]\n # Save as parquet file\n parquet_file_name = daily_csv_name.split(\"/\")[-1][:10] + \".parquet\"\n daily_data.to_parquet(\n os.path.join(daily_parquet_dir_path, parquet_file_name)\n )\n\n\ndef unzip_months_store_days(\n monthly_zip_dir_path,\n daily_parquet_dir_path,\n):\n \"\"\"Read all zipped months full of csv and split them into parquet days.\"\"\"\n monthly_zip_names = [\n name\n for name in sorted(os.listdir(monthly_zip_dir_path))\n if name.startswith(\"19_\") or name.startswith(\"18_\")\n ]\n Parallel(n_jobs=6)(\n delayed(unzip_single_month_store_days)(\n monthly_zip_dir_path, monthly_zip_name, daily_parquet_dir_path\n )\n for monthly_zip_name in tqdm(\n monthly_zip_names, desc=\"Decompressing months for 2018-2019\"\n )\n )\n\n\ndef read_days_store_months(daily_parquet_dir_path, monthly_parquet_dir_path):\n \"\"\"Read parquet days and put them together into months.\"\"\"\n for (year, month) in list(itertools.product(YEARS, MONTHS)):\n yearmonth = \"{}-{}\".format(year, month)\n daily_files = sorted(\n [file for file in os.listdir(daily_parquet_dir_path) if yearmonth in file]\n )\n if daily_files:\n monthly_data_list = []\n for date in tqdm(daily_files, desc=\"Reading \" + yearmonth):\n daily_data = pd.read_parquet(os.path.join(daily_parquet_dir_path, date))\n monthly_data_list.append(daily_data)\n monthly_data = concat_preserving_categorical(monthly_data_list)\n monthly_data.to_parquet(\n os.path.join(monthly_parquet_dir_path, yearmonth + \".parquet\")\n )\n\n\ndef read_months_return_full(\n monthly_parquet_dir_path, years=[2018, 2019]\n):\n \"\"\"Read parquet months and put them together into a full dataframe.\"\"\"\n data = concat_preserving_categorical(\n [\n pd.read_parquet(os.path.join(monthly_parquet_dir_path, monthly_file))\n for monthly_file in tqdm(\n sorted(os.listdir(monthly_parquet_dir_path)), desc=\"Reading files \"\n )\n if any(str(year) in monthly_file for year in years)\n ]\n )\n return data\n" ]
[ [ "pandas.concat", "pandas.to_datetime", "pandas.DataFrame" ] ]
jonasvj/TFDE
[ "c5d25947b28524c7a40626f797ca8c157fa70a53" ]
[ "plot_grid.py" ]
[ "#!/usr/bin/env python3\nimport sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef tt_params(K, M):\n return K + 3*M*K**2\n\ndef tt_dof(K, M):\n return (K-1) + M*K*(K-1) + 2*M*K**2\n\ndef bic(n, k, nllh_per_sample):\n log_lh = -1*nllh_per_sample*n\n return k*np.log(n) - 2*log_lh\n\ndef aic(n, k, nllh_per_sample):\n log_lh = -1*nllh_per_sample*n\n return 2*k - 2*log_lh\n\ndef n_params(model, K, M):\n if model == 'TT':\n return (K-1) + M*K*(K-1) + 2*M*K*K\n elif model == 'CP':\n return (K-1) + 2*M*K\n elif model == 'GMM':\n return (K-1) + (2*M + M*(M-1)/2)*K\n\n\nsizes = {\n 'power': {'n_train': 1659917, 'n_val': 184435, 'n_test': 204928, 'M': 6}, \n 'gas': {'n_train': 852174, 'n_val': 94685, 'n_test': 105206, 'M': 8},\n 'hepmass': {'n_train': 315123, 'n_val': 35013, 'n_test': 174987, 'M': 21},\n 'miniboone': {'n_train': 29556, 'n_val': 3284, 'n_test': 3648, 'M': 43},\n 'bsds300': {'n_train': 1000000, 'n_val': 50000, 'n_test': 250000, 'M': 63},\n '8gaussians': {'n_train': 30000, 'n_val': 30000, 'n_test': 30000, 'M': 2},\n 'checkerboard': {'n_train': 30000, 'n_val': 30000, 'n_test': 30000, 'M': 2},\n '2spirals': {'n_train': 30000, 'n_val': 30000, 'n_test': 30000, 'M': 2}\n }\n\ndf = pd.read_csv('results/grid_results.txt', index_col=0)\ndf_gmm = pd.read_csv('results/gmm_results.txt', index_col=0)\ndf = df.append(df_gmm, ignore_index=True)\n\ndf = df[df.optimal_order == 1]\nprint(df)\n# Add new columns\ndf['M'] = df.apply(lambda row: sizes[row.dataset]['M'], axis=1)\ndf['dof'] = df.apply(lambda row: n_params(row.model_type, row.K, row.M), axis=1)\ndatasets = ['hepmass', 'miniboone']\nsubsample_sizes = [1750, 7000, 28000]\n\ngroups = df.groupby(['dataset', 'subsample_size'])\n\nfig, axes = plt.subplots(nrows=2, ncols=3, figsize=(24, 12),\n sharex='all', sharey='row')\n\nfor i, (group, frame) in enumerate(groups):\n row_idx = datasets.index(group[0])\n col_idx = subsample_sizes.index(group[1])\n model_groups = frame.groupby(['model_type'])\n\n for model, model_frame in model_groups:\n mean = model_frame.groupby('dof').mean()\n sem = model_frame.groupby('dof').sem()\n min_ = model_frame.groupby('dof').min()\n\n axes[row_idx, col_idx].errorbar(\n mean.index, mean.nllh_test, yerr=sem.nllh_test, fmt='.:',\n label=model, alpha=.75, capsize=3, capthick=1)\n \n axes[row_idx, col_idx].set_xlabel('Free parameters')\n axes[row_idx, col_idx].set_ylabel(f'Test NLLH per sample ({group[0]})')\n axes[row_idx, col_idx].set_title(f'Subsample size: {group[1]}')\n axes[row_idx, col_idx].legend()\n \n\nfig.savefig('plots/' + 'grid_plot.pdf')\nplt.close()" ]
[ [ "numpy.log", "pandas.read_csv", "matplotlib.pyplot.subplots", "matplotlib.pyplot.close" ] ]
Developernation/PythonProjects
[ "d682960d060cb1daede3f2f8e814a5aea05c0ec6" ]
[ "sans_tools/NotesAppFe.py" ]
[ "from tkinter.filedialog import askopenfilename\nfrom tkinter.messagebox import showinfo\nfrom NotesApp import SansNotesApp as snp\nfrom datetime import datetime\nfrom tkinter import ttk\nimport tkinter as tk\nimport pandas as pd\nimport os\npd.set_option('display.max_rows', None)\n\n#database connection\nnotes_db = snp()\nnotes_db.database_name = 'sans'\nnotes_db.db_connect_and_cursor()\ndb_list = notes_db.show_databases()\nnotes_db.create_table('default_sans_table')\ndb_tables = notes_db.show_tables()\n\n#first frame\ndef build_frame(label_text_info,box_width,master_frame,label_width=10):\n frame1 = tk.Frame(master=master_frame,relief=border_effects['flat'],width=100, height=10)\n text_box1 = tk.Entry(master=frame1, width=box_width, borderwidth=4)\n label1 = tk.Label(master=frame1, text=label_text_info,width=label_width)\n label1.pack(side='left')\n text_box1.pack(side='left')\n frame1.pack(fill=tk.X)\n return text_box1\n\n\n#-------------------------------------------------------------------------\nborder_effects = {\n \"flat\": tk.FLAT,\n \"sunken\": tk.SUNKEN,\n \"raised\": tk.RAISED,\n \"groove\": tk.GROOVE,\n \"ridge\": tk.RIDGE,\n}\n\nmin_width, min_height = 300,400\n\nlabel_text = ['Subject:','Topic:','Book:','Page:','Notes:']\n\n\nwindow = tk.Tk()\n\ntabControl = ttk.Notebook(window)\n\nwindow.minsize(min_width, min_height)\nwindow.title('SANS NOTES APP')\n\n#setting defaults for table list\nclickedA = tk.StringVar()\nclickedA.set(db_tables[0])\n\nclickedB = tk.StringVar()\nclickedB.set(db_tables[0])\n\nclickedC = tk.StringVar()\nclickedC.set(db_tables[0])\n\n########################################################\n#################### Add Data ##########################\n########################################################\n\nsuper_frame_tab1 = ttk.Frame(master=window,relief=border_effects['flat'])\n\n\ndrop_down_frameA = tk.Frame(master=super_frame_tab1,relief=border_effects['flat'],width=50, height=10)\ndrop_down_labelA = tk.Label( drop_down_frameA , text = \"Select Table:\" )\ndrop_down_labelA.pack(side='left')\n# Create Dropdown menu\ndropA = tk.OptionMenu(drop_down_frameA , clickedA, *db_tables)\ndropA.pack(side='left')\ndrop_down_frameA.pack(fill=tk.X)\n \n\nfrm0 = build_frame(label_text[0],10,super_frame_tab1)\nfrm1 = build_frame(label_text[1],40,super_frame_tab1)\nfrm2 = build_frame(label_text[2],5,super_frame_tab1)\nfrm3 = build_frame(label_text[3],5,super_frame_tab1)\n\n\nframe3 = tk.Frame(master=super_frame_tab1,relief=border_effects['flat'],width=50, height=10)\ninputtxt = tk.Text(master= frame3, height = 5, width = 52,borderwidth=4,relief=border_effects['sunken'])\nlabel2 = tk.Label(master=frame3, text=label_text[4],width=10)\nlabel2.pack(side='left')\ninputtxt.pack(side='left')\nframe3.pack(fill=tk.X)\n\ndef write_dataA():\n input_vals = {\n 'table': clickedA.get().strip(),\n 'subject':frm0.get().strip(),\n 'topic':frm1.get().strip(),\n 'book':frm2.get().strip(),\n 'page':frm3.get().strip(),\n 'notes':inputtxt.get(\"1.0\",\"end-1c\").strip(),\n }\n\n notes_db.insert_values(\n input_vals['table'],\n input_vals['subject'],\n input_vals['topic'],\n input_vals['book'],\n input_vals['page'],\n input_vals['notes']\n )\n return input_vals\n\ndef add_opt(): \n dropA['menu'].add_command(label=frm0_tb3.get(), command=tk._setit(clickedA, frm0_tb3.get()))\n dropB['menu'].add_command(label=frm0_tb3.get(), command=tk._setit(clickedB, frm0_tb3.get()))\n dropC['menu'].add_command(label=frm0_tb3.get(), command=tk._setit(clickedC, frm0_tb3.get()))\n global db_tables\n db_tables.append(frm0_tb3.get())\n\ndef create_table():\n notes_db.create_table(frm0_tb3.get().strip())\n add_opt()\n return True\n\ndef remove_item():\n r_index1=dropB['menu'].index(frm0_tb3.get())\n dropB['menu'].delete(r_index1)\n clickedB.set(dropB['menu'].entrycget(0,\"label\")) # select the first one \n\n r_index2=dropA['menu'].index(frm0_tb3.get())\n dropA['menu'].delete(r_index2)\n clickedA.set(dropB['menu'].entrycget(0,\"label\")) # select the first one \n \n r_index3=dropC['menu'].index(frm0_tb3.get())\n dropC['menu'].delete(r_index3)\n clickedC.set(dropC['menu'].entrycget(0,\"label\")) # select the first one \n return True \n\ndef delete_table():\n notes_db.drop_table(frm0_tb3.get().strip())\n remove_item()\n return True\n\n\nframe5 = tk.Frame(master=super_frame_tab1,relief=border_effects['flat'],width=100, height=10)\nlabel_opt = tk.Label(master=frame5, text='Options',width=10)\n\nAdd_Button = tk.Button(master=frame5, \n height = 1,\n width = 10,\n text =\"Add Data\",\n relief=tk.RAISED,\n fg = \"blue\",\n command = lambda:write_dataA()\n )\n\n\n\nframe5.pack(fill=tk.X)\nlabel_opt.pack(side='left')\nAdd_Button.pack(side='left')\ntabControl.add(super_frame_tab1,text='Add Data')\n\n#############################################################\n######################## SEARCH DATA TAB ####################\n#############################################################\ndef show_search_data():\n Output.delete('1.0', tk.END)\n global show_vals\n show_vals = {\n 'table': clickedB.get(),\n 'subject':frm0_tb2.get(),\n 'topic':frm1_tb2.get(),\n 'book':frm2_tb2.get(),\n 'page':frm3_tb2.get(),\n }\n \n global search_data\n search_data = notes_db.search_data( \n show_vals['table'],\n show_vals['subject'],\n show_vals['topic'],\n show_vals['book'],\n show_vals['page'],\n strict_search = False\n )\n \n Output.insert(tk.END,search_data)\n\ndef show_all_table_data():\n Output.delete('1.0', tk.END)\n global search_data\n search_data = notes_db.show_table_data(clickedB.get())\n Output.insert(tk.END,search_data)\n\ndef show_all_ingest_columns():\n Output_tb4.delete('1.0', tk.END)\n col_data = None\n if filename.endswith('xlsx'):\n col_data = list(pd.read_excel(filename).columns)\n else:\n col_data = list(pd.read_csv(filename).columns)\n Output_tb4.insert(tk.END,\"\"\"\n *********Directions****** \n 1) Map the columns in your file to their respective column in the \n table schema by entering them in the spaces above.\n\n 2) If you do not want to map a specific column from you file you can \n leave the entry blank.\n\n Below are the columns in your file:\\n\n ******************** Ingest Data Column Names *******************\n \\n\\t{}\n *****************************************************************\n \"\"\".format('\\n\\t'.join(col_data)))\n\ndef delete_data():\n notes_db.delete_data(\n table_name=clickedB.get().strip(),\n subject=frm0_tb2.get().strip(),\n topic=frm1_tb2.get().strip(),\n book=frm2_tb2.get().strip(),\n page=frm3_tb2.get().strip(),\n )\n show_search_data()\n\ndef save_to_excel():\n save_location = f\"{os.path.join(os.path.expanduser('~'),'Downloads','search_data' + datetime.today().strftime('%y%m%d_%H%M%S'))}.xlsx\"\n search_data.sort_values(by='topic').reset_index(drop=True).to_excel(\n save_location\n )\n \n showinfo(\n title='File Saved',\n message=\"File has been saved to:\\n{}\".format(save_location)\n )\n\nsuper_frame_tab2 = ttk.Frame(master=window,relief=border_effects['flat'])\n\ndrop_down_frameB = tk.Frame(master=super_frame_tab2,relief=border_effects['flat'],width=50, height=10)\ndrop_down_labelB = tk.Label( drop_down_frameB , text = \"Select Table:\" )\ndrop_down_labelB.pack(side='left')\n\n# Create Dropdown menu\ndropB = tk.OptionMenu(drop_down_frameB , clickedB, *db_tables)\ndropB.pack(side='left')\ndrop_down_frameB.pack(fill=tk.X)\n\n\nfrm0_tb2 = build_frame(label_text[0],10,super_frame_tab2)\nfrm1_tb2 = build_frame(label_text[1],40,super_frame_tab2)\nfrm2_tb2 = build_frame(label_text[2],5,super_frame_tab2)\nfrm3_tb2 = build_frame(label_text[3],5,super_frame_tab2)\n\n\nframe0a_tb2 = tk.Frame(master=super_frame_tab2,relief=border_effects['flat'],width=100, height=10)\nlabel_opt2 = tk.Label(master=frame0a_tb2, text='Options:',width=10)\n\nShow_Search_Button = tk.Button(master=frame0a_tb2, \n height = 1,\n width = 15,\n text =\"Show Search Data\",\n relief=tk.RIDGE,\n fg = \"blue\",\n command = lambda : show_search_data() )\n\nSearch_All_Data = tk.Button(master=frame0a_tb2, \n height = 1,\n width = 15,\n text =\"Show All Data\",\n relief=tk.RIDGE,\n fg = \"blue\",\n command = lambda : show_all_table_data())\n\nTo_Excel_Button = tk.Button(master=frame0a_tb2, \n height = 1,\n width = 15,\n text =\"Save Display To Excel\",\n relief=tk.RIDGE,\n fg = \"blue\",\n command = lambda : save_to_excel())\n\nDelete_Data_Button = tk.Button(master=frame0a_tb2, \n height = 1,\n width = 15,\n text =\"Delete Displayed Data\",\n relief=tk.RIDGE,\n fg = \"red\",\n command = lambda : delete_data())\n\nlabel_opt2.pack(side='left')\nShow_Search_Button.pack(side='left')\nSearch_All_Data.pack(side='left')\nTo_Excel_Button.pack(side='left')\nDelete_Data_Button.pack(side='left')\nframe0a_tb2.pack(fill=tk.X)\n#------\nframe0b_tb2 = tk.Frame(master=super_frame_tab2,relief=border_effects['flat'],width=100, height=10)\n###\nOutput = tk.Text(frame0b_tb2, height = 50,\n width = 150,\n bg = \"light cyan\")\n###\nOutput.pack(side='left')\n\nframe0b_tb2.pack(fill=tk.X)\n\nsuper_frame_tab2.pack(fill=tk.X)\n\ntabControl.add(super_frame_tab2,text='Search Data')\n\ntabControl.pack(expand=1, fill=\"both\",side='right')\n\n############################################################################\n#################### Create / Delete Table #################################\n############################################################################\nsuper_frame_tab3 = ttk.Frame(master=window,relief=border_effects['flat'])\n\nfrm0_tb3 = build_frame('Table Nane:\\n *Only letters \\n & underscores*',20,super_frame_tab3)\n\n#------\nframe0_tb3 = tk.Frame(master=super_frame_tab3,relief=border_effects['flat'],width=100, height=10)\nlabel_opt3 = tk.Label(master=frame0_tb3, text='Options:',width=10)\nCreate_Button = tk.Button(master=frame0_tb3, \n height = 1,\n width = 15,\n text =\"Create Table\",\n relief=tk.RIDGE,\n padx=5,\n fg = \"blue\",\n command = create_table\n )\n\nDelete_Table = tk.Button(master=frame0_tb3, \n height = 1,\n width = 10,\n text =\"Delete Table\",\n relief=tk.RIDGE,\n fg = \"red\",\n command = delete_table\n )\nlabel_opt3.pack(side='left')\nCreate_Button.pack(side='left')\nDelete_Table.pack(side='left')\n\nframe0_tb3.pack(fill=tk.X)\n\ntabControl.add(super_frame_tab3,text='Create Table')\n\ntabControl.pack(expand=1, fill=\"both\",side='right')\n\n#############################################################################\n####################### Upload Excel File ###################################\n#############################################################################\nsuper_frame_tab4 = ttk.Frame(master=window,relief=border_effects['flat'])\n\ndirections_frame = tk.Frame(master=super_frame_tab4,relief=border_effects['flat'],width=70, height=50)\ndirections_text = \"\"\"\"\n ********** File Upload Directions **********\n 1) Select a table to upload data or create one in the Create Table tab.\n 2) Select your file by using the Ingest Data button below\n 3) Click Show Columns to display the availble columns for mapping to the table schema columns\n 4) Enter the columns from your file that you would like to map to table schema columns in section below\n 5) Click the Upload Data button\n\"\"\" \n\ndirections_label = tk.Label(master=directions_frame, text=directions_text ,width=70)\ndirections_label.pack(side='left')\ndirections_frame.pack(fill=tk.X) \n\ndrop_down_frameC = tk.Frame(master=super_frame_tab4,relief=border_effects['flat'],width=50, height=10)\ndrop_down_labelC = tk.Label( drop_down_frameC , text = \"Select Table:\" )\ndrop_down_labelC.pack(side='left')\n# Create Dropdown menu\ndropC = tk.OptionMenu(drop_down_frameC , clickedC, *db_tables)\ndropC.pack(side='left')\ndrop_down_frameC.pack(fill=tk.X)\n\nfrm0_tb4 = build_frame(f'{label_text[0][:-1]} Column Mapping',10,super_frame_tab4,label_width=20)\nfrm1_tb4 = build_frame(f'{label_text[1][:-1]} Column Mapping',10,super_frame_tab4,label_width=20)\nfrm2_tb4 = build_frame(f'{label_text[2][:-1]} Column Mapping',10,super_frame_tab4,label_width=20)\nfrm3_tb4 = build_frame(f'{label_text[3][:-1]} Column Mapping',10,super_frame_tab4,label_width=20)\nfrm6_tb4 = build_frame('Notes Column Mapping',10,super_frame_tab4,label_width=20)\n\ndef ingest_file_data():\n\n #select file\n filetypes = (\n ('CSV files', '*.csv'),\n ('Excel files', '*.xlsx')\n )\n global filename \n filename = askopenfilename(\n title='Open files',\n initialdir='/',\n filetypes=filetypes)\n\n showinfo(\n title='Selected Files',\n message=f'You selected:\\n {filename}'\n )\n\ndef check_len(str_):\n return str_ if len(str_) > 0 else None\n\n\ndef upload_data():\n Output_tb4.delete('1.0', tk.END)\n table = clickedC.get()\n\n subject = frm0_tb4.get()\n topic = frm1_tb4.get()\n book = frm2_tb4.get()\n page = frm3_tb4.get()\n notes = frm6_tb4.get()\n \n mapping_vals = {\n \n 'subject': check_len(subject),\n 'topic': check_len(topic),\n 'book': check_len(book),\n 'page': check_len(page),\n 'notes': check_len(notes),\n }\n\n notes_db.set_ingest_file(\n filename\n )\n\n notes_db.rename_df_columns(\n topic_column=mapping_vals['topic'],\n subject_column=mapping_vals['subject'],\n page_column=mapping_vals['page'],\n notes_column=mapping_vals['notes'],\n book_column=mapping_vals['book']\n )\n\n cursor = notes_db.get_cursor()\n\n res = notes_db.build_insert_query(\n table,\n cursor,\n topic_column=mapping_vals['topic'],\n subject_column=mapping_vals['subject'],\n page_column=mapping_vals['page'],\n notes_column=mapping_vals['notes'],\n book_column=mapping_vals['book']\n )\n\n if res:\n showinfo(\n title='File Uploaded',\n message=f'{filename} was uploaded to {table}'\n )\n\n else:\n showinfo(\n title='File Upload Failure',\n message=\"Please review input colums:\\n{}\".format(',\\n'.join(icols))\n )\n\n\n\n \n \nfrm4_tb4 = tk.Frame(master=super_frame_tab4,relief=border_effects['flat'],width=100, height=10)\nlabel_opt4a = tk.Label(master=frm4_tb4, text='Options:',width=10)\nIngest_Button = tk.Button(master=frm4_tb4, \n height = 1,\n width = 15,\n text =\"Ingest Data\",\n relief=tk.RIDGE,\n padx=5,\n fg = \"blue\",\n command = ingest_file_data\n )\n\nShow_Columns_Button = tk.Button(master=frm4_tb4, \n height = 1,\n width = 15,\n text =\"Show Columns\",\n relief=tk.RIDGE,\n padx=5,\n fg = \"green\",\n command = show_all_ingest_columns\n )\n\nUpload_Data_Button = tk.Button(master=frm4_tb4, \n height = 1,\n width = 15,\n text =\"Upload Data\",\n relief=tk.RIDGE,\n padx=5,\n fg = \"orange\",\n command = upload_data\n )\n\nfrm5_tb4 = tk.Frame(master=super_frame_tab4,relief=border_effects['flat'],width=100, height=10)\n###\nOutput_tb4 = tk.Text(frm5_tb4, height = 40,\n width = 99,\n bg = \"light green\")\n\nlabel_opt4a.pack(side='left')\nIngest_Button.pack(side='left')\nShow_Columns_Button.pack(side='left')\nUpload_Data_Button.pack(side='left')\nOutput_tb4.pack(side='bottom')\nfrm4_tb4.pack(fill=tk.X)\nfrm5_tb4.pack(fill=tk.X)\ntabControl.add(super_frame_tab4,text='Upload CSV / Excel')\ntabControl.pack(expand=1, fill=\"both\",side='right')\n##############################################################################\n\nwindow.mainloop()\n\nnotes_db.committ_and_close()" ]
[ [ "pandas.set_option", "pandas.read_excel", "pandas.read_csv" ] ]
UBC-MDS/Pystockwatch
[ "4c72dae96d392cf2681b043db6e2fd440c936e49" ]
[ "src/pystockwatch/pystockwatch.py" ]
[ "# authors: Affrin Sultana, Helin Wang, Shi Yan Wang and Pavel Levchenko\n# January,2022\n\n# import plotly.express as px\nimport plotly.graph_objects as go\nimport altair as alt\nimport pandas as pd\nimport numpy as np\nimport yfinance as yf\nimport pandas_datareader as pdr\nimport datetime\nimport warnings\nalt.renderers.enable('altair_viewer')\n\ndef percent_change(stock_ticker, start_date, end_date):\n \"\"\"\n Calculates daily percentage change of a stock price within a given period of time\n \n Parameters\n ----------\n stock_ticker : string \n Ticker of the stock such as 'AAPL'\n start_date : string\n Initial date for data extraction\n end_date : string\n Final date for stock analysis\n \n Returns\n --------\n DataFrame\n A data frame with dates and their corresponding stock price percentage changes.\n \n Examples\n --------\n >>> percent_change('AAPL', '2017-01-01', '2017-01-10')\n Price Change Percentage(%) \n Date\n 2017-01-03 0.000\n 2017-01-04 -0.112\n 2017-01-05 0.396\n 2017-01-06 1.515\n 2017-01-09 2.445\n \"\"\" \n \n # Assert ticker input value\n ticker = yf.Ticker(stock_ticker)\n if(ticker.info[\"regularMarketPrice\"] == None):\n raise NameError(\"You have entered an invalid stock ticker! Try again.\")\n \n # Assert start date input value\n format = \"%Y-%m-%d\"\n try: datetime.datetime.strptime(start_date, format)\n except ValueError:\n raise ValueError(\"You have entered an invalid start date! Try date formatted in YYYY-MM-DD.\")\n \n # Assert end date input value\n try: datetime.datetime.strptime(end_date, format)\n except ValueError:\n raise ValueError(\"You have entered an invalid end date! Try date formatted in YYYY-MM-DD.\")\n\n # Assert end date is later than start date\n format = \"%Y-%m-%d\"\n if(datetime.datetime.strptime(end_date, format) < datetime.datetime.strptime(start_date, format)):\n raise ValueError(\"You have entered an end date which is earlier than the start date! Try again.\")\n \n # Import original dataframe by giving stock ticker, start data and end date\n data = yf.download(stock_ticker, start=start_date, end=end_date)\n \n # Only Keep \"Adj Close\" Price for \n data = data.drop(columns={'Open', 'High', 'Low', 'Adj Close', 'Volume'})\n \n # Carry out calculation\n for i in range(1,len(data)):\n data.iloc[i,:] = round((data.iloc[i,:] - data.iloc[0,:])/data.iloc[0,:]*100, 3)\n \n data.iloc[0,:] = round((data.iloc[0,:] - data.iloc[0,:])/data.iloc[0,:]*100, 3)\n \n # Manipulate column name\n data = data.rename(columns={\"Close\": \"Price Change Percentage(%)\"})\n \n # Return result\n return pd.DataFrame(data)\n\n\ndef profit_viz(stock_ticker, start_date , end_date, benchmark_ticker):\n \"\"\"\n Visualizes trend of a stock price change against the market benchmark within a given period of time\n \n Parameters\n ----------\n stock_ticker : string\n Ticker of the stock such as 'AAPL'\n start_date : string \n Initial date for data extraction\n end_date : string\n Final date for stock analysis\n benchmark_ticker : string \n Ticker for benchmark comparison such as 'SP500' \n \n Returns\n --------\n Altair Chart\n A line chart which shows percentage change in stock price and market performance over time \n \n Examples\n --------\n >>> profit_viz('AAPL', '2015-01-01', '2021-12-31', 'SP500')\n \"\"\"\n\n \n ticker = yf.Ticker(stock_ticker)\n bench_ticker = yf.Ticker(benchmark_ticker)\n\n try:\n # Assert ticker input value\n if(ticker.info[\"regularMarketPrice\"] == None):\n raise NameError(\"You have entered an invalid stock ticker! Try again.\")\n\n # check data type of input\n if type(stock_ticker) != str:\n raise TypeError(\"stock_ticker should be of type string.\")\n \n # Assert benchmark ticker input value\n \n if(bench_ticker.info[\"regularMarketPrice\"] == None):\n raise NameError(\"You have entered an invalid benchmark ticker! Try again.\")\n\n # check data type of input\n if type(benchmark_ticker) != str:\n raise TypeError(\"Bench Mark ticker should be of type string.\")\n \n # #check stock ticker and bench mark ticker are not same\n # if stock_ticker is bench_ticker:\n # raise NameError(\"Stock Mark ticker should not be same as Bench Ticker.\")\n\n # #check stock ticker is not empty\n # if not stock_ticker or not bench_ticker:\n # raise ValueError(\"'Tickers' cannot be empty\")\n\n # Assert start date input value\n format = \"%Y-%m-%d\"\n try: datetime.datetime.strptime(start_date, format)\n except ValueError:\n raise ValueError(\"You have entered an invalid start date! Try date formatted in YYYY-MM-DD.\")\n \n # Assert end date input value\n try: datetime.datetime.strptime(end_date, format)\n except ValueError:\n raise ValueError(\"You have entered an invalid end date! Try date formatted in YYYY-MM-DD.\")\n\n # Assert end date is later than start date\n format = \"%Y-%m-%d\"\n if(datetime.datetime.strptime(end_date, format) < datetime.datetime.strptime(start_date, format)):\n raise ValueError(\"You have entered an end date which is earlier than the start date! Try again.\")\n \n except (TypeError, ValueError, NameError) as err:\n print(err)\n raise \n\n # Code to generate the visualization of profit \n try:\n stock_profit = percent_change(stock_ticker, start_date, end_date).reset_index()\n benchmark_profit = percent_change(benchmark_ticker, start_date, end_date).reset_index()\n profit_df = pd.merge(stock_profit, benchmark_profit, on=\"Date\")\n profit_df.rename({'Price Change Percentage(%)_x': 'Profit Percent Stock', 'Price Change Percentage(%)_y': 'Profit Percent Benchmark'}, axis=1, inplace=True)\n # catch when dataframe is None\n except AttributeError:\n pass\n\n #Checks if the datatype of data frame is correct\n try:\n isinstance(profit_df, pd.DataFrame)\n except ValueError:\n raise ValueError(\"profit_df is not a pandas dataframe.\")\n \n try:\n isinstance(stock_profit, pd.DataFrame)\n except ValueError:\n raise ValueError(\"stock_profit couldnot be converted to a pandas dataframe.\")\n\n try:\n isinstance(benchmark_profit, pd.DataFrame)\n except ValueError:\n raise ValueError(\"Benchmark_profit couldnot be converted to a pandas dataframe.\")\n\n # Code to plot the profit visualization\n chart = alt.Chart(profit_df, title='Profit Percent trend of Stock vs Benchmark ticker').mark_line().transform_fold(\n fold=['Profit Percent Stock', 'Profit Percent Benchmark'], \n as_=['company', 'Profit Percent']\n).encode(\n x='Date:T', \n y = alt.Y('Profit Percent:Q', axis=alt.Axis(format='$.2f')),\n color=alt.Color('company:N', scale= alt.Scale(domain=['Profit Percent Stock','Profit Percent Benchmark'], range=['red', 'blue'])),\n tooltip=[alt.Tooltip('Profit Percent Stock'),alt.Tooltip('Profit Percent Benchmark')]\n)\n return chart\n\n \ndef volume_change(stock_ticker, start_date, end_date):\n \"\"\" \n Calculates the daily trading volume change status of a stock within a given period of time\n\n Parameters\n ----------\n stock_ticker : string \n Ticker of the stock such as 'AAPL'\n start_date : string\n Initial date for data extraction\n end_date : string \n Final date for stock analysis\n\n Returns\n --------\n DataFrame\n A data frame with dates and their corresponding trading volume and changes\n\n Examples\n --------\n >>> volume_change('AAPL', '2021-01-01', '2022-01-01')\n Date Volume Volume_Change\n 01-01-2021 1000 Nan\n 01-02-2021 2000 Increase\n 01-03-2021 3000 Increase\n 01-04-2021 2500 Decrease\n ...\n 12-31-2021 4000 Increase\n 01-01-2022 5000 Increase\n \"\"\"\n # Assert ticker value\n ticker = yf.Ticker(stock_ticker)\n if(ticker.info[\"regularMarketPrice\"] == None):\n raise NameError(\"You have entered an invalid stock ticker! Try again.\")\n \n # Assert date value\n format = \"%Y-%m-%d\"\n try: datetime.datetime.strptime(start_date, format)\n except ValueError:\n raise ValueError(\"You have entered an invalid start date! Try again.\")\n try: datetime.datetime.strptime(end_date, format)\n except ValueError:\n raise ValueError(\"You have entered an invalid end date! Try again.\")\n \n df = pdr.get_data_yahoo(stock_ticker, start=start_date, end=end_date).reset_index()\n \n # Assert correct data fetched\n try:\n isinstance(df, pd.DataFrame)\n except ValueError:\n raise ValueError(\"Your input can't be converted to a pandas dataframe.\")\n \n df[\"Price_diff\"] = df[\"Close\"].diff().to_frame()\n df['Price_change'] = np.select([df[\"Price_diff\"] > 0, df[\"Price_diff\"] < 0],\n [\"Increase\", \"Decrease\"], default = np.nan)\n return df[[\"Date\", \"Volume\", \"Price_change\"]]\n \n\ndef volume_viz(stock_ticker, start_date, end_date):\n \"\"\"\n Visualize the daily trading volume of a stock using bar plot within a given period of time\n \n Parameters\n ----------\n stock_ticker : string \n Ticker of the stock such as 'AAPL'\n start_date : string\n Initial date for data extraction\n end_date : string \n Final date for stock analysis\n \n Returns\n --------\n Chart\n Create interactive bar plot to view the volume change\n \n Examples\n --------\n >>> volume_viz('AAPL', '2021-01-01', '2022-01-01')\n \"\"\"\n try:\n vdf = volume_change(stock_ticker, start_date, end_date)\n # catch when dataframe is None\n except AttributeError:\n raise AttributeError(\"Invalid volume change input!\")\n \n\n vdf_increase = vdf.loc[vdf['Price_change']=='Increase']\n vdf_decrease = vdf.loc[vdf['Price_change']=='Decrease']\n\n\n fig = go.Figure()\n fig.add_trace(go.Bar(x=vdf_increase['Date'], y=vdf_increase['Volume'],\n base=0,\n marker_color='green',\n name='Price Increase'))\n fig.add_trace(go.Bar(x=vdf_decrease['Date'], y=vdf_decrease['Volume'],\n base=0,\n marker_color='red',\n name='Price Decrease'\n ))\n\n return fig\n" ]
[ [ "pandas.merge", "numpy.select", "pandas.DataFrame" ] ]
LeeTehi/nnvolterra
[ "d6a084d2f5b4b716423cb4b952cf58a09ea84c23" ]
[ "npxconv.py" ]
[ "import libnpxconv as libx\n\nimport numpy as np\n\n# params for libx (sedt, kernel, srcx, /, padleft, stride)\n\ndef conv_ordern(ker, *src, oshape=None, padleft=0, stride=1):\n if len(src) == 1:\n src = src[0]\n\n if oshape is None:\n if isinstance(src, (list, tuple)):\n assert np.ndim(ker) == len(src)\n oshape = np.min([np.min(s.shape) for s in src])\n else:\n oshape = np.min(src.shape)\n ks = np.max(ker.shape)\n if oshape > ks:\n oshape = (oshape - ks) // stride + 1\n\n out = np.zeros(oshape, dtype=ker.dtype)\n\n if isinstance(src, list):\n src = [np.ascontiguousarray(x) for x in src]\n else:\n src = np.ascontiguousarray(src)\n ker = np.ascontiguousarray(ker)\n libx.conv1d_order_n(out, ker, src, padleft, stride)\n return out\n\n\ndef outerconv(g, *hx, oshape=None, padleft=0, stride=1):\n if isinstance(hx[0], (list, tuple)) and len(hx) == 1:\n hx = hx[0]\n assert np.ndim(g) == len(hx), \\\n f\"mismatch ndim(g) = {np.ndim(g)}, len(hx) = {len(hx)}\"\n if oshape is None:\n oshape = []\n for i, h in enumerate(hx):\n gsi = g.shape[i]\n for hsi in h.shape:\n oshape.append(hsi + stride*gsi-stride)\n\n out = np.zeros(oshape, dtype=g.dtype)\n g = np.ascontiguousarray(g)\n hx = [np.ascontiguousarray(h) for h in hx]\n\n libx.outerconv_nm(out, g, hx, padleft, stride)\n return out\n\ndef outerconv_diag(g, *hx, oshape=None, padleft=0, stride=1):\n # in the case of passing [x, y, z, ...]\n if isinstance(hx[0], (list, tuple)) and len(hx) == 1:\n hx = hx[0]\n assert np.ndim(g) == 1, \"only 1D signal supported\"\n assert len(hx) >= 1, \"length of hx must grater than or equals to 1\"\n\n if oshape is None:\n oshape = []\n for h in hx:\n for hsi in h.shape:\n oshape.append(hsi+g.shape[0]-1)\n\n out = np.zeros(oshape, dtype=g.dtype)\n g = np.ascontiguousarray(g)\n hx = [np.ascontiguousarray(h) for h in hx]\n\n libx.outerconv_diagonal_nm(out, g, hx, padleft, stride)\n return out\n\ndef outerconv_2d(g, h, stride=1):\n \"\"\"g @ h\n Only support Order-1 2-dimensional outer convolution\n\n <-> this equals to convTranspose2D\n \"\"\"\n assert np.ndim(g) == 2 and np.ndim(h) == 2\n\n if stride > 1:\n _hs = h.shape\n _hp = _hs[0] * (stride - 1), _hs[1] * (stride - 1)\n h = np.pad(h, [(0, _hp[0]), (0, _hp[1])])\\\n .reshape(stride, _hs[0], stride, _hs[1])\\\n .transpose(1, 0, 3, 2).reshape(stride*_hs[0], stride*_hs[1])\n \n psg = h.shape[1] - 1\n psh = g.shape[1] - 1\n\n pg = np.pad(g, [(0, 0), (0, psg)]).reshape(-1)\n ph = np.pad(h, [(0, 0), (0, psh)]).reshape(-1)\n\n goh = outerconv(pg, ph, stride=1)\n\n glen = g.shape[0] + h.shape[0]- 1\n\n R = glen * (g.shape[1] + h.shape[1] - 1)\n\n return goh[0:R].reshape(glen, -1)\n\n" ]
[ [ "numpy.pad", "numpy.min", "numpy.ascontiguousarray", "numpy.ndim", "numpy.max", "numpy.zeros" ] ]
SMMoseley/Background_Colony_Noise
[ "eb88ccf725939d501f02854b4c82659e8f6d5a3a" ]
[ "waveconverter.py" ]
[ "##Packages##\nimport h5py as h5\nimport numpy as np\nimport pandas as pd\nimport os\nimport ewave\n\n##Functions##\ndef wav_intervals(csv, sample_rate, hour_to_sample_rate):\n for row in csv.itertuples(): #iterates through each row in the csv file\n arf_file = row[0]\n start_time = row[1]*hour_to_sample_rate #takes the second column and calculates the start point\n duration = row[2]*sample_rate #takes the third column and calculates the sample duration (i.e. 7 seconds)\n return arf_file, start_time, duration \n\ndef wavdata (sample, start_time, duration):\n subsample = np.zeros(duration) #creates a one dimensional array filled with zeros that is the length of duration\n for i in range(start_time,start_time + duration): # sample a range from the start time to the start time + duration\n subsample[i - start_time] = sample[i] # pulls the data and assigns it to subsample\n data = subsample # Sets the data to be converted\n return data\n\n##Script##\nsample_rate = 48000\nhour_to_sample_rate = 60*60*sample_rate\ncsv = pd.read_csv('Hour.csv',index_col = 0) #reads in the csv and indexes the first column\narf_file, start_time, duration = wav_intervals(csv, sample_rate, hour_to_sample_rate)\nwith h5.File(arf_file, 'r') as R1: # takes the first column file path and imports the arf file\n ls = list(R1.keys()) # lists the keys\n name = ls[0]\n data = R1.get(ls[0]) # pulls the first key which has the data\n lsdata = list(data.keys()) # lists the keys in this shell\n sample = data.get(lsdata[0]) # pulls the data\n data = wavdata(sample, start_time, duration)\nstart_time_hour = int(start_time/hour_to_sample_rate)\nduration_seconds = int(duration/sample_rate)\nwith ewave.open(\"{}_{}_{}.wav\".format(name, start_time_hour, duration_seconds),\"w+\",sampling_rate=sample_rate,dtype='f') as fp: #sets the name of the file, sets the mode to open a file, the sampling rate, and the float datatype\n fp.write(data)\n" ]
[ [ "pandas.read_csv", "numpy.zeros" ] ]
timgates42/pandashells
[ "4b565435a25ac713eeeacf28c3e5b52fe94530d8" ]
[ "pandashells/bin/p_linspace.py" ]
[ "#! /usr/bin/env python\n\n# standard library imports\nimport sys # NOQA import sys to allow for mocking sys.argv in tests\nimport argparse\nimport textwrap\n\nfrom pandashells.lib import module_checker_lib, arg_lib\n\nmodule_checker_lib.check_for_modules(['pandas'])\n\nfrom pandashells.lib import io_lib\n\nimport numpy as np\nimport pandas as pd\n\n\ndef main():\n msg = \"Generate a linearly spaced set of data points.\"\n msg = textwrap.dedent(\n \"\"\"\n Generate a linearly spaced set of data points.\n\n -----------------------------------------------------------------------\n Examples:\n\n * Generate 7 points between 1 and 10\n p.linspace 1 10 7\n\n -----------------------------------------------------------------------\n \"\"\"\n )\n\n # read command line arguments\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter, description=msg)\n\n arg_lib.add_args(parser, 'io_out')\n\n msg = 'start end npoints'\n parser.add_argument(\"numbers\", help=msg, type=str, nargs=3, metavar='')\n\n # parse arguments\n args = parser.parse_args()\n min_val, max_val = float(args.numbers[0]), float(args.numbers[1])\n N = int(args.numbers[2])\n\n df = pd.DataFrame({'c0': np.linspace(min_val, max_val, N)})\n\n # write dataframe to output\n io_lib.df_to_output(args, df)\n\nif __name__ == '__main__': # pragma: no cover\n main()\n" ]
[ [ "numpy.linspace" ] ]
jmmelis/FlyTrackApp
[ "7c03eb0aeda7b0bd4e0c6181bc776c92e4fbc582" ]
[ "FlyTrackApp/flight_tracker_vis_class.py" ]
[ "import vtk\nimport sys\nimport os\nimport time\nimport numpy as np\n\n# flight tracker visualization class\n\nclass FlightTrackerVisualization:\n\n\tdef __init__(self):\n\n\t\t# window parameters\n\t\tself.window_name = \"Model\"\n\t\tself.background = (0.1,0.2,0.4)\n\t\tself.window_sz = (600, 600)\n\n\t\t# stl model parameters\n\t\tself.model_name = \"\"\n\t\tself.stl_list = []\n\t\tself.model_loc = \"\"\n\t\tself.stl_src = []\n\t\tself.stl_actors = []\n\n\t\t# point parameters\n\t\tself.pointcloud_list = []\n\n\t\t# Create the Renderer, RenderWindow, and RenderWindowInteractor\n\t\tself.ren = vtk.vtkRenderer()\n\t\tself.ren_win = vtk.vtkRenderWindow()\n\t\tself.ren_win.AddRenderer(self.ren)\n\t\tself.iren = vtk.vtkRenderWindowInteractor()\n\t\tself.iren.SetRenderWindow(self.ren_win)\n\n\t\t# Set the background color and window size\n\t\tself.ren_win.SetWindowName(self.window_name)\n\t\tself.ren.SetBackground(*self.background)\n\t\tself.ren_win.SetSize(*self.window_sz)\n\n\t\t# Render\n\t\tself.iren.Initialize()\n\t\tself.ren.ResetCameraClippingRange()\n\t\tself.ren_win.Render()\n\n\tdef load_model(self,model_name,model_loc,stl_list):\n\n\t\tself.model_name = model_name\n\t\tself.stl_list = stl_list\n\t\tself.model_loc = model_loc + '/' + model_name\n\t\tself.ren_win.SetWindowName(model_name)\n\n\t\tos.chdir(self.model_loc)\n\t\t\n\t\tfor stl_file in stl_list:\n\t\t\tsr = vtk.vtkSTLReader()\n\t\t\tsr.SetFileName(stl_file)\n\t\t\tself.stl_src.append(sr)\n\t\t\tstl_mapper = vtk.vtkPolyDataMapper()\n\t\t\tstl_mapper.ScalarVisibilityOff()\n\t\t\tstl_mapper.SetInputConnection(sr.GetOutputPort())\n\t\t\tstl_actor = vtk.vtkActor()\n\t\t\tstl_actor.SetMapper(stl_mapper)\n\t\t\tself.stl_actors.append(stl_actor)\n\t\t\tstl_props = stl_actor.GetProperty()\n\t\t\tstl_actor.SetPosition(0,0,0)\n\t\t\tstl_props.SetInterpolationToGouraud()\n\t\t\tstl_mapper.Update()\n\t\t\tself.ren.AddActor(stl_actor)\n\n\t\tself.ren_win.Render()\n\n\tdef set_state_model(self,state,parents,scale):\n\n\t\tfor i in range(state.shape[1]):\n\n\t\t\told_val = -1\n\t\t\tj = 0\n\n\t\t\ttransformation = vtk.vtkTransform()\n\n\t\t\twhile parents[i,j] > old_val:\n\t\t\t\tind = parents[i,j]\n\t\t\t\telem_mat = vtk.vtkMatrix4x4()\n\t\t\t\telem_mat.SetElement(0,0,(2.0*state[0,ind]**2-1.0+2.0*state[1,ind]**2))\n\t\t\t\telem_mat.SetElement(0,1,(2.0*state[1,ind]*state[2,ind]+2.0*state[0,ind]*state[3,ind]))\n\t\t\t\telem_mat.SetElement(0,2,(2.0*state[1,ind]*state[3,ind]-2.0*state[0,ind]*state[2,ind]))\n\t\t\t\telem_mat.SetElement(1,0,(2.0*state[1,ind]*state[2,ind]-2.0*state[0,ind]*state[3,ind]))\n\t\t\t\telem_mat.SetElement(1,1,(2.0*state[0,ind]**2-1.0+2.0*state[2,ind]**2))\n\t\t\t\telem_mat.SetElement(1,2,(2.0*state[2,ind]*state[3,ind]+2.0*state[0,ind]*state[1,ind]))\n\t\t\t\telem_mat.SetElement(2,0,(2.0*state[1,ind]*state[3,ind]+2.0*state[0,ind]*state[2,ind]))\n\t\t\t\telem_mat.SetElement(2,1,(2.0*state[2,ind]*state[3,ind]-2.0*state[0,ind]*state[1,ind]))\n\t\t\t\telem_mat.SetElement(2,2,(2.0*state[0,ind]**2-1.0+2.0*state[3,ind]**2))\n\t\t\t\telem_mat.SetElement(0,3,state[4,ind]*scale[ind])\n\t\t\t\telem_mat.SetElement(1,3,state[5,ind]*scale[ind])\n\t\t\t\telem_mat.SetElement(2,3,state[6,ind]*scale[ind])\n\n\t\t\t\ttransformation.Concatenate(elem_mat)\n\t\t\t\told_val = parents[i,j]\n\t\t\t\tj+=1\n\n\t\t\tself.stl_actors[i].SetUserMatrix(transformation.GetMatrix())\n\n\t\tself.ren_win.Render()\n\n\tdef add_pointcloud(self,pcl_in):\n\n\t\tN = pcl_in.shape[1]\n\n\t\t#points = vtk.vtkPointSource()\n\t\tpoints = vtk.vtkPoints()\n\t\tpoints.SetNumberOfPoints(N)\n\t\tpolydata = vtk.vtkPolyData()\n\n\t\tfor i in range(N):\n\t\t\tpoints.InsertNextPoint(pcl_in[:,i])\n\t\t\t#points.SetRadius(0.005)\n\n\t\tpolydata.SetPoints(points)\n\t\tmapper = vtk.vtkPolyDataMapper()\n\t\tmapper.SetInputData(polydata)\n\t\t#mapper.SetInputData(points)\n\t\t#mapper.SetInputConnection(points.GetOutputPort())\n\t\tactor = vtk.vtkActor()\n\t\tactor.SetMapper(mapper)\n\t\tself.ren.AddActor(actor)\n\n\t\t#for i in range(N_points):\n\t\t#\t#point = vtk.vtkSphereSource()\n\t\t#\t#point.SetCenter(pcl_in[:,i])\n\t\t#\t#point.SetRadius(0.005)\n\t\t#\tpoint = vtk.vtkPointSource()\n\t\t#\tpoint.SetCenter(pcl_in[:,i])\n\t\t#\tpoint.SetNumberOfPoints(1);\n\t\t#\tmapper = vtk.vtkPolyDataMapper()\n\t\t#\tmapper.ScalarVisibilityOff()\n\t\t#\tmapper.SetInputConnection(point.GetOutputPort())\n\t\t#\tactor = vtk.vtkActor()\n\t\t#\tactor.SetMapper(mapper)\n\t\t#\tprops = actor.GetProperty()\n\t\t#\tself.ren.AddActor(actor)\n\n\tdef start_interaction_window(self):\n\t\tself.ren_win.Render()\n\t\tself.iren.Start()\n\n\tdef kill_interaction_window(self):\n\t\tdel self.ren_win, self.iren\n\n\tdef load_pointcloud(self,pointCloud,pcl_in):\n\t\tfor k in range(pcl_in.shape[1]):\n\t\t\tpoint = pcl_in[:,k]\n\t\t\tpointCloud.addPoint(point)\n\n\t\treturn pointCloud\n\n\tdef show_pointcloud(self,pcl_in):\n\t\tpointCloud = self.VtkPointCloud(np.amax(pcl_in[3,:]))\n\t\tpointCloud = self.load_pointcloud(pointCloud,pcl_in)\n\t\tself.ren.AddActor(pointCloud.vtkActor)\n\n\tdef show_bboxes(self,corner_points):\n\t\tN_boxes = corner_points.shape[1]\n\t\tfor i in range(N_boxes):\n\t\t\tcorner_mat = np.empty([8,3])\n\t\t\tfor j in range(8):\n\t\t\t\tcorner_mat[j,0] = corner_points[j*3,i]\n\t\t\t\tcorner_mat[j,1] = corner_points[j*3+1,i]\n\t\t\t\tcorner_mat[j,2] = corner_points[j*3+2,i]\n\t\t\tbox = self.BoundingBox()\n\t\t\tbox.addBox(corner_mat)\n\t\t\tself.ren.AddActor(box.vtkActor)\n\n\tclass VtkPointCloud:\n\t\tdef __init__(self,scalar_range):\n\t\t\tself.vtkPolyData = vtk.vtkPolyData()\n\t\t\tself.clearPoints()\n\t\t\tmapper = vtk.vtkPolyDataMapper()\n\t\t\tmapper.SetInputData(self.vtkPolyData)\n\t\t\tmapper.SetColorModeToDefault()\n\t\t\tmapper.SetScalarRange(0.0,scalar_range)\n\t\t\tmapper.SetScalarVisibility(1)\n\t\t\tself.vtkActor = vtk.vtkActor()\n\t\t\tself.vtkActor.SetMapper(mapper)\n\n\t\tdef addPoint(self,point):\n\t\t\tpointID = self.vtkPoints.InsertNextPoint(point[0:3])\n\t\t\tself.vtkDepth.InsertNextValue(point[3])\n\t\t\tself.vtkCells.InsertNextCell(1)\n\t\t\tself.vtkCells.InsertCellPoint(pointID)\n\t\t\tself.vtkCells.Modified()\n\t\t\tself.vtkPoints.Modified()\n\t\t\tself.vtkDepth.Modified()\n\n\t\tdef clearPoints(self):\n\t\t\tself.vtkPoints = vtk.vtkPoints()\n\t\t\tself.vtkCells = vtk.vtkCellArray()\n\t\t\tself.vtkDepth = vtk.vtkDoubleArray()\n\t\t\tself.vtkDepth.SetName('DepthArray')\n\t\t\tself.vtkPolyData.SetPoints(self.vtkPoints)\n\t\t\tself.vtkPolyData.SetVerts(self.vtkCells)\n\t\t\tself.vtkPolyData.GetPointData().SetScalars(self.vtkDepth)\n\t\t\tself.vtkPolyData.GetPointData().SetActiveScalars('DepthArray')\n\n\tclass BoundingBox:\n\t\tdef __init__(self):\n\t\t\tself.mapper = vtk.vtkPolyDataMapper()\n\t\t\tself.vtkActor = vtk.vtkActor()\n\t\t\tself.vtkActor.SetMapper(self.mapper)\n\n\t\tdef addBox(self,corner_points):\n\t\t\t# Add a bounding box\n\t\t\tpoints = vtk.vtkPoints()\n\t\t\tpoints.SetNumberOfPoints(8)\n\t\t\tpoints.SetPoint(0,corner_points[0,0],corner_points[0,1],corner_points[0,2])\n\t\t\tpoints.SetPoint(1,corner_points[1,0],corner_points[1,1],corner_points[1,2])\n\t\t\tpoints.SetPoint(2,corner_points[2,0],corner_points[2,1],corner_points[2,2])\n\t\t\tpoints.SetPoint(3,corner_points[3,0],corner_points[3,1],corner_points[3,2])\n\t\t\tpoints.SetPoint(4,corner_points[4,0],corner_points[4,1],corner_points[4,2])\n\t\t\tpoints.SetPoint(5,corner_points[5,0],corner_points[5,1],corner_points[5,2])\n\t\t\tpoints.SetPoint(6,corner_points[6,0],corner_points[6,1],corner_points[6,2])\n\t\t\tpoints.SetPoint(7,corner_points[7,0],corner_points[7,1],corner_points[7,2])\n\t\t\tlines = vtk.vtkCellArray()\n\t\t\tlines.InsertNextCell(5)\n\t\t\tlines.InsertCellPoint(0)\n\t\t\tlines.InsertCellPoint(1)\n\t\t\tlines.InsertCellPoint(2)\n\t\t\tlines.InsertCellPoint(3)\n\t\t\tlines.InsertCellPoint(0)\n\t\t\tlines.InsertNextCell(5)\n\t\t\tlines.InsertCellPoint(4)\n\t\t\tlines.InsertCellPoint(5)\n\t\t\tlines.InsertCellPoint(6)\n\t\t\tlines.InsertCellPoint(7)\n\t\t\tlines.InsertCellPoint(4)\n\t\t\tlines.InsertNextCell(5)\n\t\t\tlines.InsertCellPoint(0)\n\t\t\tlines.InsertCellPoint(4)\n\t\t\tlines.InsertCellPoint(7)\n\t\t\tlines.InsertCellPoint(3)\n\t\t\tlines.InsertCellPoint(0)\n\t\t\tlines.InsertNextCell(5)\n\t\t\tlines.InsertCellPoint(1)\n\t\t\tlines.InsertCellPoint(5)\n\t\t\tlines.InsertCellPoint(6)\n\t\t\tlines.InsertCellPoint(2)\n\t\t\tlines.InsertCellPoint(1)\n\t\t\tlines.InsertNextCell(5)\n\t\t\tlines.InsertCellPoint(0)\n\t\t\tlines.InsertCellPoint(1)\n\t\t\tlines.InsertCellPoint(5)\n\t\t\tlines.InsertCellPoint(4)\n\t\t\tlines.InsertCellPoint(0)\n\t\t\tlines.InsertNextCell(5)\n\t\t\tlines.InsertCellPoint(3)\n\t\t\tlines.InsertCellPoint(2)\n\t\t\tlines.InsertCellPoint(6)\n\t\t\tlines.InsertCellPoint(7)\n\t\t\tlines.InsertCellPoint(3)\n\t\t\tpolygon = vtk.vtkPolyData()\n\t\t\tpolygon.SetPoints(points)\n\t\t\tpolygon.SetLines(lines)\n\t\t\tself.mapper.SetInputData(polygon)\n\t\t\tself.mapper.Update()\n\n\n\n\n" ]
[ [ "numpy.amax", "numpy.empty" ] ]
manny405/mcse
[ "419e4b8c144563ae0bf48982fc7ea26ce941a3eb" ]
[ "mcse/crystals/packing_factor.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom scipy.spatial.distance import cdist\nfrom scipy.spatial import cKDTree \n\nfrom ase.data import vdw_radii,atomic_numbers,covalent_radii\nfrom ase.data.vdw_alvarez import vdw_radii as vdw_radii_alvarez\n\nfrom mcse import Structure\nfrom mcse import BaseDriver_\nfrom mcse.crystals.supercell import SupercellSphere\n\n\nall_radii = []\nfor idx,value in enumerate(vdw_radii):\n if np.isnan(value):\n ## Approximate\n value = covalent_radii[idx]+0.8\n else:\n if not np.isnan(vdw_radii_alvarez[idx]):\n alvarez_value = vdw_radii_alvarez[idx]\n value = np.min([value, alvarez_value])\n all_radii.append(value)\nall_radii = np.array(all_radii)\n## 1.1 is more appropriate for molecular crystal structures, particularly \n## when hydrogen bonds are present. \nall_radii[1] = 1.1\n\nall_radii_dict = {}\nfor key,value in atomic_numbers.items():\n if value >= len(all_radii):\n continue\n all_radii_dict[key] = all_radii[value]\n\n\nclass PackingFactor(BaseDriver_):\n \"\"\"\n Calculatees the geometric packing factor using the vdW radii of the \n structure and a user specified grid spacing. The algorithm is as follows:\n 1. Generate Supercell of user specified size. This is to ensure that all\n of the necessary atoms are within the unit cell.\n 2. Keep only atoms that are within the unit cell plus a correction \n equal to the largest van der Waals radius in the system.\n 3. Generate a grid using the specified grid spacing. This is done by \n computing the grid spacing that should be used based on the lattice\n vector norm in every direction. Then, this grid is generated in \n fraction space and converted finally to real space. \n 5. For each location of the grid spacing, calculate how far it is from \n each atom. \n 6. For the distance to each atom, divide by the vdW radius of the\n respective atom. \n 7. All values less than 1 are occupied and all values greater than 1 \n are considered empty. \n 8. Divide filled by total to get the packing factor.\n \n Arguments\n ---------\n spacing: float\n Spacing is given in Angstroms\n vdw: iterable\n Iterable that can be indexed where the index is equal to the atomic \n number and the value at the index is the radius to use. \n supercell_mult: int\n Size of supercell to build in every lattice direction.\n low_memory: bool\n If True, an implementation that requires a smaller, fixed amount of \n system memory is used at the expense of additional compute time. This\n should be set to True if the user would like to use grid spacings\n below 0.25 Angstrom.\n \n \"\"\"\n def __init__(self, \n spacing=0.25, \n vdw=all_radii, \n supercell_mult=1,\n low_memory=False):\n self.spacing = spacing\n self.vdw = vdw\n self.supercell_mult = supercell_mult\n self.supercell = SupercellSphere(mult=self.supercell_mult)\n self.low_memory = low_memory\n ### Batch size not directly exposed user as argument to API cleaner.\n ### Change if you're confident.\n self.batch_size = 25000\n \n \n def calc_struct(self, struct):\n self.struct = struct\n self.supercell_struct = self.supercell.calc_struct(struct)\n \n self.lat = np.vstack(self.struct.get_lattice_vectors())\n self.norm = np.linalg.norm(self.lat,axis=-1)\n self.linv = np.linalg.inv(self.lat)\n \n self.unit_cell_struct = self.keep_inside(self.supercell_struct)\n \n self.num = self.norm / self.spacing\n self.grid_frac = self.generate_grid(self.num)\n self.grid_cart = np.dot(self.grid_frac, self.lat)\n \n if self.low_memory == False:\n ### Compute pairwise distances with unit cell modified structure\n dist = cdist(self.grid_cart, self.unit_cell_struct.get_geo_array())\n \n ### Divide dist by vdW radius\n ele = self.unit_cell_struct.elements\n self.vdw_array = [self.vdw[atomic_numbers[x]] for x in ele]\n self.vdw_array = np.array(self.vdw_array)[None,:]\n dist = dist / self.vdw_array\n self.min_dist = np.min(dist, axis=-1)\n self.occupied_idx = np.where(self.min_dist < 1)[0]\n \n ## Exact definition of packing factor\n packing_factor = np.where(self.min_dist < 1)[0].shape[0] / \\\n self.min_dist.shape[0]\n else:\n #### Certainly a batch size of 25000 should be possible for \n #### reasonably size molecular cryestal structures on a modern\n #### server. \n #### In addition, this type of operation would be excellent for \n #### GPU implementation. \n ele = self.unit_cell_struct.elements\n self.vdw_array = [self.vdw[atomic_numbers[x]] for x in ele]\n self.vdw_array = np.array(self.vdw_array)[None,:]\n total_occupied = 0\n total_points = 0\n total = len(self.grid_cart[::self.batch_size])\n \n for idx,value in enumerate(self.grid_cart[::self.batch_size]):\n print(\"{}: {}\".format(total, idx))\n \n start_idx = idx*self.batch_size\n end_idx = (idx+1)*self.batch_size\n if end_idx > len(self.grid_cart):\n end_idx = len(self.grid_cart)\n \n idx_values = np.arange(start_idx,end_idx,1)\n temp_cart = self.grid_cart[idx_values]\n temp_dist = cdist(temp_cart, \n self.unit_cell_struct.get_geo_array())\n \n ### Divide dist by vdW radius\n temp_dist = temp_dist / self.vdw_array\n \n temp_min_dist = np.min(temp_dist, axis=-1)\n temp_occupied_idx = np.where(temp_min_dist < 1)[0]\n \n total_occupied += temp_occupied_idx.shape[0]\n total_points += temp_cart.shape[0]\n \n \n packing_factor = total_occupied / total_points\n \n \n self.struct.properties[\"PackingFactor\"] = packing_factor\n \n return packing_factor\n \n \n def keep_inside(self, struct):\n \"\"\"\n Keeps only the atoms that are inside the unit cell plus a factor equal\n to the largest vdW radius. \n \n \"\"\"\n geo = struct.get_geo_array()\n ele = struct.elements\n \n vdw_list = [self.vdw[atomic_numbers[x]] for x in ele]\n correction = np.max(vdw_list)\n max_frac_correction = correction / np.min(self.norm)\n max_frac_correction = max_frac_correction*2\n \n frac = np.dot(geo,self.linv)\n \n keep_idx = np.where(\n np.logical_and(\n (frac>=(0-max_frac_correction)).all(axis=-1),\n (frac<=(1+max_frac_correction)).all(axis=-1)\n ))[0]\n \n geo = geo[keep_idx]\n ele = ele[keep_idx]\n \n unit_cell_struct = Structure.from_geo(geo, ele)\n unit_cell_struct.set_lattice_vectors(self.lat)\n \n return unit_cell_struct\n \n \n def move_atoms_in(self):\n geo = self.struct.get_geo_array()\n ele = self.struct.elements\n \n frac = np.dot(self.linv,geo.T).T\n \n ## Fix values greater than 1\n greater_idx = np.where(frac > 1)\n subtract = frac[greater_idx].astype(int)\n frac[greater_idx] -= subtract\n \n ## Fix values less than zero\n less_idx = np.where(frac < 0)\n add = -frac[less_idx].astype(int)+1\n frac[less_idx] += add\n \n cart = np.dot(frac, self.lat)\n \n struct = Structure.from_geo(cart, ele)\n struct.set_lattice_vectors(self.lat)\n \n return struct\n \n \n def generate_grid(self, num):\n \"\"\"\n Generates appropriate grid for the system. \n \n Arguments\n ---------\n num: Iterable\n Iterable of length 3 that describes how many values should be \n generated in each direction for the grid. \n \n \"\"\"\n ## This should be adjusted so that it's exactly at the edge of the \n ## unit cell.\n range_x = np.arange(0,num[0],1) / num[0]\n range_y = np.arange(0,num[1],1) / num[1]\n range_z = np.arange(0,num[2],1) / num[2]\n \n grid_x,grid_y,grid_z = np.meshgrid(range_x,range_y,range_z,\n indexing=\"ij\")\n \n grid = np.c_[grid_x.ravel(),\n grid_y.ravel(),\n grid_z.ravel()]\n \n return grid\n \n \n \nif __name__ == \"__main__\":\n pass\n \n## \n \n \n \n \n \n " ]
[ [ "numpy.dot", "numpy.meshgrid", "numpy.min", "numpy.isnan", "numpy.linalg.inv", "numpy.arange", "numpy.linalg.norm", "numpy.max", "numpy.array", "numpy.where" ] ]
TDC3Tool/TDC3
[ "c746d8e89c0eb35cc3d1b73f469a9f89f5e7bbfd" ]
[ "tdc3/models/py/data/FunctionNameConsistencyDataset.py" ]
[ "import random\nimport torch as t\nfrom py.data.XYDataset import XYDataset\nfrom py.util.Config import dtype, device, en_stops\nfrom nltk.tokenize import word_tokenize\nimport numpy as np\n\ndef genericDescriptionClassifier(description, embedding):\n some_generic_descriptions = ['work', 'success', 'test', 'filter',\n 'failure', 'explodes', 'case', 'scenario', 'screen']\n for generic_description in some_generic_descriptions:\n if embedding.similarity(generic_description, description) > 0.5:\n return True\n return False\n\n# TODO: move into more reusable class\nclass Embedding():\n def __init__(self, embedding):\n self.embedding = embedding\n self.cache = {}\n\n def get(self, token):\n if token in self.cache:\n return self.cache[token]\n else:\n vec = self.embedding[token]\n self.cache[token] = vec\n return vec\n\n def similarity(self, token, comparison_token):\n return self.embedding.similarity(token, comparison_token)\n\n\nclass FunctionNameConsistencyDataset(XYDataset):\n def __init__(self, description_embedding, test_embedding, embedding_size, max_body_length, max_description_length):\n self.description_embedding = description_embedding\n self.test_embedding = test_embedding\n self.embedding_size = embedding_size\n self.max_body_length = max_body_length\n self.max_description_length = max_description_length\n\n def prepare_data(self, json_dataset):\n print(\"Preparing dataset\")\n self.body_tensors = []\n self.description_tensors = []\n self.is_consistent_tensors = [] # consistent (1.0) inconsistent (0.0)\n self.ids = [] # unique id for each item, useful for debugging\n\n de = Embedding(self.description_embedding)\n te = Embedding(self.test_embedding)\n\n # read all data once to get test descriptions embeddings for creating negative examples\n print(f\"Reading all data once to get all test descriptions\")\n description_vectors = []\n for token_seq in json_dataset:\n test_description = token_seq[\"metadata\"][\"description\"]\n description_vec = []\n for token in word_tokenize(test_description)[:self.max_description_length]:\n if token not in en_stops:\n description_vec.append(de.get(token))\n while len(description_vec) < self.max_description_length:\n description_vec.append([0] * self.embedding_size)\n description_vectors.append(description_vec)\n\n # read all data again to create positive and negative examples\n print(f\"Creating positive and negative examples\")\n next_neg_example_id = -1 # negative ids for negative examples\n for idx in range(len(json_dataset)):\n token_seq = json_dataset[idx]\n description_vec = description_vectors[idx]\n\n body_vec = []\n for token in token_seq[\"data\"][:self.max_body_length]:\n if token not in en_stops:\n body_vec.append(te.get(token))\n while len(body_vec) < self.max_body_length:\n body_vec.append([0] * self.embedding_size)\n\n # positive example\n self.body_tensors.append(body_vec)\n self.description_tensors.append(description_vec)\n self.is_consistent_tensors.append([1.0])\n self.ids.append(token_seq[\"id\"])\n\n # negative example (randomly combine a description with a test body)\n some_other_description_vec = random.choice(description_vectors)\n self.body_tensors.append(body_vec)\n self.description_tensors.append(some_other_description_vec)\n self.is_consistent_tensors.append([0.0])\n self.ids.append(next_neg_example_id)\n next_neg_example_id -= 1\n\n if len(self.body_tensors) % 1000 == 0:\n print(\n f\"Have created {len(self.body_tensors)}/{2*len(description_vectors)} data points\")\n\n if len(self.body_tensors) % 1000 == 0:\n print(\n f\"Have created {len(self.body_tensors)}/{2*len(description_vectors)} data points\")\n\n self.body_tensors = t.as_tensor(\n self.body_tensors, dtype=dtype, device=\"cpu\")\n self.description_tensors = t.as_tensor(\n self.description_tensors, dtype=dtype, device=\"cpu\")\n self.is_consistent_tensors = t.as_tensor(\n self.is_consistent_tensors, dtype=dtype, device=\"cpu\")\n self.ids = t.as_tensor(\n self.ids, device=\"cpu\")\n print(\n f\"Done with data preparation: {len(self.body_tensors)} datapoints\")\n\n def save_to_disk(self, filename):\n t.save({\"body_tensors\": self.body_tensors,\n \"description_tensors\": self.description_tensors,\n \"is_consistent_tensors\": self.is_consistent_tensors,\n \"ids\": self.ids},\n filename)\n\n def load_from_disk(self, filename):\n tensors = t.load(filename)\n self.body_tensors = tensors[\"body_tensors\"]\n self.description_tensors = tensors[\"description_tensors\"]\n self.is_consistent_tensors = tensors[\"is_consistent_tensors\"]\n self.ids = tensors[\"ids\"]\n\n def move_to_target_device(self):\n print(\"Moving dataset to target device (e.g. GPU)\")\n self.body_tensors = t.as_tensor(\n self.body_tensors, dtype=dtype, device=device)\n self.description_tensors = t.as_tensor(\n self.description_tensors, dtype=dtype, device=device)\n self.is_consistent_tensors = t.as_tensor(\n self.is_consistent_tensors, dtype=dtype, device=device)\n self.ids = t.as_tensor(\n self.ids, dtype=dtype, device=device)\n\n def __len__(self):\n return len(self.body_tensors)\n\n def __getitem__(self, index):\n return [self.body_tensors[index], self.description_tensors[index]], self.is_consistent_tensors[index], self.ids[index]\n\n\nclass ToyDataset(XYDataset):\n def __init__(self, nb_datapoints, embedding_size, seq_length):\n self.embedding_size = embedding_size\n self.body_tensors = t.empty(\n nb_datapoints, seq_length, embedding_size, dtype=dtype, device=device)\n self.description_tensors = t.empty(\n nb_datapoints, embedding_size, dtype=dtype, device=device)\n self.is_consistent_tensors = t.empty(\n nb_datapoints, 1, dtype=dtype, device=device)\n\n for datapoint_idx in range(nb_datapoints):\n token_vec1 = t.rand(embedding_size, dtype=dtype, device=device)\n token_vec2 = t.rand(embedding_size, dtype=dtype, device=device)\n token_vec3 = t.rand(embedding_size, dtype=dtype, device=device)\n if datapoint_idx % 2 == 0:\n for seq_idx in range(seq_length):\n self.body_tensors[datapoint_idx][seq_idx] = token_vec1\n self.description_tensors[datapoint_idx] = token_vec1\n self.is_consistent_tensors[datapoint_idx] = 1.0\n else:\n for seq_idx in range(seq_length):\n self.body_tensors[datapoint_idx][seq_idx] = token_vec2\n self.description_tensors[datapoint_idx] = token_vec3\n self.is_consistent_tensors[datapoint_idx] = 0.0\n\n def __len__(self):\n return len(self.body_tensors)\n\n def __getitem__(self, i):\n return [self.body_tensors[i], self.description_tensors[i]], self.is_consistent_tensors[i]\n" ]
[ [ "torch.empty", "torch.load", "torch.as_tensor", "torch.rand", "torch.save" ] ]
samsungsds-rnd/CADD-CVAE
[ "b4a21f65440aaf7cb5c01f163356fb249a6cba30" ]
[ "cvae.py" ]
[ "\"\"\"\nThe MIT License\n\n \n\nCopyright (c) 2020 Samsung SDS\n\n \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\n \n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n\"\"\"\n\n\n\n#\n# Original code(This file is under Apache 2.0 License)\n# https://github.com/SAP-samples/security-research-membership-inference-against-generative-networks/blob/master/Monte-Carlo-Attacks/Monte-Carlo-MNIST_CVAE/vae.py\n# modified by Sunghoon Joo\n#\n\nimport tensorflow as tf\n\n\n# Gaussian MLP as conditional encoder\ndef gaussian_MLP_conditional_encoder(x, y, n_hidden, n_output, keep_prob):\n with tf.variable_scope(\"gaussian_MLP_encoder\"):\n # concatenate condition and image\n dim_y = int(y.get_shape()[1])\n input = tf.concat(axis=1, values=[x, y])\n\n # initializers\n w_init = tf.contrib.layers.variance_scaling_initializer()\n b_init = tf.constant_initializer(0.)\n\n # 1st hidden layer\n w0 = tf.get_variable('w0', [input.get_shape()[1], n_hidden+dim_y], initializer=w_init)\n b0 = tf.get_variable('b0', [n_hidden+dim_y], initializer=b_init)\n h0 = tf.matmul(input, w0) + b0\n h0 = tf.nn.elu(h0)\n h0 = tf.nn.dropout(h0, keep_prob)\n\n # 2nd hidden layer\n w1 = tf.get_variable('w1', [h0.get_shape()[1], n_hidden], initializer=w_init)\n b1 = tf.get_variable('b1', [n_hidden], initializer=b_init)\n h1 = tf.matmul(h0, w1) + b1\n h1 = tf.nn.tanh(h1)\n h1 = tf.nn.dropout(h1, keep_prob)\n\n # output layer\n # borrowed from https: // github.com / altosaar / vae / blob / master / vae.py\n wo = tf.get_variable('wo', [h1.get_shape()[1], n_output * 2], initializer=w_init)\n bo = tf.get_variable('bo', [n_output * 2], initializer=b_init)\n gaussian_params = tf.matmul(h1, wo) + bo\n\n # The mean parameter is unconstrained\n mean = gaussian_params[:, :n_output]\n # The standard deviation must be positive. Parametrize with a softplus and\n # add a small epsilon for numerical stability\n stddev = 1e-6 + tf.nn.softplus(gaussian_params[:, n_output:])\n\n return mean, stddev\n\n# Bernoulli MLP as conditional decoder\ndef bernoulli_MLP_conditional_decoder(z, y, n_hidden, n_output, keep_prob, reuse=False):\n\n with tf.variable_scope(\"bernoulli_MLP_decoder\", reuse=reuse):\n # concatenate condition and latent vectors\n input = tf.concat(axis=1, values=[z, y])\n\n # initializers\n w_init = tf.contrib.layers.variance_scaling_initializer()\n b_init = tf.constant_initializer(0.)\n\n # 1st hidden layer\n w0 = tf.get_variable('w0', [input.get_shape()[1], n_hidden], initializer=w_init)\n b0 = tf.get_variable('b0', [n_hidden], initializer=b_init)\n h0 = tf.matmul(input, w0) + b0\n h0 = tf.nn.tanh(h0)\n h0 = tf.nn.dropout(h0, keep_prob)\n\n # 2nd hidden layer\n w1 = tf.get_variable('w1', [h0.get_shape()[1], n_hidden], initializer=w_init)\n b1 = tf.get_variable('b1', [n_hidden], initializer=b_init)\n h1 = tf.matmul(h0, w1) + b1\n h1 = tf.nn.elu(h1)\n h1 = tf.nn.dropout(h1, keep_prob)\n\n # output layer-mean\n wo = tf.get_variable('wo', [h1.get_shape()[1], n_output], initializer=w_init)\n bo = tf.get_variable('bo', [n_output], initializer=b_init)\n y = tf.sigmoid(tf.matmul(h1, wo) + bo)\n\n return y\n\n\n# Gateway\ndef autoencoder(x_hat, x, y, dim_img, dim_z, n_hidden, keep_prob):\n\n # encoding\n mu, sigma = gaussian_MLP_conditional_encoder(x_hat, y, n_hidden, dim_z, keep_prob)\n\n # sampling by re-parameterization technique\n z = mu + sigma * tf.random_normal(tf.shape(mu), 0, 1, dtype=tf.float32)\n\n # decoding\n x_ = bernoulli_MLP_conditional_decoder(z, y, n_hidden, dim_img, keep_prob)\n x_ = tf.clip_by_value(x_, 1e-6, 1 - 1e-6)\n\n # ELBO\n marginal_likelihood = tf.reduce_sum(x * tf.log(x_) + (1 - x) * tf.log(1 - x_), 1)\n KL_divergence = 0.5 * tf.reduce_sum(tf.square(mu) + tf.square(sigma) - tf.log(1e-6 + tf.square(sigma)) - 1, 1)\n\n marginal_likelihood = tf.reduce_mean(marginal_likelihood)\n KL_divergence = tf.reduce_mean(KL_divergence)\n\n ELBO = marginal_likelihood - KL_divergence\n\n # minimize loss instead of maximizing ELBO\n loss = -ELBO\n return x_, z, loss, -marginal_likelihood, KL_divergence\n\n\n# Conditional Decoder (Generator)\ndef decoder(z, y, dim_img, n_hidden):\n x_ = bernoulli_MLP_conditional_decoder(z, y, n_hidden, dim_img, 1.0, reuse=True)\n return x_\n" ]
[ [ "tensorflow.clip_by_value", "tensorflow.get_variable", "tensorflow.nn.elu", "tensorflow.concat", "tensorflow.matmul", "tensorflow.contrib.layers.variance_scaling_initializer", "tensorflow.reduce_mean", "tensorflow.shape", "tensorflow.nn.tanh", "tensorflow.constant_initializer", "tensorflow.log", "tensorflow.square", "tensorflow.variable_scope", "tensorflow.nn.softplus", "tensorflow.nn.dropout" ] ]
epoch8/datapipe
[ "2358e13f6699b44950dc87fda6136f34fa719094" ]
[ "tests/test_meta_info_in_datapipe_events.py" ]
[ "import pandas as pd\nfrom sqlalchemy.sql.expression import select\n\nfrom datapipe.run_config import RunConfig\nfrom datapipe.store.database import TableStoreDB\nfrom datapipe.datatable import DataStore\nfrom datapipe.compute import Catalog, Pipeline,\\\n Table\nfrom datapipe.core_steps import BatchTransform, BatchGenerate\nfrom datapipe.compute import run_pipeline\n\nfrom sqlalchemy.sql.schema import Column\nfrom sqlalchemy.sql.sqltypes import Integer, JSON\n\n\nTEST_SCHEMA = [\n Column('pipeline_id', Integer(), primary_key=True),\n Column('offer_id', Integer(), primary_key=True),\n Column('test_field', JSON)\n]\n\n\ndef generate_data():\n df_data = [{\n \"pipeline_id\": 1,\n \"offer_id\": 1,\n \"test_field\": {\"a\": 1}\n }]\n yield pd.DataFrame(data=df_data)\n\n\ndef update_data(df: pd.DataFrame) -> pd.DataFrame:\n df[\"test_field\"].apply(lambda x: {**x, \"b\": 2})\n df.index = df.index.astype('str')\n return df\n\n\ndef test_meta_info_in_datapipe_events(dbconn) -> None:\n ds = DataStore(dbconn)\n\n run_config = RunConfig(\n filters={\n \"pipeline_id\": 1\n },\n labels={\n \"pipeline_name\": 'test_name',\n \"pipeline_id\": 1\n }\n )\n\n catalog = Catalog({\n 'test_generate': Table(\n store=TableStoreDB(\n dbconn,\n 'test_generate_data',\n TEST_SCHEMA\n )\n ),\n 'test_transform': Table(\n store=TableStoreDB(\n dbconn,\n 'test_transform_data',\n TEST_SCHEMA\n )\n )\n })\n\n pipeline = Pipeline([\n BatchGenerate(\n generate_data,\n outputs=[\"test_generate\"],\n ),\n BatchTransform(\n update_data,\n inputs=[\"test_generate\"],\n outputs=[\"test_transform\"],\n )\n ])\n\n run_pipeline(ds, catalog, pipeline, run_config)\n\n df_events = pd.read_sql_query(select(catalog.get_datatable(ds, 'test_generate').event_logger.events_table), dbconn.con)\n\n assert df_events.loc[0][\"event\"] == {\n \"meta\": {\n \"labels\": {\n \"step_name\": \"generate_data\",\n \"pipeline_name\": \"test_name\",\n \"pipeline_id\": 1,\n },\n \"filters\": {\n \"pipeline_id\": 1,\n }\n },\n \"data\": {\n \"table_name\": \"test_generate\",\n \"added_count\": 1,\n \"updated_count\": 0,\n \"deleted_count\": 0,\n \"processed_count\": 1\n }\n }\n\n assert df_events.loc[1][\"event\"] == {\n \"meta\": {\n \"labels\": {\n \"step_name\": \"update_data\",\n \"pipeline_name\": \"test_name\",\n \"pipeline_id\": 1,\n },\n \"filters\": {\n \"pipeline_id\": 1,\n }\n },\n \"data\": {\n \"table_name\": \"test_transform\",\n \"added_count\": 1,\n \"updated_count\": 0,\n \"deleted_count\": 0,\n \"processed_count\": 1\n }\n }\n" ]
[ [ "pandas.DataFrame" ] ]
michellejlin/tprk
[ "04758e40c7dd9060d4d613c52b650e250297cb7a" ]
[ "syph_visualizer.py" ]
[ "import numpy as np\nimport pandas as pd\nimport argparse\nimport sys\nfrom bokeh.palettes import brewer\nfrom bokeh import events\nfrom bokeh.io import export_png, save, export_svgs\nfrom bokeh.resources import CDN\nfrom bokeh.embed import components, file_html, autoload_static\nfrom bokeh.plotting import figure, show, output_file\nfrom bokeh.models import ColumnDataSource, Jitter, HoverTool, Slider, CustomJS, Label, WheelZoomTool, ResetTool, Button, TextInput\nfrom bokeh.transform import jitter, factor_cmap\nfrom bokeh.models.widgets import Panel, Tabs, Paragraph, Div, CheckboxGroup\nfrom bokeh.layouts import column, layout, widgetbox, row\nimport subprocess\nimport os\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description='Syph visualizer for single isolates')\n\tparser.add_argument('final_data', help='data table from syph.py, in csv format.')\n\tparser.add_argument('-t', '--title', help='name of sample to use as plot title.')\n\tparser.add_argument('-o', '--output', help='output folder to export plots.')\n\tparser.add_argument('-svg', action='store_true', help='Use this flag to output graphs in .svg format. '\n\t\t'By default, plots will be in .html.')\n\t\n\ttry:\n\t\targs = parser.parse_args()\n\texcept:\n\t\tparser.print_help()\n\t\tsys.exit(0)\n\n\t# Setting variables\n\t# Reads data from syph.py output.\n\tstrain = args.title\n\ttable = pd.read_csv(args.final_data,index_col=False)\n\tsource = ColumnDataSource(table)\n\n\t#TOOLTIPS = [\n\t#\t(\"Read\", \"@Read\"),\n\t#\t(\"Count\", \"@Count\"),\n\t#\t(\"Relative Frequency\", \"@RelativeFreq\"+\"%\"),\n\t#]\n\n\tplot_title = strain\n\toutput_path = args.output\n\n\tif args.svg:\n\t\tfig1 = figure(x_range = (0,80), y_range = (0,105), plot_height = 330, plot_width = 540, title = strain, toolbar_location = None)\n\telse:\n\t\tfig1 = figure(x_range = (0,80), y_range = (0,105), plot_height = 1000, plot_width = 1600, title = strain, toolbar_location = None)\n\t\n\t#TODO: Fix 0 on x-axis\n\tfig1.xaxis.major_label_overrides = dict(zip([10,20,30,40,50,60,70,80], [\"V1\", \"V2\", \"V3\", \"V4\", \"V5\", \"V6\", \"V7\",\"\"]))\n\tfig1.xaxis.minor_tick_line_color = None\n\tfig1.title.text_font_size = \"18pt\"\n\tfig1.xaxis.major_label_text_font_size = '16pt'\n\tfig1.yaxis.major_label_text_font_size = '16pt'\n\tfig1.yaxis.axis_label = \"Relative Frequency\"\n\tfig1.yaxis.axis_label_text_font_size = '18pt'\n\n\tblues = brewer['Blues'][9]\n\tbugn = brewer['BuGn'][9]\n\tbupu = brewer['Purples'][8]\n\torrd = brewer['OrRd'][9]\n\tgnbu = brewer['GnBu'][9]\n\tpurd = brewer['PuRd'][9]\n\tylgn = brewer['YlGn'][9]\n\tv1_bottom = 0\n\tv2_bottom = 0\n\tv3_bottom = 0\n\tv4_bottom = 0\n\tv5_bottom = 0\n\tv6_bottom = 0\n\tv7_bottom = 0\n\tregion_totals = [0,0,0,0,0,0,0]\n\tregion_counts = [0,0,0,0,0,0,0]\n\n\tfor line in open(args.final_data):\n\t\tregion, read, relativefreq, count = line.split(',')\n\t\tif (region == \"V1\"):\n\t\t\tbar = fig1.vbar(x=10, width = 6, bottom = v1_bottom, top = [v1_bottom + float(relativefreq)], \n\t\t\t\tcolor=blues[region_counts[0]%9])\n\t\t\thover = HoverTool(renderers = [bar], toggleable = False,\n\t\t\t\ttooltips=[(\"Read\", read), (\"Count\", count), (\"Relative Frequency\", relativefreq)])\n\t\t\tfig1.add_tools(hover)\n\t\t\tv1_bottom = v1_bottom + float(relativefreq)\n\t\t\tregion_totals[0] = region_totals[0] + int(count)\n\t\t\tregion_counts[0] = region_counts[0] + 1\n\n\t\telif (region == \"V2\"):\n\t\t\tbar = fig1.vbar(x=20, width = 6, bottom = v2_bottom, top = [v2_bottom + float(relativefreq)], \n\t\t\t\tcolor=bugn[region_counts[1]%9])\n\t\t\thover = HoverTool(renderers = [bar], toggleable = False,\n\t\t\t\ttooltips=[(\"Read\", read), (\"Count\", count), (\"Relative Frequency\", relativefreq)])\n\t\t\tfig1.add_tools(hover)\n\t\t\tv2_bottom = v2_bottom + float(relativefreq)\n\t\t\tregion_totals[1] = region_totals[1] + int(count)\n\t\t\tregion_counts[1] = region_counts[1] + 1\n\t\telif (region == \"V3\"):\n\t\t\tbar = fig1.vbar(x=30, width = 6, bottom = v3_bottom, top = [v3_bottom + float(relativefreq)], \n\t\t\t\tcolor=bupu[region_counts[2]%8])\n\t\t\thover = HoverTool(renderers = [bar], toggleable = False,\n\t\t\t\ttooltips=[(\"Read\", read), (\"Count\", count), (\"Relative Frequency\", relativefreq)])\n\t\t\tfig1.add_tools(hover)\n\t\t\tv3_bottom = v3_bottom + float(relativefreq)\n\t\t\tregion_totals[2] = region_totals[2] + int(count)\n\t\t\tregion_counts[2] = region_counts[2] + 1\n\t\telif (region == \"V4\"):\n\t\t\tbar = fig1.vbar(x=40, width = 6, bottom = v4_bottom, top = [v4_bottom + float(relativefreq)], \n\t\t\t\tcolor=orrd[region_counts[3]%9])\n\t\t\thover = HoverTool(renderers = [bar], \n\t\t\t\ttooltips=[(\"Read\", read), (\"Count\", count), (\"Relative Frequency\", relativefreq)])\n\t\t\tfig1.add_tools(hover)\n\t\t\tv4_bottom = v4_bottom + float(relativefreq)\n\t\t\tregion_totals[3] = region_totals[3] + int(count)\n\t\t\tregion_counts[3] = region_counts[3] + 1\n\t\telif (region == \"V5\"):\n\t\t\tbar = fig1.vbar(x=50, width = 6, bottom = v5_bottom, top = [v5_bottom + float(relativefreq)], \n\t\t\t\tcolor=gnbu[region_counts[4]%9])\n\t\t\thover = HoverTool(renderers = [bar], toggleable = False,\n\t\t\t\ttooltips=[(\"Read\", read), (\"Count\", count), (\"Relative Frequency\", relativefreq)])\n\t\t\tfig1.add_tools(hover)\n\t\t\tv5_bottom = v5_bottom + float(relativefreq)\n\t\t\tregion_totals[4] = region_totals[4] + int(count)\n\t\t\tregion_counts[4] = region_counts[4] + 1\n\t\telif (region == \"V6\"):\n\t\t\tbar = fig1.vbar(x=60, width = 6, bottom = v6_bottom, top = [v6_bottom + float(relativefreq)], \n\t\t\t\tcolor=ylgn[region_counts[5]%9])\n\t\t\thover = HoverTool(renderers = [bar], toggleable = False,\n\t\t\t\ttooltips=[(\"Read\", read), (\"Count\", count), (\"Relative Frequency\", relativefreq)])\n\t\t\tfig1.add_tools(hover)\n\t\t\tv6_bottom = v6_bottom + float(relativefreq)\n\t\t\tregion_totals[5] = region_totals[5] + int(count)\n\t\t\tregion_counts[5] = region_counts[5] + 1\n\t\telif (region == \"V7\"):\n\t\t\tbar = fig1.vbar(x=70, width = 6, bottom = v7_bottom, top = [v7_bottom + float(relativefreq)], \n\t\t\t\tcolor=purd[region_counts[6]%9])\n\t\t\thover = HoverTool(renderers = [bar], toggleable = False,\n\t\t\t\ttooltips=[(\"Read\", read), (\"Count\", count), (\"Relative Frequency\", relativefreq)])\n\t\t\tfig1.add_tools(hover)\n\t\t\tv7_bottom = v7_bottom + float(relativefreq)\n\t\t\tregion_totals[6] = region_totals[6] + int(count)\n\t\t\tregion_counts[6] = region_counts[6] + 1\n\n\tfor index, total in enumerate(region_totals):\n\t\tlabel = Label(x = (index + 1) * 10, y = 101, text = str(region_counts[index]) + \", \" + str(total), border_line_color = None, text_align = 'center', text_font_size = '11pt')\n\t\tfig1.add_layout(label)\n\n \n\t# fig2 = figure(plot_width = 1600, plot_height = 1000, title = \"Fig 2\", y_range = (0,105), x_range = table.Region.unique(), tooltips=TOOLTIPS)\n\t# circle = fig2.circle(x=jitter('Region', width = 0.3, range=fig2.x_range), y='RelativeFreq', size = 15, alpha = 0.8, source=source, color='cornflowerblue')\n\t# fig2.title.text_font_size = \"18pt\"\n\t# fig2.xaxis.major_label_text_font_size = '12pt'\n\t# fig2.yaxis.major_label_text_font_size = '12pt'\n\t# fig2.yaxis.axis_label = \"Relative Frequency\"\n\n\tif args.svg:\n\t\tfig1.output_backend = \"svg\"\n\t\toutput_filename = (strain + \"_RelativeFreqPlot.svg\")\n\t\toutput_file(output_filename)\n\t\texport_svgs(fig1, filename=output_filename)\n\telse:\n\t\toutput_filename = (strain + \"_RelativeFreqPlot.html\")\n\t\toutput_file(output_filename, title=strain)\n\n\t\tsave(fig1)\n\n\t# subprocess.call(\"mv \" + output_filename + \" \" + args.output + \"/\" + output_filename, shell=True)\n" ]
[ [ "pandas.read_csv" ] ]
kshama-msft/onnxruntime-training-examples
[ "0192a776e2fc62f1eeda3e3f1200cf40448302c1" ]
[ "huggingface-gpt2/ort_addon/ort_supplement/src/transformers/trainer_ort.py" ]
[ "import json\nimport time\nimport logging\nimport os\nimport random\nimport re\nimport shutil\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Callable, Dict, List, NamedTuple, Optional, Tuple\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.utils.data.dataloader import DataLoader\nfrom torch.utils.data.dataset import Dataset\nfrom torch.utils.data.distributed import DistributedSampler\nfrom torch.utils.data.sampler import RandomSampler\nfrom tqdm import tqdm, trange\n\nimport onnxruntime\nfrom onnxruntime.capi.ort_trainer import ORTTrainer, IODescription, ModelDescription\nfrom onnxruntime.capi.ort_trainer import LossScaler\n\nfrom .data.data_collator import DataCollator, DefaultDataCollator\nfrom .modeling_utils import PreTrainedModel\nfrom .training_args import TrainingArguments\nfrom .trainer import PredictionOutput, TrainOutput, EvalPrediction, set_seed\n\nfrom azureml.core.run import Run\n# get the Azure ML run object\nrun = Run.get_context()\n\n\ntry:\n from torch.utils.tensorboard import SummaryWriter\n\n _has_tensorboard = True\nexcept ImportError:\n try:\n from tensorboardX import SummaryWriter\n\n _has_tensorboard = True\n except ImportError:\n _has_tensorboard = False\n\n\ndef is_tensorboard_available():\n return _has_tensorboard\n\n\nlogger = logging.getLogger(__name__)\n\nPREFIX_CHECKPOINT_DIR = \"ort_checkpoint\"\n\nclass linear_schedule_with_warmup():\n def __init__(self, num_warmup_steps, num_training_steps, last_epoch=-1):\n \"\"\" Create a schedule with a learning rate that decreases linearly after\n linearly increasing during a warmup period.\n \"\"\"\n self.num_warmup_steps = num_warmup_steps\n self.num_training_steps = num_training_steps\n self.last_epoch = last_epoch\n\n def lr_lambda(self, current_step):\n if current_step < self.num_warmup_steps:\n return float(current_step) / float(max(1, self.num_warmup_steps))\n return max(\n 0.0, float(self.num_training_steps - current_step) / float(max(1, self.num_training_steps - self.num_warmup_steps))\n )\n\n def get_lr_this_step(self, current_step, base_lr):\n\n return self.lr_lambda(current_step) * base_lr\n\nclass OrtTrainer:\n \"\"\"\n Trainer is a simple but feature-complete training and eval loop for PyTorch,\n optimized for Transformers.\n \"\"\"\n\n model: PreTrainedModel\n args: TrainingArguments\n data_collator: DataCollator\n train_dataset: Optional[Dataset]\n eval_dataset: Optional[Dataset]\n compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None\n prediction_loss_only: bool\n tb_writer: Optional[\"SummaryWriter\"] = None\n\n\n def __init__(\n self,\n model: PreTrainedModel,\n args: TrainingArguments,\n data_collator: Optional[DataCollator] = None,\n train_dataset: Optional[Dataset] = None,\n eval_dataset: Optional[Dataset] = None,\n compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None,\n prediction_loss_only=False,\n ):\n \"\"\"\n Trainer is a simple but feature-complete training and eval loop for PyTorch,\n optimized for Transformers.\n\n Args:\n prediction_loss_only:\n (Optional) in evaluation and prediction, only return the loss\n \"\"\"\n self.model = model\n self.args = args\n if data_collator is not None:\n self.data_collator = data_collator\n else:\n self.data_collator = DefaultDataCollator()\n self.train_dataset = train_dataset\n self.eval_dataset = eval_dataset\n self.compute_metrics = compute_metrics\n self.prediction_loss_only = prediction_loss_only\n\n if is_tensorboard_available() and self.is_world_master():\n self.tb_writer = SummaryWriter(log_dir=self.args.logging_dir)\n if not is_tensorboard_available():\n logger.warning(\n \"You are instantiating a Trainer but Tensorboard is not installed. You should consider installing it.\"\n )\n set_seed(self.args.seed)\n onnxruntime.set_seed(self.args.seed)\n # Create output directory if needed\n if self.is_world_master():\n os.makedirs(self.args.output_dir, exist_ok=True)\n \n torch.cuda.set_device(self.args.local_rank)\n\n self.ort_model = self.to_ort_model(model, model.config, args)\n\n def update_torch_model(self,):\n if self.ort_model:\n logger.info(\n \"Updating weights of torch model from ORT model.\"\n )\n ort_state_dict = self.ort_model.state_dict()\n self.model.load_state_dict(ort_state_dict, strict=False)\n else:\n logger.warning(\n \"No ORT model found to update weights from, assuming torch model is up to date.\"\n )\n\n def gpt2_model_description(self,n_head, vocab_size, n_hidden, n_layer, n_ctx, batch_size):\n \n logger.info(\"****num of head is: {}\".format(n_head))\n logger.info(\"****vocab size is: {}\".format(vocab_size))\n logger.info(\"****num of hidden layer is: {}\".format(n_hidden))\n logger.info(\"****num of layer is: {}\".format(n_layer))\n logger.info(\"****seq length is: {}\".format(n_ctx))\n\n input_ids_desc = IODescription('input_ids', [batch_size, n_ctx], torch.int64, num_classes = vocab_size) \n labels_desc = IODescription('labels', [batch_size, n_ctx], torch.int64, num_classes = vocab_size)\n \n loss_desc = IODescription('loss', [], torch.float32)\n \n return ModelDescription([input_ids_desc, labels_desc],\n [loss_desc])\n\n def ort_trainer_learning_rate_description(self):\n return IODescription('Learning_Rate', [1,], torch.float32)\n\n def to_ort_model(self,model, config, args):\n model_desc = self.gpt2_model_description(config.n_head, config.vocab_size, config.n_embd, config.n_layer, config.n_ctx, args.per_gpu_train_batch_size)\n learning_rate_description = self.ort_trainer_learning_rate_description()\n\n def map_optimizer_attributes(name):\n no_decay_keys = [\"bias\", \"gamma\", \"beta\", \"LayerNorm\"]\n no_decay = False\n for no_decay_key in no_decay_keys:\n if no_decay_key in name:\n no_decay = True\n break\n if no_decay:\n return {\"alpha\": 0.9, \"beta\": 0.999, \"lambda\": 0.0, \"epsilon\": args.adam_epsilon}\n else:\n return {\"alpha\": 0.9, \"beta\": 0.999, \"lambda\": args.weight_decay, \"epsilon\": args.adam_epsilon}\n\n from onnxruntime.capi._pybind_state import set_cuda_device_id, set_arena_extend_strategy, ArenaExtendStrategy\n set_arena_extend_strategy(ArenaExtendStrategy.kSameAsRequested)\n set_cuda_device_id(self.args.local_rank)\n\n model = ORTTrainer(model, None, model_desc, \"AdamOptimizer\",\n map_optimizer_attributes,\n learning_rate_description,\n args.device, \n gradient_accumulation_steps=args.gradient_accumulation_steps, \n world_rank = self.args.world_rank,\n world_size = self.args.world_size,\n use_mixed_precision = self.args.fp16,\n allreduce_post_accumulation = True,\n _opset_version=12\n )\n \n logger.info(\"****************************Model converted to ORT\")\n return model\n\n def get_train_dataloader(self) -> DataLoader:\n if self.train_dataset is None:\n raise ValueError(\"Trainer: training requires a train_dataset.\")\n train_sampler = (\n RandomSampler(self.train_dataset) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset)\n )\n return DataLoader(\n self.train_dataset,\n batch_size=self.args.per_gpu_train_batch_size,\n sampler=train_sampler,\n collate_fn=self.data_collator.collate_batch,\n )\n\n def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader:\n if eval_dataset is None and self.eval_dataset is None:\n raise ValueError(\"Trainer: evaluation requires an eval_dataset.\")\n return DataLoader(\n eval_dataset if eval_dataset is not None else self.eval_dataset,\n batch_size=self.args.eval_batch_size,\n shuffle=False,\n collate_fn=self.data_collator.collate_batch,\n )\n\n def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader:\n # We use the same batch_size as for eval.\n return DataLoader(\n test_dataset,\n batch_size=self.args.eval_batch_size,\n shuffle=False,\n collate_fn=self.data_collator.collate_batch,\n )\n\n def train(self, model_path: Optional[str] = None):\n \"\"\"\n Main training entry point.\n\n Args:\n model_path:\n (Optional) Local path to model if model to train has been instantiated from a local path\n If present, we will try reloading the optimizer/scheduler states from there.\n \"\"\"\n train_dataloader = self.get_train_dataloader()\n\n if self.args.max_steps > 0:\n t_total = self.args.max_steps\n num_train_epochs = (\n self.args.max_steps // (len(train_dataloader) // self.args.gradient_accumulation_steps) + 1\n )\n else:\n t_total = int(len(train_dataloader) // self.args.gradient_accumulation_steps * self.args.num_train_epochs)\n num_train_epochs = self.args.num_train_epochs\n\n scheduler = linear_schedule_with_warmup(num_warmup_steps=self.args.warmup_steps, num_training_steps=t_total)\n\n loss_scaler = LossScaler(self.ort_model.loss_scale_input_name, True, up_scale_window=2000, loss_scale=float(1 << 20)) if self.args.fp16 else 1\n\n model = self.ort_model\n\n if self.tb_writer is not None:\n self.tb_writer.add_text(\"args\", self.args.to_json_string())\n\n # Train!\n if self.is_world_master():\n logger.info(\"***** Running training *****\")\n logger.info(\" Num examples = %d\", len(train_dataloader.dataset))\n logger.info(\" Num Epochs = %d\", num_train_epochs)\n logger.info(\" Instantaneous batch size per GPU = %d\", self.args.per_gpu_train_batch_size)\n logger.info(\n \" Total train batch size (w. parallel, distributed & accumulation) = %d\",\n self.args.train_batch_size\n * self.args.gradient_accumulation_steps\n * (self.args.world_size if self.args.local_rank != -1 else 1),\n )\n logger.info(\" Gradient Accumulation steps = %d\", self.args.gradient_accumulation_steps)\n logger.info(\" Total optimization steps = %d\", t_total)\n\n global_step = 0\n epochs_trained = 0\n steps_trained_in_current_epoch = 0\n # Check if continuing training from a checkpoint\n if model_path is not None:\n # set global_step to global_step of last saved checkpoint from model path\n try:\n global_step = int(model_path.split(\"-\")[-1].split(\"/\")[0])\n epochs_trained = global_step // (len(train_dataloader) // self.args.gradient_accumulation_steps)\n steps_trained_in_current_epoch = global_step % (\n len(train_dataloader) // self.args.gradient_accumulation_steps\n )\n\n logger.info(\" Continuing training from checkpoint, will skip to saved global_step\")\n logger.info(\" Continuing training from epoch %d\", epochs_trained)\n logger.info(\" Continuing training from global step %d\", global_step)\n logger.info(\" Will skip the first %d steps in the first epoch\", steps_trained_in_current_epoch)\n except ValueError:\n global_step = 0\n logger.info(\" Starting fine-tuning.\")\n\n tr_loss = 0.0\n logging_loss = 0.0\n global_batch_train_start = time.time()\n\n train_iterator = trange(\n epochs_trained, int(num_train_epochs), desc=\"Epoch\", disable=self.args.local_rank not in [-1, 0],\n )\n for epoch in train_iterator:\n epoch_iterator = tqdm(train_dataloader, desc=\"Iteration\", disable=self.args.local_rank not in [-1, 0])\n for step, inputs in enumerate(epoch_iterator):\n\n # Skip past any already trained steps if resuming training\n if steps_trained_in_current_epoch > 0:\n steps_trained_in_current_epoch -= 1\n continue\n \n if len(inputs['input_ids']) < self.args.per_gpu_train_batch_size:\n #skip incomplete batch\n logger.info('Skipping incomplete batch...')\n continue\n \n learning_rate = torch.tensor([scheduler.get_lr_this_step(global_step, base_lr = self.args.learning_rate)])\n loss, all_finite = self._training_step(model, inputs, learning_rate, loss_scaler)\n tr_loss += loss\n if (step + 1) % self.args.gradient_accumulation_steps == 0 or (\n # last step in epoch but step is always smaller than gradient_accumulation_steps\n len(epoch_iterator) <= self.args.gradient_accumulation_steps\n and (step + 1) == len(epoch_iterator)\n ):\n\n if self.args.fp16:\n loss_scaler.update_loss_scale(all_finite.item())\n\n global_step += 1\n global_batch_train_duration = time.time() - global_batch_train_start\n global_batch_train_start = time.time()\n\n if self.args.local_rank in [-1, 0]:\n if (self.args.logging_steps > 0 and global_step % self.args.logging_steps == 0) or (\n global_step == 1 and self.args.logging_first_step\n ):\n logs = {}\n loss_avg = (tr_loss - logging_loss) / (self.args.logging_steps * self.args.gradient_accumulation_steps)\n logs[\"learning_rate\"] = learning_rate.item()\n logs[\"loss\"] = loss_avg\n logs[\"global_step\"] = global_step\n logs[\"global_step_time\"] = global_batch_train_duration\n logging_loss = tr_loss\n\n if self.tb_writer:\n for k, v in logs.items():\n self.tb_writer.add_scalar(k, v, global_step)\n run.log(k,v)\n epoch_iterator.write(json.dumps({**logs, **{\"step\": global_step}}))\n\n if self.args.save_steps > 0 and global_step % self.args.save_steps == 0:\n # In all cases (even distributed/parallel), self.model is always a reference\n # to the model we want to save.\n if hasattr(model, \"module\"):\n assert model.module is self.ort_model\n else:\n assert model is self.ort_model\n # Save model checkpoint\n output_dir = os.path.join(self.args.output_dir, f\"{PREFIX_CHECKPOINT_DIR}-{global_step}\")\n self.save_model(output_dir)\n # self._rotate_checkpoints()\n \n if self.args.max_steps > 0 and global_step > self.args.max_steps:\n epoch_iterator.close()\n break\n if self.args.max_steps > 0 and global_step > self.args.max_steps:\n train_iterator.close()\n break\n\n if self.tb_writer:\n self.tb_writer.close()\n self.update_torch_model()\n del(self.ort_model)\n self.ort_model = None\n \n logger.info(\"\\n\\nTraining completed. Do not forget to share your model on huggingface.co/models =)\\n\\n\")\n return TrainOutput(global_step, tr_loss / global_step)\n\n def _training_step(\n self, model: nn.Module, inputs: Dict[str, torch.Tensor], learning_rate, loss_scaler\n ) -> float:\n model.train()\n\n if self.args.fp16:\n loss_scale = torch.tensor([loss_scaler.loss_scale_])\n result = model(inputs['input_ids'],inputs['labels'], learning_rate, loss_scale)\n else:\n result = model(inputs['input_ids'],inputs['labels'], learning_rate)\n \n all_finite = None\n if isinstance(result, (list, tuple)):\n loss = result[0]\n all_finite = result[-1]\n else:\n loss = result\n\n return loss.item(), all_finite\n\n def is_world_master(self) -> bool:\n \"\"\"\n This will be True only in one process, even in distributed mode,\n even when training on multiple machines.\n \"\"\"\n return self.args.local_rank == -1 or torch.distributed.get_rank() == 0\n\n def save_model(self, output_dir: Optional[str] = None):\n \"\"\"\n Saving best-practices: if you use default names for the model,\n you can reload it using from_pretrained().\n\n Will only save from the master process.\n \"\"\"\n if self.is_world_master():\n self._save(output_dir)\n\n def _save(self, output_dir: Optional[str] = None):\n output_dir = output_dir if output_dir is not None else self.args.output_dir\n os.makedirs(output_dir, exist_ok=True)\n logger.info(\"Saving model checkpoint to %s\", output_dir)\n\n self.update_torch_model()\n # Save a trained model and configuration using `save_pretrained()`.\n # They can then be reloaded using `from_pretrained()`\n if not isinstance(self.model, PreTrainedModel):\n raise ValueError(\"Trainer.model appears to not be a PreTrainedModel\")\n self.model.save_pretrained(output_dir)\n\n # Good practice: save your training arguments together with the trained model\n torch.save(self.args, os.path.join(output_dir, \"training_args.bin\"))\n\n def _sorted_checkpoints(self, checkpoint_prefix=PREFIX_CHECKPOINT_DIR, use_mtime=False) -> List[str]:\n ordering_and_checkpoint_path = []\n\n glob_checkpoints = [str(x) for x in Path(self.args.output_dir).glob(f\"{checkpoint_prefix}-*\")]\n\n for path in glob_checkpoints:\n if use_mtime:\n ordering_and_checkpoint_path.append((os.path.getmtime(path), path))\n else:\n regex_match = re.match(f\".*{checkpoint_prefix}-([0-9]+)\", path)\n if regex_match and regex_match.groups():\n ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))\n\n checkpoints_sorted = sorted(ordering_and_checkpoint_path)\n checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]\n return checkpoints_sorted\n\n def _rotate_checkpoints(self, use_mtime=False) -> None:\n if self.args.save_total_limit is None or self.args.save_total_limit <= 0:\n return\n\n # Check if we should delete older checkpoint(s)\n checkpoints_sorted = self._sorted_checkpoints(use_mtime=use_mtime)\n if len(checkpoints_sorted) <= self.args.save_total_limit:\n return\n\n number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - self.args.save_total_limit)\n checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete]\n for checkpoint in checkpoints_to_be_deleted:\n logger.info(\"Deleting older checkpoint [{}] due to args.save_total_limit\".format(checkpoint))\n shutil.rmtree(checkpoint)\n\n def evaluate(\n self, eval_dataset: Optional[Dataset] = None, prediction_loss_only: Optional[bool] = None\n ) -> Dict[str, float]:\n \"\"\"\n Run evaluation and return metrics.\n\n The calling script will be responsible for providing a method to compute metrics, as they are\n task-dependent.\n\n Args:\n eval_dataset: (Optional) Pass a dataset if you wish to override\n the one on the instance.\n Returns:\n A dict containing:\n - the eval loss\n - the potential metrics computed from the predictions\n \"\"\"\n eval_dataloader = self.get_eval_dataloader(eval_dataset)\n\n output = self._prediction_loop(eval_dataloader, description=\"Evaluation\")\n return output.metrics\n\n def predict(self, test_dataset: Dataset) -> PredictionOutput:\n \"\"\"\n Run prediction and return predictions and potential metrics.\n\n Depending on the dataset and your use case, your test dataset may contain labels.\n In that case, this method will also return metrics, like in evaluate().\n \"\"\"\n test_dataloader = self.get_test_dataloader(test_dataset)\n return self._prediction_loop(test_dataloader, description=\"Prediction\")\n\n def _prediction_loop(\n self, dataloader: DataLoader, description: str, prediction_loss_only: Optional[bool] = None\n ) -> PredictionOutput:\n \"\"\"\n Prediction/evaluation loop, shared by `evaluate()` and `predict()`.\n\n Works both with or without labels.\n \"\"\"\n\n prediction_loss_only = prediction_loss_only if prediction_loss_only is not None else self.prediction_loss_only\n self.update_torch_model()\n # multi-gpu eval\n if self.args.n_gpu > 1 and not isinstance(self.model, torch.nn.DataParallel):\n model = torch.nn.DataParallel(self.model)\n else:\n model = self.model\n \n model.to(self.args.device)\n if self.is_world_master():\n logger.info(\"***** Running %s *****\", description)\n logger.info(\" Num examples = %d\", len(dataloader.dataset))\n logger.info(\" Batch size = %d\", dataloader.batch_size)\n eval_losses: List[float] = []\n preds: np.ndarray = None\n label_ids: np.ndarray = None\n model.eval()\n\n for inputs in tqdm(dataloader, desc=description):\n has_labels = any(inputs.get(k) is not None for k in [\"labels\", \"masked_lm_labels\"])\n\n for k, v in inputs.items():\n inputs[k] = v.to(self.args.device)\n\n with torch.no_grad():\n outputs = model(**inputs)\n if has_labels:\n step_eval_loss, logits = outputs[:2]\n eval_losses += [step_eval_loss.mean().item()]\n else:\n logits = outputs[0]\n\n if not prediction_loss_only:\n if preds is None:\n preds = logits.detach().cpu().numpy()\n else:\n preds = np.append(preds, logits.detach().cpu().numpy(), axis=0)\n if inputs.get(\"labels\") is not None:\n if label_ids is None:\n label_ids = inputs[\"labels\"].detach().cpu().numpy()\n else:\n label_ids = np.append(label_ids, inputs[\"labels\"].detach().cpu().numpy(), axis=0)\n\n if self.compute_metrics is not None and preds is not None and label_ids is not None:\n metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids))\n else:\n metrics = {}\n if len(eval_losses) > 0:\n metrics[\"loss\"] = np.mean(eval_losses)\n\n return PredictionOutput(predictions=preds, label_ids=label_ids, metrics=metrics)\n" ]
[ [ "torch.utils.data.distributed.DistributedSampler", "torch.cuda.set_device", "torch.tensor", "torch.nn.DataParallel", "numpy.mean", "torch.no_grad", "torch.distributed.get_rank", "torch.utils.data.dataloader.DataLoader", "torch.utils.data.sampler.RandomSampler" ] ]
kevinleestone/mmstereo
[ "6757847000ed19cce607ce7537f2f38eed305cdd" ]
[ "losses/loss_utils.py" ]
[ "# Copyright 2021 Toyota Research Institute. All rights reserved.\n\nimport torch\nimport torch.nn.functional as F\n\n\ndef null_loss():\n return None, False\n\n\ndef dummy_loss(tensor):\n tensor[torch.isnan(tensor)] = 0.0\n return F.mse_loss(tensor, torch.zeros_like(tensor)) * 0.0, False\n\n\ndef valid_loss(tensor):\n if not torch.any(torch.isnan(tensor)):\n return tensor, True\n else:\n return dummy_loss(tensor)\n" ]
[ [ "torch.zeros_like", "torch.isnan" ] ]
speedcell4/pytorch-noreward-rl
[ "b889d78b7b2115feb80198c90e75e35956eae284" ]
[ "test.py" ]
[ "import pickle\nimport time\nfrom collections import deque\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nimport env_wrapper\nfrom model import ActorCritic\n\n\ndef test(rank, args, shared_model):\n torch.manual_seed(args.seed + rank)\n env = env_wrapper.create_doom(args.record, outdir=args.outdir)\n\n model = ActorCritic(env.observation_space.shape[0], env.action_space)\n\n model.eval()\n state = env.reset()\n state = torch.from_numpy(state)\n reward_sum = 0\n done = True\n\n start_time = time.time()\n\n # a quick hack to prevent the agent from stucking\n actions = deque(maxlen=2100)\n episode_length = 0\n result = []\n\n while True:\n episode_length += 1\n # Sync with the shared model\n if done:\n model.load_state_dict(shared_model.state_dict())\n cx = Variable(torch.zeros(1, 256), volatile=True)\n hx = Variable(torch.zeros(1, 256), volatile=True)\n else:\n cx = Variable(cx.data, volatile=True)\n hx = Variable(hx.data, volatile=True)\n\n value, logit, (hx, cx) = model(\n (Variable(state.unsqueeze(0), volatile=True), (hx, cx)),\n icm=False\n )\n\n prob = F.softmax(logit)\n action = prob.max(1)[1].data.numpy()\n\n state, reward, done, _ = env.step(action[0, 0])\n state = torch.from_numpy(state)\n\n done = done or episode_length >= args.max_episode_length\n reward_sum += reward\n\n # a quick hack to prevent the agent from stucking\n actions.append(action[0, 0])\n if actions.count(actions[0]) == actions.maxlen:\n done = True\n\n if done:\n end_time = time.time()\n print(\"Time {}, episode reward {}, episode length {}\".format(\n time.strftime(\"%Hh %Mm %Ss\",\n time.gmtime(end_time - start_time)),\n reward_sum, episode_length))\n result.append((reward_sum, end_time - start_time))\n f = open('output/result.pickle', 'w')\n pickle.dump(result, f)\n f.close()\n torch.save(model.state_dict(), 'output/{}.pth'.format((end_time - start_time)))\n\n reward_sum = 0\n episode_length = 0\n actions.clear()\n state = env.reset()\n state = torch.from_numpy(state)\n time.sleep(60)\n" ]
[ [ "torch.nn.functional.softmax", "torch.zeros", "torch.manual_seed", "torch.from_numpy", "torch.autograd.Variable" ] ]
AbhijeetKrishnan/PettingZoo
[ "d1a68923cef108b92012bfaaf2f083c839213d9f" ]
[ "pettingzoo/classic/tictactoe/tictactoe.py" ]
[ "from pettingzoo import AECEnv\nfrom pettingzoo.utils import agent_selector\nfrom gym import spaces\nimport numpy as np\nimport warnings\n\nfrom pettingzoo.utils import wrappers\n\nfrom .board import Board\n\n\ndef env():\n env = raw_env()\n env = wrappers.CaptureStdoutWrapper(env)\n env = wrappers.TerminateIllegalWrapper(env, illegal_reward=-1)\n env = wrappers.AssertOutOfBoundsWrapper(env)\n env = wrappers.OrderEnforcingWrapper(env)\n return env\n\n\nclass raw_env(AECEnv):\n metadata = {'render.modes': ['human'], \"name\": \"tictactoe_v3\"}\n\n def __init__(self):\n super().__init__()\n self.board = Board()\n\n self.agents = [\"player_1\", \"player_2\"]\n self.possible_agents = self.agents[:]\n\n self.action_spaces = {i: spaces.Discrete(9) for i in self.agents}\n self.observation_spaces = {i: spaces.Dict({\n 'observation': spaces.Box(low=0, high=1, shape=(3, 3, 2), dtype=np.int8),\n 'action_mask': spaces.Box(low=0, high=1, shape=(9,), dtype=np.int8)\n }) for i in self.agents}\n\n self.rewards = {i: 0 for i in self.agents}\n self.dones = {i: False for i in self.agents}\n self.infos = {i: {'legal_moves': list(range(0, 9))} for i in self.agents}\n\n self._agent_selector = agent_selector(self.agents)\n self.agent_selection = self._agent_selector.reset()\n\n # Key\n # ----\n # blank space = 0\n # agent 0 = 1\n # agent 1 = 2\n # An observation is list of lists, where each list represents a row\n #\n # [[0,0,2]\n # [1,2,1]\n # [2,1,0]]\n def observe(self, agent):\n board_vals = np.array(self.board.squares).reshape(3, 3)\n cur_player = self.possible_agents.index(agent)\n opp_player = (cur_player + 1) % 2\n\n cur_p_board = np.equal(board_vals, cur_player + 1)\n opp_p_board = np.equal(board_vals, opp_player + 1)\n\n observation = np.stack([cur_p_board, opp_p_board], axis=2).astype(np.int8)\n legal_moves = self._legal_moves() if agent == self.agent_selection else []\n\n action_mask = np.zeros(9, int)\n for i in legal_moves:\n action_mask[i] = 1\n\n return {'observation': observation, 'action_mask': action_mask}\n\n def _legal_moves(self):\n return [i for i in range(len(self.board.squares)) if self.board.squares[i] == 0]\n\n # action in this case is a value from 0 to 8 indicating position to move on tictactoe board\n def step(self, action):\n if self.dones[self.agent_selection]:\n return self._was_done_step(action)\n # check if input action is a valid move (0 == empty spot)\n assert (self.board.squares[action] == 0), \"played illegal move\"\n # play turn\n self.board.play_turn(self.agents.index(self.agent_selection), action)\n\n # update infos\n # list of valid actions (indexes in board)\n # next_agent = self.agents[(self.agents.index(self.agent_selection) + 1) % len(self.agents)]\n next_agent = self._agent_selector.next()\n\n if self.board.check_game_over():\n winner = self.board.check_for_winner()\n\n if winner == -1:\n # tie\n pass\n elif winner == 1:\n # agent 0 won\n self.rewards[self.agents[0]] += 1\n self.rewards[self.agents[1]] -= 1\n else:\n # agent 1 won\n self.rewards[self.agents[1]] += 1\n self.rewards[self.agents[0]] -= 1\n\n # once either play wins or there is a draw, game over, both players are done\n self.dones = {i: True for i in self.agents}\n\n # Switch selection to next agents\n self._cumulative_rewards[self.agent_selection] = 0\n self.agent_selection = next_agent\n\n self._accumulate_rewards()\n\n def reset(self):\n # reset environment\n self.board = Board()\n\n self.agents = self.possible_agents[:]\n self.rewards = {i: 0 for i in self.agents}\n self._cumulative_rewards = {i: 0 for i in self.agents}\n self.dones = {i: False for i in self.agents}\n self.infos = {i: {} for i in self.agents}\n # selects the first agent\n self._agent_selector.reinit(self.agents)\n self._agent_selector.reset()\n self.agent_selection = self._agent_selector.reset()\n\n def render(self, mode='human'):\n def getSymbol(input):\n if input == 0:\n return '-'\n elif input == 1:\n return 'X'\n else:\n return 'O'\n\n board = list(map(getSymbol, self.board.squares))\n\n print(\" \" * 5 + \"|\" + \" \" * 5 + \"|\" + \" \" * 5)\n print(f\" {board[0]} \" + \"|\" + f\" {board[3]} \" + \"|\" + f\" {board[6]} \")\n print(\"_\" * 5 + \"|\" + \"_\" * 5 + \"|\" + \"_\" * 5)\n\n print(\" \" * 5 + \"|\" + \" \" * 5 + \"|\" + \" \" * 5)\n print(f\" {board[1]} \" + \"|\" + f\" {board[4]} \" + \"|\" + f\" {board[7]} \")\n print(\"_\" * 5 + \"|\" + \"_\" * 5 + \"|\" + \"_\" * 5)\n\n print(\" \" * 5 + \"|\" + \" \" * 5 + \"|\" + \" \" * 5)\n print(f\" {board[2]} \" + \"|\" + f\" {board[5]} \" + \"|\" + f\" {board[8]} \")\n print(\" \" * 5 + \"|\" + \" \" * 5 + \"|\" + \" \" * 5)\n\n def close(self):\n pass\n" ]
[ [ "numpy.array", "numpy.zeros", "numpy.equal", "numpy.stack" ] ]
kunde122/bert
[ "def0a6534b77de915c5d39b2ffd05fd19ac3f2f2" ]
[ "run_classifier.py" ]
[ "# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"BERT finetuning runner.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport csv\nimport os\nimport modeling\nimport optimization\nimport tokenization\nimport tensorflow as tf\n\nflags = tf.flags\n\nFLAGS = flags.FLAGS\n\n## Required parameters\nflags.DEFINE_string(\n \"data_dir\", None,\n \"The input data dir. Should contain the .tsv files (or other data files) \"\n \"for the task.\")\n\nflags.DEFINE_string(\n \"bert_config_file\", None,\n \"The config json file corresponding to the pre-trained BERT model. \"\n \"This specifies the model architecture.\")\n\nflags.DEFINE_string(\"task_name\", None, \"The name of the task to train.\")\n\nflags.DEFINE_string(\"vocab_file\", None,\n \"The vocabulary file that the BERT model was trained on.\")\n\nflags.DEFINE_string(\n \"output_dir\", None,\n \"The output directory where the model checkpoints will be written.\")\n\n## Other parameters\n\nflags.DEFINE_string(\n \"init_checkpoint\", None,\n \"Initial checkpoint (usually from a pre-trained BERT model).\")\n\nflags.DEFINE_bool(\n \"do_lower_case\", True,\n \"Whether to lower case the input text. Should be True for uncased \"\n \"models and False for cased models.\")\n\nflags.DEFINE_integer(\n \"max_seq_length\", 128,\n \"The maximum total input sequence length after WordPiece tokenization. \"\n \"Sequences longer than this will be truncated, and sequences shorter \"\n \"than this will be padded.\")\n\nflags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\")\n\nflags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval on the dev set.\")\n\nflags.DEFINE_bool(\n \"do_predict\", False,\n \"Whether to run the model in inference mode on the test set.\")\n\nflags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\")\n\nflags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for eval.\")\n\nflags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for predict.\")\n\nflags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\")\n\nflags.DEFINE_float(\"num_train_epochs\", 3.0,\n \"Total number of training epochs to perform.\")\n\nflags.DEFINE_float(\n \"warmup_proportion\", 0.1,\n \"Proportion of training to perform linear learning rate warmup for. \"\n \"E.g., 0.1 = 10% of training.\")\n\nflags.DEFINE_integer(\"save_checkpoints_steps\", 1000,\n \"How often to save the model checkpoint.\")\n\nflags.DEFINE_integer(\"iterations_per_loop\", 1000,\n \"How many steps to make in each estimator call.\")\n\nflags.DEFINE_bool(\"use_tpu\", False, \"Whether to use TPU or GPU/CPU.\")\n\ntf.flags.DEFINE_string(\n \"tpu_name\", None,\n \"The Cloud TPU to use for training. This should be either the name \"\n \"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 \"\n \"url.\")\n\ntf.flags.DEFINE_string(\n \"tpu_zone\", None,\n \"[Optional] GCE zone where the Cloud TPU is located in. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\ntf.flags.DEFINE_string(\n \"gcp_project\", None,\n \"[Optional] Project name for the Cloud TPU-enabled project. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\ntf.flags.DEFINE_string(\"master\", None, \"[Optional] TensorFlow master URL.\")\n\nflags.DEFINE_integer(\n \"num_tpu_cores\", 8,\n \"Only used if `use_tpu` is True. Total number of TPU cores to use.\")\n\n\nclass InputExample(object):\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\n\n def __init__(self, guid, text_a, text_b=None, label=None):\n \"\"\"Constructs a InputExample.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n\nclass PaddingInputExample(object):\n \"\"\"Fake example so the num input examples is a multiple of the batch size.\n\n When running eval/predict on the TPU, we need to pad the number of examples\n to be a multiple of the batch size, because the TPU requires a fixed batch\n size. The alternative is to drop the last batch, which is bad because it means\n the entire output data won't be generated.\n\n We use this class instead of `None` because treating `None` as padding\n battches could cause silent errors.\n \"\"\"\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self,\n input_ids,\n input_mask,\n segment_ids,\n label_id,\n is_real_example=True):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.label_id = label_id\n self.is_real_example = is_real_example\n\n\nclass DataProcessor(object):\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\n raise NotImplementedError()\n\n def get_dev_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\n raise NotImplementedError()\n\n def get_test_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for prediction.\"\"\"\n raise NotImplementedError()\n\n def get_labels(self):\n \"\"\"Gets the list of labels for this data set.\"\"\"\n raise NotImplementedError()\n\n @classmethod\n def _read_tsv(cls, input_file, quotechar=None):\n \"\"\"Reads a tab separated value file.\"\"\"\n with tf.gfile.Open(input_file, \"r\") as f:\n reader = csv.reader(f, delimiter=\"\\t\", quotechar=quotechar)\n lines = []\n for line in reader:\n lines.append(line)\n return lines\n\n\nclass XnliProcessor(DataProcessor):\n \"\"\"Processor for the XNLI data set.\"\"\"\n\n def __init__(self):\n self.language = \"zh\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n lines = self._read_tsv(\n os.path.join(data_dir, \"multinli\",\n \"multinli.train.%s.tsv\" % self.language))\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"train-%d\" % (i)\n text_a = tokenization.convert_to_unicode(line[0])\n text_b = tokenization.convert_to_unicode(line[1])\n label = tokenization.convert_to_unicode(line[2])\n if label == tokenization.convert_to_unicode(\"contradictory\"):\n label = tokenization.convert_to_unicode(\"contradiction\")\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n lines = self._read_tsv(os.path.join(data_dir, \"xnli.dev.tsv\"))\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"dev-%d\" % (i)\n language = tokenization.convert_to_unicode(line[0])\n if language != tokenization.convert_to_unicode(self.language):\n continue\n text_a = tokenization.convert_to_unicode(line[6])\n text_b = tokenization.convert_to_unicode(line[7])\n label = tokenization.convert_to_unicode(line[1])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"contradiction\", \"entailment\", \"neutral\"]\n\n\nclass MnliProcessor(DataProcessor):\n \"\"\"Processor for the MultiNLI data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev_matched.tsv\")),\n \"dev_matched\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test_matched.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"contradiction\", \"entailment\", \"neutral\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, tokenization.convert_to_unicode(line[0]))\n text_a = tokenization.convert_to_unicode(line[8])\n text_b = tokenization.convert_to_unicode(line[9])\n if set_type == \"test\":\n label = \"contradiction\"\n else:\n label = tokenization.convert_to_unicode(line[-1])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass MrpcProcessor(DataProcessor):\n \"\"\"Processor for the MRPC data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = tokenization.convert_to_unicode(line[3])\n text_b = tokenization.convert_to_unicode(line[4])\n if set_type == \"test\":\n label = \"0\"\n else:\n label = tokenization.convert_to_unicode(line[0])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass ColaProcessor(DataProcessor):\n \"\"\"Processor for the CoLA data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n # Only the test set has a header\n if set_type == \"test\" and i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n if set_type == \"test\":\n text_a = tokenization.convert_to_unicode(line[1])\n label = \"0\"\n else:\n text_a = tokenization.convert_to_unicode(line[3])\n label = tokenization.convert_to_unicode(line[1])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n return examples\n\nclass SsProcessor(DataProcessor):\n \"\"\"Processor for the CoLA data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n # Only the test set has a header\n if set_type == \"test\" and i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n if set_type == \"test\":\n text_a = tokenization.convert_to_unicode(line[1])\n label = \"0\"\n else:\n text_a = tokenization.convert_to_unicode(line[0])\n label = tokenization.convert_to_unicode(line[1])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n return examples\n\n\ndef convert_single_example(ex_index, example, label_list, max_seq_length,\n tokenizer):\n \"\"\"Converts a single `InputExample` into a single `InputFeatures`.\"\"\"\n\n if isinstance(example, PaddingInputExample):\n return InputFeatures(\n input_ids=[0] * max_seq_length,\n input_mask=[0] * max_seq_length,\n segment_ids=[0] * max_seq_length,\n label_id=0,\n is_real_example=False)\n\n label_map = {}\n for (i, label) in enumerate(label_list):\n label_map[label] = i\n\n tokens_a = tokenizer.tokenize(example.text_a)\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n\n if tokens_b:\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[0:(max_seq_length - 2)]\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambiguously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = []\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in tokens_a:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n if tokens_b:\n for token in tokens_b:\n tokens.append(token)\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n label_id = label_map[example.label]\n if ex_index < 5:\n tf.logging.info(\"*** Example ***\")\n tf.logging.info(\"guid: %s\" % (example.guid))\n tf.logging.info(\"tokens: %s\" % \" \".join(\n [tokenization.printable_text(x) for x in tokens]))\n tf.logging.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n tf.logging.info(\"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n tf.logging.info(\"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n tf.logging.info(\"label: %s (id = %d)\" % (example.label, label_id))\n\n feature = InputFeatures(\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id,\n is_real_example=True)\n return feature\n\ndef file_based_convert_examples_to_features(\n examples, label_list, max_seq_length, tokenizer, output_file):\n \"\"\"Convert a set of `InputExample`s to a TFRecord file.\"\"\"\n\n writer = tf.python_io.TFRecordWriter(output_file)\n\n for (ex_index, example) in enumerate(examples):\n if ex_index % 10000 == 0:\n tf.logging.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n\n feature = convert_single_example(ex_index, example, label_list,\n max_seq_length, tokenizer)\n\n def create_int_feature(values):\n f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))\n return f\n\n features = collections.OrderedDict()\n features[\"input_ids\"] = create_int_feature(feature.input_ids)\n features[\"input_mask\"] = create_int_feature(feature.input_mask)\n features[\"segment_ids\"] = create_int_feature(feature.segment_ids)\n features[\"label_ids\"] = create_int_feature([feature.label_id])\n features[\"is_real_example\"] = create_int_feature(\n [int(feature.is_real_example)])\n\n tf_example = tf.train.Example(features=tf.train.Features(feature=features))\n writer.write(tf_example.SerializeToString())\n writer.close()\n\n\ndef file_based_input_fn_builder(input_file, seq_length, is_training,\n drop_remainder):\n \"\"\"Creates an `input_fn` closure to be passed to TPUEstimator.\"\"\"\n\n name_to_features = {\n \"input_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n \"input_mask\": tf.FixedLenFeature([seq_length], tf.int64),\n \"segment_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n \"label_ids\": tf.FixedLenFeature([], tf.int64),\n \"is_real_example\": tf.FixedLenFeature([], tf.int64),\n }\n\n def _decode_record(record, name_to_features):\n \"\"\"Decodes a record to a TensorFlow example.\"\"\"\n example = tf.parse_single_example(record, name_to_features)\n\n # tf.Example only supports tf.int64, but the TPU only supports tf.int32.\n # So cast all int64 to int32.\n for name in list(example.keys()):\n t = example[name]\n if t.dtype == tf.int64:\n t = tf.to_int32(t)\n example[name] = t\n\n return example\n\n def input_fn(params):\n \"\"\"The actual input function.\"\"\"\n batch_size = params[\"batch_size\"]\n\n # For training, we want a lot of parallel reading and shuffling.\n # For eval, we want no shuffling and parallel reading doesn't matter.\n d = tf.data.TFRecordDataset(input_file)\n if is_training:\n d = d.repeat()\n #每次从数据源中按顺序取buffer_size个样本,并打乱。\n # 每次从中取一个样本放入batch中,填充buffer_size,。。。,直至达到batchsize\n d = d.shuffle(buffer_size=100)\n\n d = d.apply(\n tf.contrib.data.map_and_batch(\n lambda record: _decode_record(record, name_to_features),\n batch_size=batch_size,\n drop_remainder=drop_remainder))\n\n return d\n\n return input_fn\n\n\ndef _truncate_seq_pair(tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n\ndef create_model(bert_config, is_training, input_ids, input_mask, segment_ids,\n labels, num_labels, use_one_hot_embeddings):\n \"\"\"Creates a classification model.\"\"\"\n model = modeling.BertModel(\n config=bert_config,\n is_training=is_training,\n input_ids=input_ids,\n input_mask=input_mask,\n token_type_ids=segment_ids,\n use_one_hot_embeddings=use_one_hot_embeddings)\n\n # In the demo, we are doing a simple classification task on the entire\n # segment.\n #\n # If you want to use the token-level output, use model.get_sequence_output()\n # instead.\n output_layer = model.get_pooled_output()\n\n hidden_size = output_layer.shape[-1].value\n\n output_weights = tf.get_variable(\n \"output_weights\", [num_labels, hidden_size],\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n\n output_bias = tf.get_variable(\n \"output_bias\", [num_labels], initializer=tf.zeros_initializer())\n\n with tf.variable_scope(\"loss\"):\n if is_training:\n # I.e., 0.1 dropout\n output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)\n\n logits = tf.matmul(output_layer, output_weights, transpose_b=True)\n logits = tf.nn.bias_add(logits, output_bias)\n probabilities = tf.nn.softmax(logits, axis=-1)\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n\n one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)\n\n per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)\n loss = tf.reduce_mean(per_example_loss)\n\n return (loss, per_example_loss, logits, probabilities)\n\n\ndef model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,\n num_train_steps, num_warmup_steps, use_tpu,\n use_one_hot_embeddings):\n \"\"\"Returns `model_fn` closure for TPUEstimator.\"\"\"\n\n def model_fn(features, labels, mode, params): # pylint: disable=unused-argument\n \"\"\"The `model_fn` for TPUEstimator.\"\"\"\n\n tf.logging.info(\"*** Features ***\")\n for name in sorted(features.keys()):\n tf.logging.info(\" name = %s, shape = %s\" % (name, features[name].shape))\n\n input_ids = features[\"input_ids\"]\n input_mask = features[\"input_mask\"]\n segment_ids = features[\"segment_ids\"]\n label_ids = features[\"label_ids\"]\n is_real_example = None\n if \"is_real_example\" in features:\n is_real_example = tf.cast(features[\"is_real_example\"], dtype=tf.float32)\n else:\n is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32)\n\n is_training = (mode == tf.estimator.ModeKeys.TRAIN)\n\n (total_loss, per_example_loss, logits, probabilities) = create_model(\n bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,\n num_labels, use_one_hot_embeddings)\n\n tvars = tf.trainable_variables()\n initialized_variable_names = {}\n scaffold_fn = None\n if init_checkpoint:\n (assignment_map, initialized_variable_names\n ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)\n if use_tpu:\n\n def tpu_scaffold():\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n return tf.train.Scaffold()\n\n scaffold_fn = tpu_scaffold\n else:\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n\n tf.logging.info(\"**** Trainable Variables ****\")\n for var in tvars:\n init_string = \"\"\n if var.name in initialized_variable_names:\n init_string = \", *INIT_FROM_CKPT*\"\n tf.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape,\n init_string)\n\n output_spec = None\n if mode == tf.estimator.ModeKeys.TRAIN:\n\n train_op = optimization.create_optimizer(\n total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)\n\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\n mode=mode,\n loss=total_loss,\n train_op=train_op,\n scaffold_fn=scaffold_fn)\n elif mode == tf.estimator.ModeKeys.EVAL:\n\n def metric_fn(per_example_loss, label_ids, logits, is_real_example):\n predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)\n accuracy = tf.metrics.accuracy(\n labels=label_ids, predictions=predictions, weights=is_real_example)\n loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)\n return {\n \"eval_accuracy\": accuracy,\n \"eval_loss\": loss,\n }\n\n eval_metrics = (metric_fn,\n [per_example_loss, label_ids, logits, is_real_example])\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\n mode=mode,\n loss=total_loss,\n eval_metrics=eval_metrics,\n scaffold_fn=scaffold_fn)\n else:\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\n mode=mode,\n predictions={\"probabilities\": probabilities},\n scaffold_fn=scaffold_fn)\n return output_spec\n\n return model_fn\n\n\n# This function is not used by this file but is still used by the Colab and\n# people who depend on it.\ndef input_fn_builder(features, seq_length, is_training, drop_remainder):\n \"\"\"Creates an `input_fn` closure to be passed to TPUEstimator.\"\"\"\n\n all_input_ids = []\n all_input_mask = []\n all_segment_ids = []\n all_label_ids = []\n\n for feature in features:\n all_input_ids.append(feature.input_ids)\n all_input_mask.append(feature.input_mask)\n all_segment_ids.append(feature.segment_ids)\n all_label_ids.append(feature.label_id)\n\n def input_fn(params):\n \"\"\"The actual input function.\"\"\"\n batch_size = params[\"batch_size\"]\n\n num_examples = len(features)\n\n # This is for demo purposes and does NOT scale to large data sets. We do\n # not use Dataset.from_generator() because that uses tf.py_func which is\n # not TPU compatible. The right way to load data is with TFRecordReader.\n d = tf.data.Dataset.from_tensor_slices({\n \"input_ids\":\n tf.constant(\n all_input_ids, shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"input_mask\":\n tf.constant(\n all_input_mask,\n shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"segment_ids\":\n tf.constant(\n all_segment_ids,\n shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"label_ids\":\n tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32),\n })\n\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=100)\n\n d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder)\n return d\n\n return input_fn\n\n\n# This function is not used by this file but is still used by the Colab and\n# people who depend on it.\ndef convert_examples_to_features(examples, label_list, max_seq_length,\n tokenizer):\n \"\"\"Convert a set of `InputExample`s to a list of `InputFeatures`.\"\"\"\n\n features = []\n for (ex_index, example) in enumerate(examples):\n if ex_index % 10000 == 0:\n tf.logging.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n\n feature = convert_single_example(ex_index, example, label_list,\n max_seq_length, tokenizer)\n\n features.append(feature)\n return features\n\ndef set_flags(flags):\n\n BERT_BASE_DIR='../uncased_L-12_H-768_A-12'\n print(os.path.abspath(BERT_BASE_DIR))\n GLUE_DIR='glue_data'\n\n flags.task_name='MRPC'\n flags.do_train=True\n flags.do_eval=True\n flags.data_dir=GLUE_DIR+'/MRPC'\n flags.vocab_file=BERT_BASE_DIR+'/vocab.txt'\n flags.bert_config_file=BERT_BASE_DIR+'/bert_config.json'\n flags.init_checkpoint=BERT_BASE_DIR+'/bert_model.ckpt'\n flags.max_seq_length=128\n flags.train_batch_size=32\n flags.learning_rate=2e-5\n flags.num_train_epochs=3.0\n flags.output_dir='tmp/mrpc_output/'\n return flags\n\ndef set_flags_ss(flags):\n\n BERT_BASE_DIR='../chinese_L-12_H-768_A-12'\n print(os.path.abspath(BERT_BASE_DIR))\n GLUE_DIR='my_data'\n\n flags.task_name='ssadr'\n flags.do_train=True\n flags.do_eval=True\n flags.data_dir=GLUE_DIR\n flags.vocab_file=BERT_BASE_DIR+'/vocab.txt'\n flags.bert_config_file=BERT_BASE_DIR+'/bert_config.json'\n flags.init_checkpoint=BERT_BASE_DIR+'/bert_model.ckpt'\n flags.max_seq_length=128\n flags.train_batch_size=32\n flags.learning_rate=2e-5\n flags.num_train_epochs=3.0\n flags.output_dir='tmp/ss_output/'\n return flags\n\ndef main(_):\n tf.logging.set_verbosity(tf.logging.INFO)\n\n processors = {\n \"cola\": ColaProcessor,\n \"mnli\": MnliProcessor,\n \"mrpc\": MrpcProcessor,\n \"xnli\": XnliProcessor,\n \"ssadr\":SsProcessor,\n }\n\n tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,\n FLAGS.init_checkpoint)\n\n if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict:\n raise ValueError(\n \"At least one of `do_train`, `do_eval` or `do_predict' must be True.\")\n\n bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)\n\n if FLAGS.max_seq_length > bert_config.max_position_embeddings:\n raise ValueError(\n \"Cannot use sequence length %d because the BERT model \"\n \"was only trained up to sequence length %d\" %\n (FLAGS.max_seq_length, bert_config.max_position_embeddings))\n\n tf.gfile.MakeDirs(FLAGS.output_dir)\n\n task_name = FLAGS.task_name.lower()\n\n if task_name not in processors:\n raise ValueError(\"Task not found: %s\" % (task_name))\n\n processor = processors[task_name]()\n\n label_list = processor.get_labels()\n\n tokenizer = tokenization.FullTokenizer(\n vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)\n\n tpu_cluster_resolver = None\n if FLAGS.use_tpu and FLAGS.tpu_name:\n tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(\n FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)\n\n is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2\n run_config = tf.contrib.tpu.RunConfig(\n cluster=tpu_cluster_resolver,\n master=FLAGS.master,\n model_dir=FLAGS.output_dir,\n save_checkpoints_steps=FLAGS.save_checkpoints_steps,\n tpu_config=tf.contrib.tpu.TPUConfig(\n iterations_per_loop=FLAGS.iterations_per_loop,\n num_shards=FLAGS.num_tpu_cores,\n per_host_input_for_training=is_per_host))\n\n train_examples = None\n num_train_steps = None\n num_warmup_steps = None\n if FLAGS.do_train:\n train_examples = processor.get_train_examples(FLAGS.data_dir)\n num_train_steps = int(\n len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)\n num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)\n\n model_fn = model_fn_builder(\n bert_config=bert_config,\n num_labels=len(label_list),\n init_checkpoint=FLAGS.init_checkpoint,\n learning_rate=FLAGS.learning_rate,\n num_train_steps=num_train_steps,\n num_warmup_steps=num_warmup_steps,\n use_tpu=FLAGS.use_tpu,\n use_one_hot_embeddings=FLAGS.use_tpu)\n\n # If TPU is not available, this will fall back to normal Estimator on CPU\n # or GPU.\n estimator = tf.contrib.tpu.TPUEstimator(\n use_tpu=FLAGS.use_tpu,\n model_fn=model_fn,\n config=run_config,\n train_batch_size=FLAGS.train_batch_size,\n eval_batch_size=FLAGS.eval_batch_size,\n predict_batch_size=FLAGS.predict_batch_size)\n\n if FLAGS.do_train:\n train_file = os.path.join(FLAGS.output_dir, \"train.tf_record\")\n file_based_convert_examples_to_features(\n train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)\n tf.logging.info(\"***** Running training *****\")\n tf.logging.info(\" Num examples = %d\", len(train_examples))\n tf.logging.info(\" Batch size = %d\", FLAGS.train_batch_size)\n tf.logging.info(\" Num steps = %d\", num_train_steps)\n train_input_fn = file_based_input_fn_builder(\n input_file=train_file,\n seq_length=FLAGS.max_seq_length,\n is_training=True,\n drop_remainder=True)\n estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)\n\n if FLAGS.do_eval:\n eval_examples = processor.get_dev_examples(FLAGS.data_dir)\n num_actual_eval_examples = len(eval_examples)\n if FLAGS.use_tpu:\n # TPU requires a fixed batch size for all batches, therefore the number\n # of examples must be a multiple of the batch size, or else examples\n # will get dropped. So we pad with fake examples which are ignored\n # later on. These do NOT count towards the metric (all tf.metrics\n # support a per-instance weight, and these get a weight of 0.0).\n while len(eval_examples) % FLAGS.eval_batch_size != 0:\n eval_examples.append(PaddingInputExample())\n\n eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\")\n file_based_convert_examples_to_features(\n eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)\n\n tf.logging.info(\"***** Running evaluation *****\")\n tf.logging.info(\" Num examples = %d (%d actual, %d padding)\",\n len(eval_examples), num_actual_eval_examples,\n len(eval_examples) - num_actual_eval_examples)\n tf.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size)\n\n # This tells the estimator to run through the entire set.\n eval_steps = None\n # However, if running eval on the TPU, you will need to specify the\n # number of steps.\n if FLAGS.use_tpu:\n assert len(eval_examples) % FLAGS.eval_batch_size == 0\n eval_steps = int(len(eval_examples) // FLAGS.eval_batch_size)\n\n eval_drop_remainder = True if FLAGS.use_tpu else False\n eval_input_fn = file_based_input_fn_builder(\n input_file=eval_file,\n seq_length=FLAGS.max_seq_length,\n is_training=False,\n drop_remainder=eval_drop_remainder)\n\n result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)\n\n output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\")\n with tf.gfile.GFile(output_eval_file, \"w\") as writer:\n tf.logging.info(\"***** Eval results *****\")\n for key in sorted(result.keys()):\n tf.logging.info(\" %s = %s\", key, str(result[key]))\n writer.write(\"%s = %s\\n\" % (key, str(result[key])))\n\n if FLAGS.do_predict:\n predict_examples = processor.get_test_examples(FLAGS.data_dir)\n num_actual_predict_examples = len(predict_examples)\n if FLAGS.use_tpu:\n # TPU requires a fixed batch size for all batches, therefore the number\n # of examples must be a multiple of the batch size, or else examples\n # will get dropped. So we pad with fake examples which are ignored\n # later on.\n while len(predict_examples) % FLAGS.predict_batch_size != 0:\n predict_examples.append(PaddingInputExample())\n\n predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\")\n file_based_convert_examples_to_features(predict_examples, label_list,\n FLAGS.max_seq_length, tokenizer,\n predict_file)\n\n tf.logging.info(\"***** Running prediction*****\")\n tf.logging.info(\" Num examples = %d (%d actual, %d padding)\",\n len(predict_examples), num_actual_predict_examples,\n len(predict_examples) - num_actual_predict_examples)\n tf.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size)\n\n predict_drop_remainder = True if FLAGS.use_tpu else False\n predict_input_fn = file_based_input_fn_builder(\n input_file=predict_file,\n seq_length=FLAGS.max_seq_length,\n is_training=False,\n drop_remainder=predict_drop_remainder)\n\n result = estimator.predict(input_fn=predict_input_fn)\n\n output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\")\n with tf.gfile.GFile(output_predict_file, \"w\") as writer:\n num_written_lines = 0\n tf.logging.info(\"***** Predict results *****\")\n for (i, prediction) in enumerate(result):\n probabilities = prediction[\"probabilities\"]\n if i >= num_actual_predict_examples:\n break\n output_line = \"\\t\".join(\n str(class_probability)\n for class_probability in probabilities) + \"\\n\"\n writer.write(output_line)\n num_written_lines += 1\n assert num_written_lines == num_actual_predict_examples\n\n\nif __name__ == \"__main__\":\n flags.mark_flag_as_required(\"data_dir\")\n flags.mark_flag_as_required(\"task_name\")\n flags.mark_flag_as_required(\"vocab_file\")\n flags.mark_flag_as_required(\"bert_config_file\")\n flags.mark_flag_as_required(\"output_dir\")\n flags.FLAGS = set_flags_ss(flags.FLAGS)\n tf.app.run()\n" ]
[ [ "tensorflow.contrib.cluster_resolver.TPUClusterResolver", "tensorflow.metrics.accuracy", "tensorflow.FixedLenFeature", "tensorflow.nn.log_softmax", "tensorflow.reduce_sum", "tensorflow.gfile.GFile", "tensorflow.cast", "tensorflow.train.init_from_checkpoint", "tensorflow.gfile.MakeDirs", "tensorflow.to_int32", "tensorflow.contrib.tpu.TPUEstimatorSpec", "tensorflow.contrib.tpu.TPUEstimator", "tensorflow.data.TFRecordDataset", "tensorflow.truncated_normal_initializer", "tensorflow.python_io.TFRecordWriter", "tensorflow.logging.set_verbosity", "tensorflow.trainable_variables", "tensorflow.parse_single_example", "tensorflow.argmax", "tensorflow.app.run", "tensorflow.nn.dropout", "tensorflow.metrics.mean", "tensorflow.matmul", "tensorflow.gfile.Open", "tensorflow.shape", "tensorflow.zeros_initializer", "tensorflow.logging.info", "tensorflow.one_hot", "tensorflow.contrib.tpu.TPUConfig", "tensorflow.train.Features", "tensorflow.nn.bias_add", "tensorflow.nn.softmax", "tensorflow.constant", "tensorflow.train.Scaffold", "tensorflow.reduce_mean", "tensorflow.flags.DEFINE_string", "tensorflow.variable_scope" ] ]
pfschus/fission_bicorrelation
[ "103d1d6e93f722c73e33a9af773dd7ebbf4c6f25" ]
[ "scripts/bicorr_plot.py" ]
[ "\"\"\"\nPlotting functions for Bicorr project\nMoving them here to keep the bicorr.py file cleaner\nPFS, March 2018\n \nChangelog:\n2018_03_15: Move a few functions here\n\"\"\"\n\nimport matplotlib\n#matplotlib.use('agg') # for flux\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nfrom matplotlib.pyplot import cm \nfrom matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator)\nimport seaborn as sns\nsns.set(style='ticks')\n\nimport sys\nimport os\nimport os.path\nimport scipy.io as sio\n\nimport time\nimport numpy as np\nnp.set_printoptions(threshold=np.nan) # print entire matrices\nimport pandas as pd\nfrom tqdm import *\n\n# Don't import any bicorr modules here\n# Other modules will import bicorr_plot, but not the other way around\n\n\n############### SOME GENERAL FUNCTIONS TO KEEP AROUND ########################\ndef save_fig_to_folder(fig_filename,fig_folder='fig',extensions=['png','pdf'],dpi=300):\n \"\"\"\n Summary: Save .png of current matplotlib plot to fig_folder / fig_filename\n Code will check to make sure fig_folder exists. If not, create folder then save .png to folder\n \n Parameters\n ----------\n fig_filename : str\n Filename to use for saving the figure\n fig_folder : str, optional\n Folder where to save the image, relative to cwd\n extensions: str, optional\n File save format. If several, produce all.\n\n Returns\n -------\n n/a\n \"\"\"\n # Don't cut off labels\n plt.tight_layout()\n # If saving to same folder\n if fig_folder is None:\n plt.savefig(fig_filename)\n # If saving to a subfolder\n else:\n try:\n os.stat(fig_folder)\n except:\n os.mkdir(fig_folder)\n for extension in extensions:\n plt.savefig(fig_folder+'/'+fig_filename+'.'+extension,dpi=dpi) \n \ndef histogram_metrics(values, xlabel = 'x', ylabel = 'y'):\n \"\"\"\n Plot histogram with some metrics overlaid (mean, std, median)\n \n Parameters\n ----------\n values : array-like\n Values for the histogram\n xlabel : str, optional\n ylabel : str, optional\n \"\"\"\n mu = np.mean(values)\n sigma = np.std(values)\n med = np.median(values)\n \n plt.figure(figsize=(4,3))\n sns.distplot(values, rug=True)\n plt.axvline(mu,color='k',linewidth=1)\n plt.axvline(mu-sigma,color='k',linewidth=.5)\n plt.axvline(mu+sigma,color='k',linewidth=.5)\n plt.axvline(med,color='r',linewidth=.5)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n sns.despine(right=False)\n plt.show()\n\ndef step_plot(edges,y, linewidth=.5, color='k', zorder = 1):\n \"\"\"\n Plot a step plot. Meant for use with histogram data generated by:\n counts, bin_edges = np.histogram(x_samples,bin_edges)\n bicorr.step_plot(bin_edges,counts)\n \n Parameters\n ----------\n edges : ndarray\n Bin edges\n y : ndarray\n Bin counts\n linewidth : float, optional\n Width of step lines\n color : float, optional\n Color of lines\n zorder : int, optional\n Order of layer. Lower integer = farther back\n\n Returns\n -------\n n/a\n \"\"\"\n # Horizontal lines\n for i in range(len(y)):\n plt.hlines(y[i],edges[i],edges[i+1],linewidth=linewidth,color=color,zorder=zorder)\n # Vertical lines\n for i in range(len(y)-1):\n plt.vlines(edges[i+1],y[i],y[i+1],linewidth=linewidth,color=color,zorder=zorder)\n\n \n \n##################### EXPERIMENTAL SETUP STUFF ###########################\ndef plot_det_df(det_df, which = ['index','angle'], cmap='viridis', title_flag = True, save_flag = False, fig_folder = 'fig', show_flag = True, clear_flag = True):\n \"\"\" \n Make some plots to visualize the data in det_df, which can be loaded using `load_det_df`.\n \n Parameters\n ----------\n det_df : pandas dataFrame\n dataFrame of detector pair indices and angles\n which : list of str, optional\n Which plots to show? Options include 'index', 'angle'\n cmap : str, optional\n Colormap\n title_flag : bool, optional\n save_flag : bool, optional\n save plots to file\n fig_folder : str, optional\n where to save plots\n show_flag : bool, optional\n display plots\n clear_flag : bool, optional\n whether to clear matplotlib figure\n \n Returns\n -------\n n/a \n \"\"\"\n if 'index' in which:\n # Detector pair indices\n plt.figure(figsize=(4,4))\n ax = plt.gca()\n sc = ax.scatter(det_df['d1'],det_df['d2'],s=13,marker='s',edgecolor='none',c=det_df.index.values,cmap=cmap)\n ax.grid(True, which='both')\n plt.xlim([0,48]); plt.ylim([0,48])\n plt.xlabel('Detector 1 channel'); plt.ylabel('Detector 2 channel')\n cbar =plt.colorbar(sc, fraction = 0.043, pad=0.1)\n cbar.set_label('Detector pair index value')\n if title_flag: plt.title('Detector pair indices\\n')\n ax.set_aspect('equal')\n if save_flag: save_fig_to_folder('det_df_ch_to_index',fig_folder=fig_folder) \n if show_flag: plt.show()\n if clear_flag: plt.clf()\n \n if 'angle' in which:\n # Detector pair angles\n plt.figure(figsize=(4,4))\n ax = plt.gca()\n sc = ax.scatter(det_df['d1'],det_df['d2'],c=det_df['angle'],s=18,marker='s',edgecolor='none',cmap=cmap)\n plt.xlim([0,48]); plt.ylim([0,48])\n plt.xlabel('Detector 1 channel'); plt.ylabel('Detector 2 channel')\n cbar = plt.colorbar(sc,fraction = 0.043, pad=0.1)\n cbar.set_label('Angle (degrees)')\n if title_flag: plt.title('Angle between all detector pairs (degrees)\\n')\n ax.set_aspect('equal')\n if save_flag: save_fig_to_folder('det_df_ch_to_angle',fig_folder=fig_folder) \n if show_flag: plt.show()\n if clear_flag: plt.clf()\n\n##################### GENERATING BICORR FILE ###########################\n\ndef bicorr_checkpoint_plots(bicorr_data, fig_folder = 'fig', show_flag = False):\n \"\"\"\n Construct and store checkpoint plots from the bicorr_data matrix.\n \n Require: bicorr_data\n Modify: fig_folder, show_flag\n if fig_folder = None, save to same folder\n if fig_folder = an int, that is the folder number and fig_folder is set to `#/bicorr_fig`\n Effect: Stores .png images for plots to fig_folder\n \"\"\"\n # Make a subfolder to store the checkpoint plots\n if isinstance(fig_folder,str) == False:\n fig_folder = str(fig_folder)+'/bicorr_fig'\n \n # If the folder doesn't exist yet, create it\n try:\n os.stat(fig_folder)\n except:\n os.mkdir(fig_folder) \n \n # Which detector pairs fired?\n plt.plot(bicorr_data['det1ch'],bicorr_data['det2ch'],'.k')\n plt.xlabel('Detector 1 channel')\n plt.ylabel('Detector 2 channel')\n plt.title('Detector pairs with bicorrelation events')\n save_fig_to_folder('bicorr_pairs_scatter.png',fig_folder)\n if show_flag: plt.show()\n plt.clf()\n \n # Plot count rate for each detector pair\n plt.figure(figsize=(7,6))\n plt.hist2d(bicorr_data['det1ch'],bicorr_data['det2ch'],bins=np.arange(-0.5,46.5,1),cmin=1,cmap='viridis')\n plt.ylim([-.5,46.5])\n plt.colorbar()\n plt.grid(True, which='both')\n plt.xticks([i for i in np.arange(0,46,4)])\n plt.yticks([i for i in np.arange(0,46,4)])\n plt.xlabel('Detector 1 channel')\n plt.ylabel('Detector 2 channel')\n plt.title('Frequency of detector pair interactions')\n save_fig_to_folder('bicorr_pairs_2dhist.png',fig_folder)\n if show_flag: plt.show()\n plt.clf()\n\n # Plot event number vs. line in\n plt.plot(bicorr_data['event'])\n plt.xlabel('Line number')\n plt.ylabel('Event number')\n plt.title('Event number vs. line number')\n save_fig_to_folder('bicorr_all_evnum.png',fig_folder)\n if show_flag: plt.show()\n plt.clf()\n\n\n\n\n \n \n################# SINGLES_HIST ########################\ndef plot_singles_hist(singles_hist,dt_bin_edges,\n save_flag = False, fig_folder ='fig',\n show_flag = False):\n \"\"\"\n Plot singles TOF distribution from singles_hist for all channels. \n Future development option: incorporate a channel rather than summing across all.\n \n Parameters\n ----------\n singles_hist : ndarray\n Histogram of singles timing information\n Dimension 0: particle type, 0=n, 1=g\n Dimension 1: detector channel\n Dimension 2: dt bin\n dt_bin_edges : ndarray\n Time bin edges array\n save_flag : bool, optional\n save plots to file\n fig_folder : str, optional\n where to save plots\n show_flag : bool, optional\n display plots\n \n Returns\n -------\n n/a\n \"\"\"\n plt.figure(figsize=(4,3))\n dt_bin_centers = (dt_bin_edges[:-1]+dt_bin_edges[1:])/2\n plt.plot(dt_bin_centers,np.sum(singles_hist[0,:,:],axis=(0)))\n plt.plot(dt_bin_centers,np.sum(singles_hist[1,:,:],axis=(0)))\n plt.xlabel('Time (ns)')\n plt.ylabel('Number of events')\n plt.title('Singles TOF distribution, all channels')\n plt.legend(['N','G'])\n plt.yscale('log')\n sns.despine(right=False)\n if save_flag: save_fig_to_folder('singles_TOF_dist.png',fig_folder)\n if show_flag: plt.show()\n plt.clf()\n\ndef plot_singles_hist_e_n(singles_hist_e_n,e_bin_edges,\n save_flag = False, fig_folder ='fig',\n show_flag = False, clear_flag = True):\n \"\"\"\n Plot singles TOF distribution from singles_hist for all channels. \n Future development option: incorporate a channel rather than summing across all.\n \n Parameters\n ----------\n singles_hist_e_n : ndarray\n Histogram of singles timing information\n Dimension 0: particle type, 0=n, 1=g\n Dimension 1: detector channel\n Dimension 2: dt bin\n e_bin_edges : ndarray\n Time bin edges array\n save_flag : bool, optional\n save plots to file\n fig_folder : str, optional\n where to save plots\n show_flag : bool, optional\n display plots\n \n Returns\n -------\n n/a\n \"\"\" \n plt.figure(figsize=(4,3))\n e_bin_centers = (e_bin_edges[:-1]+e_bin_edges[1:])/2\n plt.plot(e_bin_centers, np.sum(singles_hist_e_n[:,:],axis=(0)))\n plt.xlabel('Energy (MeV)') \n plt.ylabel('Number of events')\n plt.title('Singles energy distribution, all channels')\n plt.yscale('log')\n if save_flag: save_fig_to_folder('singles_e_dist',fig_folder)\n if show_flag: plt.show()\n if clear_flag: plt.clf()\n\ndef Sd_vs_ch_all(singles_df, show_flag = True, save_flag = True, \n fig_folder = 'fig', normalized = False):\n \"\"\"\n Generate plots of counts vs. angle for all pairs separately\n \n Parameters\n ----------\n singles_df : pandas dataFrame\n singles dataframe with counts already entered\n \n Returns\n -------\n n/a\n \"\"\" \n plt.figure(figsize=(4,3));\n plt.errorbar(singles_df['ch'],singles_df['Sd'],yerr=singles_df['Sd_err'],\n fmt='.',markersize=5,elinewidth=.5)\n plt.xlabel('detector channel')\n plt.ylabel('Sd (counts)')\n plt.title('br-subtracted $n$ sum')\n sns.despine(right=False)\n if save_flag: save_fig_to_folder('Sd_vs_angle_raw',fig_folder,extensions=['png','pdf'])\n if show_flag: plt.show()\n plt.clf()\n \n \n \n \n################## BHP ##########################\ndef bhp_plot(bicorr_hist_plot, dt_bin_edges, title = None,\n vmin = None, vmax = None,\n save_flag = False, save_filename = 'bicorr', \n save_folder = 'fig', extensions = ['png','pdf'],\n show_flag = False, clear = True):\n \"\"\"\n Creates 2d bicorr hist plot\n \n Parameters\n ----------\n bicorr_hist_plot : ndarray\n Array to plot. Two-dimensional with axes sizes corresponding to dt_bin_edges x dt_bin_edges.\n dt_bin_edges : ndarray\n One-dimensional array of time bin edges\n title : str, optional\n vmin : float, optional\n Minimum of colorbar range\n vmax : float, optional\n Maximum of colorbar range\n save_flag : bool, optional\n Do you want to save to disk using function save_fig_to_folder\n save_filename : str, optional\n Filename for bicorrelation image (.png will be added)\n save_folder : str, optional\n Destination folder location for storing bicorrelation image\n extensions: str, optional\n File save format. If several, produce all.\n show_flag : bool, optional \n Display plot to current session with plt.show()\n clear : bool, optional\n Clear matplotlib after creating bicorr plot. (If set to False, you can add more plots before showing, saving, or clearing the figure)\n \n Returns\n -------\n none\n \"\"\"\n fig = plt.figure(figsize=[4,3])\n ax = plt.gca()\n mesh = ax.pcolormesh(dt_bin_edges, dt_bin_edges, bicorr_hist_plot.T, \n norm=matplotlib.colors.LogNorm(), \n vmin = vmin, vmax = vmax, cmap=\"viridis\")\n cbar = plt.colorbar(mesh, ax=ax, fraction = 0.043, pad=0.1)\n if np.max(bicorr_hist_plot) >=1: # absolute counts\n cbar.set_label('counts')\n else: # normalized\n cbar.set_label('counts / (fission$\\cdot$ns$^2$$\\cdot$pair)')\n ax.set_xlabel('$\\Delta t_1$ (ns)')\n ax.set_ylabel('$\\Delta t_2$ (ns)')\n \n # Set up ticks\n ax.tick_params(axis='both',\n which='major',\n direction='inout',\n length=6,\n color='k',\n bottom=True, right=True, top=True, left=True)\n ax.tick_params(axis='both',\n which='minor',\n direction='in',\n length=3,\n bottom=True, right=True, top=True, left=True)\n # Major\n ax.xaxis.set_major_locator(MultipleLocator(50))\n ax.yaxis.set_major_locator(MultipleLocator(50))\n # Minor\n ax.xaxis.set_minor_locator(MultipleLocator(10))\n ax.yaxis.set_minor_locator(MultipleLocator(10))\n \n if title is not None: ax.set_title(title)\n ax.set_aspect('equal')\n plt.tight_layout()\n if save_flag: save_fig_to_folder(save_filename, save_folder, extensions)\n if show_flag: plt.show()\n if clear: plt.clf()\n return ax\n \n \n########################## BHP_E #########################\n\ndef bhp_e_plot(bhp_e, e_bin_edges, title = None,\n vmin = None, vmax = None, zoom_range = None,\n save_flag = False, save_filename = 'bicorr_e', \n save_folder = 'fig', extensions = ['png','pdf'],\n show_flag = False, clear_flag = True):\n \"\"\"\n Creates 2d bicorr_e hist plot\n \n Parameters\n ----------\n bhm_e : ndarray\n Master histogram of bicorrelation events in energy space. \n Dimension 0: detector pair, use dictionary 'dict_pair_to_index', where pair is (100*det1ch+det2ch)\n Dimension 1: interaction type, length 1. Only storing 0=nn.\n Dimension 2: e bin for detector 1\n Dimension 3: e bin for detector 2\n e_bin_edges : ndarray\n One-dimensional array of energy bin edges\n title : str, optional\n vmin : float, optional\n Minimum of colorbar range\n vmax : float, optional\n Maximum of colorbar range\n zoom_range : list, optional\n Range of x and y axes. Ex: [0,6] for 0 to 6 MeV\n save_flag : bool, optional\n Do you want to save to disk using function save_fig_to_folder\n save_filename : str, optional\n Filename for bicorrelation image (.png will be added)\n save_folder : str, optional\n Destination folder location for storing bicorrelation image\n extensions: str, optional\n File save format. If several, produce all.\n show_flag : bool, optional \n Display plot to current session with plt.show()\n clear_flag : bool, optional\n Clear matplotlib after creating bicorr plot. (If set to False, you can add more plots before showing, saving, or clearing the figure)\n \n Returns\n -------\n none\n \"\"\"\n fig = plt.figure(figsize=[4,3])\n ax = plt.gca()\n mesh = plt.pcolormesh(e_bin_edges, e_bin_edges, bhp_e.T, \n norm=matplotlib.colors.LogNorm(), \n vmin = vmin, vmax = vmax, cmap=\"inferno\")\n cbar = plt.colorbar(mesh, ax=ax, fraction = 0.043, pad=0.1)\n if np.max(bhp_e) >=1: # absolute counts\n cbar.set_label('counts')\n else: # normalized\n cbar.set_label('counts / (fission$\\cdot$MeV$^2$$\\cdot$pair)')\n ax.set_xlabel('$E_1$ (MeV)')\n ax.set_ylabel('$E_2$ (MeV)')\n if title is not None: plt.title(title)\n if zoom_range is not None:\n ax.set_xlim(zoom_range)\n ax.set_ylim(zoom_range)\n ax.set_aspect('equal')\n \n # Set up ticks\n ax.tick_params(axis='both',\n which='major',\n direction='inout',\n length=6,\n color='k',\n bottom=True, right=True, top=True, left=True)\n ax.tick_params(axis='both',\n which='minor',\n direction='in',\n length=3,\n bottom=True, right=True, top=True, left=True)\n # Major\n ax.xaxis.set_major_locator(MultipleLocator(1))\n ax.yaxis.set_major_locator(MultipleLocator(1))\n # Minor\n ax.xaxis.set_minor_locator(MultipleLocator(.2))\n ax.yaxis.set_minor_locator(MultipleLocator(.2))\n \n plt.tight_layout()\n if save_flag: save_fig_to_folder(save_filename, save_folder, extensions)\n if show_flag: plt.show()\n if clear_flag: plt.clf() \n return ax\n \n \n############# COUNTS VS. ANGLE #################################\ndef counts_vs_angle_all(det_df, show_flag = True, save_flag = True, \n fig_folder = 'fig', normalized = False, t_flag=False):\n \"\"\"\n Generate plots of counts vs. angle for all pairs separately\n \n Parameters\n ----------\n det_df : pandas dataFrame\n detector pair dataframe with counts already entered\n normalized : bool, optional\n option to plot normalized columns\n \n Returns\n -------\n n/a\n \"\"\"\n if t_flag:\n # Positive counts vs. angle\n plt.figure(figsize=(4,3))\n plt.errorbar(det_df['angle'],det_df['Cp'],yerr=det_df['Cp']**.5,\n fmt='.',markersize=5,elinewidth=.5,color='k')\n plt.xlabel('Angle (degrees)')\n plt.ylabel('Cp (counts)')\n plt.title('positive $nn$ sum')\n sns.despine(right=False)\n if save_flag: save_fig_to_folder('Cp_vs_angle_raw',fig_folder,extensions=['png','pdf'])\n if show_flag: plt.show()\n plt.clf() \n \n # Negative counts vs. angle\n plt.figure(figsize=(4,3))\n plt.errorbar(det_df['angle'],det_df['Cn'],yerr=det_df['Cn']**.5,\n fmt='.',markersize=5,elinewidth=.5,color='k')\n plt.xlabel('Angle (degrees)')\n plt.ylabel('Cn (counts)')\n plt.title('negative $nn$ sum')\n sns.despine(right=False)\n if save_flag: save_fig_to_folder('Cn_vs_angle_raw',fig_folder,extensions=['png','pdf'])\n if show_flag: plt.show()\n plt.clf() \n \n # Diff counts vs. angle\n plt.figure(figsize=(4,3))\n plt.errorbar(det_df['angle'],det_df['Cd'],yerr=det_df['Cd_err'],\n fmt='.',markersize=5,elinewidth=.5,color='k')\n plt.xlabel('Angle (degrees)')\n plt.ylabel('Cd (counts)')\n plt.title('$nn$ sum')\n sns.despine(right=False)\n if save_flag: save_fig_to_folder('Cd_vs_angle_raw',fig_folder,extensions=['png','pdf'])\n if show_flag: plt.show()\n plt.clf() \n \n if normalized:\n print('yes')\n # Negative counts vs. angle\n plt.figure(figsize=(4,3))\n plt.errorbar(det_df['angle'],det_df['Nd'],yerr=det_df['Nd_err'],\n fmt='.',markersize=5,elinewidth=.5)\n plt.xlabel('Angle (degrees)')\n plt.ylabel('Nd (counts/fission)')\n plt.title('normalized br-subtracted $nn$ sum')\n sns.despine(right=False)\n if save_flag: save_fig_to_folder('Nd_vs_angle_raw',fig_folder,extensions=['png','pdf'])\n if show_flag: plt.show()\n plt.clf() \n \ndef W_vs_angle_all(det_df, show_flag = True, save_flag = True, clf_flag = True,\n fig_folder = 'fig'):\n \"\"\"\n Generate plots of W vs. angle for all pairs separately\n \n Parameters\n ----------\n det_df : pandas dataFrame\n detector pair dataframe with counts already entered, W calculated\n \n Returns\n -------\n n/a\n \"\"\"\n # Positive counts vs. angle\n plt.figure(figsize=(4,3))\n plt.errorbar(det_df['angle'],det_df['W'],yerr=det_df['W_err'],\n fmt='.',markersize=5,elinewidth=.5,zorder=1)\n plt.xlabel('Angle (degrees)')\n plt.ylabel('W (relative doubles counts)')\n sns.despine(right=False)\n if save_flag: save_fig_to_folder('W_vs_angle',fig_folder,extensions=['png','pdf'])\n if show_flag: plt.show()\n if clf_flag: plt.clf() \n \ndef W_vs_angle_binned(by_angle_df, show_flag = True, save_flag = True, clf_flag = True,\n fig_folder = 'fig'):\n \"\"\"\n Generate plots of W vs. angle for pairs by bin\n \n Parameters\n ----------\n by_angle_df : pandas dataFrame\n Condensed by angle dataframe with W calculated\n \n Returns\n -------\n n/a\n \"\"\" \n angle_bin_edges = [by_angle_df.loc[0,'angle_bin_min']]+by_angle_df['angle_bin_max'].values.tolist()\n \n plt.figure(figsize=(4,3))\n plt.errorbar(by_angle_df['angle_bin_centers'],by_angle_df['W'],yerr=by_angle_df['std W'],fmt='.',color='k',zorder=3)\n step_plot(angle_bin_edges,by_angle_df['W'],linewidth=1,zorder=2)\n plt.xlabel('Angle (degrees)')\n plt.ylabel('W (relative doubles counts)')\n sns.despine(right=False)\n if save_flag: save_fig_to_folder('W_vs_angle_binned',fig_folder,extensions=['png','pdf'])\n if show_flag: plt.show() \n if clf_flag: plt.clf()\n \ndef W_vs_angle(det_df, by_angle_df, show_flag = True, save_flag = True, clf_flag = True,\n fig_folder = 'fig'):\n \"\"\" \n Generate plots of W vs. angle for all pairs, overlaid by pairs binned\n \"\"\"\n angle_bin_edges = [by_angle_df.loc[0,'angle_bin_min']]+by_angle_df['angle_bin_max'].values.tolist()\n \n plt.figure(figsize=(4,3))\n plt.errorbar(det_df['angle'],det_df['W'],yerr=det_df['W_err'],fmt='.',color='r', markersize=5,elinewidth=.5,zorder=1)\n plt.errorbar(by_angle_df['angle_bin_centers'],by_angle_df['W'],yerr=by_angle_df['std W'],fmt='.',color='k',zorder=3)\n step_plot(angle_bin_edges,by_angle_df['W'],linewidth=1,zorder=2)\n plt.xlabel('Angle (degrees)')\n plt.ylabel('W (relative doubles counts)')\n sns.despine(right=False)\n if save_flag: save_fig_to_folder('W_vs_angle_all',fig_folder,extensions=['png','pdf'])\n if show_flag: plt.show()\n if clf_flag: plt.clf() \n \n \n######################### SLICES ############################\ndef plot_bhp_slice(bhp_slice, bin_edges, bin_units = 'time', \n slice_range = None, normalized = None,\n c = 'k', title = False, show_flag = False,\n save_flag = False, save_filename = 'bhp_slice', save_folder = 'fig', new_fig = True, clear = True, msize=5,\n norm_range = None):\n \"\"\"\n Plot bhp slice.\n \n Parameters\n ----------\n bhp_slice : ndarray\n Slice through bhp at delta_tj_min, produce with slice_bhp()\n bin_edges : ndarray\n One-dimensional array of bin edges\n bin_units : str, optional\n Units for labels. 'time' or 'energy'\n slice_range : array or float, optional\n Range of time or energy values over which slice was taken. Primarily used for creating a title or legend\n if None: not provided\n if array: Min and max of slice range, ex: [slice_dt_min, slice_dt_max]\n if float: Slice position, ex: slice_dt_middle\n normalized : str, optional\n None: Don't normalize\n 'int': Normalize by integral\n 'max': Normalize by height\n c : str, optional\n Color of step plot\n title : str, optional\n Title for plot. Ex: '$\\Delta t_j$ = {}'.format(dt_bin_centers[i])\n if default True, print according to slice_dt_range\n if None, no title printed\n if a str, use custom title\n show_flag : bool\n Option to show figure\n save_flag : bool\n Option to save figure to file\n save_filename : str\n filename where to save figure\n save_folder : str\n foldername where to save figure \n new_fig : bool, optional\n option to open new fig (if False, plots on existing axes)\n clear : bool, optional\n Clear matplotlib after creating bicorr plot. (If set to False, you can add more plots before showing, saving, or clearing the figure) \n msize : int, optional\n Marker size\n norm_range : list of floats, optional\n Range of bin edges for normalization. Ex [15,150]\n Not yet available for energy units\n \n Returns\n -------\n n/a\n \"\"\"\n \n if new_fig: plt.figure(figsize=(4,4))\n ax = plt.gca()\n \n if norm_range is not None:\n imin = np.digitize(norm_range[0],bin_edges)-1\n imax = np.digitize(norm_range[1],bin_edges)-1 \n else:\n imin = 0\n imax = len(bin_edges)\n \n if normalized is 'max': \n step_plot(bin_edges, bhp_slice/np.max(bhp_slice[imin:imax]), linewidth=.5, color = c)\n ax.set_ylabel('Counts normalized by maximum')\n elif normalized is 'int': \n step_plot(bin_edges, bhp_slice/np.sum(bhp_slice[imin:imax]), linewidth=.5, color = c)\n ax.set_ylabel('Counts normalized by integral')\n else: \n step_plot(bin_edges, bhp_slice, linewidth=.5)\n ax.plot(calc_centers(bin_edges),bhp_slice,'.-',markersize=msize,linewidth = .5, color = c)\n ax.set_ylabel('Counts')\n \n if bin_units is 'time': ax.set_xlabel('$\\Delta t_i$')\n elif bin_units is 'energy': ax.set_xlabel('$\\Delta E_i$')\n \n if title is True: # Make a title according to slice_range\n if type(slice_range) is list: # Min and max boundaries\n ax.set_title('$\\Delta t_j$ = {} to {}'.format(slice_range[0],slice_range[1]))\n else: # float\n ax.set_title('$\\Delta t_j$ = {}'.format(slice_range))\n elif title is False:\n pass\n elif title is not None: # print custom title\n ax.set_title(title)\n \n # Set up ticks\n ax.tick_params(axis='both',\n which='major',\n direction='inout',\n length=6,\n color='k',\n bottom=True, right=True, top=True, left=True)\n ax.tick_params(axis='both',\n which='minor',\n direction='in',\n length=3,\n bottom=True, right=True, top=True, left=True)\n # Major\n ax.xaxis.set_major_locator(MultipleLocator(50))\n ax.yaxis.set_major_locator(MultipleLocator(50))\n # Minor\n ax.xaxis.set_minor_locator(MultipleLocator(10))\n ax.yaxis.set_minor_locator(MultipleLocator(10))\n\n # plt.axes().set_aspect('equal')\n if save_flag: save_fig_to_folder(save_filename, save_folder, extensions)\n if show_flag: plt.show()\n if clear: plt.clf()\n\ndef plot_bhp_slices(bhp_slices,bin_edges,bin_units='time',slice_range = None,new_fig=True,show_flag=True, log_flag = False):\n '''\n Plot bhp_slices on same axes, normalized by integral\n \n Parameters\n ----------\n bhp_slices : ndarray\n Array of bhp slices. Dimensions: # slices x len(dt_bin_centers) \n bin_edges : ndarray\n One-dimensional array of bin edges, time or energy\n bin_units : str, optional\n Units for labels. 'time' or 'energy'\n slice_range : ndarray\n Array of slice ranges. Dimensions: # slices x 2 (min, max)\n Either time or energy\n new_fig : bool, optional\n Option to start new figure\n show_flag : bool, optional\n Option to display\n \n Returns\n -------\n legend_text : str\n String of legend text\n '''\n if new_fig: plt.figure(figsize=(4,3))\n legend_text = [] \n \n color = iter(cm.rainbow(np.linspace(0,1,bhp_slices.shape[0]))) # Set up colors for plotting\n \n for i in range(bhp_slices.shape[0]): # Loop through slices\n c = next(color); \n plot_bhp_slice(bhp_slices[i,:],bin_edges,bin_units,slice_range[i,:],normalized='int',c=c,clear=False,new_fig=False,title=False)\n if slice_range is not None: legend_text.append('{:04.2f} to {:04.2f}'.format(np.min(slice_range[i,:]),np.max(slice_range[i,:])))\n \n plt.legend(legend_text)\n plt.title('Slices normalized by integral')\n \n # Hack legend \n ax = plt.gca()\n leg = ax.get_legend()\n color = iter(cm.rainbow(np.linspace(0,1,bhp_slices.shape[0]))) # Reset colors\n for i in range(bhp_slices.shape[0]): # Make legend\n c = next(color)\n leg.legendHandles[i].set_color(c) \n \n if show_flag: plt.show()\n\n return legend_text\n \n \n \n######################### SLICES IN ENERGY ############################\ndef plot_bhp_e_slice(bhp_e_slice, e_bin_edges, \n slice_e_range = None, normalized = None,\n c = 'k', title = True, show_flag = False,\n save_flag = False, save_filename = 'bhp_e_slice', save_folder = 'fig', new_fig = True, clear = True, msize=5,\n norm_range = None):\n \"\"\"\n Plot bhp slice.\n \n Parameters\n ----------\n bhp_e_slice : ndarray\n Slice through bhp_e at delta_E_min, produce with slice_bhp_e()\n e_bin_edges : ndarray\n One-dimensional array of bin edges\n slice_e_range : array or float, optional\n Range of time or energy values over which slice was taken. Primarily used for creating a title or legend\n if None: not provided\n if array: Min and max of slice range, ex: [slice_dt_min, slice_dt_max]\n if float: Slice position, ex: slice_dt_middle\n normalized : str, optional\n None: Don't normalize\n 'int': Normalize by integral\n 'max': Normalize by height\n c : str, optional\n Color of step plot\n title : str, optional\n Title for plot. Ex: '$E_j$ = {}'.format(e_bin_centers[i])\n if default True, print according to slice_e_range\n if None, no title printed\n if a str, use custom title\n show_flag : bool\n Option to show figure\n save_flag : bool\n Option to save figure to file\n save_filename : str\n filename where to save figure\n save_folder : str\n foldername where to save figure \n new_fig : bool, optional\n option to open new fig (if False, plots on existing axes)\n clear : bool, optional\n Clear matplotlib after creating bicorr plot. (If set to False, you can add more plots before showing, saving, or clearing the figure) \n msize : int, optional\n Marker size\n norm_range : list of floats, optional\n Range of bin edges for normalization. Ex [15,150]\n \n Returns\n -------\n n/a\n \"\"\"\n \n if new_fig: plt.figure(figsize=(6,4))\n \n if norm_range is not None:\n imin = np.digitize(norm_range[0],e_bin_edges)-1\n imax = np.digitize(norm_range[1],e_bin_edges)-1 \n else:\n imin = 0\n imax = len(e_bin_edges)\n \n if normalized is 'max': \n step_plot(e_bin_edges, bhp_e_slice/np.max(bhp_e_slice[imin:imax]), linewidth=.5, color = c)\n plt.ylabel('Counts normalized by maximum')\n elif normalized is 'int': \n step_plot(e_bin_edges, bhp_e_slice/np.sum(bhp_e_slice[imin:imax]), linewidth=.5, color = c)\n plt.ylabel('Counts normalized by integral')\n else: \n step_plot(e_bin_edges, bhp_e_slice, linewidth=.5)\n plt.ylabel('Counts')\n \n plt.xlabel('$\\Delta E_i$')\n \n if title is True: # Make a title according to slice_range\n if type(slice_e_range) is list: # Min and max boundaries\n plt.title('$E_j$ = {} to {}'.format(slice_e_range[0],slice_e_range[1]))\n else: # float\n plt.title('$E_j$ = {}'.format(slice_e_range))\n elif title is False:\n pass\n else: # print custom title\n plt.title(title)\n \n sns.despine(right=False)\n # plt.axes().set_aspect('equal')\n if save_flag: save_fig_to_folder(save_filename, save_folder, extensions)\n if show_flag: plt.show()\n if clear: plt.clf()\n\ndef plot_bhp_e_slices(bhp_e_slices,e_bin_edges,slice_e_ranges = None,\n E_min = None, E_max = None, title = None,\n new_fig=True,show_flag=True,\n log_flag = False, clear = False,\n save_flag = True, save_filename = 'bhp_e_slices'):\n '''\n Plot bhp_slices on same axes, normalized by integral\n \n Parameters\n ----------\n bhp_e_slices : ndarray\n Array of bhp_e slices. Dimensions: # slices x len(e_bin_centers) \n e_bin_edges : ndarray\n One-dimensional array of bin edges\n slice_e_ranges : ndarray\n Array of slice ranges. Dimensions: # slices x 2 (min, max)\n new_fig : bool, optional\n Option to start new figure\n show_flag : bool, optional\n Option to display\n log_flag : bool, optional\n Option for log y-axis\n clear : bool, optional\n Option to clear axes\n \n Returns\n -------\n legend_text : str\n String of legend text\n '''\n if new_fig: plt.figure(figsize=(6,4))\n legend_text = [] \n \n color = iter(cm.rainbow(np.linspace(0,1,bhp_e_slices.shape[0]))) # Set up colors for plotting\n \n for i in range(bhp_e_slices.shape[0]): # Loop through slices\n c = next(color); \n plot_bhp_e_slice(bhp_e_slices[i,:],e_bin_edges,slice_e_ranges[i,:],normalized='int',c=c,clear=False,new_fig=False,title=False)\n if slice_e_ranges[i,:] is not None: legend_text.append('{:04.2f} to {:04.2f}'.format(np.min(slice_e_ranges[i,:]),np.max(slice_e_ranges[i,:])))\n \n if E_min is not None: plt.axvline(E_min, c='r')\n if E_max is not None: plt.axvline(E_max, c='r')\n \n plt.legend(legend_text)\n if title is not None: plt.title(title)\n \n # Hack legend \n ax = plt.gca()\n leg = ax.get_legend()\n color = iter(cm.rainbow(np.linspace(0,1,bhp_e_slices.shape[0]))) # Reset colors\n for i in range(bhp_e_slices.shape[0]): # Make legend\n c = next(color)\n leg.legendHandles[i].set_color(c) \n \n if save_flag: save_fig_to_folder(save_filename, 'fig')\n if show_flag: plt.show()\n if clear: plt.clf()\n\n return legend_text\n \n \n \ndef plot_Eave_vs_Ej(Eave, Eave_err, Ej, log_flag = False, title = None,\n y_range = None,\n save_flag = False, save_filename = 'Eave_vs_Ej',\n show_flag = True, clear = False):\n \"\"\"\n Plot average energies as calculated from slices\n \n Parameters\n ----------\n Eave : ndarray\n Average energies calculated\n Eave_err : ndarray\n 1-sigma error calculated in Eave\n Ej : ndarray\n Dependent neutron energies \n y_range : list, optional\n Two-element list for y-range on plot. \n \n Returns\n -------\n n/a \n \"\"\"\n fig = plt.figure(figsize=(4,3))\n ax = plt.gca()\n \n plt.errorbar(Ej, Eave, yerr=Eave_err, fmt='.')\n plt.xlabel('$E_j$ (MeV)')\n plt.ylabel('Average $E_i$ (MeV)')\n if y_range is not None: plt.ylim(y_range)\n if title is not None: plt.title(title)\n if log_flag: plt.xscale('log')\n if save_flag: save_fig_to_folder(save_filename, 'fig')\n if show_flag: plt.show()\n if clear: plt.clf()" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.ticker.MultipleLocator", "numpy.linspace", "matplotlib.pyplot.plot", "numpy.max", "numpy.mean", "numpy.digitize", "matplotlib.pyplot.gca", "matplotlib.pyplot.tight_layout", "numpy.arange", "matplotlib.pyplot.hlines", "numpy.std", "matplotlib.pyplot.errorbar", "matplotlib.pyplot.vlines", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "numpy.min", "matplotlib.pyplot.ylim", "numpy.median", "matplotlib.pyplot.xscale", "matplotlib.pyplot.savefig", "matplotlib.pyplot.show", "numpy.sum", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.axvline", "matplotlib.colors.LogNorm", "numpy.set_printoptions", "matplotlib.pyplot.yscale", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.xlim", "matplotlib.pyplot.clf", "matplotlib.pyplot.grid", "matplotlib.pyplot.xlabel" ] ]
tnemelck/kmeans
[ "c1095c6bfc134f4fc9e2c79a781b42d5ee38620f" ]
[ "test.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 7 00:42:53 2018\n\n@author: elvex\n\"\"\"\n\nimport numpy as np\nimport numpy.random as npr\nimport random\n \ndef init_board(N, mini = -1, maxi = 1):\n X = npr.uniform(mini, maxi (N, 2))\n return X\n\ndef init_board_gauss(N, k, mini = -1, maxi = -1, ecart_min = 0.05, ecart_max = 0.10):\n n = N//k\n X = []\n for i in range(k):\n centre, s = npr.uniform(-mini, maxi, 2), random.uniform(ecart_min, ecart_max)\n x = npr.normal(centre, s, (n, 2))\n X.append(x)\n X = np.vstack(X)\n return X" ]
[ [ "numpy.random.uniform", "numpy.random.normal", "numpy.vstack" ] ]
killianlevacher/defenseInvGAN-src
[ "8fa398536773c5bc00c906562d2d9359572b8157" ]
[ "comparison/eval/metrics.py" ]
[ "import cPickle\nimport tensorflow as tf\nfrom classifiers.cifar_model import Model as CIFARModel\nimport utils\nimport numpy as np\nimport inception\nimport fid\n\n\ndef ComputeClassificationAccuracy(images, recons, labels, args, debug=True):\n model_paths = {'CIFAR': 'classifiers/model/cifar-10', \n 'CelebA': 'classifiers/model/celeba'}\n batch_size = 50\n \n dset = utils.data_loader(images, recons, labels, batch_size)\n \n # normalization, accuracy\n sess = tf.Session()\n if args.dataset == 'CIFAR':\n model = CIFARModel(model_paths[args.dataset], tiny=False, mode='eval', sess=sess)\n \n # TODO: Write CelebA model class\n \n n_data = 0\n n_correct_orig = 0\n n_correct = 0\n total = 0\n for images, recons, labels in dset:\n total += 1\n \n n_correct_orig += sess.run(model.num_correct, feed_dict={model.x_input: images, model.y_input: labels})\n n_correct += sess.run(model.num_correct, feed_dict={model.x_input: recons, model.y_input: labels})\n n_data += len(images)\n\n\n acc_orig = float(n_correct_orig) / n_data\n acc = float(n_correct) / n_data\n print('Original acc: {}'.format(acc_orig))\n print('Accuracy: {}'.format(acc))\n \n return acc\n\n\ndef ComputeMSE(reconstructions, images):\n recons = np.reshape(reconstructions, (reconstructions.shape[0], -1))\n img = np.reshape(images, (images.shape[0], -1))\n mse = ((recons - img)**2).mean(axis=1)\n mse_avg = np.mean(mse)\n mse_std = np.std(mse)\n return (mse_avg, mse_std)\n\n\ndef ComputeInception(images):\n images = ((images + 1) / 2.0)*255.0\n images = images.astype(np.uint8)\n IS = inception.get_inception_score(images)\n return IS\n\n\ndef ComputeFID(reconstructions, images):\n reconstructions = ((reconstructions + 1) / 2.0)*255.0\n reconstructions = reconstructions.astype(np.uint8)\n images = ((images + 1) / 2.0)*255.0\n images = images.astype(np.uint8)\n \n images = np.transpose(images, (0, 3, 1, 2))\n reconstructions = np.transpose(reconstructions, (0, 3, 1, 2))\n \n FID = fid.get_fid(images, reconstructions)\n return FID\n" ]
[ [ "numpy.reshape", "numpy.std", "numpy.mean", "tensorflow.Session", "numpy.transpose" ] ]
neurocaience/deepfreeze
[ "2a8c7da7519df2bacb640917695bd7d226e8d4f4" ]
[ "cnn_code/cuda.py" ]
[ "\"\"\"=============================================================================\nManage CUDA-related utility functions.\n=============================================================================\"\"\"\n\nimport torch\n\n# ------------------------------------------------------------------------------\n\ndef device():\n \"\"\"Return current CUDA device if on GPUs else CPU device.\n \"\"\"\n if torch.cuda.is_available():\n return torch.cuda.current_device()\n else:\n return torch.device('cpu')\n" ]
[ [ "torch.device", "torch.cuda.is_available", "torch.cuda.current_device" ] ]
JanSellner/pytorch-lightning
[ "0e0da8c3fc2c6d5e7ac54900621a82d213f8ebbf" ]
[ "tests/accelerators/test_accelerator_connector.py" ]
[ "# Copyright The PyTorch Lightning 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\nimport os\nfrom typing import Optional\nfrom unittest import mock\nfrom unittest.mock import Mock\n\nimport pytest\nimport torch\nimport torch.distributed\n\nimport pytorch_lightning\nfrom pytorch_lightning import Trainer\nfrom pytorch_lightning.accelerators.accelerator import Accelerator\nfrom pytorch_lightning.accelerators.cpu import CPUAccelerator\nfrom pytorch_lightning.accelerators.gpu import GPUAccelerator\nfrom pytorch_lightning.plugins import DoublePrecisionPlugin, LayerSync, NativeSyncBatchNorm, PrecisionPlugin\nfrom pytorch_lightning.plugins.environments import (\n KubeflowEnvironment,\n LightningEnvironment,\n SLURMEnvironment,\n TorchElasticEnvironment,\n)\nfrom pytorch_lightning.plugins.io import TorchCheckpointIO\nfrom pytorch_lightning.strategies import (\n DataParallelStrategy,\n DDP2Strategy,\n DDPShardedStrategy,\n DDPSpawnShardedStrategy,\n DDPSpawnStrategy,\n DDPStrategy,\n DeepSpeedStrategy,\n ParallelStrategy,\n SingleDeviceStrategy,\n)\nfrom pytorch_lightning.utilities.exceptions import MisconfigurationException\nfrom tests.helpers.runif import RunIf\n\n\n# TODO: please modify/sunset any test that has accelerator=ddp/ddp2/ddp_cpu/ddp_spawn @daniellepintz\ndef test_accelerator_choice_cpu(tmpdir):\n trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=True)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, SingleDeviceStrategy)\n\n\[email protected]((\"devices\", \"num_nodes\"), ([(1, 1), (1, 2), (2, 1), (2, 2)]))\ndef test_accelerator_choice_ddp_cpu(tmpdir, devices: int, num_nodes: int):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp_cpu\", devices=devices, num_nodes=num_nodes)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n no_spawn = devices == 1 and num_nodes > 1\n assert isinstance(trainer.strategy, DDPStrategy if no_spawn else DDPSpawnStrategy)\n assert isinstance(trainer.strategy.cluster_environment, LightningEnvironment)\n\n\[email protected](os.environ, {\"CUDA_VISIBLE_DEVICES\": \"0,1\"})\[email protected](\"torch.cuda.device_count\", return_value=2)\[email protected](\"torch.cuda.is_available\", return_value=True)\ndef test_accelerator_choice_ddp(cuda_available_mock, device_count_mock):\n with pytest.deprecated_call(match=r\"accelerator='ddp'\\)` has been deprecated\"):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp\", gpus=1)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, LightningEnvironment)\n\n\[email protected](os.environ, {\"CUDA_VISIBLE_DEVICES\": \"0,1\"})\[email protected](\"torch.cuda.device_count\", return_value=2)\[email protected](\"torch.cuda.is_available\", return_value=True)\ndef test_accelerator_choice_ddp_spawn(cuda_available_mock, device_count_mock):\n with pytest.deprecated_call(match=r\"accelerator='ddp_spawn'\\)` has been deprecated\"):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp_spawn\", gpus=1)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPSpawnStrategy)\n assert isinstance(trainer.strategy.cluster_environment, LightningEnvironment)\n\n\[email protected](\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"SLURM_PROCID\": \"1\",\n \"SLURM_LOCALID\": \"1\",\n },\n)\[email protected](\"torch.cuda.set_device\")\[email protected](\"torch.cuda.device_count\", return_value=2)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\[email protected](\"torch.cuda.is_available\", return_value=True)\ndef test_accelerator_choice_ddp_slurm(*_):\n with pytest.deprecated_call(match=r\"accelerator='ddp'\\)` has been deprecated in v1.5\"):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp\", gpus=2)\n assert trainer._accelerator_connector._is_slurm_managing_tasks()\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, SLURMEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\[email protected](\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"SLURM_PROCID\": \"1\",\n \"SLURM_LOCALID\": \"1\",\n },\n)\[email protected](\"torch.cuda.set_device\")\[email protected](\"torch.cuda.device_count\", return_value=2)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\[email protected](\"torch.cuda.is_available\", return_value=True)\ndef test_accelerator_choice_ddp2_slurm(*_):\n with pytest.deprecated_call(match=r\"accelerator='ddp2'\\)` has been deprecated in v1.5\"):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp2\", gpus=2)\n assert trainer._accelerator_connector._is_slurm_managing_tasks()\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDP2Strategy)\n assert isinstance(trainer.strategy.cluster_environment, SLURMEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\[email protected](\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"WORLD_SIZE\": \"2\",\n \"LOCAL_WORLD_SIZE\": \"2\",\n \"RANK\": \"1\",\n \"LOCAL_RANK\": \"1\",\n \"GROUP_RANK\": \"0\",\n \"TORCHELASTIC_RUN_ID\": \"1\", # present for torch >= 1.9.1\n },\n)\[email protected](\"torch.cuda.set_device\")\[email protected](\"torch.cuda.device_count\", return_value=1)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\[email protected](\"torch.cuda.is_available\", return_value=True)\ndef test_accelerator_choice_ddp_te(*_):\n with pytest.deprecated_call(match=r\"accelerator='ddp'\\)` has been deprecated in v1.5\"):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp\", gpus=2)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, TorchElasticEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\[email protected](\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"WORLD_SIZE\": \"2\",\n \"LOCAL_WORLD_SIZE\": \"2\",\n \"RANK\": \"1\",\n \"LOCAL_RANK\": \"1\",\n \"GROUP_RANK\": \"0\",\n \"TORCHELASTIC_RUN_ID\": \"1\",\n },\n)\[email protected](\"torch.cuda.set_device\")\[email protected](\"torch.cuda.device_count\", return_value=1)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\[email protected](\"torch.cuda.is_available\", return_value=True)\ndef test_accelerator_choice_ddp2_te(*_):\n with pytest.deprecated_call(match=r\"accelerator='ddp2'\\)` has been deprecated in v1.5\"):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp2\", gpus=2)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDP2Strategy)\n assert isinstance(trainer.strategy.cluster_environment, TorchElasticEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\[email protected](\n os.environ,\n {\n \"WORLD_SIZE\": \"2\",\n \"LOCAL_WORLD_SIZE\": \"2\",\n \"RANK\": \"1\",\n \"LOCAL_RANK\": \"1\",\n \"GROUP_RANK\": \"0\",\n \"TORCHELASTIC_RUN_ID\": \"1\",\n },\n)\[email protected](\"torch.cuda.device_count\", return_value=0)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\ndef test_accelerator_choice_ddp_cpu_te(*_):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp_cpu\", devices=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, TorchElasticEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\[email protected](\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0\",\n \"KUBERNETES_PORT\": \"tcp://127.0.0.1:443\",\n \"MASTER_ADDR\": \"1.2.3.4\",\n \"MASTER_PORT\": \"500\",\n \"WORLD_SIZE\": \"20\",\n \"RANK\": \"1\",\n },\n)\[email protected](\"torch.cuda.set_device\")\[email protected](\"torch.cuda.device_count\", return_value=1)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\[email protected](\"torch.cuda.is_available\", return_value=True)\ndef test_accelerator_choice_ddp_kubeflow(*_):\n with pytest.deprecated_call(match=r\"accelerator='ddp'\\)` has been deprecated in v1.5\"):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp\", gpus=1)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, KubeflowEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 0\n assert trainer.strategy.local_rank == 0\n\n\[email protected](\n os.environ,\n {\n \"KUBERNETES_PORT\": \"tcp://127.0.0.1:443\",\n \"MASTER_ADDR\": \"1.2.3.4\",\n \"MASTER_PORT\": \"500\",\n \"WORLD_SIZE\": \"20\",\n \"RANK\": \"1\",\n },\n)\[email protected](\"torch.cuda.device_count\", return_value=0)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\ndef test_accelerator_choice_ddp_cpu_kubeflow(*_):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp_cpu\", devices=1)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, KubeflowEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 0\n assert trainer.strategy.local_rank == 0\n\n\[email protected](\n os.environ,\n {\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"LOCAL_RANK\": \"0\",\n \"SLURM_PROCID\": \"0\",\n \"SLURM_LOCALID\": \"0\",\n },\n)\[email protected](\"torch.cuda.device_count\", return_value=0)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\ndef test_accelerator_choice_ddp_cpu_slurm(*_):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp_cpu\", devices=2)\n assert trainer._accelerator_connector._is_slurm_managing_tasks()\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, SLURMEnvironment)\n assert trainer.strategy.local_rank == 0\n\n\n@RunIf(skip_windows=True, standalone=True)\ndef test_accelerator_choice_ddp_cpu_and_strategy(tmpdir):\n \"\"\"Test that accelerator=\"ddp_cpu\" can work together with an instance of DDPStrategy.\"\"\"\n _test_accelerator_choice_ddp_cpu_and_strategy(tmpdir, ddp_strategy_class=DDPStrategy)\n\n\n@RunIf(skip_windows=True, skip_49370=True)\ndef test_accelerator_choice_ddp_cpu_and_strategy_spawn(tmpdir):\n \"\"\"Test that accelerator=\"ddp_cpu\" can work together with an instance of DDPPSpawnPlugin.\"\"\"\n _test_accelerator_choice_ddp_cpu_and_strategy(tmpdir, ddp_strategy_class=DDPSpawnStrategy)\n\n\ndef _test_accelerator_choice_ddp_cpu_and_strategy(tmpdir, ddp_strategy_class):\n trainer = Trainer(\n default_root_dir=tmpdir,\n strategy=ddp_strategy_class(find_unused_parameters=True),\n fast_dev_run=True,\n accelerator=\"ddp_cpu\",\n devices=2,\n )\n assert isinstance(trainer.strategy, ddp_strategy_class)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert trainer.strategy.num_processes == 2\n assert trainer.strategy.parallel_devices == [torch.device(\"cpu\")] * 2\n\n\[email protected](\n os.environ,\n {\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"LOCAL_RANK\": \"0\",\n \"SLURM_PROCID\": \"0\",\n \"SLURM_LOCALID\": \"0\",\n },\n)\[email protected](\"torch.cuda.device_count\", return_value=0)\ndef test_accelerator_choice_ddp_cpu_custom_cluster(_, tmpdir):\n \"\"\"Test that we choose the custom cluster even when SLURM or TE flags are around.\"\"\"\n\n class CustomCluster(LightningEnvironment):\n @property\n def main_address(self):\n return \"asdf\"\n\n @property\n def creates_processes_externally(self) -> bool:\n return True\n\n trainer = Trainer(\n default_root_dir=tmpdir, plugins=[CustomCluster()], fast_dev_run=True, accelerator=\"ddp_cpu\", devices=2\n )\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, CustomCluster)\n\n\[email protected](\n os.environ,\n {\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"LOCAL_RANK\": \"0\",\n \"SLURM_PROCID\": \"0\",\n \"SLURM_LOCALID\": \"0\",\n },\n)\[email protected](\"torch.cuda.device_count\", return_value=0)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\ndef test_custom_accelerator(device_count_mock, setup_distributed_mock):\n class Accel(Accelerator):\n @staticmethod\n def parse_devices(devices):\n return devices\n\n @staticmethod\n def get_parallel_devices(devices):\n return [torch.device(\"cpu\")] * devices\n\n @staticmethod\n def auto_device_count() -> int:\n return 1\n\n @staticmethod\n def is_available() -> bool:\n return True\n\n @staticmethod\n def name() -> str:\n return \"custom_acc_name\"\n\n class Prec(PrecisionPlugin):\n pass\n\n class Strat(SingleDeviceStrategy):\n pass\n\n strategy = Strat(device=torch.device(\"cpu\"), accelerator=Accel(), precision_plugin=Prec())\n trainer = Trainer(strategy=strategy, fast_dev_run=True, devices=2)\n assert isinstance(trainer.accelerator, Accel)\n assert isinstance(trainer.strategy, Strat)\n assert isinstance(trainer.precision_plugin, Prec)\n assert trainer._accelerator_connector.strategy is strategy\n\n class Strat(DDPStrategy):\n pass\n\n strategy = Strat(accelerator=Accel(), precision_plugin=Prec())\n trainer = Trainer(strategy=strategy, fast_dev_run=True, devices=2)\n assert isinstance(trainer.accelerator, Accel)\n assert isinstance(trainer.strategy, Strat)\n assert isinstance(trainer.precision_plugin, Prec)\n assert trainer._accelerator_connector.strategy is strategy\n\n\[email protected](\n os.environ,\n {\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"LOCAL_RANK\": \"0\",\n \"SLURM_PROCID\": \"0\",\n \"SLURM_LOCALID\": \"0\",\n },\n)\[email protected](\"torch.cuda.device_count\", return_value=0)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\ndef test_dist_backend_accelerator_mapping(*_):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp_spawn\", accelerator=\"cpu\", devices=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert trainer.strategy.local_rank == 0\n\n\[email protected](\"torch.cuda.device_count\", return_value=2)\ndef test_ipython_incompatible_backend_error(_, monkeypatch):\n monkeypatch.setattr(pytorch_lightning.utilities, \"_IS_INTERACTIVE\", True)\n with pytest.raises(MisconfigurationException, match=r\"strategy='ddp'\\)`.*is not compatible\"):\n Trainer(strategy=\"ddp\", accelerator=\"gpu\", devices=2)\n\n with pytest.raises(MisconfigurationException, match=r\"strategy='ddp2'\\)`.*is not compatible\"):\n Trainer(strategy=\"ddp2\", accelerator=\"gpu\", devices=2)\n\n with pytest.raises(MisconfigurationException, match=r\"strategy='ddp_spawn'\\)`.*is not compatible\"):\n Trainer(strategy=\"ddp_spawn\", accelerator=\"gpu\", devices=2)\n\n with pytest.raises(MisconfigurationException, match=r\"strategy='ddp_sharded_spawn'\\)`.*is not compatible\"):\n Trainer(strategy=\"ddp_sharded_spawn\", accelerator=\"gpu\", devices=2)\n\n with pytest.raises(MisconfigurationException, match=r\"strategy='ddp'\\)`.*is not compatible\"):\n # Edge case: AcceleratorConnector maps dp to ddp if accelerator != gpu\n Trainer(strategy=\"dp\")\n\n\[email protected](\"torch.cuda.device_count\", return_value=2)\ndef test_ipython_compatible_dp_strategy_gpu(_, monkeypatch):\n monkeypatch.setattr(pytorch_lightning.utilities, \"_IS_INTERACTIVE\", True)\n trainer = Trainer(strategy=\"dp\", accelerator=\"gpu\")\n assert trainer.strategy.launcher is None or trainer.strategy.launcher.is_interactive_compatible\n\n\[email protected](\"pytorch_lightning.accelerators.tpu.TPUAccelerator.is_available\", return_value=True)\[email protected](\"pytorch_lightning.accelerators.tpu.TPUAccelerator.parse_devices\", return_value=8)\ndef test_ipython_compatible_strategy_tpu(mock_devices, mock_tpu_acc_avail, monkeypatch):\n monkeypatch.setattr(pytorch_lightning.utilities, \"_IS_INTERACTIVE\", True)\n trainer = Trainer(accelerator=\"tpu\")\n assert trainer.strategy.launcher is None or trainer.strategy.launcher.is_interactive_compatible\n\n\[email protected]([\"accelerator\", \"plugin\"], [(\"ddp_spawn\", \"ddp_sharded\"), (None, \"ddp_sharded\")])\ndef test_plugin_accelerator_choice(accelerator: Optional[str], plugin: str):\n \"\"\"Ensure that when a plugin and accelerator is passed in, that the plugin takes precedent.\"\"\"\n if accelerator is None:\n with pytest.deprecated_call(match=\"Passing .* `strategy` to the `plugins`\"):\n trainer = Trainer(accelerator=accelerator, plugins=plugin, num_processes=2)\n else:\n with pytest.deprecated_call(match=r\"accelerator=.*\\)` has been deprecated\"):\n trainer = Trainer(accelerator=accelerator, plugins=plugin, num_processes=2)\n assert isinstance(trainer.strategy, DDPShardedStrategy)\n\n with pytest.deprecated_call(match=\"Passing .* `strategy` to the `plugins`\"):\n trainer = Trainer(plugins=plugin, accelerator=\"cpu\", devices=2)\n assert isinstance(trainer.strategy, DDPShardedStrategy)\n\n\[email protected](\n [\"accelerator\", \"plugin\"],\n [\n (\"ddp\", DDPStrategy),\n (\"ddp_spawn\", DDPSpawnStrategy),\n (\"ddp_sharded\", DDPShardedStrategy),\n (\"ddp_sharded_spawn\", DDPSpawnShardedStrategy),\n pytest.param(\"deepspeed\", DeepSpeedStrategy, marks=RunIf(deepspeed=True)),\n ],\n)\[email protected](\"torch.cuda.is_available\", return_value=True)\[email protected](\"torch.cuda.device_count\", return_value=2)\[email protected](\"devices\", [1, 2])\ndef test_accelerator_choice_multi_node_gpu(\n mock_is_available, mock_device_count, tmpdir, accelerator: str, plugin: ParallelStrategy, devices: int\n):\n with pytest.deprecated_call(match=r\"accelerator=.*\\)` has been deprecated\"):\n trainer = Trainer(default_root_dir=tmpdir, num_nodes=2, accelerator=accelerator, devices=devices)\n assert isinstance(trainer.strategy, plugin)\n\n\[email protected](\"torch.cuda.is_available\", return_value=False)\ndef test_accelerator_cpu(_):\n trainer = Trainer(accelerator=\"cpu\")\n assert isinstance(trainer.accelerator, CPUAccelerator)\n\n with pytest.raises(MisconfigurationException, match=\"You requested gpu:\"):\n trainer = Trainer(gpus=1)\n with pytest.raises(\n MisconfigurationException,\n match=\"GPUAccelerator can not run on your system since the accelerator is not available.\",\n ):\n trainer = Trainer(accelerator=\"gpu\")\n with pytest.raises(MisconfigurationException, match=\"You requested gpu:\"):\n trainer = Trainer(accelerator=\"cpu\", gpus=1)\n\n\[email protected](\"torch.cuda.is_available\", return_value=False)\[email protected](\"devices\", [\"0\", 0, []])\ndef test_passing_zero_and_empty_list_to_devices_flag(_, devices):\n with pytest.raises(\n MisconfigurationException, match=\"can not run on your system since the accelerator is not available.\"\n ):\n Trainer(accelerator=\"gpu\", devices=devices)\n\n\n@RunIf(min_gpus=1)\ndef test_accelerator_gpu():\n trainer = Trainer(accelerator=\"gpu\", devices=1)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n\n trainer = Trainer(accelerator=\"gpu\")\n assert isinstance(trainer.accelerator, GPUAccelerator)\n\n trainer = Trainer(accelerator=\"auto\", devices=1)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n\n\[email protected]([\"devices\", \"plugin\"], [(1, SingleDeviceStrategy), (5, DDPSpawnStrategy)])\ndef test_accelerator_cpu_with_devices(devices, plugin):\n\n trainer = Trainer(accelerator=\"cpu\", devices=devices)\n\n assert trainer.num_devices == devices\n assert isinstance(trainer.strategy, plugin)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n\n\n@RunIf(min_gpus=2)\[email protected](\n [\"devices\", \"plugin\"], [(1, SingleDeviceStrategy), ([1], SingleDeviceStrategy), (2, DDPSpawnStrategy)]\n)\ndef test_accelerator_gpu_with_devices(devices, plugin):\n\n trainer = Trainer(accelerator=\"gpu\", devices=devices)\n\n assert trainer.num_devices == len(devices) if isinstance(devices, list) else devices\n assert isinstance(trainer.strategy, plugin)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n\n\n@RunIf(min_gpus=1)\ndef test_accelerator_auto_with_devices_gpu():\n trainer = Trainer(accelerator=\"auto\", devices=1)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert trainer.num_devices == 1\n\n\ndef test_validate_accelerator_and_devices():\n\n trainer = Trainer(accelerator=\"ddp_cpu\", devices=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert trainer.num_devices == 2\n\n\ndef test_set_devices_if_none_cpu():\n\n trainer = Trainer(accelerator=\"cpu\", devices=3)\n assert trainer.num_devices == 3\n\n\ndef test_devices_with_cpu_only_supports_integer():\n\n with pytest.warns(UserWarning, match=\"The flag `devices` must be an int\"):\n trainer = Trainer(accelerator=\"cpu\", devices=\"1,3\")\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert trainer.num_devices == 1\n\n\[email protected](\"training_type\", [\"ddp2\", \"dp\"])\ndef test_unsupported_strategy_types_on_cpu(training_type):\n with pytest.warns(UserWarning, match=\"is not supported on CPUs, hence setting `strategy='ddp\"):\n trainer = Trainer(accelerator=training_type, num_processes=2)\n assert isinstance(trainer.strategy, DDPStrategy)\n\n\ndef test_accelerator_ddp_for_cpu(tmpdir):\n with pytest.deprecated_call(match=r\"accelerator='ddp'\\)` has been deprecated\"):\n trainer = Trainer(accelerator=\"ddp\", num_processes=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n\n\ndef test_exception_when_strategy_used_with_accelerator():\n with pytest.raises(MisconfigurationException, match=\"but have also passed\"), pytest.deprecated_call(\n match=r\"accelerator='ddp'\\)` has been deprecated\"\n ):\n Trainer(accelerator=\"ddp\", strategy=\"ddp_spawn\")\n\n\ndef test_exception_when_strategy_used_with_plugins():\n with pytest.raises(MisconfigurationException, match=\"only specify one strategy, but you have passed\"):\n with pytest.deprecated_call(match=r\"`strategy` to the `plugins` flag in Trainer has been deprecated\"):\n Trainer(plugins=\"ddp_find_unused_parameters_false\", strategy=\"ddp_spawn\")\n\n\ndef test_exception_invalid_strategy():\n with pytest.raises(MisconfigurationException, match=r\"strategy='ddp_cpu'\\)` is not a valid\"):\n Trainer(strategy=\"ddp_cpu\")\n with pytest.raises(MisconfigurationException, match=r\"strategy='tpu_spawn'\\)` is not a valid\"):\n Trainer(strategy=\"tpu_spawn\")\n\n\[email protected](\n [\"strategy\", \"plugin\"],\n [\n (\"ddp_spawn\", DDPSpawnStrategy),\n (\"ddp_spawn_find_unused_parameters_false\", DDPSpawnStrategy),\n (\"ddp\", DDPStrategy),\n (\"ddp_find_unused_parameters_false\", DDPStrategy),\n ],\n)\ndef test_strategy_choice_cpu_str(tmpdir, strategy, plugin):\n trainer = Trainer(strategy=strategy, accelerator=\"cpu\", devices=2)\n assert isinstance(trainer.strategy, plugin)\n\n\[email protected](\"plugin\", [DDPSpawnStrategy, DDPStrategy])\ndef test_strategy_choice_cpu_plugin(tmpdir, plugin):\n trainer = Trainer(strategy=plugin(), accelerator=\"cpu\", devices=2)\n assert isinstance(trainer.strategy, plugin)\n\n\n@RunIf(min_gpus=2)\[email protected](\n [\"strategy\", \"plugin\"],\n [\n (\"ddp_spawn\", DDPSpawnStrategy),\n (\"ddp_spawn_find_unused_parameters_false\", DDPSpawnStrategy),\n (\"ddp\", DDPStrategy),\n (\"ddp_find_unused_parameters_false\", DDPStrategy),\n (\"ddp2\", DDP2Strategy),\n (\"dp\", DataParallelStrategy),\n (\"ddp_sharded\", DDPShardedStrategy),\n (\"ddp_sharded_spawn\", DDPSpawnShardedStrategy),\n pytest.param(\"deepspeed\", DeepSpeedStrategy, marks=RunIf(deepspeed=True)),\n ],\n)\ndef test_strategy_choice_gpu_str(tmpdir, strategy, plugin):\n trainer = Trainer(strategy=strategy, accelerator=\"gpu\", devices=2)\n assert isinstance(trainer.strategy, plugin)\n\n\n@RunIf(min_gpus=2)\[email protected](\"plugin\", [DDPSpawnStrategy, DDPStrategy])\ndef test_strategy_choice_gpu_plugin(tmpdir, plugin):\n trainer = Trainer(strategy=plugin(), accelerator=\"gpu\", devices=2)\n assert isinstance(trainer.strategy, plugin)\n\n\n@RunIf(min_gpus=2)\[email protected](\"plugin\", [DDPSpawnStrategy, DDPStrategy])\ndef test_device_type_when_training_plugin_gpu_passed(tmpdir, plugin):\n\n trainer = Trainer(strategy=plugin(), accelerator=\"gpu\", devices=2)\n assert isinstance(trainer.strategy, plugin)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n\n\[email protected](\"precision\", [1, 12, \"invalid\"])\ndef test_validate_precision_type(tmpdir, precision):\n\n with pytest.raises(MisconfigurationException, match=f\"Precision {repr(precision)} is invalid\"):\n Trainer(precision=precision)\n\n\ndef test_amp_level_raises_error_with_native():\n with pytest.raises(MisconfigurationException, match=\"O2'` but it's only supported with `amp_backend='apex'`\"):\n _ = Trainer(amp_level=\"O2\", amp_backend=\"native\", precision=16)\n\n\ndef test_strategy_choice_ddp_spawn_cpu(tmpdir):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp_spawn\", accelerator=\"cpu\", devices=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPSpawnStrategy)\n assert isinstance(trainer.strategy.cluster_environment, LightningEnvironment)\n\n\[email protected](os.environ, {\"CUDA_VISIBLE_DEVICES\": \"0,1\"})\[email protected](\"torch.cuda.device_count\", return_value=2)\[email protected](\"torch.cuda.is_available\", return_value=True)\ndef test_strategy_choice_ddp(cuda_available_mock, device_count_mock):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp\", accelerator=\"gpu\", devices=1)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, LightningEnvironment)\n\n\[email protected](os.environ, {\"CUDA_VISIBLE_DEVICES\": \"0,1\"})\[email protected](\"torch.cuda.device_count\", return_value=2)\[email protected](\"torch.cuda.is_available\", return_value=True)\ndef test_strategy_choice_ddp_spawn(cuda_available_mock, device_count_mock):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp_spawn\", accelerator=\"gpu\", devices=1)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPSpawnStrategy)\n assert isinstance(trainer.strategy.cluster_environment, LightningEnvironment)\n\n\n@RunIf(min_gpus=2)\[email protected](\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"SLURM_PROCID\": \"1\",\n \"SLURM_LOCALID\": \"1\",\n },\n)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\[email protected](\"strategy\", [\"ddp\", DDPStrategy()])\ndef test_strategy_choice_ddp_slurm(setup_distributed_mock, strategy):\n trainer = Trainer(fast_dev_run=True, strategy=strategy, accelerator=\"gpu\", devices=2)\n assert trainer._accelerator_connector._is_slurm_managing_tasks()\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, SLURMEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\[email protected](\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"SLURM_PROCID\": \"1\",\n \"SLURM_LOCALID\": \"1\",\n },\n)\[email protected](\"torch.cuda.set_device\")\[email protected](\"torch.cuda.device_count\", return_value=2)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\[email protected](\"torch.cuda.is_available\", return_value=True)\[email protected](\"strategy\", [\"ddp2\", DDP2Strategy()])\ndef test_strategy_choice_ddp2_slurm(\n set_device_mock, device_count_mock, setup_distributed_mock, is_available_mock, strategy\n):\n trainer = Trainer(fast_dev_run=True, strategy=strategy, accelerator=\"gpu\", devices=2)\n assert trainer._accelerator_connector._is_slurm_managing_tasks()\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDP2Strategy)\n assert isinstance(trainer.strategy.cluster_environment, SLURMEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\[email protected](\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"WORLD_SIZE\": \"2\",\n \"LOCAL_WORLD_SIZE\": \"2\",\n \"RANK\": \"1\",\n \"LOCAL_RANK\": \"1\",\n \"GROUP_RANK\": \"0\",\n \"TORCHELASTIC_RUN_ID\": \"1\",\n },\n)\[email protected](\"torch.cuda.set_device\")\[email protected](\"torch.cuda.device_count\", return_value=2)\[email protected](\"torch.cuda.is_available\", return_value=True)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\[email protected](\"torch.cuda.is_available\", return_value=True)\ndef test_strategy_choice_ddp_te(*_):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp\", accelerator=\"gpu\", devices=2)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, TorchElasticEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\[email protected](\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"WORLD_SIZE\": \"2\",\n \"LOCAL_WORLD_SIZE\": \"2\",\n \"RANK\": \"1\",\n \"LOCAL_RANK\": \"1\",\n \"GROUP_RANK\": \"0\",\n \"TORCHELASTIC_RUN_ID\": \"1\",\n },\n)\[email protected](\"torch.cuda.set_device\")\[email protected](\"torch.cuda.device_count\", return_value=2)\[email protected](\"torch.cuda.is_available\", return_value=True)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\[email protected](\"torch.cuda.is_available\", return_value=True)\ndef test_strategy_choice_ddp2_te(*_):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp2\", accelerator=\"gpu\", devices=2)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDP2Strategy)\n assert isinstance(trainer.strategy.cluster_environment, TorchElasticEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\[email protected](\n os.environ,\n {\n \"WORLD_SIZE\": \"2\",\n \"LOCAL_WORLD_SIZE\": \"2\",\n \"RANK\": \"1\",\n \"LOCAL_RANK\": \"1\",\n \"GROUP_RANK\": \"0\",\n \"TORCHELASTIC_RUN_ID\": \"1\",\n },\n)\[email protected](\"torch.cuda.device_count\", return_value=0)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\ndef test_strategy_choice_ddp_cpu_te(*_):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp_spawn\", accelerator=\"cpu\", devices=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, TorchElasticEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\[email protected](\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0\",\n \"KUBERNETES_PORT\": \"tcp://127.0.0.1:443\",\n \"MASTER_ADDR\": \"1.2.3.4\",\n \"MASTER_PORT\": \"500\",\n \"WORLD_SIZE\": \"20\",\n \"RANK\": \"1\",\n },\n)\[email protected](\"torch.cuda.set_device\")\[email protected](\"torch.cuda.device_count\", return_value=1)\[email protected](\"torch.cuda.is_available\", return_value=True)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\[email protected](\"torch.cuda.is_available\", return_value=True)\ndef test_strategy_choice_ddp_kubeflow(*_):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp\", accelerator=\"gpu\", devices=1)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, KubeflowEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 0\n assert trainer.strategy.local_rank == 0\n\n\[email protected](\n os.environ,\n {\n \"KUBERNETES_PORT\": \"tcp://127.0.0.1:443\",\n \"MASTER_ADDR\": \"1.2.3.4\",\n \"MASTER_PORT\": \"500\",\n \"WORLD_SIZE\": \"20\",\n \"RANK\": \"1\",\n },\n)\[email protected](\"torch.cuda.device_count\", return_value=0)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\ndef test_strategy_choice_ddp_cpu_kubeflow(*_):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp_spawn\", accelerator=\"cpu\", devices=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, KubeflowEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 0\n assert trainer.strategy.local_rank == 0\n\n\[email protected](\n os.environ,\n {\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"LOCAL_RANK\": \"0\",\n \"SLURM_PROCID\": \"0\",\n \"SLURM_LOCALID\": \"0\",\n },\n)\[email protected](\"torch.cuda.device_count\", return_value=0)\[email protected](\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\[email protected](\"strategy\", [\"ddp\", DDPStrategy()])\ndef test_strategy_choice_ddp_cpu_slurm(device_count_mock, setup_distributed_mock, strategy):\n trainer = Trainer(fast_dev_run=True, strategy=strategy, accelerator=\"cpu\", devices=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, SLURMEnvironment)\n assert trainer.strategy.local_rank == 0\n\n\[email protected](\"pytorch_lightning.accelerators.tpu.TPUAccelerator.is_available\", return_value=True)\[email protected](\"pytorch_lightning.accelerators.tpu.TPUAccelerator.parse_devices\", return_value=8)\ndef test_unsupported_tpu_choice(mock_devices, mock_tpu_acc_avail):\n\n with pytest.raises(MisconfigurationException, match=r\"accelerator='tpu', precision=64\\)` is not implemented\"):\n Trainer(accelerator=\"tpu\", precision=64)\n\n # if user didn't set strategy, AcceleratorConnector will choose the TPUSingleStrategy or TPUSpawnStrategy\n with pytest.raises(ValueError, match=\"TPUAccelerator` can only be used with a `SingleTPUStrategy`\"):\n with pytest.warns(UserWarning, match=r\"accelerator='tpu', precision=16\\)` but native AMP is not supported\"):\n Trainer(accelerator=\"tpu\", precision=16, strategy=\"ddp\")\n\n with pytest.raises(ValueError, match=\"TPUAccelerator` can only be used with a `SingleTPUStrategy`\"):\n with pytest.warns(UserWarning, match=r\"accelerator='tpu', precision=16\\)` but apex AMP is not supported\"):\n Trainer(accelerator=\"tpu\", precision=16, amp_backend=\"apex\", strategy=\"single_device\")\n\n\[email protected](\"pytorch_lightning.accelerators.ipu.IPUAccelerator.is_available\", return_value=True)\ndef test_unsupported_ipu_choice(mock_ipu_acc_avail, monkeypatch):\n import pytorch_lightning.strategies.ipu as ipu\n import pytorch_lightning.utilities.imports as imports\n\n monkeypatch.setattr(imports, \"_IPU_AVAILABLE\", True)\n monkeypatch.setattr(ipu, \"_IPU_AVAILABLE\", True)\n with pytest.raises(ValueError, match=r\"accelerator='ipu', precision='bf16'\\)` is not supported\"):\n Trainer(accelerator=\"ipu\", precision=\"bf16\")\n with pytest.raises(ValueError, match=r\"accelerator='ipu', precision=64\\)` is not supported\"):\n Trainer(accelerator=\"ipu\", precision=64)\n\n\[email protected](\"torch.cuda.is_available\", return_value=False)\[email protected](\"pytorch_lightning.utilities.imports._TPU_AVAILABLE\", return_value=False)\[email protected](\"pytorch_lightning.utilities.imports._IPU_AVAILABLE\", return_value=False)\[email protected](\"pytorch_lightning.utilities.imports._HPU_AVAILABLE\", return_value=False)\ndef test_devices_auto_choice_cpu(\n is_ipu_available_mock, is_tpu_available_mock, is_gpu_available_mock, is_hpu_available_mock\n):\n trainer = Trainer(accelerator=\"auto\", devices=\"auto\")\n assert trainer.num_devices == 1\n\n\[email protected](\"torch.cuda.is_available\", return_value=True)\[email protected](\"torch.cuda.device_count\", return_value=2)\ndef test_devices_auto_choice_gpu(is_gpu_available_mock, device_count_mock):\n trainer = Trainer(accelerator=\"auto\", devices=\"auto\")\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert trainer.num_devices == 2\n\n\[email protected](\n [\"parallel_devices\", \"accelerator\"],\n [([torch.device(\"cpu\")], \"gpu\"), ([torch.device(\"cuda\", i) for i in range(8)], (\"tpu\"))],\n)\ndef test_parallel_devices_in_strategy_confilict_with_accelerator(parallel_devices, accelerator):\n with pytest.raises(MisconfigurationException, match=r\"parallel_devices set through\"):\n Trainer(strategy=DDPStrategy(parallel_devices=parallel_devices), accelerator=accelerator)\n\n\[email protected](\"deterministic\", [True, False])\ndef test_deterministic_init(deterministic):\n trainer = Trainer(accelerator=\"auto\", deterministic=deterministic)\n assert trainer._accelerator_connector.deterministic == deterministic\n if deterministic:\n assert os.environ.get(\"CUBLAS_WORKSPACE_CONFIG\") == \":4096:8\"\n assert os.environ.get(\"HOROVOD_FUSION_THRESHOLD\") == \"0\"\n\n\[email protected](\n \"sync_batchnorm,plugins,expected\",\n [\n (False, [], type(None)),\n (True, [], NativeSyncBatchNorm),\n (False, [NativeSyncBatchNorm()], NativeSyncBatchNorm),\n (True, [NativeSyncBatchNorm()], NativeSyncBatchNorm),\n (False, [Mock(spec=LayerSync)], LayerSync),\n ],\n)\ndef test_sync_batchnorm_set(tmpdir, sync_batchnorm, plugins, expected):\n \"\"\"Test valid combinations of the sync_batchnorm Trainer flag and the plugins list of layer-sync plugins.\"\"\"\n trainer = Trainer(sync_batchnorm=sync_batchnorm, plugins=plugins, strategy=\"ddp\")\n assert isinstance(trainer._accelerator_connector._layer_sync, expected)\n assert isinstance(trainer.strategy._layer_sync, expected)\n\n\ndef test_sync_batchnorm_invalid_choice(tmpdir):\n \"\"\"Test that a conflicting specification of enabled sync batchnorm and a custom plugin leads to an error.\"\"\"\n custom = Mock(spec=LayerSync)\n with pytest.raises(\n MisconfigurationException,\n match=r\"You set `Trainer\\(sync_batchnorm=True\\)` and provided a `LayerSync` plugin, but this is not allowed\",\n ):\n Trainer(sync_batchnorm=True, plugins=[custom])\n\n\n@RunIf(skip_windows=True)\ndef test_sync_batchnorm_set_in_custom_strategy(tmpdir):\n \"\"\"Tests if layer_sync is automatically set for custom strategy.\"\"\"\n\n class CustomParallelStrategy(DDPStrategy):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n # Set to None so it will be overwritten by the accelerator connector.\n self._layer_sync = None\n\n strategy = CustomParallelStrategy()\n assert strategy._layer_sync is None\n Trainer(strategy=strategy, sync_batchnorm=True)\n assert isinstance(strategy._layer_sync, NativeSyncBatchNorm)\n\n\[email protected](\n [\"plugins\", \"expected\"],\n [\n ([LightningEnvironment(), SLURMEnvironment()], \"ClusterEnvironment\"),\n ([TorchCheckpointIO(), TorchCheckpointIO()], \"CheckpointIO\"),\n (\n [PrecisionPlugin(), DoublePrecisionPlugin(), LightningEnvironment(), SLURMEnvironment()],\n \"PrecisionPlugin, ClusterEnvironment\",\n ),\n ],\n)\ndef test_plugin_only_one_instance_for_one_type(plugins, expected):\n with pytest.raises(MisconfigurationException, match=f\"Received multiple values for {expected}\"):\n Trainer(plugins=plugins)\n" ]
[ [ "torch.device" ] ]
emdgroup/brain_waves_for_planning_problems
[ "4b4356f40470d8ecfb6152960d9c4f25a7a11b46" ]
[ "Hybrid_Neuron_Simulation.py" ]
[ "\"\"\"\nAttractor Network for 2DoF Robot Arm\n\nAuthor: Henry Powell and Mathias Winkel\n\"\"\"\nimport sys\nimport numpy as np\n\nfrom graphics import Graphics\nfrom ContinuousAttractorLayer import ContinuousAttractorLayer\nfrom WavePropagationLayer import WavePropagationLayer\nfrom setups import SETUPS\n\nif len(sys.argv) > 1:\n selected_setup = sys.argv[1]\nelse:\n selected_setup = 's_maze'\n\ntry:\n setup = SETUPS[selected_setup]\nexcept KeyError as e:\n raise ValueError('Selected setup \"{}\" does not exist. Chose one of \\n\\t{}'.format(selected_setup, '\\n\\t'.join(SETUPS.keys()))) from e\n\nJ = 12 # continuous attractor synaptic connection strength\nT = 0.05 # continuous attractor Gaussian shift\nσ = 0.03 # continuous attractor Gaussian width\nτ = 0.8 # continuous attractor stabilization strength\nR = setup.get('R', 12) # continuous attractor movement recovery period\n\nI = 25 # external DC current to stimulate selected wave propagation layer neurons\ndt = 1 # simulation timestep\n\nshape = setup['size']\n\nwave_propagation_layer = WavePropagationLayer(shape, setup['randomize_neurons'], setup['randomize_synapses'])\ncontinuous_attractor_layer = ContinuousAttractorLayer(shape, J, T, σ, τ)\ngraphics = Graphics(shape, selected_setup, setup['blocked'], setup['target_neurons'])\n\nfor region in setup['blocked']:\n continuous_attractor_layer.block_region(region)\n wave_propagation_layer.block_region(region)\n\ncontinuous_attractor_layer.set_activation(setup['start_neuron'])\n\nΔ = np.array([0, 0])\nthalamic_input = np.zeros((2, *shape))\n\ndirec_update_delay = 0\n\ncoords = np.asarray(np.meshgrid(range(shape[0]), range(shape[1]))).T\n\nfor t in range(setup['t_max']):\n # random thalamic input if requested\n if setup['thalamic_input']:\n thalamic_input = np.random.uniform(0, 1, (2, *shape))\n\n # external drive\n for target_neuron in setup['target_neurons']:\n thalamic_input[(0, *reversed(target_neuron))] = I\n\n # update the continuous attractor, store the center position for computing the direction vector later\n place_cell_peak = continuous_attractor_layer.update(Δ / np.asarray(shape))\n\n # update the wave propagation layer, store the firing pattern\n spiking_fired = wave_propagation_layer.update(dt, thalamic_input)\n\n # layer interaction - compute direction vector\n if direc_update_delay <= 0:\n # the continuous attractor is not in its recoverz period\n overlap = continuous_attractor_layer.A * spiking_fired[0]\n total = np.sum(overlap)\n\n if total > 0:\n # there is some overlap --> compute a direction vector and start the recovery period\n distance = coords - place_cell_peak[np.newaxis, np.newaxis, :]\n Δ = np.sum(distance * overlap[..., np.newaxis], axis=(0, 1)) / total\n direc_update_delay = R\n else:\n # no overlap --> no direction vector\n Δ = np.array([0, 0])\n else:\n # recovery period is still running - do not set a direction vector\n direc_update_delay -= dt\n Δ = np.array([0, 0])\n\n # dump all data as images / videos, abort of figures have been closed manually\n if not graphics.update(t, place_cell_peak, Δ, spiking_fired, wave_propagation_layer.v, continuous_attractor_layer.A, overlap):\n print('Figure closed. Finalizing simulation.')\n break\n\n # abort simulation after reaching the target\n if tuple(place_cell_peak) in setup['target_neurons']:\n print('Reached target. Finalizing simulation.')\n break\n\ngraphics.save_video(fps=8, keep_frame_images=False)\n" ]
[ [ "numpy.asarray", "numpy.random.uniform", "numpy.array", "numpy.zeros", "numpy.sum" ] ]
JonesRobM/SAPPHIRE
[ "fba875af56e48e2c5a4a3cf6788f51f359f63800" ]
[ "main/Sapphire/Post_Process/DistFuncs.py" ]
[ "import numpy as np\nimport os\n\ndef distance(a, b):\n \n dx = abs(a[0] - b[0])\n \n dy = abs(a[1] - b[1])\n \n dz = abs(a[2] - b[2])\n \n return np.sqrt(dx**2 + dy**2 + dz**2)\n\ndef CoMDist(positions, CoM = None, homo = False, specie = None, elements = None):\n \n if homo == False:\n return [distance(x, CoM) for x in positions]\n elif homo:\n Temp = get_subspecieslist(specie, elements, positions)\n CoM = get_CoM(Temp)\n return [distance(x, CoM) for x in Temp]\n \ndef get_CoM(positions):\n return (np.average(positions, axis = 0))\n\ndef get_subspecieslist(specie, elements, positions):\n Temp = np.column_stack((elements,positions))\n Temp = [x for x in Temp if x[0] == specie]\n return np.array(np.delete(Temp,0,1), dtype = np.float64)\n\ndef Euc_Dist(positions, homo = False, specie = None, elements = None):\n \n if homo == False:\n Distances=[]\n for i in range(len(positions)-1):\n for j in range(i+1,len(positions)):\n Euc = distance(positions[i],positions[j])\n\n Distances.append(Euc)\n return Distances\n \n elif homo:\n Distances = []\n Temp = get_subspecieslist(specie, elements, positions)\n if (len(Temp)>1) is False:\n return None\n else:\n for i in range(len(Temp)-1):\n for j in range(i+1,len(Temp)):\n Euc = distance(Temp[i],Temp[j])\n\n Distances.append(Euc)\n return Distances\n else:\n print(\"Variables used were:\\n%s\\n%s\\n%s\\n\" %(homo, specie, (elements[0], elements[1])))\n raise TypeError(\"Euc_Dist function has encountered an error.\\n\")\n \n \ndef Hetero(positions, species, elements):\n \n \"\"\" Robert\n \n Note that no species need to be defined for this function as it is understood that LoDiS\n only has provision for mono/bimetallic systems (for the time being) although this\n function could be further generalised (albeit it a potential cost to computation time).\n \"\"\"\n \n TempA = get_subspecieslist(species[0], elements, positions)\n TempB = get_subspecieslist(species[1], elements, positions)\n try:\n np.shape(TempA)[1]\n try:\n np.shape(TempB)[1]\n Dist=[]\n for a in TempA:\n Temp = [ distance(a,b) for b in TempB]\n Dist.append(Temp)\n return Dist\n except IndexError:\n Dist=[]\n for x in TempA:\n Dist.append( [distance(x, TempB) ])\n return Dist\n print(\"You have only one of a specific atom type in your simulation. I hope that this is correct.\", \"\\n\")\n except IndexError:\n try:\n np.shape(TempB)[1] \n return [ distance(TempA, b) for b in TempB ]\n print(\"You have only one of a specific atom type in your simulation. I hope that this is correct.\", \"\\n\")\n except IndexError:\n print(\"You only have two atoms.\\nIs this correct?\", \"\\n\")\n return None\n \n\nclass CoM_Dist():\n \n def __init__(self, System, Positions, CoM = None, Type = False, Specie = None, Elements = None, Frame = None):\n self.System = System\n self.Positions = Positions\n self.CoM =Positions\n self.Type = Type\n self.Specie= Specie\n self.Elements = Elements\n self.Frame = Frame\n self.calculate()\n self.write()\n \n def ensure_dir(self, base_dir='', file_path=''):\n \"\"\"\n\n Robert:\n\n A simple script to verify the existence of a directory\n given the path to it. If it does not exist, will create it.\n\n \"\"\"\n\n directory = base_dir + file_path\n if not os.path.exists(directory):\n\n os.makedirs(directory)\n\n def MakeFile(self, Attributes):\n self.out = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']\n\n if not os.path.isfile(self.out):\n with open(self.System['base_dir'] + Attributes['Dir'] + Attributes['File'], 'w') as out:\n out.close()\n else:\n pass \n \n def calculate(self):\n \n if self.Type == 'Full':\n self.Dist = np.array([distance(x, self.CoM) for x in self.Positions])\n elif self.Type == 'Homo':\n Temp = get_subspecieslist(self.Specie, self.Elements, self.Positions)\n self.Dist = np.array([distance(x, self.CoM) for x in Temp])\n self.CoM = get_CoM(Temp)\n self.MidDist = np.array([distance(x, self.CoM) for x in Temp])\n \n def write(self):\n \n if self.Type == 'Full':\n from Sapphire.IO import OutputInfoFull as Out # Case 1\n \n #Write object for the CoM\n Attributes = getattr(Out, str('com')) #Loads in the write information for the object \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.CoM) +'\\n')\n\n #Write object for the CoMDistances\n Attributes = getattr(Out, str('comdist')) #Loads in the write information for the object \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.Dist) +'\\n')\n\n elif self.Type == 'Homo':\n from Sapphire.IO import OutputInfoHomo as Out # Case 2\n \n #Write object for the homo CoM \n Attributes = getattr(Out, str('hocom')) #Loads in the write information for the object \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']+self.Specie\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.CoM) +'\\n')\n \n #Write object for the homo CoM distances\n Attributes = getattr(Out, str('hocomdist')) #Loads in the write information for the object \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']+self.Specie\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.Dist) +'\\n')\n \n #Write object for the sub-cluster specific homo CoM distances\n Attributes = getattr(Out, str('homidcomdist')) #Loads in the write information for the object \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']+self.Specie\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.MidDist) +'\\n')\n\n \nclass RDF():\n \n\n def __init__(self, System, Positions, Res=100, R_Cut=10.0, Type = None, Species = None, Elements = None, Frame = None):\n \n \n \"\"\" Robert\n \n Args:\n Res: \n int data type representing how finely you wish to make \n the grid. Usually set in the order of 100\n \n positions: \n Single frame of xyz coordinates for a set of atoms\n Is expected to be iterated over and so will only take a single frame of xyz\n \n R_Cut: \n Float type variable which indicates how far you wish to create\n the distribution for.\n Good practice is to set it to ~0.5 Diameter of the cluster\n Tested with 10 Angstroms\n Returns:\n Radii:\n A numpy array of all the radii the distribution has been computed over\n Will have length of \"Resolution\" and is to be used as the x axis on\n an RDF plot.\n \n G:\n A numpy array of the (unnormalised) calculated RDF values corresponding \n to the respective radius in Radii. To be set on the y axis in a given\n RDF plot.\n \n \"\"\"\n \n self.R_Cut = R_Cut\n self.System = System\n self.Res = Res\n self.Positions = Positions\n self.Type = Type\n self.Species = Species\n self.Elements = Elements\n self.Frame = Frame\n self.dr = self.R_Cut / self.Res #Increments to grow the spheres by\n self.Radii = np.linspace(0, self.R_Cut, self.Res) #List of Sphere radii to use\n self.Volumes=np.zeros(self.Res)\n self.G=np.zeros(self.Res)\n self.calculate()\n self.write()\n \n def ensure_dir(self, base_dir='', file_path=''):\n \"\"\"\n\n Robert:\n\n A simple script to verify the existence of a directory\n given the path to it. If it does not exist, will create it.\n\n \"\"\"\n\n directory = base_dir + file_path\n if not os.path.exists(directory):\n\n os.makedirs(directory)\n\n def MakeFile(self, Attributes):\n self.out = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']\n\n if not os.path.isfile(self.out):\n with open(self.System['base_dir'] + Attributes['Dir'] + Attributes['File'], 'w') as out:\n out.close()\n else:\n pass\n \n def calculate(self):\n \n if not self.Type == 'Hetero':\n for i, atom1 in enumerate(self.Positions):\n for j in range(self.Res):\n r1 = j * self.dr #Inner radius for the spherical shell\n r2 = r1 + self.dr #Outer radius increased by increment dr\n v1 = 4.0 / 3.0 * np.pi * r1**3\n v2 = 4.0 / 3.0 * np.pi * r2**3\n self.Volumes[j] += v2 - v1 #Volume to consider when evaluating distribution\n \n for atom2 in self.Positions[i:]:\n self.Distance = distance(atom1, atom2)\n index = int(self.Distance / self.dr)\n if 0 < index < self.Res:\n self.G[index] += 2 #Identifies when there is an atom at this distance\n \n for i, value in enumerate(self.G):\n self.G[i] = value / self.Volumes[i] #Rescaling the distribution with respect to enclosing volume\n elif self.Type == 'Hetero':\n TempA = get_subspecieslist(self.Species[0], self.Elements, self.Positions)\n TempB = get_subspecieslist(self.Species[1], self.Elements, self.Positions)\n for i, atom1 in enumerate(TempA):\n for j in range(self.Res):\n r1 = j * self.dr #Inner radius for the spherical shell\n r2 = r1 + self.dr #Outer radius increased by increment dr\n v1 = 4.0 / 3.0 * np.pi * r1**3\n v2 = 4.0 / 3.0 * np.pi * r2**3\n self.Volumes[j] += v2 - v1 #Volume to consider when evaluating distribution\n \n for atom2 in TempB:\n self.Distance = distance(atom1, atom2)\n index = int(self.Distance / self.dr)\n if 0 < index < self.Res:\n self.G[index] += 2 #Identifies when there is an atom at this distance\n \n \n for i, value in enumerate(self.G):\n self.G[i] = value / self.Volumes[i] #Rescaling the distribution with respect to enclosing volume\n \n def write(self):\n \n if self.Type == 'Full':\n from Sapphire.IO import OutputInfoFull as Out # Case 1\n \n Attributes = getattr(Out, str('rdf')) #Loads in the write information for the object \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.G) +'\\n')\n\n \n Attributes = getattr(Out, str('rdfspace')) #Loads in the write information for the object \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.Radii) +'\\n')\n\n elif self.Type == 'Homo':\n from Sapphire.IO import OutputInfoHomo as Out # Case 2\n \n Attributes = getattr(Out, str('hordf')) #Loads in the write information for the object \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']+self.Species\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.G) +'\\n')\n \n Attributes = getattr(Out, str('hordfspace')) #Loads in the write information for the object \n \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']+self.Species\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.Radii) +'\\n')\n\n elif self.Type == 'Hetero':\n from Sapphire.IO import OutputInfoHetero as Out # Case 3\n \n Attributes = getattr(Out, str('herdf')) #Loads in the write information for the object \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.G) +'\\n')\n \n \n Attributes = getattr(Out, str('herdfspace')) #Loads in the write information for the object \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.Radii) +'\\n')\n\nclass Pair_Dist():\n \n def __init__(self, System, Positions, Type = None, Specie = None, Elements = None, Frame = None):\n self.System = System\n self.Positions = Positions\n self.Type = Type\n self.Specie = Specie\n self.Elements = Elements\n self.Frame = Frame\n self.calculate()\n self.write()\n \n def ensure_dir(self, base_dir='', file_path=''):\n \"\"\"\n\n Robert:\n\n A simple script to verify the existence of a directory\n given the path to it. If it does not exist, will create it.\n\n \"\"\"\n\n directory = base_dir + file_path\n if not os.path.exists(directory):\n\n os.makedirs(directory)\n\n def MakeFile(self, Attributes):\n self.out = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']\n\n if not os.path.isfile(self.out):\n with open(self.System['base_dir'] + Attributes['Dir'] + Attributes['File'], 'w') as out:\n out.close()\n else:\n pass\n \n def calculate(self):\n \n if self.Type == 'Homo':\n try:\n self.distances = Euc_Dist(self.Positions, True, self.Specie, self.Elements)\n #(positions, homo = False, specie = None, elements = None)\n except Exception as e:\n pass\n elif self.Type == 'Hetero':\n try:\n self.distances = Hetero(self.Positions, self.Specie, self.Elements)\n except Exception as e:\n pass\n else:\n self.distances = Euc_Dist(self.Positions)\n \n self.bins = int(round(200/(1+20*np.exp(-len(self.distances)/1000)))) #Wait, what the fuck???\n self.a, b = np.histogram(self.distances, self.bins)\n bin_width = b[1]-b[0]\n self.bin_cents = [ b[i]+ bin_width for i in range(len(b)-1) ]\n #bin_cents, a\n \n def write(self):\n \n if self.Type == 'Full':\n from Sapphire.IO import OutputInfoFull as Out # Case 1\n \n Attributes = getattr(Out, str('pair_distance')) #Loads in the write information for the object \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.a) +'\\n')\n\n \n Attributes = getattr(Out, str('pair_distancespace')) #Loads in the write information for the object \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.bin_cents) +'\\n')\n\n elif self.Type == 'Homo':\n from Sapphire.IO import OutputInfoHomo as Out # Case 2\n \n Attributes = getattr(Out, str('hopair_distance')) #Loads in the write information for the object \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']+self.Specie\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.a) +'\\n')\n \n Attributes = getattr(Out, str('hopair_distancespace')) #Loads in the write information for the object \n \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']+self.Specie\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.bin_cents) +'\\n')\n\n elif self.Type == 'Hetero':\n from Sapphire.IO import OutputInfoHetero as Out # Case 3\n \n Attributes = getattr(Out, str('hepair_distance')) #Loads in the write information for the object \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.a) +'\\n')\n \n \n Attributes = getattr(Out, str('hepair_distancespace')) #Loads in the write information for the object \n OutFile = self.System['base_dir'] + Attributes['Dir'] + Attributes['File']\n self.ensure_dir(base_dir=self.System['base_dir'], file_path=Attributes['Dir']) \n self.MakeFile(Attributes)\n with open(OutFile, 'a') as outfile:\n outfile.write(str(self.Frame) + ' ' + ' '.join(str(item) for item in self.bin_cents) +'\\n')" ]
[ [ "numpy.sqrt", "numpy.linspace", "numpy.histogram", "numpy.delete", "numpy.shape", "numpy.column_stack", "numpy.average", "numpy.zeros" ] ]
Kalana304/KORSAL
[ "b7a0c7cf5428f632e99d2ca5c5e10a8288f10cc0" ]
[ "CenterNet/src/lib/datasets/sample/ctdet.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch.utils.data as data\nimport numpy as np\nimport torch\nimport json\nimport cv2\nimport os\nfrom utils.image import flip, color_aug\nfrom utils.image import get_affine_transform, affine_transform\nfrom utils.image import gaussian_radius, draw_umich_gaussian, draw_msra_gaussian\nfrom utils.image import draw_dense_reg\nimport math\n\nclass CTDetDataset(data.Dataset):\n def _coco_box_to_bbox(self, box):\n bbox = np.array([box[0], box[1], box[0] + box[2], box[1] + box[3]],\n dtype=np.float32)\n return bbox\n\n def _transform_to_coco(self, bboxs, labels):\n anns = []\n for t in range(len(labels)):\n bbox = bboxs[t, :]\n bbox[2] = bbox[2] - bbox[0]\n bbox[3] = bbox[3] - bbox[1]\n label = labels[t]\n anns.append({'bbox': bbox, 'category_id': label + 1})\n return anns\n \n def _scale_bbox(self, bbox, i_h, i_w, h, w):\n bbox[0] = float(bbox[0])*i_w/w\n bbox[2] = float(bbox[2])*i_w/w\n bbox[1] = float(bbox[1])*i_h/h\n bbox[3] = float(bbox[3])*i_h/h\n return bbox\n\n def _get_border(self, border, size):\n i = 1\n while size - border // i <= border // i:\n i *= 2\n return border // i\n\n def __getitem__(self, index):\n annot_info = self.ids[index]\n frame_num = annot_info[1]\n video_id = annot_info[0]\n videoname = self.video_list[video_id]\n img_name = os.path.join(self._imgpath, videoname, '{:05d}{}'.format(frame_num, self.extension))\n # ann_ids = self.coco.getAnnIds(imgIds=[img_id])\n # anns = self.coco.loadAnns(ids=ann_ids)\n anns = self._transform_to_coco(annot_info[3], annot_info[2])\n num_objs = min(len(anns), self.max_objs)\n\n img = cv2.imread(img_name)\n\n height, width = img.shape[0], img.shape[1]\n c = np.array([img.shape[1] / 2., img.shape[0] / 2.], dtype=np.float32)\n if self.opt.keep_res:\n input_h = (height | self.opt.pad) + 1\n input_w = (width | self.opt.pad) + 1\n s = np.array([input_w, input_h], dtype=np.float32)\n else:\n s = max(img.shape[0], img.shape[1]) * 1.0\n input_h, input_w = self.opt.input_h, self.opt.input_w\n \n flipped = False\n if self.split == 'train':\n if not self.opt.not_rand_crop:\n s = s * np.random.choice(np.arange(0.6, 1.4, 0.1))\n w_border = self._get_border(128, img.shape[1])\n h_border = self._get_border(128, img.shape[0])\n c[0] = np.random.randint(low=w_border, high=img.shape[1] - w_border)\n c[1] = np.random.randint(low=h_border, high=img.shape[0] - h_border)\n else:\n sf = self.opt.scale\n cf = self.opt.shift\n c[0] += s * np.clip(np.random.randn()*cf, -2*cf, 2*cf)\n c[1] += s * np.clip(np.random.randn()*cf, -2*cf, 2*cf)\n s = s * np.clip(np.random.randn()*sf + 1, 1 - sf, 1 + sf)\n \n if np.random.random() < self.opt.flip:\n flipped = True\n img = img[:, ::-1, :]\n c[0] = width - c[0] - 1\n\n\n trans_input = get_affine_transform(\n c, s, 0, [input_w, input_h])\n inp = cv2.warpAffine(img, trans_input, \n (input_w, input_h),\n flags=cv2.INTER_LINEAR)\n inp = (inp.astype(np.float32) / 255.)\n if self.split == 'train' and not self.opt.no_color_aug:\n color_aug(self._data_rng, inp, self._eig_val, self._eig_vec)\n inp = (inp - self.mean) / self.std\n inp = inp.transpose(2, 0, 1)\n\n output_h = input_h // self.opt.down_ratio\n output_w = input_w // self.opt.down_ratio\n num_classes = self.num_classes\n trans_output = get_affine_transform(c, s, 0, [output_w, output_h])\n\n hm = np.zeros((num_classes, output_h, output_w), dtype=np.float32)\n wh = np.zeros((self.max_objs, 2), dtype=np.float32)\n dense_wh = np.zeros((2, output_h, output_w), dtype=np.float32)\n reg = np.zeros((self.max_objs, 2), dtype=np.float32)\n ind = np.zeros((self.max_objs), dtype=np.int64)\n reg_mask = np.zeros((self.max_objs), dtype=np.uint8)\n cat_spec_wh = np.zeros((self.max_objs, num_classes * 2), dtype=np.float32)\n cat_spec_mask = np.zeros((self.max_objs, num_classes * 2), dtype=np.uint8)\n \n draw_gaussian = draw_msra_gaussian if self.opt.mse_loss else \\\n draw_umich_gaussian\n\n gt_det = []\n for k in range(num_objs):\n ann = anns[k]\n bbox = self._coco_box_to_bbox(ann['bbox'])\n # bbox = self._scale_bbox(bbox, input_h, input_w, height, width)\n cls_id = int(self.cat_ids[ann['category_id']])\n if flipped:\n bbox[[0, 2]] = width - bbox[[2, 0]] - 1\n bbox[:2] = affine_transform(bbox[:2], trans_output)\n bbox[2:] = affine_transform(bbox[2:], trans_output)\n bbox[[0, 2]] = np.clip(bbox[[0, 2]], 0, output_w - 1)\n bbox[[1, 3]] = np.clip(bbox[[1, 3]], 0, output_h - 1)\n h, w = bbox[3] - bbox[1], bbox[2] - bbox[0]\n if h > 0 and w > 0:\n radius = gaussian_radius((math.ceil(h), math.ceil(w)))\n radius = max(0, int(radius))\n radius = self.opt.hm_gauss if self.opt.mse_loss else radius\n ct = np.array(\n [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2], dtype=np.float32)\n ct_int = ct.astype(np.int32)\n draw_gaussian(hm[cls_id], ct_int, radius)\n wh[k] = 1. * w, 1. * h\n ind[k] = ct_int[1] * output_w + ct_int[0]\n reg[k] = ct - ct_int\n reg_mask[k] = 1\n cat_spec_wh[k, cls_id * 2: cls_id * 2 + 2] = wh[k]\n cat_spec_mask[k, cls_id * 2: cls_id * 2 + 2] = 1\n if self.opt.dense_wh:\n draw_dense_reg(dense_wh, hm.max(axis=0), ct_int, wh[k], radius)\n gt_det.append([ct[0] - w / 2, ct[1] - h / 2, \n ct[0] + w / 2, ct[1] + h / 2, 1, cls_id])\n ret = {'input': inp, 'hm': hm, 'reg_mask': reg_mask, 'ind': ind, 'index':index, 'wh': wh}\n if self.opt.dense_wh:\n hm_a = hm.max(axis=0, keepdims=True)\n dense_wh_mask = np.concatenate([hm_a, hm_a], axis=0)\n ret.update({'dense_wh': dense_wh, 'dense_wh_mask': dense_wh_mask})\n del ret['wh']\n elif self.opt.cat_spec_wh:\n ret.update({'cat_spec_wh': cat_spec_wh, 'cat_spec_mask': cat_spec_mask})\n del ret['wh']\n if self.opt.reg_offset:\n ret.update({'reg': reg})\n if self.opt.debug > 0 or not self.split == 'train':\n gt_det = np.array(gt_det, dtype=np.float32) if len(gt_det) > 0 else \\\n np.zeros((1, 6), dtype=np.float32)\n meta = {'c': c, 's': s, 'gt_det': gt_det, 'img_id': index, 'out_height':output_h, 'out_width':output_w}\n ret['meta'] = meta\n return ret" ]
[ [ "numpy.random.random", "numpy.clip", "numpy.arange", "numpy.concatenate", "numpy.random.randn", "numpy.array", "numpy.zeros", "numpy.random.randint" ] ]
pdiercks/pymor
[ "e94f05714d666a929113543c49e88f8f494d64e1" ]
[ "src/pymordemos/parabolic_mor.py" ]
[ "#!/usr/bin/env python\n# This file is part of the pyMOR project (http://www.pymor.org).\n# Copyright 2013-2020 pyMOR developers and contributors. All rights reserved.\n# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\n\"\"\"Reduced basis approximation of the heat equation.\n\nUsage:\n parabolic_mor.py BACKEND ALG SNAPSHOTS RBSIZE TEST\n\nArguments:\n BACKEND Discretization toolkit to use (pymor, fenics).\n\n ALG The model reduction algorithm to use\n (greedy, adaptive_greedy, pod).\n\n SNAPSHOTS greedy/pod: number of training set parameters\n adaptive_greedy: size of validation set.\n\n RBSIZE Size of the reduced basis.\n TEST Number of test parameters for reduction error estimation.\n\"\"\"\n\nfrom functools import partial # fix parameters of given function\n\nimport numpy as np\n\nfrom pymor.basic import * # most common pyMOR functions and classes\nfrom pymor.algorithms.timestepping import ImplicitEulerTimeStepper\n\n\n# parameters for high-dimensional models\nGRID_INTERVALS = 100\nFENICS_ORDER = 2\nNT = 100\nDT = 1. / NT\n\n\n####################################################################################################\n# High-dimensional models #\n####################################################################################################\n\n\ndef discretize_pymor():\n\n # setup analytical problem\n problem = InstationaryProblem(\n\n StationaryProblem(\n domain=RectDomain(top='dirichlet', bottom='neumann'),\n\n diffusion=LincombFunction(\n [ConstantFunction(1., dim_domain=2),\n ExpressionFunction('(x[..., 0] > 0.45) * (x[..., 0] < 0.55) * (x[..., 1] < 0.7) * 1.',\n dim_domain=2),\n ExpressionFunction('(x[..., 0] > 0.35) * (x[..., 0] < 0.40) * (x[..., 1] > 0.3) * 1. + '\n '(x[..., 0] > 0.60) * (x[..., 0] < 0.65) * (x[..., 1] > 0.3) * 1.',\n dim_domain=2)],\n [1.,\n 100. - 1.,\n ExpressionParameterFunctional('top - 1.', {'top': 0})]\n ),\n\n rhs=ConstantFunction(value=100., dim_domain=2) * ExpressionParameterFunctional('sin(10*pi*_t)', {'_t': ()}),\n\n dirichlet_data=ConstantFunction(value=0., dim_domain=2),\n\n neumann_data=ExpressionFunction('(x[..., 0] > 0.45) * (x[..., 0] < 0.55) * -1000.',\n dim_domain=2),\n ),\n\n T=1.,\n\n initial_data=ExpressionFunction('(x[..., 0] > 0.45) * (x[..., 0] < 0.55) * (x[..., 1] < 0.7) * 10.',\n dim_domain=2),\n\n parameter_space=CubicParameterSpace({'top': 0}, minimum=1, maximum=100.)\n )\n\n # discretize using continuous finite elements\n fom, _ = discretize_instationary_cg(analytical_problem=problem, diameter=1./GRID_INTERVALS, nt=NT)\n fom.enable_caching('disk')\n\n return fom\n\n\ndef discretize_fenics():\n from pymor.tools import mpi\n\n if mpi.parallel:\n from pymor.models.mpi import mpi_wrap_model\n return mpi_wrap_model(_discretize_fenics, use_with=True, pickle_local_spaces=False)\n else:\n return _discretize_fenics()\n\n\ndef _discretize_fenics():\n\n # assemble system matrices - FEniCS code\n ########################################\n\n import dolfin as df\n\n # discrete function space\n mesh = df.UnitSquareMesh(GRID_INTERVALS, GRID_INTERVALS, 'crossed')\n V = df.FunctionSpace(mesh, 'Lagrange', FENICS_ORDER)\n u = df.TrialFunction(V)\n v = df.TestFunction(V)\n\n # data functions\n bottom_diffusion = df.Expression('(x[0] > 0.45) * (x[0] < 0.55) * (x[1] < 0.7) * 1.',\n element=df.FunctionSpace(mesh, 'DG', 0).ufl_element())\n top_diffusion = df.Expression('(x[0] > 0.35) * (x[0] < 0.40) * (x[1] > 0.3) * 1. +'\n '(x[0] > 0.60) * (x[0] < 0.65) * (x[1] > 0.3) * 1.',\n element=df.FunctionSpace(mesh, 'DG', 0).ufl_element())\n initial_data = df.Expression('(x[0] > 0.45) * (x[0] < 0.55) * (x[1] < 0.7) * 10.',\n element=df.FunctionSpace(mesh, 'DG', 0).ufl_element())\n neumann_data = df.Expression('(x[0] > 0.45) * (x[0] < 0.55) * 1000.',\n element=df.FunctionSpace(mesh, 'DG', 0).ufl_element())\n\n # assemble matrices and vectors\n l2_mat = df.assemble(df.inner(u, v) * df.dx)\n l2_0_mat = l2_mat.copy()\n h1_mat = df.assemble(df.inner(df.nabla_grad(u), df.nabla_grad(v)) * df.dx)\n h1_0_mat = h1_mat.copy()\n mat0 = h1_mat.copy()\n mat0.zero()\n bottom_mat = df.assemble(bottom_diffusion * df.inner(df.nabla_grad(u), df.nabla_grad(v)) * df.dx)\n top_mat = df.assemble(top_diffusion * df.inner(df.nabla_grad(u), df.nabla_grad(v)) * df.dx)\n u0 = df.project(initial_data, V).vector()\n f = df.assemble(neumann_data * v * df.ds)\n\n # boundary treatment\n def dirichlet_boundary(x, on_boundary):\n tol = 1e-14\n return on_boundary and (abs(x[0]) < tol or abs(x[0] - 1) < tol or abs(x[1] - 1) < tol)\n\n bc = df.DirichletBC(V, df.Constant(0.), dirichlet_boundary)\n bc.apply(l2_0_mat)\n bc.apply(h1_0_mat)\n bc.apply(mat0)\n bc.zero(bottom_mat)\n bc.zero(top_mat)\n bc.apply(f)\n bc.apply(u0)\n\n # wrap everything as a pyMOR model\n ##################################\n\n from pymor.bindings.fenics import FenicsVectorSpace, FenicsMatrixOperator, FenicsVisualizer\n\n fom = InstationaryModel(\n T=1.,\n\n initial_data=FenicsVectorSpace(V).make_array([u0]),\n\n operator=LincombOperator([FenicsMatrixOperator(mat0, V, V),\n FenicsMatrixOperator(h1_0_mat, V, V),\n FenicsMatrixOperator(bottom_mat, V, V),\n FenicsMatrixOperator(top_mat, V, V)],\n [1.,\n 1.,\n 100. - 1.,\n ExpressionParameterFunctional('top - 1.', {'top': 0})]),\n\n rhs=VectorOperator(FenicsVectorSpace(V).make_array([f])),\n\n mass=FenicsMatrixOperator(l2_0_mat, V, V, name='l2'),\n\n products={'l2': FenicsMatrixOperator(l2_mat, V, V, name='l2'),\n 'l2_0': FenicsMatrixOperator(l2_0_mat, V, V, name='l2_0'),\n 'h1': FenicsMatrixOperator(h1_mat, V, V, name='h1'),\n 'h1_0_semi': FenicsMatrixOperator(h1_0_mat, V, V, name='h1_0_semi')},\n\n time_stepper=ImplicitEulerTimeStepper(nt=NT),\n\n parameter_space=CubicParameterSpace({'top': 0}, minimum=1, maximum=100.),\n\n visualizer=FenicsVisualizer(FenicsVectorSpace(V))\n )\n\n return fom\n\n\n####################################################################################################\n# Reduction algorithms #\n####################################################################################################\n\n\ndef reduce_greedy(fom, reductor, snapshots, basis_size):\n\n training_set = fom.parameter_space.sample_uniformly(snapshots)\n pool = new_parallel_pool()\n\n greedy_data = rb_greedy(fom, reductor, training_set, max_extensions=basis_size, pool=pool)\n\n return greedy_data['rom']\n\n\ndef reduce_adaptive_greedy(fom, reductor, validation_mus, basis_size):\n\n pool = new_parallel_pool()\n\n greedy_data = rb_adaptive_greedy(fom, reductor, validation_mus=validation_mus,\n max_extensions=basis_size, pool=pool)\n\n return greedy_data['rom']\n\n\ndef reduce_pod(fom, reductor, snapshots, basis_size):\n\n training_set = fom.parameter_space.sample_uniformly(snapshots)\n\n snapshots = fom.operator.source.empty()\n for mu in training_set:\n snapshots.append(fom.solve(mu))\n\n basis, singular_values = pod(snapshots, modes=basis_size, product=fom.h1_0_semi_product)\n reductor.extend_basis(basis, method='trivial')\n\n rom = reductor.reduce()\n\n return rom\n\n\n####################################################################################################\n# Main script #\n####################################################################################################\n\ndef main(BACKEND, ALG, SNAPSHOTS, RBSIZE, TEST):\n # discretize\n ############\n if BACKEND == 'pymor':\n fom = discretize_pymor()\n elif BACKEND == 'fenics':\n fom = discretize_fenics()\n else:\n raise NotImplementedError\n\n # select reduction algorithm with error estimator\n #################################################\n coercivity_estimator = ExpressionParameterFunctional('1.', fom.parameter_type)\n reductor = ParabolicRBReductor(fom, product=fom.h1_0_semi_product, coercivity_estimator=coercivity_estimator)\n\n # generate reduced model\n ########################\n if ALG == 'greedy':\n rom = reduce_greedy(fom, reductor, SNAPSHOTS, RBSIZE)\n elif ALG == 'adaptive_greedy':\n rom = reduce_adaptive_greedy(fom, reductor, SNAPSHOTS, RBSIZE)\n elif ALG == 'pod':\n rom = reduce_pod(fom, reductor, SNAPSHOTS, RBSIZE)\n else:\n raise NotImplementedError\n\n # evaluate the reduction error\n ##############################\n results = reduction_error_analysis(\n rom, fom=fom, reductor=reductor, estimator=True,\n error_norms=[lambda U: DT * np.sqrt(np.sum(fom.h1_0_semi_norm(U)[1:]**2))],\n error_norm_names=['l^2-h^1'],\n condition=False, test_mus=TEST, random_seed=999, plot=True\n )\n\n # show results\n ##############\n print(results['summary'])\n import matplotlib.pyplot as plt\n plt.show(results['figure'])\n\n # write results to disk\n #######################\n from pymor.core.pickle import dump\n dump(rom, open('reduced_model.out', 'wb'))\n results.pop('figure') # matplotlib figures cannot be serialized\n dump(results, open('results.out', 'wb'))\n\n # visualize reduction error for worst-approximated mu\n #####################################################\n mumax = results['max_error_mus'][0, -1]\n U = fom.solve(mumax)\n U_RB = reductor.reconstruct(rom.solve(mumax))\n if BACKEND == 'fenics': # right now the fenics visualizer does not support time trajectories\n U = U[len(U) - 1].copy()\n U_RB = U_RB[len(U_RB) - 1].copy()\n fom.visualize((U, U_RB, U - U_RB), legend=('Detailed Solution', 'Reduced Solution', 'Error'),\n separate_colorbars=True)\n\n return results\n\n\nif __name__ == '__main__':\n import sys\n if len(sys.argv) != 6:\n print(__doc__)\n sys.exit(1)\n BACKEND, ALG, SNAPSHOTS, RBSIZE, TEST = sys.argv[1:]\n BACKEND, ALG, SNAPSHOTS, RBSIZE, TEST = BACKEND.lower(), ALG.lower(), int(SNAPSHOTS), int(RBSIZE), int(TEST)\n main(BACKEND, ALG, SNAPSHOTS, RBSIZE, TEST)\n" ]
[ [ "matplotlib.pyplot.show" ] ]
gbmarc1/ExploranceAnonymizer
[ "ff3616ef929269b5c8420266b3c32225cfa4b4a3" ]
[ "src/__main__.py" ]
[ "from argparse import ArgumentParser\nfrom pathlib import Path\n\nimport pandas as pd\nimport spacy\nfrom tqdm import tqdm\n\n\ndef get_parser():\n parser = ArgumentParser()\n parser.add_argument(\"--file\", type=Path)\n return parser\n\n\ndef replace_entities(text, ents):\n new_text = ''\n start = 0\n for e in sorted(ents, key=lambda x: x.start):\n new_text += text[start:e.start_char] + '<' + e.label_ + '>'\n start = e.end_char\n\n new_text += text[start:]\n return new_text\n\n\ndef anonymize(data):\n nlp = spacy.load(\"en_core_web_sm\")\n anonimized_data, entities, raw_data = [], [], []\n valid_entities = ['PERSON']\n\n for d in tqdm(data.iloc[:, 0]):\n raw_data.append(d)\n doc = nlp(d, disable=[\"tagger\", \"parser\"])\n ents = [e for e in doc.ents if e.label_ in valid_entities]\n anonimized_data.append(replace_entities(d, ents))\n entities.append(str([((e.start, e.end), e.text+'->'+e.label_) for e in ents]))\n\n return pd.DataFrame(\n {\"Raw\": raw_data, \"Anonymized\": anonimized_data, \"Entities\": entities}\n )\n\n\ndef main(args):\n\n args = get_parser().parse_args(args)\n data = pd.read_csv(args.file, header=None)\n data = anonymize(data)\n data.to_csv(args.file.parent/('anonymized_'+args.file.name), index=False)\n\n\nif __name__ == \"__main__\":\n main(None)\n" ]
[ [ "pandas.read_csv", "pandas.DataFrame" ] ]
Casper-Smet/turing-route-66
[ "b797485586c3491ddbcd76367aff88b7672d8d9a" ]
[ "route_66/model.py" ]
[ "import numpy as np\nfrom mesa import Model\nfrom mesa.datacollection import DataCollector\nfrom mesa.space import SingleGrid\nfrom mesa.time import StagedActivation\n\nfrom route_66.agent import CarAgent, TrafficLight\n\n\ndef get_average_velocity(model):\n \"\"\"\n Gets the total average velocity over all the agents\n\n :param model: The model (environment) where the agents exist\n\n :return: The total average velocity over all the agents\n \"\"\"\n df = model.datacollector.get_agent_vars_dataframe()\n df.reset_index(inplace=True)\n velocities = df[\"Velocity\"]\n\n return velocities.mean()\n\n\ndef get_standard_deviation_velocity(model):\n \"\"\"\n Gets the total standard deviation of the velocity over all agents\n\n :param model: The model (environment) where the agents exist\n\n :return: The total standard deviation over all agents\n \"\"\"\n df = model.datacollector.get_agent_vars_dataframe()\n df.reset_index(inplace=True)\n velocities = df[\"Velocity\"]\n\n return velocities.std()\n\n\ndef get_on_ramp_queue(model):\n \"\"\"Gets the total queue on the on ramp after the simulation\"\"\"\n return model.traffic_light.on_ramp_queue\n\n\ndef get_waiting_queue(model):\n \"\"\"Gets the total queue on the waiting ramp after the simulation\"\"\"\n return model.traffic_light.wait_queue\n\n\nclass RoadModel(Model):\n \"\"\"\n A model with a number of cars, Nagel-Schreckenberg\n \"\"\"\n\n def __init__(self, N, length=100, lanes=1, timer=3):\n self.num_agents = N\n self.grid = SingleGrid(length, lanes, torus=True)\n model_stages = [\"acceleration\", \"braking\", \"randomisation\", \"move\", \"delete\"]\n self.schedule = StagedActivation(self, stage_list=model_stages)\n\n # Create agent\n for i in range(self.num_agents):\n agent = CarAgent(i, self, False)\n # Add to schedule\n self.schedule.add(agent)\n # Add to grid (randomly)\n self.grid.position_agent(agent)\n\n # Add the traffic light\n self.traffic_light = TrafficLight(0, self, timer, 20, 20)\n self.average_velocity = CarAgent.init_velocity\n self.datacollector = DataCollector(agent_reporters={\n \"Position\": \"pos\",\n \"Velocity\": \"velocity\"},\n model_reporters={\n \"Average Velocity\": \"average_velocity\",\n \"Amount of cars\": \"agent_count\",\n \"On Ramp Queue\": get_on_ramp_queue,\n \"Waiting Queue\": get_waiting_queue})\n\n self.running = True\n\n def step(self):\n \"\"\"\n The model takes a new step and updates\n \"\"\"\n # Calculate amount of agents\n self.agent_count = len(self.schedule.agents)\n # Calculate average velocity\n self.average_velocity = np.mean([a.velocity for a in self.schedule.agents])\n # Collect data\n self.datacollector.collect(self)\n # Run a step of the traffic light\n self.traffic_light.step()\n # Run next step\n self.schedule.step()\n\n def add_agent(self, label, x_corr):\n \"\"\"\n Adds an agent to the scheduler and model on a particular coordinate\n\n :param label: The label of the agents that gets created\n :param x_corr: The x-coordinate of where the agent will be spawned\n \"\"\"\n # Create agent\n agent = CarAgent(label, self, True)\n # Add to schedule\n self.schedule.add(agent)\n # Add to grid on a certain position\n self.grid.position_agent(agent, x_corr, 0)\n\n def delete_agent(self, agent):\n \"\"\"\n Deletes an agent from the scheduler and model\n\n :param agent: The agents that gets deleted\n \"\"\"\n # remove from schedule\n self.schedule.remove(agent)\n # remove from grid\n self.grid.remove_agent(agent)\n" ]
[ [ "numpy.mean" ] ]
quadraticmuffin/nd_maze
[ "8f41d923d1839c0d6fb34c02f165b247f181743b" ]
[ "run.py" ]
[ "import numpy as np\n\n\nclass NdMaze():\n '''\n\n '''\n def __init__(self, nd, size, start=None):\n self.board = np.zeros(shape=[size]*nd)\n self.nd = nd\n self.size = size\n self.pos = start\n if start is None:\n self.pos = [0]*nd\n self.dimr = 0\n self.dimc = 1\n \n def move(self, dim, amt):\n if (self.pos[dim] + amt) not in range(self.size):\n raise ValueError('Attempted to move out of bounds')\n temp_pos = list(self.pos)\n temp_pos[dim] += amt\n self.pos = tuple(temp_pos)\n return self.get2d()\n\n def seeDim(self, newdim):\n if newdim not in range(self.nd):\n raise ValueError(f'Dimension {newdim} does not exist in board of {self.nd} dimensions.')\n self.dimr = self.dimc\n self.dimc = newdim\n return self.get2d()\n\n def get2d(self):\n idx = list(self.pos)\n idx[self.dimr] = slice(None)\n idx[self.dimc] = slice(None)\n ret = self.board[tuple(idx)]\n if self.dimr > self.dimc:\n return ret.T\n else:\n return ret\n \n def __repr__(self):\n return str(self.board)\n \n def __str__(self):\n return str(self.get2d())\n\n\nif __name__ == '__main__':\n game = NdMaze(5, 2)\n game.board = np.arange(32).reshape([2]*5)" ]
[ [ "numpy.arange", "numpy.zeros" ] ]
basharbme/unet
[ "85117087c1cb73c81a8eea4e127fae7cb47b4fe1" ]
[ "2D/convert_raw_to_hdf5.py" ]
[ "#!/usr/bin/env python\n#\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2019 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# SPDX-License-Identifier: EPL-2.0\n#\n\"\"\"\nConverts the Medical Decathlon raw Nifti files into\nsingle HDF5 file for easier use in TensorFlow/Keras.\n\nYou'll need to download the raw dataset from\nthe Medical Decathlon website (http://medicaldecathlon.com),\nextract the data (untar), and run this script.\n\nThe raw dataset has the CC-BY-SA 4.0 license.\nhttps://creativecommons.org/licenses/by-sa/4.0/\n\nFor BraTS (Task 1):\n\nINPUT CHANNELS: \"modality\": {\n\t \"0\": \"FLAIR\",\n\t \"1\": \"T1w\",\n\t \"2\": \"t1gd\",\n\t \"3\": \"T2w\"\n },\nLABEL_CHANNELS: \"labels\": {\n\t \"0\": \"background\",\n\t \"1\": \"edema\",\n\t \"2\": \"non-enhancing tumor\",\n\t \"3\": \"enhancing tumour\"\n }\n\n\"\"\"\n\nimport os\nimport nibabel as nib # pip install nibabel\nimport numpy as np\nfrom tqdm import tqdm # pip install tqdm\nimport h5py # pip install h5py\nimport json\n\nimport argparse\n\nparser = argparse.ArgumentParser(\n\tdescription=\"Convert Decathlon raw Nifti data \"\n\t\"(http://medicaldecathlon.com) \"\n\t\"files to Numpy data files\",\n\tadd_help=True, formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\nparser.add_argument(\"--data_path\",\n\t\t\t\t\tdefault=\"../../data/decathlon/Task01_BrainTumour/\",\n\t\t\t\t\thelp=\"Path to the raw BraTS datafiles\")\nparser.add_argument(\"--save_path\",\n\t\t\t\t\tdefault=\"../../data/decathlon/\",\n\t\t\t\t\thelp=\"Folder to save Numpy data files\")\nparser.add_argument(\"--output_filename\",\n\t\t\t\t\tdefault=\"decathlon_brats.h5\",\n\t\t\t\t\thelp=\"Name of the output HDF5 file\")\nparser.add_argument(\"--resize\", type=int, default=144,\n\t\t\t\t\thelp=\"Resize height and width to this size. \"\n\t\t\t\t\t\"Original size = 240\")\nparser.add_argument(\"--split\", type=float, default=0.85,\n\t\t\t\t\thelp=\"Train/test split ratio\")\n\nargs = parser.parse_args()\n\n\ndef crop_center(img, cropx, cropy, cropz):\n\t\"\"\"\n\tTake a center crop of the images.\n\tIf we are using a 2D model, then we'll just stack the\n\tz dimension.\n\t\"\"\"\n\n\tx, y, z, c = img.shape\n\n\t# Make sure starting index is >= 0\n\tstartx = max(x // 2 - (cropx // 2), 0)\n\tstarty = max(y // 2 - (cropy // 2), 0)\n\tstartz = max(z // 2 - (cropz // 2), 0)\n\n\t# Make sure ending index is <= size\n\tendx = min(startx + cropx, x)\n\tendy = min(starty + cropy, y)\n\tendz = min(startz + cropz, z)\n\n\treturn img[startx:endx, starty:endy, startz:endz, :]\n\n\ndef normalize_img(img):\n\t\"\"\"\n\tNormalize the pixel values.\n\tThis is one of the most important preprocessing steps.\n\tWe need to make sure that the pixel values have a mean of 0\n\tand a standard deviation of 1 to help the model to train\n\tfaster and more accurately.\n\t\"\"\"\n\n\tfor channel in range(img.shape[3]):\n\t\timg[:, :, :, channel] = (\n\t\t\timg[:, :, :, channel] - np.mean(img[:, :, :, channel])) \\\n\t\t\t/ np.std(img[:, :, :, channel])\n\n\treturn img\n\n\ndef attach_attributes(df, json_data, name):\n\t\"\"\"\n\tSave the json data\n\t\"\"\"\n\n\tif type(json_data) is str:\n\t\tlength = 1\n\telse:\n\t\tlength = len(json_data)\n\n\tdt = h5py.special_dtype(vlen=str)\n\tdset = df.create_dataset(name, (length,), dtype=dt)\n\tdset[:] = json_data\n\n\ndef preprocess_inputs(img):\n\t\"\"\"\n\tProcess the input images\n\n\tFor BraTS subset:\n\tINPUT CHANNELS: \"modality\": {\n\t\t \"0\": \"FLAIR\", T2-weighted-Fluid-Attenuated Inversion Recovery MRI\n\t\t \"1\": \"T1w\", T1-weighted MRI\n\t\t \"2\": \"t1gd\", T1-gadolinium contrast MRI\n\t\t \"3\": \"T2w\" T2-weighted MRI\n\t }\n\t\"\"\"\n\tif len(img.shape) != 4: # Make sure 4D\n\t\timg = np.expand_dims(img, -1)\n\n\timg = crop_center(img, args.resize, args.resize, args.resize)\n\timg = normalize_img(img)\n\n\timg = np.swapaxes(np.array(img), 0, -2)\n\n\t# img = img[:,:,:,[0]] # Just get the FLAIR channel\n\n\treturn img\n\n\ndef preprocess_labels(msk):\n\t\"\"\"\n\tProcess the ground truth labels\n\n\tFor BraTS subset:\n\tLABEL_CHANNELS: \"labels\": {\n\t\t \"0\": \"background\", No tumor\n\t\t \"1\": \"edema\", Swelling around tumor\n\t\t \"2\": \"non-enhancing tumor\", Tumor that isn't enhanced by Gadolinium contrast\n\t\t \"3\": \"enhancing tumour\" Gadolinium contrast enhanced regions\n\t }\n\n\t\"\"\"\n\tif len(msk.shape) != 4: # Make sure 4D\n\t\tmsk = np.expand_dims(msk, -1)\n\n\tmsk = crop_center(msk, args.resize, args.resize, args.resize)\n\n\t# Combining all masks assumes that a mask value of 0 is the background\n\tmsk[msk > 1] = 1 # Combine all masks\n\tmsk = np.swapaxes(np.array(msk), 0, -2)\n\n\treturn msk\n\n\ndef convert_raw_data_to_hdf5(trainIdx, validateIdx, testIdx, fileIdx,\n\t\t\t\t\t\t\t filename, dataDir, json_data):\n\t\"\"\"\n\tGo through the Decathlon dataset.json file.\n\tWe've already split into training and validation subsets.\n\tRead in Nifti format files. Crop images and masks.\n\tSave to HDF5 format.\n\tThis code is will convert the 3D images and masks\n\tinto a stack of 2D slices.\n\t\"\"\"\n\thdf_file = h5py.File(filename, \"w\")\n\n\t# Save the dataset attributes\n\tattach_attributes(hdf_file, str(json_data[\"modality\"]), \"modalities\")\n\tattach_attributes(hdf_file, json_data[\"licence\"], \"license\")\n\tattach_attributes(hdf_file, json_data[\"reference\"], \"reference\")\n\tattach_attributes(hdf_file, json_data[\"name\"], \"name\")\n\tattach_attributes(hdf_file, json_data[\"description\"], \"description\")\n\tattach_attributes(hdf_file, json_data[\"release\"], \"release\")\n\tattach_attributes(\n\t\thdf_file, json_data[\"tensorImageSize\"], \"tensorImageSize\")\n\n\t# Training filenames\n\ttrain_image_files = []\n\ttrain_label_files = []\n\tfor idx in trainIdx:\n\t\ttrain_image_files.append(fileIdx[idx][\"image\"])\n\t\ttrain_label_files.append(fileIdx[idx][\"label\"])\n\n\t# Validation filenames\n\tvalidate_image_files = []\n\tvalidate_label_files = []\n\tfor idx in validateIdx:\n\t\tvalidate_image_files.append(fileIdx[idx][\"image\"])\n\t\tvalidate_label_files.append(fileIdx[idx][\"label\"])\n\n\t# Testing filenames\n\ttest_image_files = []\n\ttest_label_files = []\n\tfor idx in testIdx:\n\t\ttest_image_files.append(fileIdx[idx][\"image\"])\n\t\ttest_label_files.append(fileIdx[idx][\"label\"])\n\n\tattach_attributes(hdf_file, train_image_files, \"training_input_files\")\n\tattach_attributes(hdf_file, train_label_files, \"training_label_files\")\n\tattach_attributes(hdf_file, validate_image_files, \"validation_input_files\")\n\tattach_attributes(hdf_file, validate_label_files, \"validation_label_files\")\n\tattach_attributes(hdf_file, test_image_files, \"testing_input_files\")\n\tattach_attributes(hdf_file, test_label_files, \"testing_label_files\")\n\n\t\"\"\"\n\tPrint shapes of raw data\n\t\"\"\"\n\tprint(\"Data shapes\")\n\tprint(\"===========\")\n\tprint(\"n.b. All tensors converted to stacks of 2D slices.\")\n\tprint(\"If you want true 3D tensors, then modify this code appropriately.\")\n\tdata_filename = os.path.join(dataDir, train_image_files[0])\n\timg = np.array(nib.load(data_filename).dataobj)\n\tprint(\"Raw Image shape = \", img.shape)\n\tcrop_shape = preprocess_inputs(img).shape[1:]\n\tprint(\"Cropped Image shape = (?, {}, {}, {})\".format(crop_shape[0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t crop_shape[1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t crop_shape[2]))\n\n\tdata_filename = os.path.join(dataDir, train_label_files[0])\n\tmsk = np.array(nib.load(data_filename).dataobj)\n\tprint(\"Raw Masks shape = \", msk.shape)\n\tcrop_shape = preprocess_labels(msk).shape[1:]\n\tprint(\"Cropped Masks shape = (?, {}, {}, {})\".format(crop_shape[0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t crop_shape[1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t crop_shape[2]))\n\n\t# Save training set images\n\tprint(\"Step 1 of 6. Save training set images.\")\n\tfirst = True\n\tfor idx in tqdm(train_image_files):\n\n\t\tdata_filename = os.path.join(dataDir, idx)\n\t\timg = np.array(nib.load(data_filename).dataobj)\n\n\t\timg = preprocess_inputs(img)\n\t\tnum_rows = img.shape[0]\n\n\t\tif first:\n\t\t\tfirst = False\n\t\t\timg_train_dset = hdf_file.create_dataset(\"imgs_train\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t img.shape,\n\t\t\t\t\t\t\t\t\t\t\t\t\t maxshape=(None,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t img.shape[1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t img.shape[2],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t img.shape[3]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t dtype=float,\n\t\t\t\t\t\t\t\t\t\t\t\t\t compression=\"gzip\")\n\t\t\timg_train_dset[:] = img\n\t\telse:\n\t\t\trow = img_train_dset.shape[0] # Count current dataset rows\n\t\t\timg_train_dset.resize(row + num_rows, axis=0) # Add new row\n\t\t\t# Insert data into new row\n\t\t\timg_train_dset[row:(row + num_rows), :] = img\n\n\t# Save validation set images\n\tprint(\"Step 2 of 6. Save validation set images.\")\n\tfirst = True\n\tfor idx in tqdm(validate_image_files):\n\n\t\t# Nibabel should read the file as X,Y,Z,C\n\t\tdata_filename = os.path.join(dataDir, idx)\n\t\timg = np.array(nib.load(data_filename).dataobj)\n\t\timg = preprocess_inputs(img)\n\n\t\tnum_rows = img.shape[0]\n\n\t\tif first:\n\t\t\tfirst = False\n\t\t\timg_validation_dset = hdf_file.create_dataset(\"imgs_validation\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t img.shape,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t maxshape=(None,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\timg.shape[1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\timg.shape[2],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\timg.shape[3]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t dtype=float,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t compression=\"gzip\")\n\t\t\timg_validation_dset[:] = img\n\t\telse:\n\t\t\trow = img_validation_dset.shape[0] # Count current dataset rows\n\t\t\timg_validation_dset.resize(row + num_rows, axis=0) # Add new row\n\t\t\t# Insert data into new row\n\t\t\timg_validation_dset[row:(row + num_rows), :] = img\n\n\t# Save validation set images\n\tprint(\"Step 3 of 6. Save testing set images.\")\n\tfirst = True\n\tfor idx in tqdm(test_image_files):\n\n\t\t# Nibabel should read the file as X,Y,Z,C\n\t\tdata_filename = os.path.join(dataDir, idx)\n\t\timg = np.array(nib.load(data_filename).dataobj)\n\t\timg = preprocess_inputs(img)\n\n\t\tnum_rows = img.shape[0]\n\n\t\tif first:\n\t\t\tfirst = False\n\t\t\timg_testing_dset = hdf_file.create_dataset(\"imgs_testing\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t img.shape,\n\t\t\t\t\t\t\t\t\t\t\t\t\t maxshape=(None,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t img.shape[1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t img.shape[2],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t img.shape[3]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t dtype=float,\n\t\t\t\t\t\t\t\t\t\t\t\t\t compression=\"gzip\")\n\t\t\timg_testing_dset[:] = img\n\t\telse:\n\t\t\trow = img_testing_dset.shape[0] # Count current dataset rows\n\t\t\timg_testing_dset.resize(row + num_rows, axis=0) # Add new row\n\t\t\t# Insert data into new row\n\t\t\timg_testing_dset[row:(row + num_rows), :] = img\n\n\t# Save training set masks\n\tprint(\"Step 4 of 6. Save training set masks.\")\n\tfirst = True\n\tfor idx in tqdm(train_label_files):\n\n\t\tdata_filename = os.path.join(dataDir, idx)\n\t\tmsk = np.array(nib.load(data_filename).dataobj)\n\t\tmsk = preprocess_labels(msk)\n\t\tnum_rows = msk.shape[0]\n\n\t\tif first:\n\t\t\tfirst = False\n\t\t\tmsk_train_dset = hdf_file.create_dataset(\"msks_train\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t msk.shape,\n\t\t\t\t\t\t\t\t\t\t\t\t\t maxshape=(None,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t msk.shape[1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t msk.shape[2],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t msk.shape[3]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t dtype=float,\n\t\t\t\t\t\t\t\t\t\t\t\t\t compression=\"gzip\")\n\t\t\tmsk_train_dset[:] = msk\n\t\telse:\n\t\t\trow = msk_train_dset.shape[0] # Count current dataset rows\n\t\t\tmsk_train_dset.resize(row + num_rows, axis=0) # Add new row\n\t\t\t# Insert data into new row\n\t\t\tmsk_train_dset[row:(row + num_rows), :] = msk\n\n\t# Save testing/validation set masks\n\n\tprint(\"Step 5 of 6. Save validation set masks.\")\n\tfirst = True\n\tfor idx in tqdm(validate_label_files):\n\n\t\tdata_filename = os.path.join(dataDir, idx)\n\t\tmsk = np.array(nib.load(data_filename).dataobj)\n\t\tmsk = preprocess_labels(msk)\n\n\t\tnum_rows = msk.shape[0]\n\n\t\tif first:\n\t\t\tfirst = False\n\t\t\tmsk_validation_dset = hdf_file.create_dataset(\"msks_validation\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t msk.shape,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t maxshape=(None,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmsk.shape[1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmsk.shape[2],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmsk.shape[3]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t dtype=float,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t compression=\"gzip\")\n\t\t\tmsk_validation_dset[:] = msk\n\t\telse:\n\t\t\trow = msk_validation_dset.shape[0] # Count current dataset rows\n\t\t\tmsk_validation_dset.resize(row + num_rows, axis=0) # Add new row\n\t\t\t# Insert data into new row\n\t\t\tmsk_validation_dset[row:(row + num_rows), :] = msk\n\n\tprint(\"Step 6 of 6. Save testing set masks.\")\n\tfirst = True\n\tfor idx in tqdm(test_label_files):\n\n\t\tdata_filename = os.path.join(dataDir, idx)\n\t\tmsk = np.array(nib.load(data_filename).dataobj)\n\t\tmsk = preprocess_labels(msk)\n\n\t\tnum_rows = msk.shape[0]\n\n\t\tif first:\n\t\t\tfirst = False\n\t\t\tmsk_testing_dset = hdf_file.create_dataset(\"msks_testing\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t msk.shape,\n\t\t\t\t\t\t\t\t\t\t\t\t\t maxshape=(None,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t msk.shape[1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t msk.shape[2],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t msk.shape[3]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t dtype=float,\n\t\t\t\t\t\t\t\t\t\t\t\t\t compression=\"gzip\")\n\t\t\tmsk_testing_dset[:] = msk\n\t\telse:\n\t\t\trow = msk_testing_dset.shape[0] # Count current dataset rows\n\t\t\tmsk_testing_dset.resize(row + num_rows, axis=0) # Add new row\n\t\t\t# Insert data into new row\n\t\t\tmsk_testing_dset[row:(row + num_rows), :] = msk\n\n\thdf_file.close()\n\tprint(\"Finished processing.\")\n\tprint(\"HDF5 saved to {}\".format(filename))\n\n\nif __name__ == \"__main__\":\n\n\tprint(\"Converting Decathlon raw Nifti data files to single \"\n\t\t \"training and validation HDF5 data file.\")\n\tprint(args)\n\n\tsave_dir = os.path.join(\n\t\targs.save_path, \"{}x{}/\".format(args.resize, args.resize))\n\n\t# Create directory\n\ttry:\n\t\tos.makedirs(save_dir)\n\texcept OSError:\n\t\tif not os.path.isdir(save_dir):\n\t\t\traise\n\n\tfilename = os.path.join(save_dir, args.output_filename)\n\t# Check for existing output file and delete if exists\n\tif os.path.exists(filename):\n\t\tprint(\"Removing existing data file: {}\".format(filename))\n\t\tos.remove(filename)\n\n\t\"\"\"\n\tGet the training file names from the data directory.\n\tDecathlon should always have a dataset.json file in the\n\tsubdirectory which lists the experiment information including\n\tthe input and label filenames.\n\t\"\"\"\n\n\tjson_filename = os.path.join(args.data_path, \"dataset.json\")\n\n\ttry:\n\t\twith open(json_filename, \"r\") as fp:\n\t\t\texperiment_data = json.load(fp)\n\texcept IOError as e:\n\t\tprint(\"File {} doesn't exist. It should be part of the \"\n\t\t\t \"Decathlon directory\".format(json_filename))\n\n\t# Print information about the Decathlon experiment data\n\tprint(\"*\" * 30)\n\tprint(\"=\" * 30)\n\tprint(\"Dataset name: \", experiment_data[\"name\"])\n\tprint(\"Dataset description: \", experiment_data[\"description\"])\n\tprint(\"Tensor image size: \", experiment_data[\"tensorImageSize\"])\n\tprint(\"Dataset release: \", experiment_data[\"release\"])\n\tprint(\"Dataset reference: \", experiment_data[\"reference\"])\n\tprint(\"Dataset license: \", experiment_data[\"licence\"]) # sic\n\tprint(\"=\" * 30)\n\tprint(\"*\" * 30)\n\n\t\"\"\"\n\tRandomize the file list. Then separate into training and\n\tvalidation lists. We won't use the testing set since we\n\tdon't have ground truth masks for this; instead we'll\n\tsplit the validation set into separate test and validation\n\tsets.\n\t\"\"\"\n\t# Set the random seed so that always get same random mix\n\tnp.random.seed(816)\n\tnumFiles = experiment_data[\"numTraining\"]\n\tidxList = np.arange(numFiles) # List of file indices\n\trandomList = np.random.random(numFiles) # List of random numbers\n\t# Random number go from 0 to 1. So anything above\n\t# args.train_split is in the validation list.\n\ttrainList = idxList[randomList < args.split]\n\n\totherList = idxList[randomList >= args.split]\n\trandomList = np.random.random(len(otherList)) # List of random numbers\n\tvalidateList = otherList[randomList >= 0.5]\n\ttestList = otherList[randomList < 0.5]\n\n\tconvert_raw_data_to_hdf5(trainList, validateList, testList,\n\t experiment_data[\"training\"],\n\t filename, args.data_path,\n\t experiment_data)\n" ]
[ [ "numpy.expand_dims", "numpy.random.random", "numpy.random.seed", "numpy.arange", "numpy.std", "numpy.mean", "numpy.array" ] ]
anatfl/IML.HUJI
[ "b4a01e04fff4181837780cc603446fd73defd349" ]
[ "exercises/adaboost_scenario.py" ]
[ "import numpy as np\nfrom typing import Tuple\nfrom IMLearn.metalearners.adaboost import AdaBoost\nfrom IMLearn.learners.classifiers.decision_stump import DecisionStump\nfrom utils import *\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nfrom IMLearn.metrics import accuracy\n\n\ndef generate_data(n: int, noise_ratio: float) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Generate a dataset in R^2 of specified size\n\n Parameters\n ----------\n n: int\n Number of samples to generate\n\n noise_ratio: float\n Ratio of labels to invert\n\n Returns\n -------\n X: np.ndarray of shape (n_samples,2)\n Design matrix of samples\n\n y: np.ndarray of shape (n_samples,)\n Labels of samples\n \"\"\"\n '''\n generate samples X with shape: (num_samples, 2) and labels y with shape \n (num_samples).\n num_samples: the number of samples to generate\n noise_ratio: invert the label for this ratio of the samples\n '''\n X, y = np.random.rand(n, 2) * 2 - 1, np.ones(n)\n y[np.sum(X ** 2, axis=1) < 0.5 ** 2] = -1\n y[np.random.choice(n, int(noise_ratio * n))] *= -1\n return X, y\n\n\ndef fit_and_evaluate_adaboost(noise, n_learners=250, train_size=5000,\n test_size=500):\n (train_X, train_y), (test_X, test_y) =\\\n generate_data(train_size, noise), generate_data(test_size, noise)\n\n # Question 1: Train- and test errors of AdaBoost in noiseless case\n ad_obj = AdaBoost(DecisionStump, n_learners)\n ad_obj.fit(train_X, train_y)\n train_err = []\n test_err = []\n num_of_learners = np.arange(1, n_learners)\n for t in num_of_learners:\n train_err.append(ad_obj.partial_loss(train_X, train_y, t))\n test_err.append(ad_obj.partial_loss(test_X, test_y, t))\n fig1 = go.Figure()\n fig1.add_trace(go.Scatter(x=num_of_learners, y=train_err, mode=\"lines\",\n name=r'train samples'))\n fig1.add_trace(go.Scatter(x=num_of_learners, y=test_err, mode=\"lines\",\n name=r'test samples'))\n fig1.update_layout(title=\"(1) Adaboost error on train and test as function\"\n \" of number of learners\",\n xaxis_title=\"number of learners\",\n yaxis_title=\"error\")\n fig1.show()\n\n # Question 2: Plotting decision surfaces\n T = [5, 50, 100, 250]\n limits = np.array([np.r_[train_X, test_X].min(axis=0), np.r_[\n train_X, test_X].max(axis=0)]).T + np.array([-.1, .1])\n fig2 = make_subplots(rows=2, cols=2,\n subplot_titles=[rf\"{num} models\" for num in T],\n horizontal_spacing=0.01, vertical_spacing=.03)\n for i, t in enumerate(T):\n fig2.add_traces([decision_surface(\n lambda x: ad_obj.partial_predict(x, t),\n limits[0], limits[1], showscale=False),\n go.Scatter(x=test_X[:, 0], y=test_X[:, 1], mode=\"markers\",\n showlegend=False,\n marker=dict(color=test_y.astype(int),\n colorscale=[custom[0], custom[-1]],\n line=dict(color=\"black\", width=1)))],\n rows=(i // 2) + 1, cols=(i % 2) + 1)\n\n fig2.update_layout(\n title=r\"(2) Decision Boundaries Of Models according to number \"\n r\"of models\",\n margin=dict(t=100)).update_xaxes(visible=False).update_yaxes(\n visible=False)\n\n fig2.show()\n\n # Question 3: Decision surface of best performing ensemble\n min_loss_num = np.argmin([ad_obj.partial_loss(test_X, test_y, k) for\n k in np.arange(1, n_learners)]) + 1\n y_hat = ad_obj.partial_predict(test_X, min_loss_num)\n fig3 = go.Figure()\n fig3.add_traces([decision_surface(\n lambda x: ad_obj.partial_predict(x, min_loss_num),\n limits[0], limits[1], showscale=False),\n go.Scatter(x=test_X[:, 0], y=test_X[:, 1], mode=\"markers\",\n showlegend=False,\n marker=dict(color=test_y.astype(int),\n colorscale=[custom[0], custom[-1]],\n line=dict(color=\"black\", width=1)))])\n\n fig3.update_layout(\n title=rf\"(3) Decision Surface Of ensemble with minimal error,\"\n rf\" ensemble size: {min_loss_num}, \"\n rf\"accuracy: {accuracy(test_y, y_hat):.4f}\",\n margin=dict(t=100)).update_xaxes(visible=False).update_yaxes(\n visible=False)\n\n fig3.show()\n\n # Question 4: Decision surface with weighted samples\n fig4 = go.Figure()\n fig4.add_traces([decision_surface(ad_obj.predict, limits[0], limits[1],\n showscale=False),\n go.Scatter(x=train_X[:, 0], y=train_X[:, 1],\n mode=\"markers\",\n showlegend=False,\n marker=\n dict(color=train_y.astype(int),\n colorscale=[custom[0], custom[-1]],\n line=dict(color=\"black\", width=1),\n size=ad_obj.D_/np.max(ad_obj.D_) * 10))])\n\n fig4.update_layout(\n title=r\"(4) Decision Surface Of ensemble with size 250 and\"\n r\" weighted samples\",\n margin=dict(t=100)).update_xaxes(visible=False).update_yaxes(\n visible=False)\n fig4.show()\n\n\nif __name__ == '__main__':\n np.random.seed(0)\n fit_and_evaluate_adaboost(0.0)\n fit_and_evaluate_adaboost(0.4)\n" ]
[ [ "numpy.random.seed", "numpy.arange", "numpy.ones", "numpy.max", "numpy.random.rand", "numpy.array", "numpy.sum" ] ]
hrdipto/COVID19-L3-Net
[ "3ae2bba16c2ab0d96650e790dc2e6b896c377183" ]
[ "src/models/semseg.py" ]
[ "import torch\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import transforms\nimport os\nimport tqdm\nimport pylab as plt\nimport numpy as np\nimport scipy.sparse as sps\nfrom collections.abc import Sequence\nimport time\nfrom src import utils as ut\nfrom sklearn.metrics import confusion_matrix\nimport skimage\nfrom haven import haven_utils as hu\nfrom haven import haven_img as hi\nfrom torchvision import transforms\nfrom src import models\nfrom src.models import base_networks\n\nfrom skimage.segmentation import mark_boundaries\nfrom skimage.color import label2rgb\n\nfrom . import losses, metrics\n\n\nclass SemSeg(torch.nn.Module):\n def __init__(self, exp_dict, train_set):\n super().__init__()\n self.exp_dict = exp_dict\n self.n_classes = train_set.n_classes\n self.exp_dict = exp_dict\n\n self.model_base = models.base_networks.get_base(self.exp_dict['model'].get('base', 'unet2d'),\n self.exp_dict, n_classes=self.n_classes)\n\n if self.exp_dict[\"optimizer\"] == \"adam\":\n self.opt = torch.optim.Adam(\n self.model_base.parameters(), lr=self.exp_dict[\"lr\"], betas=(0.99, 0.999))\n\n elif self.exp_dict[\"optimizer\"] == \"sgd\":\n self.opt = torch.optim.SGD(\n self.model_base.parameters(), lr=self.exp_dict[\"lr\"])\n\n else:\n raise ValueError\n\n def get_state_dict(self):\n state_dict = {\"model\": self.model_base.state_dict(),\n \"opt\": self.opt.state_dict()}\n\n return state_dict\n\n def load_state_dict(self, state_dict):\n self.model_base.load_state_dict(state_dict[\"model\"])\n if 'opt' not in state_dict:\n return\n self.opt.load_state_dict(state_dict[\"opt\"])\n\n def train_on_loader(self, train_loader):\n self.train()\n\n n_batches = len(train_loader)\n\n pbar = tqdm.tqdm(desc=\"Training\", total=n_batches, leave=False)\n train_monitor = TrainMonitor()\n \n for batch in train_loader:\n score_dict = self.train_on_batch(batch)\n \n train_monitor.add(score_dict)\n msg = ' '.join([\"%s: %.3f\" % (k, v) for k,v in train_monitor.get_avg_score().items()])\n pbar.set_description('Training - %s' % msg)\n pbar.update(1)\n \n pbar.close()\n\n return train_monitor.get_avg_score()\n\n\n @torch.no_grad()\n def val_on_loader(self, val_loader, savedir_images=None, n_images=0, save_preds=False):\n self.eval()\n\n # metrics\n seg_monitor = metrics.SegMonitor()\n\n n_batches = len(val_loader)\n pbar = tqdm.tqdm(desc=\"Validating\", total=n_batches, leave=False)\n for i, batch in enumerate(val_loader):\n seg_monitor.val_on_batch(self, batch)\n \n pbar.update(1)\n\n if savedir_images and i < n_images:\n os.makedirs(savedir_images, exist_ok=True)\n self.vis_on_batch(batch, savedir_image=os.path.join(\n savedir_images, \"%d.jpg\" % i), save_preds=save_preds)\n pbar.set_description(\"Validating & Saving Images: %.4f mIoU\" %\n (seg_monitor.get_avg_score()['val_score']))\n else:\n pbar.set_description(\"Validating: %.4f mIoU\" %\n (seg_monitor.get_avg_score()['val_score']))\n\n pbar.close()\n val_dict = seg_monitor.get_avg_score()\n out_dict = {}\n for c in range(self.n_classes):\n out_dict['iou_group%d' % c] = val_dict['iou'][c]\n out_dict['val_score'] = val_dict['val_score']\n return out_dict\n\n def train_on_batch(self, batch, **extras):\n self.train()\n self.model_base.train()\n self.opt.zero_grad()\n\n images, labels = batch[\"images\"], batch[\"masks\"]\n images, labels = images.cuda(), labels.cuda()\n \n logits = self.model_base(images)\n # match image size\n logits = match_image_size(images, logits)\n # compute loss\n loss_name = self.exp_dict['model'].get('loss', 'cross_entropy')\n loss = losses.compute_loss(loss_name, logits, labels)\n \n if loss != 0:\n loss.backward()\n\n self.opt.step()\n\n return {\"train_loss\": float(loss)}\n\n def predict_on_batch(self, batch):\n images = batch[\"images\"].cuda()\n n = images.shape[0]\n logits = self.model_base.forward(images)\n # match image size\n logits = match_image_size(images, logits)\n return logits.argmax(dim=1)\n\n @torch.no_grad()\n def vis_on_batch(self, batch, savedir_image, save_preds=False):\n # os.makedirs(savedir_image, exist_ok=True)\n self.eval()\n # clf\n pred_mask = self.predict_on_batch(batch).cpu()\n # print(pred_mask.sum())\n img = hu.f2l(batch['images'])[0]\n img += abs(img.min())\n img /= img.max()\n img = img.repeat(1,1,3)\n\n mask_vis = batch[\"masks\"].clone().float()[0][..., None]\n mask_vis[mask_vis == 255] = 0\n\n pred_mask_vis = pred_mask.clone().float()[0][..., None]\n vmax = 0.1\n\n fig, ax_list = plt.subplots(ncols=3, nrows=1)\n ax_list[0].imshow(img[:, :, 0], cmap='gray',\n # interpolation='sinc', vmin=0, vmax=0.4\n )\n\n colors_all = np.array(['black', 'red', 'blue', 'green', 'purple'])\n colors = colors_all[np.unique(mask_vis).astype(int)]\n\n vis = label2rgb(mask_vis[:, :, 0].numpy(), image=img.numpy(\n ), colors=colors, bg_label=255, bg_color=None, alpha=0.6, kind='overlay')\n vis = mark_boundaries(\n vis, mask_vis[:, :, 0].numpy().astype('uint8'), color=(1, 1, 1))\n\n ax_list[1].imshow(vis, cmap='gray')\n\n colors = colors_all[np.unique(pred_mask_vis).astype(int)]\n vis = label2rgb(pred_mask_vis[:, :, 0].numpy(), image=img.numpy(\n ), colors=colors, bg_label=255, bg_color=None, alpha=0.6, kind='overlay')\n vis = mark_boundaries(\n vis, pred_mask_vis[:, :, 0].numpy().astype('uint8'), color=(1, 1, 1))\n\n ax_list[2].imshow(vis, cmap='gray')\n\n for i in range(1, self.n_classes):\n plt.plot([None], [None], label='group %d' % i, color=colors_all[i])\n # ax_list[1].axis('off')\n ax_list[0].grid()\n ax_list[1].grid()\n ax_list[2].grid()\n\n ax_list[0].tick_params(axis='x', labelsize=6)\n ax_list[0].tick_params(axis='y', labelsize=6)\n\n ax_list[1].tick_params(axis='x', labelsize=6)\n ax_list[1].tick_params(axis='y', labelsize=6)\n\n ax_list[2].tick_params(axis='x', labelsize=6)\n ax_list[2].tick_params(axis='y', labelsize=6)\n\n ax_list[0].set_title('Original image', fontsize=8)\n ax_list[1].set_title('Ground-truth', fontsize=8)\n ax_list[2].set_title('Prediction', fontsize=8)\n\n legend_kwargs = {\"loc\": 2, \"bbox_to_anchor\": (1.05, 1),\n 'borderaxespad': 0., \"ncol\": 1}\n ax_list[2].legend(fontsize=6, **legend_kwargs)\n plt.savefig(savedir_image.replace('.jpg', '.png'),\n bbox_inches='tight', dpi=300)\n plt.close()\n\n # save predictions\n if save_preds:\n from PIL import Image\n pred_dict = {}\n pred_numpy = pred_mask.cpu().numpy().squeeze().astype('uint8')\n\n uniques = np.unique(np.array(pred_numpy))\n # print(uniques)\n meta_dict = batch['meta'][0]\n\n for u in range(self.n_classes):\n meta_dict['gt_group%d_n_pixels'%u] = float((batch['masks']==u).float().sum())\n meta_dict['pred_group%d_n_pixels'%u] = float((pred_mask==u).float().sum())\n \n if u == 0:\n continue\n pred = Image.fromarray(pred_numpy==u)\n pred.save(savedir_image.replace('.jpg', '_group%d.png'%u))\n\n hu.save_json(savedir_image.replace('.jpg', '.json'), meta_dict)\n \n\ndef match_image_size(images, logits):\n h, w = images.shape[-2:]\n hl, wl = logits.shape[-2:]\n if hl != h or wl != w:\n logits = F.interpolate(logits, (h,w), mode='bilinear', align_corners=True)\n return logits\n\nclass TrainMonitor:\n def __init__(self):\n self.score_dict_sum = {}\n self.n = 0\n\n def add(self, score_dict):\n for k,v in score_dict.items():\n if k not in self.score_dict_sum:\n self.score_dict_sum[k] = score_dict[k]\n else:\n self.n += 1\n self.score_dict_sum[k] += score_dict[k]\n\n def get_avg_score(self):\n return {k:v/(self.n + 1) for k,v in self.score_dict_sum.items()}\n" ]
[ [ "numpy.array", "torch.no_grad", "torch.nn.functional.interpolate", "numpy.unique" ] ]
EthanChen1234/bert4keras
[ "149b8abe4f5696f7762f49547533873b935f85b9", "de66f9b66a57152816920a6b068a3f28648dd547" ]
[ "bert4keras/layers.py", "examples/task_image_caption.py" ]
[ "#! -*- coding: utf-8 -*-\n# 自定义层\n\nimport numpy as np\nimport tensorflow as tf\nfrom bert4keras.backend import keras, K\nfrom bert4keras.backend import sequence_masking\nfrom bert4keras.backend import recompute_grad\nfrom keras import initializers, activations\nfrom keras.layers import *\n\n\ndef integerize_shape(func):\n \"\"\"装饰器,保证input_shape一定是int或None\n \"\"\"\n def convert(item):\n if hasattr(item, '__iter__'):\n return [convert(i) for i in item]\n elif hasattr(item, 'value'):\n return item.value\n else:\n return item\n\n def new_func(self, input_shape):\n input_shape = convert(input_shape)\n return func(self, input_shape)\n\n return new_func\n\n\nif keras.__version__[-2:] != 'tf' and keras.__version__ < '2.3':\n\n class Layer(keras.layers.Layer):\n \"\"\"重新定义Layer,赋予“层中层”功能\n (仅keras 2.3以下版本需要)\n \"\"\"\n def __init__(self, **kwargs):\n super(Layer, self).__init__(**kwargs)\n self.supports_masking = True # 本项目的自定义层均可mask\n\n def __setattr__(self, name, value):\n if isinstance(value, keras.layers.Layer):\n if not hasattr(self, '_layers'):\n self._layers = []\n if value not in self._layers:\n self._layers.append(value)\n super(Layer, self).__setattr__(name, value)\n\n @property\n def trainable_weights(self):\n trainable = getattr(self, 'trainable', True)\n if trainable:\n trainable_weights = super(Layer, self).trainable_weights[:]\n for l in getattr(self, '_layers', []):\n trainable_weights += l.trainable_weights\n return trainable_weights\n else:\n return []\n\n @property\n def non_trainable_weights(self):\n trainable = getattr(self, 'trainable', True)\n non_trainable_weights = super(Layer, self).non_trainable_weights[:]\n for l in getattr(self, '_layers', []):\n if trainable:\n non_trainable_weights += l.non_trainable_weights\n else:\n non_trainable_weights += l.weights\n return non_trainable_weights\n\nelse:\n\n class Layer(keras.layers.Layer):\n def __init__(self, **kwargs):\n super(Layer, self).__init__(**kwargs)\n self.supports_masking = True # 本项目的自定义层均可mask\n\n\nclass Embedding(keras.layers.Embedding):\n \"\"\"拓展Embedding层\n \"\"\"\n def compute_mask(self, inputs, mask=None):\n \"\"\"为了适配T5,保证第一个token不被mask\n \"\"\"\n if self._current_mode == 'embedding':\n mask = super(Embedding, self).compute_mask(inputs, mask)\n if mask is not None:\n mask1 = K.ones_like(mask[:, :1], dtype='bool')\n mask2 = mask[:, 1:]\n return K.concatenate([mask1, mask2], 1)\n else:\n return mask\n\n def call(self, inputs, mode='embedding'):\n \"\"\"新增mode参数,可以为embedding或dense。如果为embedding,\n 则等价于普通Embedding层;如果为dense,则等价于无bias的Dense层。\n \"\"\"\n self._current_mode = mode\n if mode == 'embedding':\n return super(Embedding, self).call(inputs)\n else:\n kernel = K.transpose(self.embeddings)\n return K.dot(inputs, kernel)\n\n def compute_output_shape(self, input_shape):\n if self._current_mode == 'embedding':\n return super(Embedding, self).compute_output_shape(input_shape)\n else:\n return input_shape[:2] + (K.int_shape(self.embeddings)[0],)\n\n\nclass BiasAdd(Layer):\n \"\"\"加上偏置项\n \"\"\"\n @integerize_shape\n def build(self, input_shape):\n super(BiasAdd, self).build(input_shape)\n output_dim = input_shape[-1]\n self.bias = self.add_weight(\n name='bias',\n shape=(output_dim,),\n initializer='zeros',\n trainable=True\n )\n\n def call(self, inputs):\n return K.bias_add(inputs, self.bias)\n\n\nclass MultiHeadAttention(Layer):\n \"\"\"多头注意力机制\n \"\"\"\n def __init__(\n self,\n heads,\n head_size,\n key_size=None,\n use_bias=True,\n attention_scale=True,\n kernel_initializer='glorot_uniform',\n **kwargs\n ):\n super(MultiHeadAttention, self).__init__(**kwargs)\n self.heads = heads\n self.head_size = head_size\n self.out_dim = heads * head_size\n self.key_size = key_size or head_size\n self.use_bias = use_bias\n self.attention_scale = attention_scale\n self.kernel_initializer = initializers.get(kernel_initializer)\n\n def build(self, input_shape):\n super(MultiHeadAttention, self).build(input_shape)\n self.q_dense = Dense(\n units=self.key_size * self.heads,\n use_bias=self.use_bias,\n kernel_initializer=self.kernel_initializer\n )\n self.k_dense = Dense(\n units=self.key_size * self.heads,\n use_bias=self.use_bias,\n kernel_initializer=self.kernel_initializer\n )\n self.v_dense = Dense(\n units=self.out_dim,\n use_bias=self.use_bias,\n kernel_initializer=self.kernel_initializer\n )\n self.o_dense = Dense(\n units=self.out_dim,\n use_bias=self.use_bias,\n kernel_initializer=self.kernel_initializer\n )\n\n @recompute_grad\n def call(self, inputs, mask=None, a_mask=None, p_bias=None):\n \"\"\"实现多头注意力\n q_mask: 对输入的query序列的mask。\n 主要是将输出结果的padding部分置0。\n v_mask: 对输入的value序列的mask。\n 主要是防止attention读取到padding信息。\n a_mask: 对attention矩阵的mask。\n 不同的attention mask对应不同的应用。\n p_bias: 在attention里的位置偏置。\n 一般用来指定相对位置编码的种类。\n \"\"\"\n q, k, v = inputs[:3]\n q_mask, v_mask, n = None, None, 3\n if mask is not None:\n if mask[0] is not None:\n q_mask = K.cast(mask[0], K.floatx())\n if mask[2] is not None:\n v_mask = K.cast(mask[2], K.floatx())\n if a_mask:\n a_mask = inputs[n]\n n += 1\n # 线性变换\n qw = self.q_dense(q)\n kw = self.k_dense(k)\n vw = self.v_dense(v)\n # 形状变换\n qw = K.reshape(qw, (-1, K.shape(q)[1], self.heads, self.key_size))\n kw = K.reshape(kw, (-1, K.shape(k)[1], self.heads, self.key_size))\n vw = K.reshape(vw, (-1, K.shape(v)[1], self.heads, self.head_size))\n # Attention\n a = tf.einsum('bjhd,bkhd->bhjk', qw, kw)\n # 处理位置编码\n if p_bias == 'typical_relative':\n pos_embeddings = inputs[n]\n a = a + tf.einsum('bjhd,jkd->bhjk', qw, pos_embeddings)\n elif p_bias == 't5_relative':\n pos_embeddings = K.permute_dimensions(inputs[n], (2, 0, 1))\n a = a + K.expand_dims(pos_embeddings, 0)\n # Attention(续)\n if self.attention_scale:\n a = a / self.key_size**0.5\n a = sequence_masking(a, v_mask, 1, -1)\n if a_mask is not None:\n a = a - (1 - a_mask) * 1e12\n a = K.softmax(a)\n # 完成输出\n o = tf.einsum('bhjk,bkhd->bjhd', a, vw)\n if p_bias == 'typical_relative':\n o = o + tf.einsum('bhjk,jkd->bjhd', a, pos_embeddings)\n o = K.reshape(o, (-1, K.shape(o)[1], self.out_dim))\n o = self.o_dense(o)\n # 返回结果\n o = sequence_masking(o, q_mask, 0)\n return o\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0][0], input_shape[0][1], self.out_dim)\n\n def compute_mask(self, inputs, mask):\n return mask[0]\n\n def get_config(self):\n config = {\n 'heads': self.heads,\n 'head_size': self.head_size,\n 'key_size': self.key_size,\n 'use_bias': self.use_bias,\n 'attention_scale': self.attention_scale,\n 'kernel_initializer':\n initializers.serialize(self.kernel_initializer),\n }\n base_config = super(MultiHeadAttention, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass LayerNormalization(Layer):\n \"\"\"(Conditional) Layer Normalization\n hidden_*系列参数仅为有条件输入时(conditional=True)使用\n \"\"\"\n def __init__(\n self,\n center=True,\n scale=True,\n epsilon=None,\n conditional=False,\n hidden_units=None,\n hidden_activation='linear',\n hidden_initializer='glorot_uniform',\n **kwargs\n ):\n super(LayerNormalization, self).__init__(**kwargs)\n self.center = center\n self.scale = scale\n self.conditional = conditional\n self.hidden_units = hidden_units\n self.hidden_activation = activations.get(hidden_activation)\n self.hidden_initializer = initializers.get(hidden_initializer)\n self.epsilon = epsilon or 1e-12\n\n def compute_mask(self, inputs, mask=None):\n if self.conditional:\n masks = [K.expand_dims(m, 0) for m in mask if m is not None]\n if len(masks) == 0:\n return None\n else:\n return K.all(K.concatenate(masks, axis=0), axis=0)\n else:\n return mask\n\n def build(self, input_shape):\n super(LayerNormalization, self).build(input_shape)\n\n if self.conditional:\n shape = (input_shape[0][-1],)\n else:\n shape = (input_shape[-1],)\n\n if self.center:\n self.beta = self.add_weight(\n shape=shape, initializer='zeros', name='beta'\n )\n if self.scale:\n self.gamma = self.add_weight(\n shape=shape, initializer='ones', name='gamma'\n )\n\n if self.conditional:\n\n if self.hidden_units is not None:\n self.hidden_dense = Dense(\n units=self.hidden_units,\n activation=self.hidden_activation,\n use_bias=False,\n kernel_initializer=self.hidden_initializer\n )\n\n if self.center:\n self.beta_dense = Dense(\n units=shape[0], use_bias=False, kernel_initializer='zeros'\n )\n if self.scale:\n self.gamma_dense = Dense(\n units=shape[0], use_bias=False, kernel_initializer='zeros'\n )\n\n @recompute_grad\n def call(self, inputs):\n \"\"\"如果是条件Layer Norm,则默认以list为输入,第二个是condition\n \"\"\"\n if self.conditional:\n inputs, cond = inputs\n if self.hidden_units is not None:\n cond = self.hidden_dense(cond)\n for _ in range(K.ndim(inputs) - K.ndim(cond)):\n cond = K.expand_dims(cond, 1)\n if self.center:\n beta = self.beta_dense(cond) + self.beta\n if self.scale:\n gamma = self.gamma_dense(cond) + self.gamma\n else:\n if self.center:\n beta = self.beta\n if self.scale:\n gamma = self.gamma\n\n outputs = inputs\n if self.center:\n mean = K.mean(outputs, axis=-1, keepdims=True)\n outputs = outputs - mean\n if self.scale:\n variance = K.mean(K.square(outputs), axis=-1, keepdims=True)\n std = K.sqrt(variance + self.epsilon)\n outputs = outputs / std\n outputs = outputs * gamma\n if self.center:\n outputs = outputs + beta\n\n return outputs\n\n def compute_output_shape(self, input_shape):\n if self.conditional:\n return input_shape[0]\n else:\n return input_shape\n\n def get_config(self):\n config = {\n 'center': self.center,\n 'scale': self.scale,\n 'epsilon': self.epsilon,\n 'conditional': self.conditional,\n 'hidden_units': self.hidden_units,\n 'hidden_activation': activations.serialize(self.hidden_activation),\n 'hidden_initializer':\n initializers.serialize(self.hidden_initializer),\n }\n base_config = super(LayerNormalization, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass PositionEmbedding(Layer):\n \"\"\"定义位置Embedding,这里的Embedding是可训练的。\n \"\"\"\n def __init__(\n self,\n input_dim,\n output_dim,\n merge_mode='add',\n embeddings_initializer='zeros',\n custom_position_ids=False,\n **kwargs\n ):\n super(PositionEmbedding, self).__init__(**kwargs)\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.merge_mode = merge_mode\n self.embeddings_initializer = initializers.get(embeddings_initializer)\n self.custom_position_ids = custom_position_ids\n\n def build(self, input_shape):\n super(PositionEmbedding, self).build(input_shape)\n self.embeddings = self.add_weight(\n name='embeddings',\n shape=(self.input_dim, self.output_dim),\n initializer=self.embeddings_initializer\n )\n\n def call(self, inputs):\n \"\"\"如果custom_position_ids,那么第二个输入为自定义的位置id\n \"\"\"\n if self.custom_position_ids:\n inputs, position_ids = inputs\n if K.dtype(position_ids) != 'int32':\n position_ids = K.cast(position_ids, 'int32')\n pos_embeddings = K.gather(self.embeddings, position_ids)\n else:\n input_shape = K.shape(inputs)\n batch_size, seq_len = input_shape[0], input_shape[1]\n pos_embeddings = self.embeddings[:seq_len]\n pos_embeddings = K.expand_dims(pos_embeddings, 0)\n if self.merge_mode != 'add':\n pos_embeddings = K.tile(pos_embeddings, [batch_size, 1, 1])\n\n if self.merge_mode == 'add':\n return inputs + pos_embeddings\n else:\n return K.concatenate([inputs, pos_embeddings])\n\n def compute_output_shape(self, input_shape):\n if self.custom_position_ids:\n input_shape = input_shape[0]\n\n if self.merge_mode == 'add':\n return input_shape\n else:\n return input_shape[:2] + (input_shape[2] + self.output_dim,)\n\n def get_config(self):\n config = {\n 'input_dim': self.input_dim,\n 'output_dim': self.output_dim,\n 'merge_mode': self.merge_mode,\n 'embeddings_initializer':\n initializers.serialize(self.embeddings_initializer),\n 'custom_position_ids': self.custom_position_ids,\n }\n base_config = super(PositionEmbedding, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass RelativePositionEmbedding(Layer):\n \"\"\"相对位置编码\n 来自论文:https://arxiv.org/abs/1803.02155\n \"\"\"\n def __init__(\n self, input_dim, output_dim, embeddings_initializer='zeros', **kwargs\n ):\n super(RelativePositionEmbedding, self).__init__(**kwargs)\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.embeddings_initializer = initializers.get(embeddings_initializer)\n\n def build(self, input_shape):\n super(RelativePositionEmbedding, self).build(input_shape)\n self.embeddings = self.add_weight(\n name='embeddings',\n shape=(self.input_dim, self.output_dim),\n initializer=self.embeddings_initializer,\n )\n\n def call(self, inputs):\n pos_ids = self.compute_position_ids(inputs)\n return K.gather(self.embeddings, pos_ids)\n\n def compute_position_ids(self, inputs):\n q, v = inputs\n # 计算位置差\n q_idxs = K.arange(0, K.shape(q)[1], dtype='int32')\n q_idxs = K.expand_dims(q_idxs, 1)\n v_idxs = K.arange(0, K.shape(v)[1], dtype='int32')\n v_idxs = K.expand_dims(v_idxs, 0)\n pos_ids = v_idxs - q_idxs\n # 后处理操作\n max_position = (self.input_dim - 1) // 2\n pos_ids = K.clip(pos_ids, -max_position, max_position)\n pos_ids = pos_ids + max_position\n return pos_ids\n\n def compute_output_shape(self, input_shape):\n return (None, None, self.output_dim)\n\n def compute_mask(self, inputs, mask):\n return mask[0]\n\n def get_config(self):\n config = {\n 'input_dim': self.input_dim,\n 'output_dim': self.output_dim,\n 'embeddings_initializer':\n initializers.serialize(self.embeddings_initializer),\n }\n base_config = super(RelativePositionEmbedding, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass RelativePositionEmbeddingT5(RelativePositionEmbedding):\n \"\"\"Google T5的相对位置编码\n 来自论文:https://arxiv.org/abs/1910.10683\n \"\"\"\n def __init__(\n self,\n input_dim,\n output_dim,\n max_distance=128,\n bidirectional=True,\n embeddings_initializer='zeros',\n **kwargs\n ):\n super(RelativePositionEmbeddingT5,\n self).__init__(input_dim, output_dim, **kwargs)\n self.max_distance = max_distance\n self.bidirectional = bidirectional\n\n def compute_position_ids(self, inputs):\n \"\"\"T5的相对位置分桶(直接翻译自官方T5源码)\n \"\"\"\n q, v = inputs\n # 计算位置差\n q_idxs = K.arange(0, K.shape(q)[1], dtype='int32')\n q_idxs = K.expand_dims(q_idxs, 1)\n v_idxs = K.arange(0, K.shape(v)[1], dtype='int32')\n v_idxs = K.expand_dims(v_idxs, 0)\n pos_ids = v_idxs - q_idxs\n # 后处理操作\n num_buckets, max_distance = self.input_dim, self.max_distance\n ret = 0\n n = -pos_ids\n if self.bidirectional:\n num_buckets //= 2\n ret += K.cast(K.less(n, 0), 'int32') * num_buckets\n n = K.abs(n)\n else:\n n = K.maximum(n, 0)\n # now n is in the range [0, inf)\n max_exact = num_buckets // 2\n is_small = K.less(n, max_exact)\n val_if_large = max_exact + K.cast(\n K.log(K.cast(n, K.floatx()) / max_exact) /\n np.log(max_distance / max_exact) * (num_buckets - max_exact),\n 'int32',\n )\n val_if_large = K.minimum(val_if_large, num_buckets - 1)\n ret += K.switch(is_small, n, val_if_large)\n return ret\n\n def get_config(self):\n config = {\n 'max_distance': self.max_distance,\n 'bidirectional': self.bidirectional,\n }\n base_config = super(RelativePositionEmbeddingT5, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass FeedForward(Layer):\n \"\"\"FeedForward层,其实就是两个Dense层的叠加\n \"\"\"\n def __init__(\n self,\n units,\n activation='relu',\n use_bias=True,\n kernel_initializer='glorot_uniform',\n **kwargs\n ):\n super(FeedForward, self).__init__(**kwargs)\n self.units = units\n self.activation = activations.get(activation)\n self.use_bias = use_bias\n self.kernel_initializer = initializers.get(kernel_initializer)\n\n @integerize_shape\n def build(self, input_shape):\n super(FeedForward, self).build(input_shape)\n output_dim = input_shape[-1]\n\n self.dense_1 = Dense(\n units=self.units,\n activation=self.activation,\n use_bias=self.use_bias,\n kernel_initializer=self.kernel_initializer\n )\n self.dense_2 = Dense(\n units=output_dim,\n use_bias=self.use_bias,\n kernel_initializer=self.kernel_initializer\n )\n\n @recompute_grad\n def call(self, inputs):\n x = inputs\n x = self.dense_1(x)\n x = self.dense_2(x)\n return x\n\n def get_config(self):\n config = {\n 'units': self.units,\n 'activation': activations.serialize(self.activation),\n 'use_bias': self.use_bias,\n 'kernel_initializer':\n initializers.serialize(self.kernel_initializer),\n }\n base_config = super(FeedForward, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass ConditionalRandomField(Layer):\n \"\"\"纯Keras实现CRF层\n CRF层本质上是一个带训练参数的loss计算层。\n \"\"\"\n def __init__(self, lr_multiplier=1, **kwargs):\n super(ConditionalRandomField, self).__init__(**kwargs)\n self.lr_multiplier = lr_multiplier # 当前层学习率的放大倍数\n\n @integerize_shape\n def build(self, input_shape):\n super(ConditionalRandomField, self).build(input_shape)\n output_dim = input_shape[-1]\n self.trans = self.add_weight(\n name='trans',\n shape=(output_dim, output_dim),\n initializer='glorot_uniform',\n trainable=True\n )\n if self.lr_multiplier != 1:\n K.set_value(self.trans, K.eval(self.trans) / self.lr_multiplier)\n self.trans = self.lr_multiplier * self.trans\n\n def compute_mask(self, inputs, mask=None):\n return None\n\n def call(self, inputs, mask=None):\n if mask is not None:\n mask = K.cast(mask, K.floatx())\n\n return sequence_masking(inputs, mask, 1, 1)\n\n def target_score(self, y_true, y_pred):\n \"\"\"计算目标路径的相对概率(还没有归一化)\n 要点:逐标签得分,加上转移概率得分。\n \"\"\"\n point_score = tf.einsum('bni,bni->b', y_true, y_pred) # 逐标签得分\n trans_score = tf.einsum(\n 'bni,ij,bnj->b', y_true[:, :-1], self.trans, y_true[:, 1:]\n ) # 标签转移得分\n return point_score + trans_score\n\n def log_norm_step(self, inputs, states):\n \"\"\"递归计算归一化因子\n 要点:1、递归计算;2、用logsumexp避免溢出。\n \"\"\"\n inputs, mask = inputs[:, :-1], inputs[:, -1:]\n states = K.expand_dims(states[0], 2) # (batch_size, output_dim, 1)\n trans = K.expand_dims(self.trans, 0) # (1, output_dim, output_dim)\n outputs = tf.reduce_logsumexp(\n states + trans, 1\n ) # (batch_size, output_dim)\n outputs = outputs + inputs\n outputs = mask * outputs + (1 - mask) * states[:, :, 0]\n return outputs, [outputs]\n\n def dense_loss(self, y_true, y_pred):\n \"\"\"y_true需要是one hot形式\n \"\"\"\n # 导出mask并转换数据类型\n mask = K.all(K.greater(y_pred, -1e6), axis=2, keepdims=True)\n mask = K.cast(mask, K.floatx())\n # 计算目标分数\n y_true, y_pred = y_true * mask, y_pred * mask\n target_score = self.target_score(y_true, y_pred)\n # 递归计算log Z\n init_states = [y_pred[:, 0]]\n y_pred = K.concatenate([y_pred, mask], axis=2)\n input_length = K.int_shape(y_pred[:, 1:])[1]\n log_norm, _, _ = K.rnn(\n self.log_norm_step,\n y_pred[:, 1:],\n init_states,\n input_length=input_length\n ) # 最后一步的log Z向量\n log_norm = tf.reduce_logsumexp(log_norm, 1) # logsumexp得标量\n # 计算损失 -log p\n return log_norm - target_score\n\n def sparse_loss(self, y_true, y_pred):\n \"\"\"y_true需要是整数形式(非one hot)\n \"\"\"\n # y_true需要重新明确一下shape和dtype\n y_true = K.reshape(y_true, K.shape(y_pred)[:-1])\n y_true = K.cast(y_true, 'int32')\n # 转为one hot\n y_true = K.one_hot(y_true, K.shape(self.trans)[0])\n return self.dense_loss(y_true, y_pred)\n\n def dense_accuracy(self, y_true, y_pred):\n \"\"\"训练过程中显示逐帧准确率的函数,排除了mask的影响\n 此处y_true需要是one hot形式\n \"\"\"\n y_true = K.argmax(y_true, 2)\n return self.sparse_accuracy(y_true, y_pred)\n\n def sparse_accuracy(self, y_true, y_pred):\n \"\"\"训练过程中显示逐帧准确率的函数,排除了mask的影响\n 此处y_true需要是整数形式(非one hot)\n \"\"\"\n # 导出mask并转换数据类型\n mask = K.all(K.greater(y_pred, -1e6), axis=2)\n mask = K.cast(mask, K.floatx())\n # y_true需要重新明确一下shape和dtype\n y_true = K.reshape(y_true, K.shape(y_pred)[:-1])\n y_true = K.cast(y_true, 'int32')\n # 逐标签取最大来粗略评测训练效果\n y_pred = K.cast(K.argmax(y_pred, 2), 'int32')\n isequal = K.cast(K.equal(y_true, y_pred), K.floatx())\n return K.sum(isequal * mask) / K.sum(mask)\n\n def get_config(self):\n config = {\n 'lr_multiplier': self.lr_multiplier,\n }\n base_config = super(ConditionalRandomField, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass MaximumEntropyMarkovModel(Layer):\n \"\"\"(双向)最大熵隐马尔可夫模型\n 作用和用法都类似CRF,但是比CRF更快更简单。\n \"\"\"\n def __init__(self, lr_multiplier=1, hidden_dim=None, **kwargs):\n super(MaximumEntropyMarkovModel, self).__init__(**kwargs)\n self.lr_multiplier = lr_multiplier # 当前层学习率的放大倍数\n self.hidden_dim = hidden_dim # 如果非None,则将转移矩阵低秩分解\n\n @integerize_shape\n def build(self, input_shape):\n super(MaximumEntropyMarkovModel, self).build(input_shape)\n output_dim = input_shape[-1]\n\n if self.hidden_dim is None:\n self.trans = self.add_weight(\n name='trans',\n shape=(output_dim, output_dim),\n initializer='glorot_uniform',\n trainable=True\n )\n if self.lr_multiplier != 1:\n K.set_value(self.trans, K.eval(self.trans) / self.lr_multiplier)\n self.trans = self.lr_multiplier * self.trans\n else:\n self.l_trans = self.add_weight(\n name='l_trans',\n shape=(output_dim, self.hidden_dim),\n initializer='glorot_uniform',\n trainable=True\n )\n self.r_trans = self.add_weight(\n name='r_trans',\n shape=(output_dim, self.hidden_dim),\n initializer='glorot_uniform',\n trainable=True\n )\n\n if self.lr_multiplier != 1:\n K.set_value(\n self.l_trans,\n K.eval(self.l_trans) / self.lr_multiplier\n )\n self.l_trans = self.lr_multiplier * self.l_trans\n K.set_value(\n self.r_trans,\n K.eval(self.r_trans) / self.lr_multiplier\n )\n self.r_trans = self.lr_multiplier * self.r_trans\n\n def compute_mask(self, inputs, mask=None):\n return None\n\n def call(self, inputs, mask=None):\n if mask is not None:\n mask = K.cast(mask, K.floatx())\n\n return sequence_masking(inputs, mask, 1, 1)\n\n def reverse_sequence(self, inputs, mask=None):\n if mask is None:\n return [x[:, ::-1] for x in inputs]\n else:\n length = K.cast(K.sum(mask, 1), 'int32')\n return [tf.reverse_sequence(x, length, seq_axis=1) for x in inputs]\n\n def basic_loss(self, y_true, y_pred, go_backwards=False):\n \"\"\"y_true需要是整数形式(非one hot)\n \"\"\"\n # 导出mask并转换数据类型\n mask = K.all(K.greater(y_pred, -1e6), axis=2)\n mask = K.cast(mask, K.floatx())\n # y_true需要重新明确一下shape和dtype\n y_true = K.reshape(y_true, K.shape(y_pred)[:-1])\n y_true = K.cast(y_true, 'int32')\n # 反转相关\n if self.hidden_dim is None:\n if go_backwards: # 是否反转序列\n y_true, y_pred = self.reverse_sequence([y_true, y_pred], mask)\n trans = K.transpose(self.trans)\n else:\n trans = self.trans\n histoty = K.gather(trans, y_true)\n else:\n if go_backwards: # 是否反转序列\n y_true, y_pred = self.reverse_sequence([y_true, y_pred], mask)\n r_trans, l_trans = self.l_trans, self.r_trans\n else:\n l_trans, r_trans = self.l_trans, self.r_trans\n histoty = K.gather(l_trans, y_true)\n histoty = tf.einsum('bnd,kd->bnk', histoty, r_trans)\n # 计算loss\n histoty = K.concatenate([y_pred[:, :1], histoty[:, :-1]], 1)\n y_pred = (y_pred + histoty) / 2\n loss = K.sparse_categorical_crossentropy(\n y_true, y_pred, from_logits=True\n )\n return K.sum(loss * mask) / K.sum(mask)\n\n def sparse_loss(self, y_true, y_pred):\n \"\"\"y_true需要是整数形式(非one hot)\n \"\"\"\n loss = self.basic_loss(y_true, y_pred, False)\n loss = loss + self.basic_loss(y_true, y_pred, True)\n return loss / 2\n\n def dense_loss(self, y_true, y_pred):\n \"\"\"y_true需要是one hot形式\n \"\"\"\n y_true = K.argmax(y_true, 2)\n return self.sparse_loss(y_true, y_pred)\n\n def basic_accuracy(self, y_true, y_pred, go_backwards=False):\n \"\"\"训练过程中显示逐帧准确率的函数,排除了mask的影响\n 此处y_true需要是整数形式(非one hot)\n \"\"\"\n # 导出mask并转换数据类型\n mask = K.all(K.greater(y_pred, -1e6), axis=2)\n mask = K.cast(mask, K.floatx())\n # y_true需要重新明确一下shape和dtype\n y_true = K.reshape(y_true, K.shape(y_pred)[:-1])\n y_true = K.cast(y_true, 'int32')\n # 反转相关\n if self.hidden_dim is None:\n if go_backwards: # 是否反转序列\n y_true, y_pred = self.reverse_sequence([y_true, y_pred], mask)\n trans = K.transpose(self.trans)\n else:\n trans = self.trans\n histoty = K.gather(trans, y_true)\n else:\n if go_backwards: # 是否反转序列\n y_true, y_pred = self.reverse_sequence([y_true, y_pred], mask)\n r_trans, l_trans = self.l_trans, self.r_trans\n else:\n l_trans, r_trans = self.l_trans, self.r_trans\n histoty = K.gather(l_trans, y_true)\n histoty = tf.einsum('bnd,kd->bnk', histoty, r_trans)\n # 计算逐标签accuracy\n histoty = K.concatenate([y_pred[:, :1], histoty[:, :-1]], 1)\n y_pred = (y_pred + histoty) / 2\n y_pred = K.cast(K.argmax(y_pred, 2), 'int32')\n isequal = K.cast(K.equal(y_true, y_pred), K.floatx())\n return K.sum(isequal * mask) / K.sum(mask)\n\n def sparse_accuracy(self, y_true, y_pred):\n \"\"\"训练过程中显示逐帧准确率的函数,排除了mask的影响\n 此处y_true需要是整数形式(非one hot)\n \"\"\"\n accuracy = self.basic_accuracy(y_true, y_pred, False)\n accuracy = accuracy + self.basic_accuracy(y_true, y_pred, True)\n return accuracy / 2\n\n def dense_accuracy(self, y_true, y_pred):\n \"\"\"训练过程中显示逐帧准确率的函数,排除了mask的影响\n 此处y_true需要是one hot形式\n \"\"\"\n y_true = K.argmax(y_true, 2)\n return self.sparse_accuracy(y_true, y_pred)\n\n def get_config(self):\n config = {\n 'lr_multiplier': self.lr_multiplier,\n 'hidden_dim': self.hidden_dim,\n }\n base_config = super(MaximumEntropyMarkovModel, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass Loss(Layer):\n \"\"\"特殊的层,用来定义复杂loss\n \"\"\"\n def __init__(self, output_axis=None, **kwargs):\n super(Loss, self).__init__(**kwargs)\n self.output_axis = output_axis\n\n def call(self, inputs, mask=None):\n loss = self.compute_loss(inputs, mask)\n self.add_loss(loss)\n if self.output_axis is None:\n return inputs\n elif isinstance(self.output_axis, list):\n return [inputs[i] for i in self.output_axis]\n else:\n return inputs[self.output_axis]\n\n def compute_loss(self, inputs, mask=None):\n raise NotImplementedError\n\n def compute_output_shape(self, input_shape):\n if self.output_axis is None:\n return input_shape\n elif isinstance(self.output_axis, list):\n return [input_shape[i] for i in self.output_axis]\n else:\n return input_shape[self.output_axis]\n\n def get_config(self):\n config = {\n 'output_axis': self.output_axis,\n }\n base_config = super(Loss, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\ncustom_objects = {\n 'Embedding': Embedding,\n 'BiasAdd': BiasAdd,\n 'MultiHeadAttention': MultiHeadAttention,\n 'LayerNormalization': LayerNormalization,\n 'PositionEmbedding': PositionEmbedding,\n 'RelativePositionEmbedding': RelativePositionEmbedding,\n 'RelativePositionEmbeddingT5': RelativePositionEmbeddingT5,\n 'FeedForward': FeedForward,\n 'ConditionalRandomField': ConditionalRandomField,\n 'MaximumEntropyMarkovModel': MaximumEntropyMarkovModel,\n 'Loss': Loss,\n}\n\nkeras.utils.get_custom_objects().update(custom_objects)\n", "#! -*- coding: utf-8 -*-\n# bert做image caption任务,coco数据集\n# 通过Conditional Layer Normalization融入条件信息\n# 请参考:https://kexue.fm/archives/7124\n\nfrom __future__ import print_function\nimport json\nimport numpy as np\nfrom bert4keras.backend import keras, K\nfrom bert4keras.layers import Loss\nfrom bert4keras.models import build_transformer_model\nfrom bert4keras.tokenizers import Tokenizer, load_vocab\nfrom bert4keras.optimizers import Adam\nfrom bert4keras.snippets import sequence_padding, is_string\nfrom bert4keras.snippets import DataGenerator, AutoRegressiveDecoder\nfrom keras.models import Model\nimport cv2\n\n# 模型配置\nmaxlen = 64\nbatch_size = 32\nsteps_per_epoch = 1000\nepochs = 10000\n\n# bert配置\nconfig_path = '/root/kg/bert/uncased_L-12_H-768_A-12/bert_config.json'\ncheckpoint_path = '/root/kg/bert/uncased_L-12_H-768_A-12/bert_model.ckpt'\ndict_path = '/root/kg/bert/uncased_L-12_H-768_A-12/vocab.txt'\n\n# 加载并精简词表,建立分词器\ntoken_dict, keep_tokens = load_vocab(\n dict_path=dict_path,\n simplified=True,\n startswith=['[PAD]', '[UNK]', '[CLS]', '[SEP]'],\n)\ntokenizer = Tokenizer(token_dict, do_lower_case=True)\n\n\ndef read_caption(f):\n \"\"\"读取并整理COCO的Caption数据\n \"\"\"\n data = json.load(open(f))\n images = {}\n for img in data['images']:\n images[img['id']] = {\n 'image_id': img['file_name'],\n 'caption': [],\n 'url': img['coco_url']\n }\n for caption in data['annotations']:\n images[caption['image_id']]['caption'].append(caption['caption'])\n return list(images.values())\n\n\ndef read_image(f):\n \"\"\"单图读取函数(对非方形的图片进行白色填充,使其变为方形)\n \"\"\"\n img = cv2.imread(f)\n height, width = img.shape[:2]\n if height > width:\n height, width = img_size, width * img_size // height\n img = cv2.resize(img, (width, height))\n delta = (height - width) // 2\n img = cv2.copyMakeBorder(\n img,\n top=0,\n bottom=0,\n left=delta,\n right=height - width - delta,\n borderType=cv2.BORDER_CONSTANT,\n value=[255, 255, 255]\n )\n else:\n height, width = height * img_size // width, img_size\n img = cv2.resize(img, (width, height))\n delta = (width - height) // 2\n img = cv2.copyMakeBorder(\n img,\n top=delta,\n bottom=width - height - delta,\n left=0,\n right=0,\n borderType=cv2.BORDER_CONSTANT,\n value=[255, 255, 255]\n )\n img = img.astype('float32')\n return img[..., ::-1] # cv2的读取模式为BGR,但keras的模型要求为RGB\n\n\nclass data_generator(DataGenerator):\n \"\"\"数据生成器\n \"\"\"\n def __iter__(self, random=False):\n batch_images, batch_token_ids, batch_segment_ids = [], [], []\n for is_end, D in self.sample(random):\n img = '/root/caption/coco/train2014/%s' % D['image_id']\n caption = np.random.choice(D['caption'])\n token_ids, segment_ids = tokenizer.encode(\n caption, max_length=maxlen\n )\n batch_images.append(read_image(img))\n batch_token_ids.append(token_ids)\n batch_segment_ids.append(segment_ids)\n if len(batch_token_ids) == self.batch_size or is_end:\n batch_images = np.array(batch_images)\n batch_images = preprocess_input(batch_images)\n batch_token_ids = sequence_padding(batch_token_ids)\n batch_segment_ids = sequence_padding(batch_segment_ids)\n yield [batch_token_ids, batch_segment_ids, batch_images], None\n batch_images, batch_token_ids, batch_segment_ids = [], [], []\n\n\n# 加载数据\ntrain_data = read_caption(\n '/root/caption/coco/annotations/captions_train2014.json'\n)\nvalid_data = read_caption(\n '/root/caption/coco/annotations/captions_val2014.json'\n)\n\n\nclass CrossEntropy(Loss):\n \"\"\"交叉熵作为loss,并mask掉padding部分\n \"\"\"\n def compute_loss(self, inputs, mask=None):\n y_true, y_pred = inputs\n if mask[1] is None:\n y_mask = 1.0\n else:\n y_mask = K.cast(mask[1], K.floatx())[:, 1:]\n y_true = y_true[:, 1:] # 目标token_ids\n y_pred = y_pred[:, :-1] # 预测序列,错开一位\n loss = K.sparse_categorical_crossentropy(y_true, y_pred)\n loss = K.sum(loss * y_mask) / K.sum(y_mask)\n return loss\n\n\n# 图像模型\nMobileNetV2 = keras.applications.mobilenet_v2.MobileNetV2\npreprocess_input = keras.applications.mobilenet_v2.preprocess_input\nimage_model = MobileNetV2(include_top=False, pooling='avg')\nimg_size = 299\n\n# Bert模型\nmodel = build_transformer_model(\n config_path,\n checkpoint_path,\n application='lm',\n keep_tokens=keep_tokens, # 只保留keep_tokens中的字,精简原字表\n layer_norm_cond=image_model.output,\n layer_norm_cond_hidden_size=128,\n layer_norm_cond_hidden_act='swish',\n additional_input_layers=image_model.input,\n)\n\noutput = CrossEntropy(1)([model.inputs[0], model.outputs[0]])\n\nmodel = Model(model.inputs, output)\nmodel.compile(optimizer=Adam(1e-5))\nmodel.summary()\n\n\nclass AutoCaption(AutoRegressiveDecoder):\n \"\"\"img2seq解码器\n \"\"\"\n @AutoRegressiveDecoder.set_rtype('probas')\n def predict(self, inputs, output_ids, step):\n image = inputs[0]\n token_ids = output_ids\n segment_ids = np.zeros_like(token_ids)\n return model.predict([token_ids, segment_ids, image])[:, -1]\n\n def generate(self, image, topk=1):\n if is_string(image):\n image = read_image(image)\n image = preprocess_input(image)\n output_ids = self.beam_search([image], topk) # 基于beam search\n return tokenizer.decode(output_ids)\n\n\nautocaption = AutoCaption(\n start_id=tokenizer._token_start_id,\n end_id=tokenizer._token_end_id,\n maxlen=maxlen\n)\n\n\ndef just_show():\n samples = [valid_data[i] for i in np.random.choice(len(valid_data), 2)]\n for D in samples:\n img = '/root/caption/coco/val2014/%s' % D['image_id']\n print(u'image_id:', D['image_id'])\n print(u'url:', D['url'])\n print(u'predict:', autocaption.generate(img))\n print(u'references:', D['caption'])\n print()\n\n\nclass Evaluate(keras.callbacks.Callback):\n def __init__(self):\n self.lowest = 1e10\n\n def on_epoch_end(self, epoch, logs=None):\n # 保存最优\n if logs['loss'] <= self.lowest:\n self.lowest = logs['loss']\n model.save_weights('./best_model.weights')\n # 演示效果\n just_show()\n\n\nif __name__ == '__main__':\n\n evaluator = Evaluate()\n train_generator = data_generator(train_data, batch_size)\n\n model.fit_generator(\n train_generator.forfit(),\n steps_per_epoch=steps_per_epoch,\n epochs=epochs,\n callbacks=[evaluator]\n )\n\nelse:\n\n model.load_weights('./best_model.weights')\n\"\"\"\nimage_id: COCO_val2014_000000524611.jpg\nurl: http://images.cocodataset.org/val2014/COCO_val2014_000000524611.jpg\npredict: a train that is sitting on the tracks.\nreferences: [u'A train carrying chemical tanks traveling past a water tower.', u'Dual train tracks with a train on one of them and a water tower in the background.', u'a train some trees and a water tower ', u'Train on tracks with water tower for Davis Junction in the rear.', u'A train on a train track going through a bunch of trees.']\n\nimage_id: COCO_val2014_000000202923.jpg\nurl: http://images.cocodataset.org/val2014/COCO_val2014_000000202923.jpg\npredict: a baseball game in progress with the batter up to plate.\nreferences: [u'Batter, catcher, and umpire anticipating the next pitch.', u'A baseball player holding a baseball bat in the game.', u'A baseball player stands ready at the plate.', u'Baseball players on the field ready for the pitch.', u'A view from behind a mesh fence of a baseball game.']\n\"\"\"\n" ]
[ [ "numpy.log", "tensorflow.reverse_sequence", "tensorflow.reduce_logsumexp", "tensorflow.einsum" ], [ "numpy.array", "numpy.zeros_like", "numpy.random.choice" ] ]
ligongzzz/MCM2020_Code
[ "7e5e6f9a6b09b3eb7e21774535c977ba6e974d79" ]
[ "problem_visual3.py" ]
[ "# Plays of the season.\nimport numpy as np\nimport cv2\nimport csv\nimport matplotlib.pyplot as plt\nimport matlab.engine\nplt.rc('font', family='Times New Roman')\n\n\n# Read the csv file.\ncsv_reader = csv.reader(open('./data/passingevents.csv'))\n\n# The first match.(First match and self passing only.)\npassing_list = [row for row in csv_reader if row[1] == 'Huskies']\n# Fix the time of 2H.\nfor p in passing_list:\n if p[4] == '2H':\n p[5] = str(float(p[5])+2700)\npassing_cnt = len(passing_list)\n\n# Count the player's average pos in a single play.\nplayer_map = {}\n\nt = 0\npass_i = 0\n\n\ndef add_to_player_map(player: str, x, y):\n '''\n A function to add the position to the player.\n '''\n if player_map.get(player) is None:\n player_map[player] = {'x': x, 'y': y, 'cnt': 1}\n else:\n player_map[player]['x'] += x\n player_map[player]['y'] += y\n player_map[player]['cnt'] += 1\n\n\ncenter_x = []\ncenter_y = []\nds = []\nspd = []\n\nwhile pass_i < len(passing_list):\n t += 1\n dx_sum = 0.0\n dy_sum = 0.0\n player_map.clear()\n while pass_i < len(passing_list) and float(passing_list[pass_i][0]) <= t:\n cur_pass = passing_list[pass_i]\n add_to_player_map(cur_pass[2], float(cur_pass[7]), float(cur_pass[8]))\n add_to_player_map(cur_pass[3], float(cur_pass[9]), float(cur_pass[10]))\n\n dx_sum += abs(float(cur_pass[9]) - float(cur_pass[7]))\n dy_sum += abs(float(cur_pass[10]) - float(cur_pass[8]))\n pass_i += 1\n\n # Caculate the center x.\n x_sum = 0\n y_sum = 0\n d_sum = 0\n\n for k, v in player_map.items():\n x_sum += v['x'] / v['cnt']\n y_sum += v['y'] / v['cnt']\n center_x.append(x_sum / len(player_map))\n center_y.append(y_sum / len(player_map))\n\n for k, v in player_map.items():\n d_sum += (v['x'] / v['cnt'] - center_x[-1]) ** 2 + \\\n (v['y'] / v['cnt'] - center_y[-1]) ** 2\n ds.append(d_sum / len(player_map))\n spd.append(dx_sum / dy_sum)\n\n# Plot\nplt.plot(center_x, color='blue', linewidth=1.0)\nplt.ylim((0, 100))\nplt.xlabel('Match ID')\nplt.ylabel('x')\nplt.title('<X> pos')\nplt.show()\n\nplt.plot(center_y, color='blue', linewidth=1.0)\nplt.ylim((0, 100))\nplt.xlabel('Match ID')\nplt.ylabel('y')\nplt.title('<Y> pos')\nplt.show()\n\nplt.plot(ds, color='blue', linewidth=1.0)\nplt.ylim((0, 1300))\nplt.xlabel('Match ID')\nplt.ylabel('ds')\nplt.title('D')\nplt.show()\n\nplt.plot(spd, color='blue', linewidth=1.0)\nplt.ylim((0, 1.0))\nplt.xlabel('Match ID')\nplt.ylabel('speed')\nplt.title('Speed')\nplt.show()\n" ]
[ [ "matplotlib.pyplot.title", "matplotlib.pyplot.ylim", "matplotlib.pyplot.rc", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
PujithaKurakula/BreastCancer-android-python-ml-app
[ "ae1cd5b683a13e72169eda400322b3e17bb48bd9", "ae1cd5b683a13e72169eda400322b3e17bb48bd9" ]
[ "python-flask/app.py", "python-flask/model.py" ]
[ "import numpy as np\nimport pandas as pd\nfrom flask import Flask, request, render_template\n\nimport pickle\n\napp = Flask(__name__)\nmodel = pickle.load(open('model.pkl', 'rb'))\n\[email protected]('/')\ndef home():\n \n return render_template('h.html')\[email protected]('/detect')\ndef detect():\n return render_template('index.html')\[email protected]('/riskpred')\ndef riskpred():\n return render_template('r.html')\n\n\n\[email protected]('/predict',methods=['POST'])\ndef predict():\n meantexture=request.json['meantexture']\n meanperimeter=request.json['meanperimeter']\n meansmoothness=request.json['meansmoothness']\n meancompactness=request.json['meancompactness']\n meanconcavity=request.json['meanconcavity']\n meanconcavepoints=request.json['meanconcavepoints']\n meansymmetry=request.json['meansymmetry']\n meanfractaldimension=request.json['meanfractaldimension']\n radiuserror=request.json['radiuserror']\n textureerror=request.json['textureerror']\n perimetererror=request.json['perimetererror']\n areaerror=request.json['areaerror']\n smoothnesserror=request.json['smoothnesserror']\n compactnesserror=request.json['compactnesserror']\n concavityerror=request.json['concavityerror']\n concavepointserror=request.json['concavepointserror']\n symmetryerror=request.json['symmetryerror']\n fractaldimensionerror=request.json['fractaldimensionerror']\n worstradius=request.json['worstradius']\n worsttexture=request.json['worsttexture']\n worstsmoothness=request.json['worstsmoothness']\n worstcompactness=request.json['worstcompactness']\n worstconcavity=request.json['worstconcavity']\n worstconcavepoints=request.json['worstconcavepoints']\n worstsymmetry=request.json['worstsymmetry']\n worstfractaldimension=request.json['worstfractaldimension']\n \n datavalues = [[meantexture,meanperimeter,meansmoothness,meancompactness,meanconcavity,\n meanconcavepoints,meansymmetry,meanfractaldimension,\n radiuserror,textureerror,perimetererror,areaerror,\n smoothnesserror,compactnesserror,concavityerror,\n concavepointserror,symmetryerror,fractaldimensionerror,\n worstradius,worsttexture,worstsmoothness,worstcompactness,worstconcavity,\n worstconcavepoints,worstsymmetry,worstfractaldimension ]]\n\t \n\t \n data=pd.DataFrame(datavalues,columns=['meantexture','meanperimeter','meansmoothness', 'meancompactness', 'meanconcavity','meanconcavepoints', 'meansymmetry', 'meanfractaldimension','radiuserror', 'textureerror', 'perimetererror', 'areaerror','smoothnesserror', 'compactnesserror', 'concavityerror','concavepointserror', 'symmetryerror', 'fractaldimensionerror','worstradius', 'worsttexture','worstsmoothness', 'worstcompactness', 'worstconcavity','worstconcavepoints', 'worstsymmetry', 'worstfractaldimension'])\n \n \n res=model.predict(data)\n output=res[0]\n \n if output == 0:\n res_val = \" breast cancer \"\n else:\n res_val = \"no breast cancer\"\n \n\n return res_val\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n ", "import sys\nsys.path\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport pickle\ndata=pd.read_csv(\"./breast_cancer_dataframe.csv\")\nprint(data.columns)\ndata=data.iloc[:,2:]\nprint(data.columns)\n\ndef remove_outlier(df_in, col_name):\n q1 = df_in[col_name].quantile(0.25)\n q3 = df_in[col_name].quantile(0.75)\n iqr = q3-q1 #Interquartile range\n fence_low = q1-1.5*iqr\n fence_high = q3+1.5*iqr\n df_out = df_in.loc[(df_in[col_name] > fence_low) & (df_in[col_name] < fence_high)]\n return df_out\nl=['mean area','area error','worst area']\nfor i in l:\n data=remove_outlier(data,i)\nupper = data.corr().where(np.triu(np.ones(data.corr().shape),\n k=1).astype(np.bool))\nto_drop = [column for column in upper.columns if any(upper[column] > 0.97)]\nprint(to_drop)\nprint(data.columns)\ndata = data.drop(data[to_drop], axis=1)\nplt.figure(figsize=(50,50))\ny=data.target\nx=data.drop(['target'],axis=1)\nfrom sklearn.model_selection import train_test_split\npx_train,x_test,py_train,y_test=train_test_split(x, y, test_size=0.2, random_state=5)\nfrom imblearn.over_sampling import SMOTE\nsm = SMOTE(random_state = 2)\nx_train, y_train = sm.fit_sample(px_train, py_train.ravel())\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(x_train, y_train, test_size = 0.2, random_state= 5)\nfrom sklearn.ensemble import RandomForestClassifier\nrf_classifier = RandomForestClassifier(n_estimators = 20, criterion = 'entropy', random_state = 51)\nrf_classifier.fit(X_train, y_train)\ny_pred_rf = rf_classifier.predict(X_test)\npickle.dump(rf_classifier, open('model.pkl','wb'))\n\n # Loading model to compare the results\nmodel = pickle.load(open('model.pkl','rb'))\nprint(model.predict([[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]]))\n" ]
[ [ "pandas.DataFrame" ], [ "pandas.read_csv", "sklearn.model_selection.train_test_split", "sklearn.ensemble.RandomForestClassifier", "matplotlib.pyplot.figure" ] ]
jacob-heglund/ece598-xmase
[ "7345b713fbb6d4f84c795cd52778312058cd80f8" ]
[ "PPO.py" ]
[ "from numpy.core.fromnumeric import trace\nimport torch\nimport torch.nn as nn\nfrom torch.distributions import MultivariateNormal\nfrom torch.distributions import Categorical\n\nimport pdb\n\n################################## set device ##################################\n\nprint(\"============================================================================================\")\n\n# set device to cpu or cuda\ndevice = torch.device('cpu')\n\nif(torch.cuda.is_available()):\n device = torch.device('cuda:0')\n torch.cuda.empty_cache()\n print(\"Device set to : \" + str(torch.cuda.get_device_name(device)))\nelse:\n print(\"Device set to : cpu\")\n\n################################## PPO Policy ##################################\nclass RolloutBuffer:\n def __init__(self):\n self.actions = []\n self.states = []\n self.logprobs = []\n self.rewards = []\n self.is_terminals = []\n\n\n def clear(self):\n del self.actions[:]\n del self.states[:]\n del self.logprobs[:]\n del self.rewards[:]\n del self.is_terminals[:]\n\n\nclass ActorCritic(nn.Module):\n def __init__(self, obs_dim, obs_size, action_dim, has_continuous_action_space, action_std_init):\n super(ActorCritic, self).__init__()\n self.obs_dim = obs_dim\n self.shap_mode = True\n self.has_continuous_action_space = has_continuous_action_space\n\n if has_continuous_action_space:\n self.action_dim = action_dim\n self.action_var = torch.full((action_dim,), action_std_init * action_std_init).to(device)\n\n if has_continuous_action_space :\n self.actor = nn.Sequential(\n nn.Linear(obs_dim, 64),\n nn.Tanh(),\n nn.Linear(64, 64),\n nn.Tanh(),\n nn.Linear(64, action_dim),\n nn.Softmax(dim=-1)\n )\n else:\n # self.actor = nn.Sequential(\n # nn.Linear(obs_dim, 64),\n # nn.Tanh(),\n # nn.Linear(64, 64),\n # nn.Tanh(),\n # nn.Linear(64, action_dim),\n # )\n\n self.actor = nn.Sequential(\n nn.Conv2d(self.obs_dim, 32, kernel_size=4, padding=1),\n nn.ReLU(),\n nn.Conv2d(32, 64, kernel_size=4, padding=1),\n nn.ReLU(),\n nn.Conv2d(64, 64, kernel_size=3, padding=2),\n nn.ReLU(),\n nn.Flatten(),\n nn.Linear(64 * obs_size * obs_size, action_dim),\n nn.Softmax(dim=-1)\n )\n\n # self.critic = nn.Sequential(\n # nn.Linear(obs_dim, 64),\n # nn.Tanh(),\n # nn.Linear(64, 64),\n # nn.Tanh(),\n # nn.Linear(64, 1)\n # )\n\n self.critic = nn.Sequential(\n nn.Conv2d(self.obs_dim, 32, kernel_size=4, padding=1),\n nn.ReLU(),\n nn.Conv2d(32, 64, kernel_size=4, padding=1),\n nn.ReLU(),\n nn.Conv2d(64, 64, kernel_size=3, padding=2),\n nn.ReLU(),\n nn.Flatten(),\n nn.Linear(64 * obs_size * obs_size, 1),\n )\n\n # self.relu = nn.ReLU()\n # self.softmax = nn.Softmax(dim=-1)\n # self.flatten = nn.Flatten()\n # self.conv1_actor = nn.Conv2d(self.obs_dim, 32, kernel_size=4, padding=1)\n # self.conv2_actor = nn.Conv2d(32, 64, kernel_size=4, padding=1)\n # self.conv3_actor = nn.Conv2d(64, 64, kernel_size=3, padding=2)\n # self.mlp_actor = nn.Linear(64 * obs_size * obs_size, action_dim)\n\n # def actor(self, obs):\n # # actor\n # tmp = self.relu(self.conv1_actor(obs.permute(0, 3, 1, 2)))\n # tmp = self.relu(self.conv2_actor(tmp))\n # tmp = self.conv3_actor(tmp)\n # tmp = self.mlp_actor(self.flatten(tmp))\n # tmp = self.softmax(tmp)\n\n # return tmp\n\n def set_action_std(self, new_action_std):\n\n if self.has_continuous_action_space:\n self.action_var = torch.full((self.action_dim,), new_action_std * new_action_std).to(device)\n else:\n print(\"--------------------------------------------------------------------------------------------\")\n print(\"WARNING : Calling ActorCritic::set_action_std() on discrete action space policy\")\n print(\"--------------------------------------------------------------------------------------------\")\n\n\n def forward(self):\n raise NotImplementedError\n\n\n def act(self, state):\n if len(state.shape) == 3:\n state = torch.unsqueeze(state, 0)\n if self.has_continuous_action_space:\n action_mean = self.actor(state)\n cov_mat = torch.diag(self.action_var).unsqueeze(dim=0)\n dist = MultivariateNormal(action_mean, cov_mat)\n else:\n action_probs = self.actor(state.permute(0, 3, 1, 2))\n dist = Categorical(action_probs)\n\n action = dist.sample()\n action_logprob = dist.log_prob(action)\n\n return action.detach(), action_logprob.detach(), action_probs.detach()\n\n\n def evaluate(self, state, action):\n if len(state.shape) == 3:\n state = torch.unsqueeze(state, 0)\n\n if self.has_continuous_action_space:\n action_mean = self.actor(state)\n\n action_var = self.action_var.expand_as(action_mean)\n cov_mat = torch.diag_embed(action_var).to(device)\n dist = MultivariateNormal(action_mean, cov_mat)\n\n # For Single Action Environments.\n if self.action_dim == 1:\n action = action.reshape(-1, self.action_dim)\n else:\n action_probs = self.actor(state.permute(0, 3, 1, 2))\n dist = Categorical(action_probs)\n action_logprobs = dist.log_prob(action)\n dist_entropy = dist.entropy()\n state_values = self.critic(state.permute(0, 3, 1, 2)).squeeze()\n\n return action_logprobs, state_values, dist_entropy\n\n\nclass PPO:\n def __init__(self, obs_dim, obs_size, action_dim, lr_actor, lr_critic, gamma, K_epochs, eps_clip, has_continuous_action_space, action_std_init=0.6):\n\n self.has_continuous_action_space = has_continuous_action_space\n\n if has_continuous_action_space:\n self.action_std = action_std_init\n\n self.gamma = gamma\n self.eps_clip = eps_clip\n self.K_epochs = K_epochs\n\n self.buffer = RolloutBuffer()\n\n self.policy = ActorCritic(obs_dim, obs_size, action_dim, has_continuous_action_space, action_std_init).to(device)\n self.optimizer = torch.optim.Adam([\n {'params': self.policy.actor.parameters(), 'lr': lr_actor},\n {'params': self.policy.critic.parameters(), 'lr': lr_critic}\n ])\n\n self.policy_old = ActorCritic(obs_dim, obs_size, action_dim, has_continuous_action_space, action_std_init).to(device)\n self.policy_old.load_state_dict(self.policy.state_dict())\n\n self.MseLoss = nn.MSELoss()\n\n\n def set_action_std(self, new_action_std):\n\n if self.has_continuous_action_space:\n self.action_std = new_action_std\n self.policy.set_action_std(new_action_std)\n self.policy_old.set_action_std(new_action_std)\n\n else:\n print(\"--------------------------------------------------------------------------------------------\")\n print(\"WARNING : Calling PPO::set_action_std() on discrete action space policy\")\n print(\"--------------------------------------------------------------------------------------------\")\n\n\n def decay_action_std(self, action_std_decay_rate, min_action_std):\n print(\"--------------------------------------------------------------------------------------------\")\n\n if self.has_continuous_action_space:\n self.action_std = self.action_std - action_std_decay_rate\n self.action_std = round(self.action_std, 4)\n if (self.action_std <= min_action_std):\n self.action_std = min_action_std\n print(\"setting actor output action_std to min_action_std : \", self.action_std)\n else:\n print(\"setting actor output action_std to : \", self.action_std)\n self.set_action_std(self.action_std)\n\n else:\n print(\"WARNING : Calling PPO::decay_action_std() on discrete action space policy\")\n\n print(\"--------------------------------------------------------------------------------------------\")\n\n\n def select_action(self, state, return_action_prob_shap=False, debug=False):\n\n if self.has_continuous_action_space:\n with torch.no_grad():\n state = torch.FloatTensor(state).to(device)\n action, action_logprob = self.policy_old.act(state)\n\n self.buffer.states.append(state)\n self.buffer.actions.append(action)\n self.buffer.logprobs.append(action_logprob)\n\n return action.detach().cpu().numpy().flatten()\n\n else:\n #TODO trying to debug the explainer issues. Apparently the outputs are the wrong size but SHAP doesn't tell you how you have to structure your model outputs so they work, so we're debugging here now\n with torch.no_grad():\n state = torch.FloatTensor(state).to(device)\n action, action_logprob, action_probs = self.policy_old.act(state)\n\n self.buffer.states.append(state)\n self.buffer.actions.append(action)\n self.buffer.logprobs.append(action_logprob)\n if return_action_prob_shap:\n return action_probs.cpu()\n else:\n return action.item()\n\n\n def update(self):\n\n # Monte Carlo estimate of returns\n rewards = []\n discounted_reward = 0\n for reward, is_terminal in zip(reversed(self.buffer.rewards), reversed(self.buffer.is_terminals)):\n if is_terminal:\n discounted_reward = 0\n discounted_reward = reward + (self.gamma * discounted_reward)\n rewards.insert(0, discounted_reward)\n\n # Normalizing the rewards\n rewards = torch.tensor(rewards, dtype=torch.float32).to(device).squeeze()\n rewards = (rewards - rewards.mean()) / (rewards.std() + 1e-7)\n\n # convert list to tensor\n #TODO creating tensors from list of np arrays is slow, go to 1 np array first\n old_states = torch.squeeze(torch.stack(self.buffer.states, dim=0)).detach().to(device)\n old_actions = torch.squeeze(torch.stack(self.buffer.actions, dim=0)).detach().to(device)\n old_logprobs = torch.squeeze(torch.stack(self.buffer.logprobs, dim=0)).detach().to(device)\n\n\n # Optimize policy for K epochs\n for _ in range(self.K_epochs):\n\n # Evaluating old actions and values\n logprobs, state_values, dist_entropy = self.policy.evaluate(old_states, old_actions)\n\n # match state_values tensor dimensions with rewards tensor\n state_values = torch.squeeze(state_values)\n\n # Finding the ratio (pi_theta / pi_theta__old)\n ratios = torch.exp(logprobs - old_logprobs.detach())\n\n # Finding Surrogate Loss\n advantages = rewards - state_values.detach()\n surr1 = ratios * advantages\n surr2 = torch.clamp(ratios, 1-self.eps_clip, 1+self.eps_clip) * advantages\n\n # final loss of clipped objective PPO\n loss = -torch.min(surr1, surr2) + 0.5*self.MseLoss(state_values, rewards) - 0.01*dist_entropy\n\n # take gradient step\n self.optimizer.zero_grad()\n loss.mean().backward()\n self.optimizer.step()\n\n # Copy new weights into old policy\n self.policy_old.load_state_dict(self.policy.state_dict())\n\n # clear buffer\n self.buffer.clear()\n\n\n def save(self, checkpoint_path):\n torch.save(self.policy_old.state_dict(), checkpoint_path)\n\n\n def load(self, checkpoint_path):\n self.policy_old.load_state_dict(torch.load(checkpoint_path, map_location=lambda storage, loc: storage))\n self.policy.load_state_dict(torch.load(checkpoint_path, map_location=lambda storage, loc: storage))\n\n" ]
[ [ "torch.nn.Softmax", "torch.load", "torch.diag_embed", "torch.no_grad", "torch.FloatTensor", "torch.cuda.is_available", "torch.device", "torch.tensor", "torch.squeeze", "torch.distributions.MultivariateNormal", "torch.full", "torch.nn.ReLU", "torch.nn.Conv2d", "torch.min", "torch.cuda.empty_cache", "torch.unsqueeze", "torch.nn.Linear", "torch.diag", "torch.stack", "torch.nn.Flatten", "torch.nn.Tanh", "torch.distributions.Categorical", "torch.cuda.get_device_name", "torch.clamp", "torch.nn.MSELoss" ] ]
ICHEC/QNLP
[ "2966c7f71e6979c7ddef62520c3749cf6473fabe" ]
[ "modules/py/pkgs/QNLP/proc/DisCoCat.py" ]
[ "###############################################################################\n\nimport sqlite3\nimport os\nfrom typing import Dict, Tuple\nimport QNLP.proc.process_corpus as pc\nimport numpy as np\nfrom QNLP.io.qnlp_db import qnlp_db as qnlp_db\n\n###############################################################################\n\n#Use mixin to modify the insert statements and the structure of database\nclass qdb_mixin(qnlp_db):\n def create_table_discocat(self, table_name=\"qnlp\"):\n \"\"\"\n Create the database table for tagging the required data. The DB has columns\n for dataset ('basis' or 'corpus'), data_type ('verb', 'noun', etc.), token (the string value), mapping_idx (the index of the mapped binary value; for superpos states, this index labels the number of values in the superposition), map_bin_id (the binary value representing the quantum state in the register), map_coeff_r/i (real and imaginary coefficients of the map_bin_id state), mapping_dir (indicates the direction of the mapping; may not be used).\n \"\"\"\n cr_tbl = \"\"\"CREATE TABLE {}(\n id INTEGER PRIMARY KEY, \n dataset TEXT,\n data_type TEXT,\n token TEXT,\n mapping_idx INTEGER,\n map_bin_id INTEGER,\n map_coeff_r REAL,\n map_coeff_i REAL,\n mapping_dir INTEGER\n );\"\"\".format(table_name)\n conn = super(qdb_mixin, self).connect_db()\n c = conn.cursor()\n\n try:\n c.execute(cr_tbl)\n\n except sqlite3.OperationalError as oe:\n remove_db = input(\"Table '{}' already exists. Remove? y/n: \".format(table_name))\n if remove_db is \"y\":\n self.drop_table(table_name)\n self.create_table_discocat(table_name)\n\n except Exception as e:\n print(\"SQLITE exception thrown: {0}\".format(e), \"Exiting program.\")\n exit()\n\n finally:\n conn.commit()\n\n def db_insert_discocat(self, values, dataset=\"basis\", data_type=\"noun\", table_name=\"qnlp\"):\n \"\"\"\n Insert the tag to binary encoding mapping into the DB.\n\n values -- Dict mapping string to binary value, and binary value to string.\n data_type -- String to indicate the type of data to be stored\n table_name -- Name of table to store in DB\n \"\"\"\n\n '''\n The DB insert operation below assumes the value field of a key in DB is a tuple,\n containing (binary_id, weight of occurrence), where weight of occurrence cant be\n determined by the proximity of the word to other words; essentially a count in the \n simplest case. The mapping checks to see if the index is convertible to a numeric\n type. If so, this will imply the reverse mapping (ie qubit result to string val), \n and is indicated by -1. Otherwise, this will be a forward mapping, and given by 1.\n '''\n conn = super(qdb_mixin, self).connect_db()\n c = conn.cursor()\n self.create_table_discocat(table_name)\n \n for corpus_token, superpos in values.items():\n l_superpos = len(superpos)\n for idx, (distance_measure, basis_state) in enumerate(superpos):\n c.execute(\"\"\"INSERT INTO {} ( \n dataset, \n data_type, \n token, \n mapping_idx, \n map_bin_id, \n map_coeff_r, \n map_coeff_i, \n mapping_dir ) VALUES(?,?,?,?,?,?,?,?)\"\"\".format(table_name), \n (dataset, \n data_type, \n corpus_token, \n idx, \n basis_state, \n distance_measure.real, \n distance_measure.imag, \n 0)\n )\n conn.commit()\n\n###############################################################################\n\nclass DisCoCat:\n \"\"\"\n Implements precomputation for the DisCo(Cat) model to represent sentence meanings\n using category theory methods. See <PAPERS> for details.\n \"\"\"\n def __init__(self, fd = lambda x : [1.0/(i+1) for i in x]):\n self.distance_func = fd\n\n def load_corpus(self, corpus_path):\n return pc.load_corpus(corpus_path)\n \n def tokenise_corpus(self, corpus_text):\n return pc.tokenize_corpus(corpus_text)\n\n###############################################################################\n\n def word_occurrence(self, corpus_list : list):\n \"\"\"\n Counts word occurrence in a given corpus, presented as a tokenised word list.\n Returns a dictionary with keys as the tokens and values as the occurrences.\n \"\"\"\n word_dict = {}\n for word in corpus_list:\n if word in word_dict:\n word_dict[word] += 1\n else:\n word_dict[word] = 1\n return word_dict\n\n###############################################################################\n\n def define_basis_words(self, word_dict : dict, max_words : int):\n \"\"\"\n Chooses the max_words number of most common words from word_dict\n and return as list for use as basis.\n \"\"\"\n k = list(word_dict.keys())\n v = list(word_dict.values())\n res_list = []\n\n for i in range(max_words):\n max_val = max(v)\n val_idx = v.index(max_val)\n res_list.append((k[val_idx],max_val))\n k.remove(k[val_idx])\n v.remove(max_val)\n\n return res_list\n\n###############################################################################\n #from multimethod import multimethod #Allow multiple dispatch\n\n #@multimethod\n def map_to_basis(self, corpus_list : dict, basis : list, basis_dist_cutoff=10, distance_func=None):\n \"\"\"\n Maps the words from the corpus into the chosen basis. \n Returns word_map dictionary, mapping corpus tokens -> basis states\n\n Keyword arguments:\n corpus_list -- List of tokens representing corpus\n basis -- List of basis tokens\n basis_dist_cutoff -- Cut-off for token distance from basis for it to be significant\n distance_func -- Function accepting distance between basis and token, and\n returning the resulting scaling. If 'None', defaults to \n 1/coeff for scaling param\n \"\"\"\n\n if distance_func == None:\n distance_func = self.distance_func #lambda x : [1.0/(i+1) for i in x]\n\n word_map = {}\n\n # map distance between basis words and other words in token list\n for word, locations in corpus_list.items():\n word_map.update({word : None})\n for b_idx, b_val in enumerate(basis):\n # Basis elements are orthogonal\n if(b_val == word):\n word_map.update({b_val : {b_val : 0}})\n break\n # to add left-right ordering here, remove the abs and use sign of distance to indicate where words appear relative to one another. \n min_dist = np.min(np.abs(locations[1][:, np.newaxis] - corpus_list[b_val][1]))\n m = (word, b_val, min_dist <= basis_dist_cutoff)\n\n if m[2] != False:\n if(word_map.get(m[0]) != None):\n update_val = word_map.get(m[0])\n update_val.update({m[1] : min_dist})\n word_map.update({m[0] : update_val })\n else:\n word_map.update({m[0] : {m[1] : min_dist} })\n return word_map\n\n def nvn_distances(self, corpus_list_n : dict, corpus_list_v : dict, dist_cutoff=2, distance_func=None):\n \"\"\"This function matches the NVN sentence structure, by locating adjacent\n nouns and verbs, following the same procedure as used to map corpus words \n onto the basis. With this, we can construct relationships between the\n verbs and their subject/object nouns.\"\"\"\n\n if distance_func == None:\n distance_func = self.distance_func #lambda x : [1.0/(i+1) for i in x]\n\n word_map = {}\n\n # map distance between words\n for word_v, locations_v in corpus_list_v.items():\n for word_n, locations_n in corpus_list_n.items():#######!!!!!!!#######\n from IPython import embed; embed()\n\n dists = locations_n[1][:, np.newaxis] - locations_v[1]\n if any([np.abs(x) <= dist_cutoff for x in dists]):\n print(\"Pattern between {} and {}\".format(word_n, word_v))\n continue\n\n if(0):# if dist between v and noun is negative, order 1, if positive, order 2\n word_map.update({word : None})\n\n # to add left-right ordering here, remove the abs and use sign of distance to indicate where words appear relative to one another. \n min_dist = np.min(np.abs(locations[1][:, np.newaxis] - corpus_list[b_val][1]))\n m = (word, b_val, min_dist <= basis_dist_cutoff)\n\n if m[2] != False:\n if(word_map.get(m[0]) != None):\n update_val = word_map.get(m[0])\n update_val.update({m[1] : min_dist})\n word_map.update({m[0] : update_val })\n else:\n word_map.update({m[0] : {m[1] : min_dist} })\n return word_map \n\n###############################################################################\n\n def map_to_bitstring(self, basis : list):\n upper_bound_bitstrings = int(np.ceil(np.log2(len(basis))))\n bit_map = {}\n bitstring = 0 # Assume |0...0> state reserved for initialisation only\n for k, v in basis:\n bitstring += 1\n bit_map.update({k: bitstring})\n return (upper_bound_bitstrings, bit_map)\n\n###############################################################################\n\n def generate_state_mapping(self, bit_map, dat_map):\n \"\"\"\n Takes the basis bitstring map, and the token-to-basis relationship, and returns a normalised set of states, with coefficients determined by the distance_func lambda, given the distance between the token and the resulting basis element.\n \"\"\"\n num_states = bit_map[0]\n\n # Mapping token to array of tuples, first index the basis state coefficient and second the integer representation of the bitstring state\n state_encoding = {}\n for token, basis_dist_map in dat_map.items():\n local_coeffs = []\n local_states = []\n for basis_token, distance_list in basis_dist_map.items():\n # If more than one occurrence for the same word, apply the distance relation function then sum the results for that basis work coefficient\n local_coeffs.append( np.sum( self.distance_func(distance_list) ) )\n local_states.append( bit_map[1][basis_token] )\n\n # Calc normalisation factor over all the respective basis states for a given token\n norm_factor = np.linalg.norm(local_coeffs)\n for state_idx in range( len(local_states) ):\n # Normalise the coefficient\n local_coeffs[state_idx] /= norm_factor\n current = state_encoding.get(token)\n if current != None:\n current.append( (local_coeffs[state_idx], local_states[state_idx],) )\n else:\n state_encoding.update({token : [(local_coeffs[state_idx], local_states[state_idx],)] })\n return state_encoding\n\n###############################################################################\n\n def latex_states(self, bit_map, dat_map, file_name = \"state\"):\n \"\"\"\n LaTeX file outputter for state generation. Given the above data structures, file_name.tex is generated. Beware, as output may need to replace '_' with '\\_' for non-math-mode usage.\n \"\"\"\n\n mapping = self.generate_state_mapping(bit_map, dat_map)\n with open(file_name + \".tex\", \"w\") as f:\n f.write(\"\\\\documentclass{article} \\n \\\\usepackage{amsmath} \\\\usepackage{multicol} \\n \\\\begin{document} \\n\")\n tex_string_format_bit = r'\\vert {:0%db} \\rangle'%(bit_map[0])\n f.write(\"\\\\section{Basis} \\\\begin{multicols}{2} \\n \\\\noindent \")\n for b_key, b_val in bit_map[1].items():\n f.write(b_key + \" $\\\\rightarrow \" + tex_string_format_bit.format(b_val) + \"$\\\\\\\\ \")\n f.write(\"\\\\end{multicols}\")\n f.write(\"\\\\noindent\\\\rule{\\\\textwidth}{1pt} \\n\")\n f.write(\"\\\\noindent\\\\rule{\\\\textwidth}{1pt} \\n\")\n f.write(\"\\\\section{Encoding} \\n\")\n for token, basis_map in mapping.items():\n f.write(r\"\\begin{align}\\vert \\textrm{\" + token + \"} \\\\rangle &= \\\\\\\\ \\n &\" )\n for i,b in enumerate(basis_map):\n if( i != 0 ):\n if(i%3 == 0):\n f.write(r\" \\\\ & \")\n f.write(\"{0:.3f}\".format(round(b[0],3)))\n f.write(tex_string_format_bit.format(b[1]) )\n if(i != len(basis_map) - 1):\n f.write(r\"+\")\n f.write(\" \\\\nonumber \")\n f.write(r\"\"\"\\end{align}\"\"\")\n f.write(\"\\\\noindent\\\\rule{\\\\textwidth}{1pt} \\n\")\n f.write(r\"\\end{document}\")\n\n###############################################################################" ]
[ [ "numpy.abs", "numpy.linalg.norm" ] ]
wavefancy/BIDMC-PYTHON
[ "97c7d3e1bec19dd7fea34d4ecebbdf2af2b1faed" ]
[ "Utilities/BootstrapMean/BootstrapMean.py" ]
[ "#!/usr/bin/env python3\n\n\"\"\"\n\n Bootstrap values to estimate confidence interval for mean.\n\n @Author: [email protected]\n\n Usage:\n BootstrapMean.py -n times -c confidence\n BootstrapMean.py -h | --help | -v | --version | -f | --format\n\n Notes:\n 1. Read content from stdin, and output results to stdout.\n 2. Input separated by 'white' characteres, including '\\\\n'.\n\n Options:\n -n times Number of times for bootstrapping\n -c confidence Confidence interval, float1, float2 ..., eg. 0.8,0.95\n -h --help Show this screen.\n -v --version Show version.\n\n\"\"\"\nimport sys\nfrom docopt import docopt\nfrom signal import signal, SIGPIPE, SIG_DFL\nsignal(SIGPIPE,SIG_DFL)\n\n\nif __name__ == '__main__':\n args = docopt(__doc__, version='1.0')\n #print(args)\n\n ntimes = 100\n confidence = []\n if args['-n']:\n ntimes = int(args['-n'])\n if args['-c']:\n confidence = [float(x) for x in args['-c'].split(',')]\n\n#-------------------------------------------------\n data = []\n for line in sys.stdin:\n line = line.strip()\n if line:\n data = data + [float(x) for x in line.split()]\n #print(data)\n import numpy\n npData = numpy.array(data)\n dataMean = numpy.mean(npData)\n means = numpy.empty(ntimes)\n for x in range(ntimes):\n # resampling with replacement.\n # print(numpy.random.choice(npData, len(npData), True))\n means.put(x, numpy.mean(numpy.random.choice(npData, len(npData), True)))\n sortedMeans = numpy.sort(means)\n # print(sortedMeans)\n sys.stdout.write('InputMean\\tCI\\tLeft\\tRight\\n')\n for x in confidence:\n skip = numpy.rint(len(means) * (1-x)/2)\n # print(skip)\n sys.stdout.write('%.4e\\t%.4f\\t%.4e\\t%.4e\\n'%(dataMean, x, sortedMeans[skip], sortedMeans[len(means)-skip-1]))\n\nsys.stdout.flush()\nsys.stdout.close()\nsys.stderr.flush()\nsys.stderr.close()\n" ]
[ [ "numpy.sort", "numpy.array", "numpy.mean", "numpy.empty" ] ]
danilodsp/quantstats
[ "67a647baeba756c57d87bc7028f55d4dee8702b4" ]
[ "quantstats/_plotting/core.py" ]
[ "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n#\n# Quantreturns: Portfolio analytics for quants\n# https://github.com/ranaroussi/quantreturns\n#\n# Copyright 2019 Ran Aroussi\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 matplotlib.pyplot as _plt\ntry:\n _plt.rcParams[\"font.family\"] = \"Arial\"\nexcept Exception:\n pass\n\nimport matplotlib.dates as _mdates\nfrom matplotlib.ticker import (\n FormatStrFormatter as _FormatStrFormatter,\n FuncFormatter as _FuncFormatter\n)\n\nimport pandas as _pd\nimport numpy as _np\nimport seaborn as _sns\nfrom .. import stats as _stats\n\n_sns.set(font_scale=1.1, rc={\n 'figure.figsize': (10, 6),\n 'axes.facecolor': 'white',\n 'figure.facecolor': 'white',\n 'grid.color': '#dddddd',\n 'grid.linewidth': 0.5,\n \"lines.linewidth\": 1.5,\n 'text.color': '#333333',\n 'xtick.color': '#666666',\n 'ytick.color': '#666666'\n})\n\n_FLATUI_COLORS = [\"#fedd78\", \"#348dc1\", \"#af4b64\",\n \"#4fa487\", \"#9b59b6\", \"#808080\"]\n_GRAYSCALE_COLORS = ['silver', '#222222', 'gray'] * 3\n\n\ndef _get_colors(grayscale):\n colors = _FLATUI_COLORS\n ls = '-'\n alpha = .8\n if grayscale:\n colors = _GRAYSCALE_COLORS\n ls = '-'\n alpha = 0.5\n return colors, ls, alpha\n\n\ndef plot_returns_bars(returns, benchmark=None,\n returns_label=\"Strategy\",\n hline=None, hlw=None, hlcolor=\"red\", hllabel=\"\",\n resample=\"A\", title=\"Returns\", match_volatility=False,\n log_scale=False, figsize=(10, 6),\n grayscale=False, fontname='Arial', ylabel=True,\n subtitle=True, savefig=None, show=True):\n\n if match_volatility and benchmark is None:\n raise ValueError('match_volatility requires passing of '\n 'benchmark.')\n elif match_volatility and benchmark is not None:\n bmark_vol = benchmark.loc[returns.index].std()\n returns = (returns / returns.std()) * bmark_vol\n\n # ---------------\n colors, ls, alpha = _get_colors(grayscale)\n df = _pd.DataFrame(index=returns.index, data={returns_label: returns})\n if isinstance(benchmark, _pd.Series):\n df['Benchmark'] = benchmark[benchmark.index.isin(returns.index)]\n df = df[['Benchmark', returns_label]]\n\n df = df.dropna()\n if resample is not None:\n df = df.resample(resample).apply(\n _stats.comp).resample(resample).last()\n # ---------------\n\n fig, ax = _plt.subplots(figsize=figsize)\n\n # use a more precise date string for the x axis locations in the toolbar\n fig.suptitle(title+\"\\n\", y=.99, fontweight=\"bold\", fontname=fontname,\n fontsize=14, color=\"black\")\n\n if subtitle:\n ax.set_title(\"\\n%s - %s \" % (\n df.index.date[:1][0].strftime('%Y'),\n df.index.date[-1:][0].strftime('%Y')\n ), fontsize=12, color='gray')\n\n if benchmark is None:\n colors = colors[1:]\n df.plot(kind='bar', ax=ax, color=colors)\n\n fig.set_facecolor('white')\n ax.set_facecolor('white')\n\n ax.set_xticklabels(df.index.year)\n # ax.fmt_xdata = _mdates.DateFormatter('%Y-%m-%d')\n years = sorted(list(set(df.index.year)))\n if len(years) > 10:\n mod = int(len(years)/10)\n _plt.xticks(_np.arange(len(years)), [\n str(year) if not i % mod else '' for i, year in enumerate(years)])\n\n # rotate and align the tick labels so they look better\n fig.autofmt_xdate()\n\n if hline:\n if grayscale:\n hlcolor = 'gray'\n ax.axhline(hline, ls=\"--\", lw=hlw, color=hlcolor,\n label=hllabel, zorder=2)\n\n ax.axhline(0, ls=\"--\", lw=1, color=\"#000000\", zorder=2)\n\n if isinstance(benchmark, _pd.Series) or hline:\n ax.legend(fontsize=12)\n\n _plt.yscale(\"symlog\" if log_scale else \"linear\")\n\n ax.set_xlabel('')\n if ylabel:\n ax.set_ylabel(\"Returns\", fontname=fontname,\n fontweight='bold', fontsize=12, color=\"black\")\n ax.yaxis.set_label_coords(-.1, .5)\n\n ax.yaxis.set_major_formatter(_FuncFormatter(format_pct_axis))\n\n try:\n _plt.subplots_adjust(hspace=0, bottom=0, top=1)\n except Exception:\n pass\n\n try:\n fig.tight_layout()\n except Exception:\n pass\n\n if savefig:\n if isinstance(savefig, dict):\n _plt.savefig(**savefig)\n else:\n _plt.savefig(savefig)\n\n if show:\n _plt.show(fig)\n\n _plt.close()\n\n if not show:\n return fig\n\n\ndef plot_timeseries(returns, benchmark=None,\n title=\"Returns\", compound=False, cumulative=True,\n fill=False, returns_label=\"Strategy\",\n hline=None, hlw=None, hlcolor=\"red\", hllabel=\"\",\n percent=True, match_volatility=False, log_scale=False,\n resample=None, lw=1.5, figsize=(10, 6), ylabel=\"\",\n grayscale=False, fontname=\"Arial\",\n subtitle=True, savefig=None, show=True):\n\n colors, ls, alpha = _get_colors(grayscale)\n\n returns.fillna(0, inplace=True)\n if isinstance(benchmark, _pd.Series):\n benchmark.fillna(0, inplace=True)\n\n if match_volatility and benchmark is None:\n raise ValueError('match_volatility requires passing of '\n 'benchmark.')\n elif match_volatility and benchmark is not None:\n bmark_vol = benchmark.std()\n returns = (returns / returns.std()) * bmark_vol\n\n # ---------------\n if compound is True:\n if cumulative:\n returns = _stats.compsum(returns)\n if isinstance(benchmark, _pd.Series):\n benchmark = _stats.compsum(benchmark)\n else:\n returns = returns.cumsum()\n if isinstance(benchmark, _pd.Series):\n benchmark = benchmark.cumsum()\n\n if resample:\n returns = returns.resample(resample)\n returns = returns.last() if compound is True else returns.sum()\n if isinstance(benchmark, _pd.Series):\n benchmark = benchmark.resample(resample)\n benchmark = benchmark.last(\n ) if compound is True else benchmark.sum()\n # ---------------\n\n fig, ax = _plt.subplots(figsize=figsize)\n fig.suptitle(title+\"\\n\", y=.99, fontweight=\"bold\", fontname=fontname,\n fontsize=14, color=\"black\")\n\n if subtitle:\n ax.set_title(\"\\n%s - %s \" % (\n returns.index.date[:1][0].strftime('%e %b \\'%y'),\n returns.index.date[-1:][0].strftime('%e %b \\'%y')\n ), fontsize=12, color='gray')\n\n fig.set_facecolor('white')\n ax.set_facecolor('white')\n\n if isinstance(benchmark, _pd.Series):\n ax.plot(benchmark, lw=lw, ls=ls, label=\"Benchmark\", color=colors[0])\n\n alpha = .25 if grayscale else 1\n ax.plot(returns, lw=lw, label=returns_label, color=colors[1], alpha=alpha)\n\n if fill:\n ax.fill_between(returns.index, 0, returns, color=colors[1], alpha=.25)\n\n # rotate and align the tick labels so they look better\n fig.autofmt_xdate()\n\n # use a more precise date string for the x axis locations in the toolbar\n # ax.fmt_xdata = _mdates.DateFormatter('%Y-%m-%d')\n\n if hline:\n if grayscale:\n hlcolor = 'black'\n ax.axhline(hline, ls=\"--\", lw=hlw, color=hlcolor,\n label=hllabel, zorder=2)\n\n ax.axhline(0, ls=\"-\", lw=1,\n color='gray', zorder=1)\n ax.axhline(0, ls=\"--\", lw=1,\n color='white' if grayscale else 'black', zorder=2)\n\n if isinstance(benchmark, _pd.Series) or hline:\n ax.legend(fontsize=12)\n\n _plt.yscale(\"symlog\" if log_scale else \"linear\")\n\n if percent:\n ax.yaxis.set_major_formatter(_FuncFormatter(format_pct_axis))\n # ax.yaxis.set_major_formatter(_plt.FuncFormatter(\n # lambda x, loc: \"{:,}%\".format(int(x*100))))\n\n ax.set_xlabel('')\n if ylabel:\n ax.set_ylabel(ylabel, fontname=fontname,\n fontweight='bold', fontsize=12, color=\"black\")\n ax.yaxis.set_label_coords(-.1, .5)\n\n try:\n _plt.subplots_adjust(hspace=0, bottom=0, top=1)\n except Exception:\n pass\n\n try:\n fig.tight_layout()\n except Exception:\n pass\n\n if savefig:\n if isinstance(savefig, dict):\n _plt.savefig(**savefig)\n else:\n _plt.savefig(savefig)\n\n if show:\n _plt.show(fig)\n\n _plt.close()\n\n if not show:\n return fig\n\n\ndef plot_histogram(returns, resample=\"M\", bins=20,\n fontname='Arial', grayscale=False,\n title=\"Returns\", kde=True, figsize=(10, 6),\n ylabel=True, subtitle=True, compounded=True,\n savefig=None, show=True):\n\n colors = ['#348dc1', '#003366', 'red']\n if grayscale:\n colors = ['silver', 'gray', 'black']\n\n apply_fnc = _stats.comp if compounded else _np.sum\n returns = returns.fillna(0).resample(resample).apply(\n apply_fnc).resample(resample).last()\n\n fig, ax = _plt.subplots(figsize=figsize)\n fig.suptitle(title+\"\\n\", y=.99, fontweight=\"bold\", fontname=fontname,\n fontsize=14, color=\"black\")\n\n if subtitle:\n ax.set_title(\"\\n%s - %s \" % (\n returns.index.date[:1][0].strftime('%Y'),\n returns.index.date[-1:][0].strftime('%Y')\n ), fontsize=12, color='gray')\n\n fig.set_facecolor('white')\n ax.set_facecolor('white')\n\n ax.axvline(returns.mean(), ls=\"--\", lw=1.5,\n color=colors[2], zorder=2, label=\"Average\")\n\n _sns.distplot(returns, bins=bins,\n axlabel=\"\", color=colors[0], hist_kws=dict(alpha=1),\n kde=kde,\n # , label=\"Kernel Estimate\"\n kde_kws=dict(color='black', alpha=.7),\n ax=ax)\n\n ax.xaxis.set_major_formatter(_plt.FuncFormatter(\n lambda x, loc: \"{:,}%\".format(int(x*100))))\n\n ax.axhline(0.01, lw=1, color=\"#000000\", zorder=2)\n ax.axvline(0, lw=1, color=\"#000000\", zorder=2)\n\n ax.set_xlabel('')\n if ylabel:\n ax.set_ylabel(\"Occurrences\", fontname=fontname,\n fontweight='bold', fontsize=12, color=\"black\")\n ax.yaxis.set_label_coords(-.1, .5)\n\n ax.legend(fontsize=12)\n\n # fig.autofmt_xdate()\n\n try:\n _plt.subplots_adjust(hspace=0, bottom=0, top=1)\n except Exception:\n pass\n\n try:\n fig.tight_layout()\n except Exception:\n pass\n\n if savefig:\n if isinstance(savefig, dict):\n _plt.savefig(**savefig)\n else:\n _plt.savefig(savefig)\n\n if show:\n _plt.show(fig)\n\n _plt.close()\n\n if not show:\n return fig\n\n\ndef plot_rolling_stats(returns, benchmark=None, title=\"\",\n returns_label=\"Strategy\",\n hline=None, hlw=None, hlcolor=\"red\", hllabel=\"\",\n lw=1.5, figsize=(10, 6), ylabel=\"\",\n grayscale=False, fontname=\"Arial\", subtitle=True,\n savefig=None, show=True):\n\n colors, ls, alpha = _get_colors(grayscale)\n\n fig, ax = _plt.subplots(figsize=figsize)\n\n df = _pd.DataFrame(index=returns.index, data={returns_label: returns})\n if isinstance(benchmark, _pd.Series):\n df['Benchmark'] = benchmark[benchmark.index.isin(returns.index)]\n df = df[['Benchmark', returns_label]].dropna()\n ax.plot(df['Benchmark'], lw=lw, label=\"Benchmark\",\n color=colors[0], alpha=.8)\n\n ax.plot(df[returns_label].dropna(), lw=lw,\n label=returns_label, color=colors[1])\n\n # rotate and align the tick labels so they look better\n fig.autofmt_xdate()\n\n # use a more precise date string for the x axis locations in the toolbar\n # ax.fmt_xdata = _mdates.DateFormatter('%Y-%m-%d')\\\n fig.suptitle(title+\"\\n\", y=.99, fontweight=\"bold\", fontname=fontname,\n fontsize=14, color=\"black\")\n\n if subtitle:\n ax.set_title(\"\\n%s - %s \" % (\n df.index.date[:1][0].strftime('%e %b \\'%y'),\n df.index.date[-1:][0].strftime('%e %b \\'%y')\n ), fontsize=12, color='gray')\n\n if hline:\n if grayscale:\n hlcolor = 'black'\n ax.axhline(hline, ls=\"--\", lw=hlw, color=hlcolor,\n label=hllabel, zorder=2)\n\n ax.axhline(0, ls=\"--\", lw=1, color=\"#000000\", zorder=2)\n\n if ylabel:\n ax.set_ylabel(ylabel, fontname=fontname,\n fontweight='bold', fontsize=12, color=\"black\")\n ax.yaxis.set_label_coords(-.1, .5)\n\n ax.yaxis.set_major_formatter(_FormatStrFormatter('%.2f'))\n\n ax.legend(fontsize=12)\n\n try:\n _plt.subplots_adjust(hspace=0, bottom=0, top=1)\n except Exception:\n pass\n\n try:\n fig.tight_layout()\n except Exception:\n pass\n\n if savefig:\n if isinstance(savefig, dict):\n _plt.savefig(**savefig)\n else:\n _plt.savefig(savefig)\n if show:\n _plt.show(fig)\n\n _plt.close()\n\n if not show:\n return fig\n\n\ndef plot_rolling_beta(returns, benchmark,\n window1=126, window1_label=\"\",\n window2=None, window2_label=\"\",\n title=\"\", hlcolor=\"red\", figsize=(10, 6),\n grayscale=False, fontname=\"Arial\", lw=1.5,\n ylabel=True, subtitle=True, savefig=None, show=True):\n\n colors, ls, alpha = _get_colors(grayscale)\n\n fig, ax = _plt.subplots(figsize=figsize)\n fig.suptitle(title+\"\\n\", y=.99, fontweight=\"bold\", fontname=fontname,\n fontsize=14, color=\"black\")\n\n if subtitle:\n ax.set_title(\"\\n%s - %s \" % (\n returns.index.date[:1][0].strftime('%e %b \\'%y'),\n returns.index.date[-1:][0].strftime('%e %b \\'%y')\n ), fontsize=12, color='gray')\n\n beta = _stats.rolling_greeks(returns, benchmark, window1)['beta']\n ax.plot(beta, lw=lw, label=window1_label, color=colors[1])\n\n if window2:\n ax.plot(_stats.rolling_greeks(returns, benchmark, window2)['beta'],\n lw=lw, label=window2_label, color=\"gray\", alpha=0.8)\n mmin = min([-100, int(beta.min()*100)])\n mmax = max([100, int(beta.max()*100)])\n step = 50 if (mmax-mmin) >= 200 else 100\n ax.set_yticks([x / 100 for x in list(range(mmin, mmax, step))])\n\n hlcolor = 'black' if grayscale else hlcolor\n ax.axhline(beta.mean(), ls=\"--\", lw=1.5,\n color=hlcolor, zorder=2)\n\n ax.axhline(0, ls=\"--\", lw=1, color=\"#000000\", zorder=2)\n\n fig.autofmt_xdate()\n\n # use a more precise date string for the x axis locations in the toolbar\n ax.fmt_xdata = _mdates.DateFormatter('%Y-%m-%d')\n\n if ylabel:\n ax.set_ylabel(\"Beta\", fontname=fontname,\n fontweight='bold', fontsize=12, color=\"black\")\n ax.yaxis.set_label_coords(-.1, .5)\n\n ax.legend(fontsize=12)\n try:\n _plt.subplots_adjust(hspace=0, bottom=0, top=1)\n except Exception:\n pass\n\n try:\n fig.tight_layout()\n except Exception:\n pass\n\n if savefig:\n if isinstance(savefig, dict):\n _plt.savefig(**savefig)\n else:\n _plt.savefig(savefig)\n\n if show:\n _plt.show(fig)\n\n _plt.close()\n\n if not show:\n return fig\n\n\ndef plot_longest_drawdowns(returns, periods=5, lw=1.5,\n fontname='Arial', grayscale=False,\n log_scale=False, figsize=(10, 6), ylabel=True,\n subtitle=True, compounded=True,\n savefig=None, show=True):\n\n colors = ['#348dc1', '#003366', 'red']\n if grayscale:\n colors = ['#000000'] * 3\n\n dd = _stats.to_drawdown_series(returns.fillna(0))\n dddf = _stats.drawdown_details(dd)\n longest_dd = dddf.sort_values(\n by='days', ascending=False, kind='mergesort')[:periods]\n\n fig, ax = _plt.subplots(figsize=figsize)\n fig.suptitle(\"Top %.0f Drawdown Periods\\n\" %\n periods, y=.99, fontweight=\"bold\", fontname=fontname,\n fontsize=14, color=\"black\")\n if subtitle:\n ax.set_title(\"\\n%s - %s \" % (\n returns.index.date[:1][0].strftime('%e %b \\'%y'),\n returns.index.date[-1:][0].strftime('%e %b \\'%y')\n ), fontsize=12, color='gray')\n\n fig.set_facecolor('white')\n ax.set_facecolor('white')\n series = _stats.compsum(returns) if compounded else returns.cumsum()\n ax.plot(series, lw=lw, label=\"Backtest\", color=colors[0])\n\n highlight = 'black' if grayscale else 'red'\n for idx, row in longest_dd.iterrows():\n ax.axvspan(*_mdates.datestr2num([str(row['start']), str(row['end'])]),\n color=highlight, alpha=.1)\n\n # rotate and align the tick labels so they look better\n fig.autofmt_xdate()\n\n # use a more precise date string for the x axis locations in the toolbar\n ax.fmt_xdata = _mdates.DateFormatter('%Y-%m-%d')\n\n ax.axhline(0, ls=\"--\", lw=1, color=\"#000000\", zorder=2)\n _plt.yscale(\"symlog\" if log_scale else \"linear\")\n if ylabel:\n ax.set_ylabel(\"Cumulative Returns\", fontname=fontname,\n fontweight='bold', fontsize=12, color=\"black\")\n ax.yaxis.set_label_coords(-.1, .5)\n\n ax.yaxis.set_major_formatter(_FuncFormatter(format_pct_axis))\n # ax.yaxis.set_major_formatter(_plt.FuncFormatter(\n # lambda x, loc: \"{:,}%\".format(int(x*100))))\n\n fig.autofmt_xdate()\n\n try:\n _plt.subplots_adjust(hspace=0, bottom=0, top=1)\n except Exception:\n pass\n\n try:\n fig.tight_layout()\n except Exception:\n pass\n\n if savefig:\n if isinstance(savefig, dict):\n _plt.savefig(**savefig)\n else:\n _plt.savefig(savefig)\n\n if show:\n _plt.show(fig)\n\n _plt.close()\n\n if not show:\n return fig\n\n\ndef plot_distribution(returns, figsize=(10, 6),\n fontname='Arial', grayscale=False, ylabel=True,\n subtitle=True, compounded=True,\n savefig=None, show=True):\n\n colors = _FLATUI_COLORS\n if grayscale:\n colors = ['#f9f9f9', '#dddddd', '#bbbbbb', '#999999', '#808080']\n # colors, ls, alpha = _get_colors(grayscale)\n\n port = _pd.DataFrame(returns.fillna(0))\n port.columns = ['Daily']\n\n apply_fnc = _stats.comp if compounded else _np.sum\n\n port['Weekly'] = port['Daily'].resample(\n 'W-MON').apply(apply_fnc).resample('W-MON').last()\n port['Weekly'].ffill(inplace=True)\n\n port['Monthly'] = port['Daily'].resample(\n 'M').apply(apply_fnc).resample('M').last()\n port['Monthly'].ffill(inplace=True)\n\n port['Quarterly'] = port['Daily'].resample(\n 'Q').apply(apply_fnc).resample('Q').last()\n port['Quarterly'].ffill(inplace=True)\n\n port['Yearly'] = port['Daily'].resample(\n 'A').apply(apply_fnc).resample('A').last()\n port['Yearly'].ffill(inplace=True)\n\n fig, ax = _plt.subplots(figsize=figsize)\n fig.suptitle(\"Return Quantiles\\n\", y=.99,\n fontweight=\"bold\", fontname=fontname,\n fontsize=14, color=\"black\")\n\n if subtitle:\n ax.set_title(\"\\n%s - %s \" % (\n returns.index.date[:1][0].strftime('%e %b \\'%y'),\n returns.index.date[-1:][0].strftime('%e %b \\'%y')\n ), fontsize=12, color='gray')\n\n fig.set_facecolor('white')\n ax.set_facecolor('white')\n\n _sns.boxplot(data=port, ax=ax, palette=tuple(colors[:5]))\n\n ax.yaxis.set_major_formatter(_plt.FuncFormatter(\n lambda x, loc: \"{:,}%\".format(int(x*100))))\n\n if ylabel:\n ax.set_ylabel('Rerurns', fontname=fontname,\n fontweight='bold', fontsize=12, color=\"black\")\n ax.yaxis.set_label_coords(-.1, .5)\n\n fig.autofmt_xdate()\n\n try:\n _plt.subplots_adjust(hspace=0)\n except Exception:\n pass\n try:\n fig.tight_layout(w_pad=0, h_pad=0)\n except Exception:\n pass\n\n if savefig:\n if isinstance(savefig, dict):\n _plt.savefig(**savefig)\n else:\n _plt.savefig(savefig)\n\n if show:\n _plt.show(fig)\n\n _plt.close()\n\n if not show:\n return fig\n\n\ndef plot_table(tbl, columns=None, title=\"\", title_loc=\"left\",\n header=True,\n colWidths=None,\n rowLoc='right',\n colLoc='right',\n colLabels=[],\n edges='horizontal',\n orient='horizontal',\n figsize=(10, 6),\n savefig=None,\n show=False):\n\n if columns is not None:\n try:\n tbl.columns = columns\n except Exception:\n pass\n\n fig = _plt.figure(figsize=(5.5, 6))\n ax = _plt.subplot(111, frame_on=False)\n\n if title != \"\":\n ax.set_title(title, fontweight=\"bold\",\n fontsize=14, color=\"black\", loc=title_loc)\n\n the_table = ax.table(cellText=tbl.values,\n colWidths=colWidths,\n rowLoc=rowLoc,\n colLoc=colLoc,\n edges=edges,\n colLabels=(tbl.columns if header else None),\n loc='center',\n zorder=2\n )\n\n the_table.auto_set_font_size(False)\n the_table.set_fontsize(12)\n the_table.scale(1, 1)\n\n for (row, col), cell in the_table.get_celld().items():\n cell.set_height(0.08)\n cell.set_text_props(color='black')\n cell.set_edgecolor('#dddddd')\n if row == 0 and header:\n cell.set_edgecolor('black')\n cell.set_facecolor('black')\n cell.set_linewidth(2)\n cell.set_text_props(weight='bold', color='black')\n elif col == 0 and \"vertical\" in orient:\n cell.set_edgecolor('#dddddd')\n cell.set_linewidth(1)\n cell.set_text_props(weight='bold', color='black')\n elif row > 1:\n cell.set_linewidth(1)\n\n ax.grid(False)\n ax.set_xticks([])\n ax.set_yticks([])\n\n try:\n _plt.subplots_adjust(hspace=0)\n except Exception:\n pass\n try:\n fig.tight_layout(w_pad=0, h_pad=0)\n except Exception:\n pass\n\n if savefig:\n if isinstance(savefig, dict):\n _plt.savefig(**savefig)\n else:\n _plt.savefig(savefig)\n\n if show:\n _plt.show(fig)\n\n _plt.close()\n\n if not show:\n return fig\n\n\ndef format_cur_axis(x, pos):\n if x >= 1e12:\n res = '$%1.1fT' % (x * 1e-12)\n return res.replace('.0T', 'T')\n if x >= 1e9:\n res = '$%1.1fB' % (x * 1e-9)\n return res.replace('.0B', 'B')\n if x >= 1e6:\n res = '$%1.1fM' % (x * 1e-6)\n return res.replace('.0M', 'M')\n if x >= 1e3:\n res = '$%1.0fK' % (x * 1e-3)\n return res.replace('.0K', 'K')\n res = '$%1.0f' % x\n return res.replace('.0', '')\n\n\ndef format_pct_axis(x, pos):\n x *= 100 # lambda x, loc: \"{:,}%\".format(int(x * 100))\n if x >= 1e12:\n res = '%1.1fT%%' % (x * 1e-12)\n return res.replace('.0T%', 'T%')\n if x >= 1e9:\n res = '%1.1fB%%' % (x * 1e-9)\n return res.replace('.0B%', 'B%')\n if x >= 1e6:\n res = '%1.1fM%%' % (x * 1e-6)\n return res.replace('.0M%', 'M%')\n if x >= 1e3:\n res = '%1.1fK%%' % (x * 1e-3)\n return res.replace('.0K%', 'K%')\n res = '%1.0f%%' % x\n return res.replace('.0%', '%')\n" ]
[ [ "matplotlib.dates.DateFormatter", "matplotlib.pyplot.yscale", "matplotlib.pyplot.subplots", "pandas.DataFrame", "matplotlib.pyplot.savefig", "matplotlib.pyplot.subplot", "matplotlib.pyplot.close", "matplotlib.pyplot.subplots_adjust", "matplotlib.ticker.FormatStrFormatter", "matplotlib.ticker.FuncFormatter", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
csehong/stanford-tensorflow-tutorials
[ "fd93ff0568914724f2b9e97920eb8d6138efc52c" ]
[ "examples/08_tfRecord.py" ]
[ "\"\"\" Examples to demonstrate how to write an image file to a TFRecord,\nand how to read a TFRecord file using TFRecordReader.\nAuthor: Chip Huyen\nPrepared for the class CS 20SI: \"TensorFlow for Deep Learning Research\"\ncs20si.stanford.edu\n\"\"\"\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n\nimport sys\nsys.path.append('..')\n\nfrom PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\n# image supposed to have shape: 480 x 640 x 3 = 921600\nIMAGE_PATH = 'data/'\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\ndef get_image_binary(filename):\n \"\"\" You can read in the image using tensorflow too, but it's a drag\n since you have to create graphs. It's much easier using Pillow and NumPy\n \"\"\"\n image = Image.open(filename)\n image = np.asarray(image, np.uint8)\n shape = np.array(image.shape, np.int32)\n return shape.tobytes(), image.tobytes() # convert image to raw data bytes in the array.\n\ndef write_to_tfrecord(label, shape, binary_image, tfrecord_file):\n \"\"\" This example is to write a sample to TFRecord file. If you want to write\n more samples, just use a loop.\n \"\"\"\n writer = tf.python_io.TFRecordWriter(tfrecord_file)\n # write label, shape, and image content to the TFRecord file\n example = tf.train.Example(features=tf.train.Features(feature={\n 'label': _int64_feature(label),\n 'shape': _bytes_feature(shape),\n 'image': _bytes_feature(binary_image)\n }))\n writer.write(example.SerializeToString())\n writer.close()\n\ndef write_tfrecord(label, image_file, tfrecord_file):\n shape, binary_image = get_image_binary(image_file)\n write_to_tfrecord(label, shape, binary_image, tfrecord_file)\n\n\n\n\n\n\ndef read_from_tfrecord(filenames):\n tfrecord_file_queue = tf.train.string_input_producer(filenames, name='queue')\n reader = tf.TFRecordReader()\n _, tfrecord_serialized = reader.read(tfrecord_file_queue)\n\n # label and image are stored as bytes but could be stored as\n # int64 or float64 values in a serialized tf.Example protobuf.\n tfrecord_features = tf.parse_single_example(tfrecord_serialized,\n features={\n 'label': tf.FixedLenFeature([], tf.int64),\n 'shape': tf.FixedLenFeature([], tf.string),\n 'image': tf.FixedLenFeature([], tf.string),\n }, name='features')\n # image was saved as uint8, so we have to decode as uint8.\n image = tf.decode_raw(tfrecord_features['image'], tf.uint8)\n shape = tf.decode_raw(tfrecord_features['shape'], tf.int32)\n # the image tensor is flattened out, so we have to reconstruct the shape\n image = tf.reshape(image, shape)\n label = tfrecord_features['label']\n return label, shape, image\n\ndef read_tfrecord(tfrecord_file):\n label, shape, image = read_from_tfrecord([tfrecord_file])\n\n with tf.Session() as sess:\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n label, image, shape = sess.run([label, image, shape])\n coord.request_stop()\n coord.join(threads)\n print(label)\n print(shape)\n plt.imshow(image)\n plt.show()\n\ndef main():\n # assume the image has the label Chihuahua, which corresponds to class number 1\n label = 1\n image_file = IMAGE_PATH + 'friday.jpg'\n tfrecord_file = IMAGE_PATH + 'friday.tfrecord'\n write_tfrecord(label, image_file, tfrecord_file)\n read_tfrecord(tfrecord_file)\n\nif __name__ == '__main__':\n main()" ]
[ [ "matplotlib.pyplot.imshow", "tensorflow.FixedLenFeature", "numpy.asarray", "tensorflow.train.start_queue_runners", "tensorflow.decode_raw", "tensorflow.reshape", "tensorflow.train.Coordinator", "tensorflow.python_io.TFRecordWriter", "tensorflow.train.string_input_producer", "tensorflow.Session", "tensorflow.TFRecordReader", "tensorflow.train.BytesList", "numpy.array", "matplotlib.pyplot.show", "tensorflow.train.Int64List" ] ]
afish880/TensorTest
[ "a41f00ac171cf53539b4e2de47f2e15ccb848c90" ]
[ "research/maskgan/models/rnn_zaremba.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\n\"\"\"Simple RNN model definitions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nFLAGS = tf.app.flags.FLAGS\n\n\ndef generator(hparams,\n inputs,\n targets,\n targets_present,\n is_training,\n is_validating,\n reuse=None):\n \"\"\"Define the Generator graph.\n\n G will now impute tokens that have been masked from the input seqeunce.\n \"\"\"\n tf.logging.warning(\n 'Undirectional generative model is not a useful model for this MaskGAN '\n 'because future context is needed. Use only for debugging purposes.')\n init_scale = 0.05\n initializer = tf.random_uniform_initializer(-init_scale, init_scale)\n with tf.variable_scope('gen', reuse=reuse, initializer=initializer):\n\n def lstm_cell():\n return tf.contrib.rnn.BasicLSTMCell(hparams.gen_rnn_size,\n forget_bias=0.0,\n state_is_tuple=True,\n reuse=reuse)\n\n attn_cell = lstm_cell\n if is_training and FLAGS.keep_prob < 1:\n\n def attn_cell():\n return tf.contrib.rnn.DropoutWrapper(\n lstm_cell(), output_keep_prob=FLAGS.keep_prob)\n\n cell_gen = tf.contrib.rnn.MultiRNNCell(\n [attn_cell() for _ in range(hparams.gen_num_layers)],\n state_is_tuple=True)\n\n initial_state = cell_gen.zero_state(FLAGS.batch_size, tf.float32)\n\n with tf.variable_scope('rnn'):\n sequence, logits, log_probs = [], [], []\n embedding = tf.get_variable('embedding',\n [FLAGS.vocab_size, hparams.gen_rnn_size])\n softmax_w = tf.get_variable('softmax_w',\n [hparams.gen_rnn_size, FLAGS.vocab_size])\n softmax_b = tf.get_variable('softmax_b', [FLAGS.vocab_size])\n\n rnn_inputs = tf.nn.embedding_lookup(embedding, inputs)\n\n if is_training and FLAGS.keep_prob < 1:\n rnn_inputs = tf.nn.dropout(rnn_inputs, FLAGS.keep_prob)\n\n fake = None\n for t in xrange(FLAGS.sequence_length):\n if t > 0:\n tf.get_variable_scope().reuse_variables()\n\n # Input to the model is the first token to provide context. The\n # model will then predict token t > 0.\n if t == 0:\n # Always provide the real input at t = 0.\n state_gen = initial_state\n rnn_inp = rnn_inputs[:, t]\n\n # If the input is present, read in the input at t.\n # If the input is not present, read in the previously generated.\n else:\n real_rnn_inp = rnn_inputs[:, t]\n fake_rnn_inp = tf.nn.embedding_lookup(embedding, fake)\n\n # While validating, the decoder should be operating in teacher\n # forcing regime. Also, if we're just training with cross_entropy\n # use teacher forcing.\n if is_validating or (is_training and\n FLAGS.gen_training_strategy == 'cross_entropy'):\n rnn_inp = real_rnn_inp\n else:\n rnn_inp = tf.where(targets_present[:, t - 1], real_rnn_inp,\n fake_rnn_inp)\n\n # RNN.\n rnn_out, state_gen = cell_gen(rnn_inp, state_gen)\n logit = tf.matmul(rnn_out, softmax_w) + softmax_b\n\n # Real sample.\n real = targets[:, t]\n\n categorical = tf.contrib.distributions.Categorical(logits=logit)\n fake = categorical.sample()\n log_prob = categorical.log_prob(fake)\n\n # Output for Generator will either be generated or the input.\n #\n # If present: Return real.\n # If not present: Return fake.\n output = tf.where(targets_present[:, t], real, fake)\n\n # Add to lists.\n sequence.append(output)\n log_probs.append(log_prob)\n logits.append(logit)\n\n # Produce the RNN state had the model operated only\n # over real data.\n real_state_gen = initial_state\n for t in xrange(FLAGS.sequence_length):\n tf.get_variable_scope().reuse_variables()\n\n rnn_inp = rnn_inputs[:, t]\n\n # RNN.\n rnn_out, real_state_gen = cell_gen(rnn_inp, real_state_gen)\n\n final_state = real_state_gen\n\n return (tf.stack(sequence, axis=1), tf.stack(logits, axis=1), tf.stack(\n log_probs, axis=1), initial_state, final_state)\n\n\ndef discriminator(hparams, sequence, is_training, reuse=None):\n \"\"\"Define the Discriminator graph.\"\"\"\n tf.logging.warning(\n 'Undirectional Discriminative model is not a useful model for this '\n 'MaskGAN because future context is needed. Use only for debugging '\n 'purposes.')\n sequence = tf.cast(sequence, tf.int32)\n\n with tf.variable_scope('dis', reuse=reuse):\n\n def lstm_cell():\n return tf.contrib.rnn.BasicLSTMCell(hparams.dis_rnn_size,\n forget_bias=0.0,\n state_is_tuple=True,\n reuse=reuse)\n\n attn_cell = lstm_cell\n if is_training and FLAGS.keep_prob < 1:\n\n def attn_cell():\n return tf.contrib.rnn.DropoutWrapper(\n lstm_cell(), output_keep_prob=FLAGS.keep_prob)\n\n cell_dis = tf.contrib.rnn.MultiRNNCell(\n [attn_cell() for _ in range(hparams.dis_num_layers)],\n state_is_tuple=True)\n\n state_dis = cell_dis.zero_state(FLAGS.batch_size, tf.float32)\n\n with tf.variable_scope('rnn') as vs:\n predictions = []\n embedding = tf.get_variable('embedding',\n [FLAGS.vocab_size, hparams.dis_rnn_size])\n\n rnn_inputs = tf.nn.embedding_lookup(embedding, sequence)\n\n if is_training and FLAGS.keep_prob < 1:\n rnn_inputs = tf.nn.dropout(rnn_inputs, FLAGS.keep_prob)\n\n for t in xrange(FLAGS.sequence_length):\n if t > 0:\n tf.get_variable_scope().reuse_variables()\n\n rnn_in = rnn_inputs[:, t]\n rnn_out, state_dis = cell_dis(rnn_in, state_dis)\n\n # Prediction is linear output for Discriminator.\n pred = tf.contrib.layers.linear(rnn_out, 1, scope=vs)\n\n predictions.append(pred)\n predictions = tf.stack(predictions, axis=1)\n return tf.squeeze(predictions, axis=2)\n" ]
[ [ "tensorflow.logging.warning", "tensorflow.get_variable", "tensorflow.contrib.layers.linear", "tensorflow.matmul", "tensorflow.random_uniform_initializer", "tensorflow.stack", "tensorflow.contrib.rnn.BasicLSTMCell", "tensorflow.cast", "tensorflow.squeeze", "tensorflow.contrib.distributions.Categorical", "tensorflow.where", "tensorflow.variable_scope", "tensorflow.get_variable_scope", "tensorflow.nn.embedding_lookup", "tensorflow.nn.dropout" ] ]
Numlet/pgw-python
[ "1731fccdd0d3a3a199246fdc6dc04058273237ab" ]
[ "timesmoothing.py" ]
[ "# -*- coding: utf-8 -*-\n\n#from settings import annualcycleraw, variablename_to_smooth, outputpath\nimport xarray as xr\nimport numpy as np\nimport sys\nimport math\nfrom pathlib import Path\n\ndef filterdata(annualcycleraw, variablename_to_smooth, outputpath):\n\n\t\"\"\"\n\tThis function performs a temporal smoothing of an annual timeseries (typically daily resolution) using a spectral filter \n (Bosshard et al. 2011).\n\n\tInput:\n\t\tInput 1: Path to a netcdf file of the annual cycle to be smoothed. \n Normally this is the change in a specific variable between two simulations (e.g. warming). \n Can be 4 or 3 dimensional, where the time is one dimension and the others are space dimensions.\n\t\tInput 2: The name of the variable within the given netcdf file\n\t\tInput 3: Path where to save the output\n\t\t\n\tOutput:\n\t\tA netcdf file containing the smoothed annual cycle. Format: \"variablename\"_filteredcycle.nc\n\t\"\"\"\t\n\n\tDiff = xr.open_dataset(annualcycleraw)[variablename_to_smooth].squeeze()\n\tcoords = Diff.coords\n\n\tprint('Dimension that is assumed to be time dimension is called: ', Diff.dims[0])\n\tprint('shape of data: ', Diff.shape)\n\n\tDiff = Diff.data\n\n\t#create an array to store the smoothed timeseries\n\t#Diff_smooth=np.zeros_like(Diff, dtype=np.float32) \n\n\tif len(Diff.shape) == 4:\n\t\ttimes = Diff.shape[0] \n\t\tlevels = Diff.shape[1]\n\t\tygrids = Diff.shape[2]\n\t\txgrids = Diff.shape[3]\n\telif len(Diff.shape) == 3:\n\t\ttimes = Diff.shape[0]\n\t\tygrids = Diff.shape[1]\n\t\txgrids = Diff.shape[2]\n\t\tlevels = 0\n\telse:\n\t\tsys.exit('Wrog dimensions of input file should be 3 or 4-D')\n\n\n\tif len(Diff.shape) == 4:\n\t\tfor i in range(levels): #loop over levels to smooth the timeseries on every level\n\t\t\tfor yy in range(ygrids):\n\t\t\t\tfor xx in range(xgrids):\t\n\t\t\t\t\tDiff[:,i,yy,xx] = harmonic_ac_analysis(Diff[:,i,yy,xx]) #reconstruct the smoothed timeseries using function below\n\n\n\n\tif len(Diff.shape) == 3:\t\t\n\t\tfor yy in range(ygrids):\n\t\t\tfor xx in range(xgrids):\t\n\t\t\t\tDiff[:,yy,xx] = harmonic_ac_analysis(Diff[:,yy,xx]) #dump the smoothed timeseries in the array on the original level\n\t\t\t\n\n\tprint('Done with smoothing')\n\n\t#del Diff\n\n\tDiff = xr.DataArray(Diff, coords=coords, name=variablename_to_smooth)\n\tPath(outputpath).mkdir(parents=True, exist_ok=True)\n\tDiff.to_netcdf(outputpath+'/'+variablename_to_smooth+'_filteredcycle.nc', mode='w')\n\n\tprint('saved file '+outputpath+'/'+variablename_to_smooth+'_filteredcycle.nc')\n\n\ndef harmonic_ac_analysis(ts):\n\t\"\"\"\n\tEstimation of the harmonics according to formula 12.19 -\n\t12.23 on p. 264 in Storch & Zwiers\n\n\tIs incomplete since it is only for use in surrogate smoothing --> only the part of the formulas that is needed there\n\n\tArguments:\n\t\tts: a 1-d numpy array of a timeseries\n\n\tReturns:\n\t\thcts: a reconstructed smoothed timeseries (the more modes are summed the less smoothing)\n\t\tmean: the mean of the timeseries (needed for reconstruction)\n\t\"\"\"\n\t\n\tif np.any(np.isnan(ts) == True): #if there are nans, return nans\n\t\tsmooths = np.full_like(ts, np.nan) #sys.exit('There are nan values')\n\t\treturn smooths\n\telse:\n\t\tmean = ts.mean() #calculate the mean of the timeseries (used for reconstruction)\n\t\n\t\tlt = len(ts) #how long is the timeseries?\n\t\tP = lt\n\n\t\t#initialize the output array. we will use at max 4 modes for reconstruction (for peformance reasons, it can be increased)\n\t\thcts = np.zeros((4,lt))\n\n\t\ttimevector=np.arange(1,lt+1,1)\t#timesteps used in calculation\t\n\n\t\tq = math.floor(P/2.) #a measure that is to check that the performed calculation is justified.\n\t\n\t\tfor i in range(1,4): #create the reconstruction timeseries, mode by mode (starting at 1 until 5, if one wants more smoothing this number can be increased.)\n\t\t\tif i < q: #only if this is true the calculation is valid\n\t\t\t\n\t\t\t\t#these are the formulas from Storch & Zwiers\n\t\t\t\tbracket = 2.*math.pi*i/P*timevector\n\t\t\t\ta = 2./lt*(ts.dot(np.cos(bracket))) #careful with multiplications of vectors (ts and timevector)..\n\t\t\t\tb = 2./lt*(ts.dot(np.sin(bracket))) #dot product (Skalarprodukt) for scalar number output!\n\t\t\t\t\n\t\t\t\thcts[i-1,:] = a * np.cos(bracket) + b * np.sin(bracket) #calculate the reconstruction time series\n\t\t\t\n\t\t\telse: #abort if the above condition is not fulfilled. In this case more programming is needed.\n\t\t\t\tsys.exit('Whooops that should not be the case for a yearly timeseries! i (reconstruction grade) is larger than the number of timeseries elements / 2.')\n\n\t\tsmooths = sum(hcts[0:3,:]) + mean\n\t\treturn smooths\n\n\nif __name__ == \"__main__\":\n\tannualcycleraw = str(sys.argv[1])\n\tvariablename_to_smooth = str(sys.argv[2])\n\toutputpath = str(sys.argv[3])\n\tfilterdata(annualcycleraw, variablename_to_smooth, outputpath)\n\n\n" ]
[ [ "numpy.isnan", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.full_like", "numpy.zeros" ] ]
fabiodepa/ForestQC
[ "aba6d0f2f6925c62229bd01ace7370be314f5886" ]
[ "other/abnormal_sample_detection/scripts/calculate_sampleAB.py" ]
[ "from sample_level_vcf_stat import *\nimport os\nimport sys\nimport pandas as pd\n\n# sample = os.listdir('/u/home/k/k8688933/Jaehoon/data')\n# good_variants_rsid_file = '/u/scratch2/k/k8688933/stat_output/vqsr_qc4/good.all.clfB.rsid'\nvcf_file = sys.argv[1]\noutfile = sys.argv[2]\n# list_ = []\n\n# with open(good_variants_rsid_file, 'r') as f:\n # for line in f:\n # if not line.startswith('RSID'):\n # list_.append(line.strip())\n\nsample_ab = sampleLevelAB([vcf_file])\nab = pd.DataFrame(sample_ab)\nab.to_csv(outfile)\n" ]
[ [ "pandas.DataFrame" ] ]
jcw780/numpy
[ "1912db21e0f5e61739168864f6b1f37dff3b4006" ]
[ "numpy/lib/tests/test_arraypad.py" ]
[ "\"\"\"Tests for the array padding functions.\n\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\n\nimport pytest\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal, assert_allclose, assert_equal\nfrom numpy.lib.arraypad import _as_pairs\n\n\n_numeric_dtypes = (\n np.sctypes[\"uint\"]\n + np.sctypes[\"int\"]\n + np.sctypes[\"float\"]\n + np.sctypes[\"complex\"]\n)\n_all_modes = {\n 'constant': {'constant_values': 0},\n 'edge': {},\n 'linear_ramp': {'end_values': 0},\n 'maximum': {'stat_length': None},\n 'mean': {'stat_length': None},\n 'median': {'stat_length': None},\n 'minimum': {'stat_length': None},\n 'reflect': {'reflect_type': 'even'},\n 'symmetric': {'reflect_type': 'even'},\n 'wrap': {},\n 'empty': {}\n}\n\n\nclass TestAsPairs(object):\n def test_single_value(self):\n \"\"\"Test casting for a single value.\"\"\"\n expected = np.array([[3, 3]] * 10)\n for x in (3, [3], [[3]]):\n result = _as_pairs(x, 10)\n assert_equal(result, expected)\n # Test with dtype=object\n obj = object()\n assert_equal(\n _as_pairs(obj, 10),\n np.array([[obj, obj]] * 10)\n )\n\n def test_two_values(self):\n \"\"\"Test proper casting for two different values.\"\"\"\n # Broadcasting in the first dimension with numbers\n expected = np.array([[3, 4]] * 10)\n for x in ([3, 4], [[3, 4]]):\n result = _as_pairs(x, 10)\n assert_equal(result, expected)\n # and with dtype=object\n obj = object()\n assert_equal(\n _as_pairs([\"a\", obj], 10),\n np.array([[\"a\", obj]] * 10)\n )\n\n # Broadcasting in the second / last dimension with numbers\n assert_equal(\n _as_pairs([[3], [4]], 2),\n np.array([[3, 3], [4, 4]])\n )\n # and with dtype=object\n assert_equal(\n _as_pairs([[\"a\"], [obj]], 2),\n np.array([[\"a\", \"a\"], [obj, obj]])\n )\n\n def test_with_none(self):\n expected = ((None, None), (None, None), (None, None))\n assert_equal(\n _as_pairs(None, 3, as_index=False),\n expected\n )\n assert_equal(\n _as_pairs(None, 3, as_index=True),\n expected\n )\n\n def test_pass_through(self):\n \"\"\"Test if `x` already matching desired output are passed through.\"\"\"\n expected = np.arange(12).reshape((6, 2))\n assert_equal(\n _as_pairs(expected, 6),\n expected\n )\n\n def test_as_index(self):\n \"\"\"Test results if `as_index=True`.\"\"\"\n assert_equal(\n _as_pairs([2.6, 3.3], 10, as_index=True),\n np.array([[3, 3]] * 10, dtype=np.intp)\n )\n assert_equal(\n _as_pairs([2.6, 4.49], 10, as_index=True),\n np.array([[3, 4]] * 10, dtype=np.intp)\n )\n for x in (-3, [-3], [[-3]], [-3, 4], [3, -4], [[-3, 4]], [[4, -3]],\n [[1, 2]] * 9 + [[1, -2]]):\n with pytest.raises(ValueError, match=\"negative values\"):\n _as_pairs(x, 10, as_index=True)\n\n def test_exceptions(self):\n \"\"\"Ensure faulty usage is discovered.\"\"\"\n with pytest.raises(ValueError, match=\"more dimensions than allowed\"):\n _as_pairs([[[3]]], 10)\n with pytest.raises(ValueError, match=\"could not be broadcast\"):\n _as_pairs([[1, 2], [3, 4]], 3)\n with pytest.raises(ValueError, match=\"could not be broadcast\"):\n _as_pairs(np.ones((2, 3)), 3)\n\n\nclass TestConditionalShortcuts(object):\n @pytest.mark.parametrize(\"mode\", _all_modes.keys())\n def test_zero_padding_shortcuts(self, mode):\n test = np.arange(120).reshape(4, 5, 6)\n pad_amt = [(0, 0) for _ in test.shape]\n assert_array_equal(test, np.pad(test, pad_amt, mode=mode))\n\n @pytest.mark.parametrize(\"mode\", ['maximum', 'mean', 'median', 'minimum',])\n def test_shallow_statistic_range(self, mode):\n test = np.arange(120).reshape(4, 5, 6)\n pad_amt = [(1, 1) for _ in test.shape]\n assert_array_equal(np.pad(test, pad_amt, mode='edge'),\n np.pad(test, pad_amt, mode=mode, stat_length=1))\n\n @pytest.mark.parametrize(\"mode\", ['maximum', 'mean', 'median', 'minimum',])\n def test_clip_statistic_range(self, mode):\n test = np.arange(30).reshape(5, 6)\n pad_amt = [(3, 3) for _ in test.shape]\n assert_array_equal(np.pad(test, pad_amt, mode=mode),\n np.pad(test, pad_amt, mode=mode, stat_length=30))\n\n\nclass TestStatistic(object):\n def test_check_mean_stat_length(self):\n a = np.arange(100).astype('f')\n a = np.pad(a, ((25, 20), ), 'mean', stat_length=((2, 3), ))\n b = np.array(\n [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,\n 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,\n 0.5, 0.5, 0.5, 0.5, 0.5,\n\n 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,\n 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.,\n 20., 21., 22., 23., 24., 25., 26., 27., 28., 29.,\n 30., 31., 32., 33., 34., 35., 36., 37., 38., 39.,\n 40., 41., 42., 43., 44., 45., 46., 47., 48., 49.,\n 50., 51., 52., 53., 54., 55., 56., 57., 58., 59.,\n 60., 61., 62., 63., 64., 65., 66., 67., 68., 69.,\n 70., 71., 72., 73., 74., 75., 76., 77., 78., 79.,\n 80., 81., 82., 83., 84., 85., 86., 87., 88., 89.,\n 90., 91., 92., 93., 94., 95., 96., 97., 98., 99.,\n\n 98., 98., 98., 98., 98., 98., 98., 98., 98., 98.,\n 98., 98., 98., 98., 98., 98., 98., 98., 98., 98.\n ])\n assert_array_equal(a, b)\n\n def test_check_maximum_1(self):\n a = np.arange(100)\n a = np.pad(a, (25, 20), 'maximum')\n b = np.array(\n [99, 99, 99, 99, 99, 99, 99, 99, 99, 99,\n 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,\n 99, 99, 99, 99, 99,\n\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,\n 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,\n 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,\n 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,\n 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,\n 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,\n 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,\n\n 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,\n 99, 99, 99, 99, 99, 99, 99, 99, 99, 99]\n )\n assert_array_equal(a, b)\n\n def test_check_maximum_2(self):\n a = np.arange(100) + 1\n a = np.pad(a, (25, 20), 'maximum')\n b = np.array(\n [100, 100, 100, 100, 100, 100, 100, 100, 100, 100,\n 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,\n 100, 100, 100, 100, 100,\n\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,\n 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,\n 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,\n 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,\n 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,\n 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,\n 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,\n 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,\n 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,\n\n 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,\n 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]\n )\n assert_array_equal(a, b)\n\n def test_check_maximum_stat_length(self):\n a = np.arange(100) + 1\n a = np.pad(a, (25, 20), 'maximum', stat_length=10)\n b = np.array(\n [10, 10, 10, 10, 10, 10, 10, 10, 10, 10,\n 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,\n 10, 10, 10, 10, 10,\n\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,\n 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,\n 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,\n 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,\n 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,\n 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,\n 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,\n 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,\n 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,\n\n 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,\n 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]\n )\n assert_array_equal(a, b)\n\n def test_check_minimum_1(self):\n a = np.arange(100)\n a = np.pad(a, (25, 20), 'minimum')\n b = np.array(\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0,\n\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,\n 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,\n 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,\n 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,\n 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,\n 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,\n 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n )\n assert_array_equal(a, b)\n\n def test_check_minimum_2(self):\n a = np.arange(100) + 2\n a = np.pad(a, (25, 20), 'minimum')\n b = np.array(\n [2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2,\n\n 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,\n 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,\n 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,\n 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,\n 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,\n 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,\n 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,\n 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,\n 92, 93, 94, 95, 96, 97, 98, 99, 100, 101,\n\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]\n )\n assert_array_equal(a, b)\n\n def test_check_minimum_stat_length(self):\n a = np.arange(100) + 1\n a = np.pad(a, (25, 20), 'minimum', stat_length=10)\n b = np.array(\n [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1,\n\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,\n 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,\n 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,\n 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,\n 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,\n 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,\n 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,\n 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,\n 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,\n\n 91, 91, 91, 91, 91, 91, 91, 91, 91, 91,\n 91, 91, 91, 91, 91, 91, 91, 91, 91, 91]\n )\n assert_array_equal(a, b)\n\n def test_check_median(self):\n a = np.arange(100).astype('f')\n a = np.pad(a, (25, 20), 'median')\n b = np.array(\n [49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5,\n 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5,\n 49.5, 49.5, 49.5, 49.5, 49.5,\n\n 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,\n 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.,\n 20., 21., 22., 23., 24., 25., 26., 27., 28., 29.,\n 30., 31., 32., 33., 34., 35., 36., 37., 38., 39.,\n 40., 41., 42., 43., 44., 45., 46., 47., 48., 49.,\n 50., 51., 52., 53., 54., 55., 56., 57., 58., 59.,\n 60., 61., 62., 63., 64., 65., 66., 67., 68., 69.,\n 70., 71., 72., 73., 74., 75., 76., 77., 78., 79.,\n 80., 81., 82., 83., 84., 85., 86., 87., 88., 89.,\n 90., 91., 92., 93., 94., 95., 96., 97., 98., 99.,\n\n 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5,\n 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5]\n )\n assert_array_equal(a, b)\n\n def test_check_median_01(self):\n a = np.array([[3, 1, 4], [4, 5, 9], [9, 8, 2]])\n a = np.pad(a, 1, 'median')\n b = np.array(\n [[4, 4, 5, 4, 4],\n\n [3, 3, 1, 4, 3],\n [5, 4, 5, 9, 5],\n [8, 9, 8, 2, 8],\n\n [4, 4, 5, 4, 4]]\n )\n assert_array_equal(a, b)\n\n def test_check_median_02(self):\n a = np.array([[3, 1, 4], [4, 5, 9], [9, 8, 2]])\n a = np.pad(a.T, 1, 'median').T\n b = np.array(\n [[5, 4, 5, 4, 5],\n\n [3, 3, 1, 4, 3],\n [5, 4, 5, 9, 5],\n [8, 9, 8, 2, 8],\n\n [5, 4, 5, 4, 5]]\n )\n assert_array_equal(a, b)\n\n def test_check_median_stat_length(self):\n a = np.arange(100).astype('f')\n a[1] = 2.\n a[97] = 96.\n a = np.pad(a, (25, 20), 'median', stat_length=(3, 5))\n b = np.array(\n [ 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,\n 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,\n 2., 2., 2., 2., 2.,\n\n 0., 2., 2., 3., 4., 5., 6., 7., 8., 9.,\n 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.,\n 20., 21., 22., 23., 24., 25., 26., 27., 28., 29.,\n 30., 31., 32., 33., 34., 35., 36., 37., 38., 39.,\n 40., 41., 42., 43., 44., 45., 46., 47., 48., 49.,\n 50., 51., 52., 53., 54., 55., 56., 57., 58., 59.,\n 60., 61., 62., 63., 64., 65., 66., 67., 68., 69.,\n 70., 71., 72., 73., 74., 75., 76., 77., 78., 79.,\n 80., 81., 82., 83., 84., 85., 86., 87., 88., 89.,\n 90., 91., 92., 93., 94., 95., 96., 96., 98., 99.,\n\n 96., 96., 96., 96., 96., 96., 96., 96., 96., 96.,\n 96., 96., 96., 96., 96., 96., 96., 96., 96., 96.]\n )\n assert_array_equal(a, b)\n\n def test_check_mean_shape_one(self):\n a = [[4, 5, 6]]\n a = np.pad(a, (5, 7), 'mean', stat_length=2)\n b = np.array(\n [[4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6],\n [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6],\n [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6],\n [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6],\n [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6],\n\n [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6],\n\n [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6],\n [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6],\n [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6],\n [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6],\n [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6],\n [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6],\n [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6]]\n )\n assert_array_equal(a, b)\n\n def test_check_mean_2(self):\n a = np.arange(100).astype('f')\n a = np.pad(a, (25, 20), 'mean')\n b = np.array(\n [49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5,\n 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5,\n 49.5, 49.5, 49.5, 49.5, 49.5,\n\n 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,\n 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.,\n 20., 21., 22., 23., 24., 25., 26., 27., 28., 29.,\n 30., 31., 32., 33., 34., 35., 36., 37., 38., 39.,\n 40., 41., 42., 43., 44., 45., 46., 47., 48., 49.,\n 50., 51., 52., 53., 54., 55., 56., 57., 58., 59.,\n 60., 61., 62., 63., 64., 65., 66., 67., 68., 69.,\n 70., 71., 72., 73., 74., 75., 76., 77., 78., 79.,\n 80., 81., 82., 83., 84., 85., 86., 87., 88., 89.,\n 90., 91., 92., 93., 94., 95., 96., 97., 98., 99.,\n\n 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5,\n 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5]\n )\n assert_array_equal(a, b)\n\n @pytest.mark.parametrize(\"mode\", [\n \"mean\",\n \"median\",\n \"minimum\",\n \"maximum\"\n ])\n def test_same_prepend_append(self, mode):\n \"\"\" Test that appended and prepended values are equal \"\"\"\n # This test is constructed to trigger floating point rounding errors in\n # a way that caused gh-11216 for mode=='mean'\n a = np.array([-1, 2, -1]) + np.array([0, 1e-12, 0], dtype=np.float64)\n a = np.pad(a, (1, 1), mode)\n assert_equal(a[0], a[-1])\n\n @pytest.mark.parametrize(\"mode\", [\"mean\", \"median\", \"minimum\", \"maximum\"])\n @pytest.mark.parametrize(\n \"stat_length\", [-2, (-2,), (3, -1), ((5, 2), (-2, 3)), ((-4,), (2,))]\n )\n def test_check_negative_stat_length(self, mode, stat_length):\n arr = np.arange(30).reshape((6, 5))\n match = \"index can't contain negative values\"\n with pytest.raises(ValueError, match=match):\n np.pad(arr, 2, mode, stat_length=stat_length)\n\n def test_simple_stat_length(self):\n a = np.arange(30)\n a = np.reshape(a, (6, 5))\n a = np.pad(a, ((2, 3), (3, 2)), mode='mean', stat_length=(3,))\n b = np.array(\n [[6, 6, 6, 5, 6, 7, 8, 9, 8, 8],\n [6, 6, 6, 5, 6, 7, 8, 9, 8, 8],\n\n [1, 1, 1, 0, 1, 2, 3, 4, 3, 3],\n [6, 6, 6, 5, 6, 7, 8, 9, 8, 8],\n [11, 11, 11, 10, 11, 12, 13, 14, 13, 13],\n [16, 16, 16, 15, 16, 17, 18, 19, 18, 18],\n [21, 21, 21, 20, 21, 22, 23, 24, 23, 23],\n [26, 26, 26, 25, 26, 27, 28, 29, 28, 28],\n\n [21, 21, 21, 20, 21, 22, 23, 24, 23, 23],\n [21, 21, 21, 20, 21, 22, 23, 24, 23, 23],\n [21, 21, 21, 20, 21, 22, 23, 24, 23, 23]]\n )\n assert_array_equal(a, b)\n\n @pytest.mark.filterwarnings(\"ignore:Mean of empty slice:RuntimeWarning\")\n @pytest.mark.filterwarnings(\n \"ignore:invalid value encountered in (true_divide|double_scalars):\"\n \"RuntimeWarning\"\n )\n @pytest.mark.parametrize(\"mode\", [\"mean\", \"median\"])\n def test_zero_stat_length_valid(self, mode):\n arr = np.pad([1., 2.], (1, 2), mode, stat_length=0)\n expected = np.array([np.nan, 1., 2., np.nan, np.nan])\n assert_equal(arr, expected)\n\n @pytest.mark.parametrize(\"mode\", [\"minimum\", \"maximum\"])\n def test_zero_stat_length_invalid(self, mode):\n match = \"stat_length of 0 yields no value for padding\"\n with pytest.raises(ValueError, match=match):\n np.pad([1., 2.], 0, mode, stat_length=0)\n with pytest.raises(ValueError, match=match):\n np.pad([1., 2.], 0, mode, stat_length=(1, 0))\n with pytest.raises(ValueError, match=match):\n np.pad([1., 2.], 1, mode, stat_length=0)\n with pytest.raises(ValueError, match=match):\n np.pad([1., 2.], 1, mode, stat_length=(1, 0))\n\n\nclass TestConstant(object):\n def test_check_constant(self):\n a = np.arange(100)\n a = np.pad(a, (25, 20), 'constant', constant_values=(10, 20))\n b = np.array(\n [10, 10, 10, 10, 10, 10, 10, 10, 10, 10,\n 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,\n 10, 10, 10, 10, 10,\n\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,\n 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,\n 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,\n 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,\n 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,\n 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,\n 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,\n\n 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n 20, 20, 20, 20, 20, 20, 20, 20, 20, 20]\n )\n assert_array_equal(a, b)\n\n def test_check_constant_zeros(self):\n a = np.arange(100)\n a = np.pad(a, (25, 20), 'constant')\n b = np.array(\n [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0,\n\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,\n 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,\n 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,\n 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,\n 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,\n 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,\n 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n )\n assert_array_equal(a, b)\n\n def test_check_constant_float(self):\n # If input array is int, but constant_values are float, the dtype of\n # the array to be padded is kept\n arr = np.arange(30).reshape(5, 6)\n test = np.pad(arr, (1, 2), mode='constant',\n constant_values=1.1)\n expected = np.array(\n [[ 1, 1, 1, 1, 1, 1, 1, 1, 1],\n\n [ 1, 0, 1, 2, 3, 4, 5, 1, 1],\n [ 1, 6, 7, 8, 9, 10, 11, 1, 1],\n [ 1, 12, 13, 14, 15, 16, 17, 1, 1],\n [ 1, 18, 19, 20, 21, 22, 23, 1, 1],\n [ 1, 24, 25, 26, 27, 28, 29, 1, 1],\n\n [ 1, 1, 1, 1, 1, 1, 1, 1, 1],\n [ 1, 1, 1, 1, 1, 1, 1, 1, 1]]\n )\n assert_allclose(test, expected)\n\n def test_check_constant_float2(self):\n # If input array is float, and constant_values are float, the dtype of\n # the array to be padded is kept - here retaining the float constants\n arr = np.arange(30).reshape(5, 6)\n arr_float = arr.astype(np.float64)\n test = np.pad(arr_float, ((1, 2), (1, 2)), mode='constant',\n constant_values=1.1)\n expected = np.array(\n [[ 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1],\n\n [ 1.1, 0. , 1. , 2. , 3. , 4. , 5. , 1.1, 1.1],\n [ 1.1, 6. , 7. , 8. , 9. , 10. , 11. , 1.1, 1.1],\n [ 1.1, 12. , 13. , 14. , 15. , 16. , 17. , 1.1, 1.1],\n [ 1.1, 18. , 19. , 20. , 21. , 22. , 23. , 1.1, 1.1],\n [ 1.1, 24. , 25. , 26. , 27. , 28. , 29. , 1.1, 1.1],\n\n [ 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1],\n [ 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1]]\n )\n assert_allclose(test, expected)\n\n def test_check_constant_float3(self):\n a = np.arange(100, dtype=float)\n a = np.pad(a, (25, 20), 'constant', constant_values=(-1.1, -1.2))\n b = np.array(\n [-1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1,\n -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1,\n -1.1, -1.1, -1.1, -1.1, -1.1,\n\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,\n 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,\n 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,\n 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,\n 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,\n 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,\n 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,\n\n -1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2,\n -1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2]\n )\n assert_allclose(a, b)\n\n def test_check_constant_odd_pad_amount(self):\n arr = np.arange(30).reshape(5, 6)\n test = np.pad(arr, ((1,), (2,)), mode='constant',\n constant_values=3)\n expected = np.array(\n [[ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],\n\n [ 3, 3, 0, 1, 2, 3, 4, 5, 3, 3],\n [ 3, 3, 6, 7, 8, 9, 10, 11, 3, 3],\n [ 3, 3, 12, 13, 14, 15, 16, 17, 3, 3],\n [ 3, 3, 18, 19, 20, 21, 22, 23, 3, 3],\n [ 3, 3, 24, 25, 26, 27, 28, 29, 3, 3],\n\n [ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]]\n )\n assert_allclose(test, expected)\n\n def test_check_constant_pad_2d(self):\n arr = np.arange(4).reshape(2, 2)\n test = np.lib.pad(arr, ((1, 2), (1, 3)), mode='constant',\n constant_values=((1, 2), (3, 4)))\n expected = np.array(\n [[3, 1, 1, 4, 4, 4],\n [3, 0, 1, 4, 4, 4],\n [3, 2, 3, 4, 4, 4],\n [3, 2, 2, 4, 4, 4],\n [3, 2, 2, 4, 4, 4]]\n )\n assert_allclose(test, expected)\n\n def test_check_large_integers(self):\n uint64_max = 2 ** 64 - 1\n arr = np.full(5, uint64_max, dtype=np.uint64)\n test = np.pad(arr, 1, mode=\"constant\", constant_values=arr.min())\n expected = np.full(7, uint64_max, dtype=np.uint64)\n assert_array_equal(test, expected)\n\n int64_max = 2 ** 63 - 1\n arr = np.full(5, int64_max, dtype=np.int64)\n test = np.pad(arr, 1, mode=\"constant\", constant_values=arr.min())\n expected = np.full(7, int64_max, dtype=np.int64)\n assert_array_equal(test, expected)\n\n def test_check_object_array(self):\n arr = np.empty(1, dtype=object)\n obj_a = object()\n arr[0] = obj_a\n obj_b = object()\n obj_c = object()\n arr = np.pad(arr, pad_width=1, mode='constant',\n constant_values=(obj_b, obj_c))\n\n expected = np.empty((3,), dtype=object)\n expected[0] = obj_b\n expected[1] = obj_a\n expected[2] = obj_c\n\n assert_array_equal(arr, expected)\n\n def test_pad_empty_dimension(self):\n arr = np.zeros((3, 0, 2))\n result = np.pad(arr, [(0,), (2,), (1,)], mode=\"constant\")\n assert result.shape == (3, 4, 4)\n\n\nclass TestLinearRamp(object):\n def test_check_simple(self):\n a = np.arange(100).astype('f')\n a = np.pad(a, (25, 20), 'linear_ramp', end_values=(4, 5))\n b = np.array(\n [4.00, 3.84, 3.68, 3.52, 3.36, 3.20, 3.04, 2.88, 2.72, 2.56,\n 2.40, 2.24, 2.08, 1.92, 1.76, 1.60, 1.44, 1.28, 1.12, 0.96,\n 0.80, 0.64, 0.48, 0.32, 0.16,\n\n 0.00, 1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00, 9.00,\n 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0,\n 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0,\n 30.0, 31.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0,\n 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0,\n 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0, 58.0, 59.0,\n 60.0, 61.0, 62.0, 63.0, 64.0, 65.0, 66.0, 67.0, 68.0, 69.0,\n 70.0, 71.0, 72.0, 73.0, 74.0, 75.0, 76.0, 77.0, 78.0, 79.0,\n 80.0, 81.0, 82.0, 83.0, 84.0, 85.0, 86.0, 87.0, 88.0, 89.0,\n 90.0, 91.0, 92.0, 93.0, 94.0, 95.0, 96.0, 97.0, 98.0, 99.0,\n\n 94.3, 89.6, 84.9, 80.2, 75.5, 70.8, 66.1, 61.4, 56.7, 52.0,\n 47.3, 42.6, 37.9, 33.2, 28.5, 23.8, 19.1, 14.4, 9.7, 5.]\n )\n assert_allclose(a, b, rtol=1e-5, atol=1e-5)\n\n def test_check_2d(self):\n arr = np.arange(20).reshape(4, 5).astype(np.float64)\n test = np.pad(arr, (2, 2), mode='linear_ramp', end_values=(0, 0))\n expected = np.array(\n [[0., 0., 0., 0., 0., 0., 0., 0., 0.],\n [0., 0., 0., 0.5, 1., 1.5, 2., 1., 0.],\n [0., 0., 0., 1., 2., 3., 4., 2., 0.],\n [0., 2.5, 5., 6., 7., 8., 9., 4.5, 0.],\n [0., 5., 10., 11., 12., 13., 14., 7., 0.],\n [0., 7.5, 15., 16., 17., 18., 19., 9.5, 0.],\n [0., 3.75, 7.5, 8., 8.5, 9., 9.5, 4.75, 0.],\n [0., 0., 0., 0., 0., 0., 0., 0., 0.]])\n assert_allclose(test, expected)\n\n @pytest.mark.xfail(exceptions=(AssertionError,))\n def test_object_array(self):\n from fractions import Fraction\n arr = np.array([Fraction(1, 2), Fraction(-1, 2)])\n actual = np.pad(arr, (2, 3), mode='linear_ramp', end_values=0)\n\n # deliberately chosen to have a non-power-of-2 denominator such that\n # rounding to floats causes a failure.\n expected = np.array([\n Fraction( 0, 12),\n Fraction( 3, 12),\n Fraction( 6, 12),\n Fraction(-6, 12),\n Fraction(-4, 12),\n Fraction(-2, 12),\n Fraction(-0, 12),\n ])\n assert_equal(actual, expected)\n\n def test_end_values(self):\n \"\"\"Ensure that end values are exact.\"\"\"\n a = np.pad(np.ones(10).reshape(2, 5), (223, 123), mode=\"linear_ramp\")\n assert_equal(a[:, 0], 0.)\n assert_equal(a[:, -1], 0.)\n assert_equal(a[0, :], 0.)\n assert_equal(a[-1, :], 0.)\n\n @pytest.mark.parametrize(\"dtype\", _numeric_dtypes)\n def test_negative_difference(self, dtype):\n \"\"\"\n Check correct behavior of unsigned dtypes if there is a negative\n difference between the edge to pad and `end_values`. Check both cases\n to be independent of implementation. Test behavior for all other dtypes\n in case dtype casting interferes with complex dtypes. See gh-14191.\n \"\"\"\n x = np.array([3], dtype=dtype)\n result = np.pad(x, 3, mode=\"linear_ramp\", end_values=0)\n expected = np.array([0, 1, 2, 3, 2, 1, 0], dtype=dtype)\n assert_equal(result, expected)\n\n x = np.array([0], dtype=dtype)\n result = np.pad(x, 3, mode=\"linear_ramp\", end_values=3)\n expected = np.array([3, 2, 1, 0, 1, 2, 3], dtype=dtype)\n assert_equal(result, expected)\n\n\nclass TestReflect(object):\n def test_check_simple(self):\n a = np.arange(100)\n a = np.pad(a, (25, 20), 'reflect')\n b = np.array(\n [25, 24, 23, 22, 21, 20, 19, 18, 17, 16,\n 15, 14, 13, 12, 11, 10, 9, 8, 7, 6,\n 5, 4, 3, 2, 1,\n\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,\n 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,\n 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,\n 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,\n 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,\n 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,\n 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,\n\n 98, 97, 96, 95, 94, 93, 92, 91, 90, 89,\n 88, 87, 86, 85, 84, 83, 82, 81, 80, 79]\n )\n assert_array_equal(a, b)\n\n def test_check_odd_method(self):\n a = np.arange(100)\n a = np.pad(a, (25, 20), 'reflect', reflect_type='odd')\n b = np.array(\n [-25, -24, -23, -22, -21, -20, -19, -18, -17, -16,\n -15, -14, -13, -12, -11, -10, -9, -8, -7, -6,\n -5, -4, -3, -2, -1,\n\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,\n 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,\n 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,\n 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,\n 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,\n 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,\n 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,\n\n 100, 101, 102, 103, 104, 105, 106, 107, 108, 109,\n 110, 111, 112, 113, 114, 115, 116, 117, 118, 119]\n )\n assert_array_equal(a, b)\n\n def test_check_large_pad(self):\n a = [[4, 5, 6], [6, 7, 8]]\n a = np.pad(a, (5, 7), 'reflect')\n b = np.array(\n [[7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7],\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7],\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7],\n\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7],\n\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7],\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7],\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7],\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5]]\n )\n assert_array_equal(a, b)\n\n def test_check_shape(self):\n a = [[4, 5, 6]]\n a = np.pad(a, (5, 7), 'reflect')\n b = np.array(\n [[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],\n [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5]]\n )\n assert_array_equal(a, b)\n\n def test_check_01(self):\n a = np.pad([1, 2, 3], 2, 'reflect')\n b = np.array([3, 2, 1, 2, 3, 2, 1])\n assert_array_equal(a, b)\n\n def test_check_02(self):\n a = np.pad([1, 2, 3], 3, 'reflect')\n b = np.array([2, 3, 2, 1, 2, 3, 2, 1, 2])\n assert_array_equal(a, b)\n\n def test_check_03(self):\n a = np.pad([1, 2, 3], 4, 'reflect')\n b = np.array([1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3])\n assert_array_equal(a, b)\n\n\nclass TestEmptyArray(object):\n \"\"\"Check how padding behaves on arrays with an empty dimension.\"\"\"\n\n @pytest.mark.parametrize(\n # Keep parametrization ordered, otherwise pytest-xdist might believe\n # that different tests were collected during parallelization\n \"mode\", sorted(_all_modes.keys() - {\"constant\", \"empty\"})\n )\n def test_pad_empty_dimension(self, mode):\n match = (\"can't extend empty axis 0 using modes other than 'constant' \"\n \"or 'empty'\")\n with pytest.raises(ValueError, match=match):\n np.pad([], 4, mode=mode)\n with pytest.raises(ValueError, match=match):\n np.pad(np.ndarray(0), 4, mode=mode)\n with pytest.raises(ValueError, match=match):\n np.pad(np.zeros((0, 3)), ((1,), (0,)), mode=mode)\n\n @pytest.mark.parametrize(\"mode\", _all_modes.keys())\n def test_pad_non_empty_dimension(self, mode):\n result = np.pad(np.ones((2, 0, 2)), ((3,), (0,), (1,)), mode=mode)\n assert result.shape == (8, 0, 4)\n\n\nclass TestSymmetric(object):\n def test_check_simple(self):\n a = np.arange(100)\n a = np.pad(a, (25, 20), 'symmetric')\n b = np.array(\n [24, 23, 22, 21, 20, 19, 18, 17, 16, 15,\n 14, 13, 12, 11, 10, 9, 8, 7, 6, 5,\n 4, 3, 2, 1, 0,\n\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,\n 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,\n 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,\n 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,\n 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,\n 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,\n 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,\n\n 99, 98, 97, 96, 95, 94, 93, 92, 91, 90,\n 89, 88, 87, 86, 85, 84, 83, 82, 81, 80]\n )\n assert_array_equal(a, b)\n\n def test_check_odd_method(self):\n a = np.arange(100)\n a = np.pad(a, (25, 20), 'symmetric', reflect_type='odd')\n b = np.array(\n [-24, -23, -22, -21, -20, -19, -18, -17, -16, -15,\n -14, -13, -12, -11, -10, -9, -8, -7, -6, -5,\n -4, -3, -2, -1, 0,\n\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,\n 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,\n 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,\n 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,\n 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,\n 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,\n 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,\n\n 99, 100, 101, 102, 103, 104, 105, 106, 107, 108,\n 109, 110, 111, 112, 113, 114, 115, 116, 117, 118]\n )\n assert_array_equal(a, b)\n\n def test_check_large_pad(self):\n a = [[4, 5, 6], [6, 7, 8]]\n a = np.pad(a, (5, 7), 'symmetric')\n b = np.array(\n [[5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [7, 8, 8, 7, 6, 6, 7, 8, 8, 7, 6, 6, 7, 8, 8],\n [7, 8, 8, 7, 6, 6, 7, 8, 8, 7, 6, 6, 7, 8, 8],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [7, 8, 8, 7, 6, 6, 7, 8, 8, 7, 6, 6, 7, 8, 8],\n\n [7, 8, 8, 7, 6, 6, 7, 8, 8, 7, 6, 6, 7, 8, 8],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [7, 8, 8, 7, 6, 6, 7, 8, 8, 7, 6, 6, 7, 8, 8],\n [7, 8, 8, 7, 6, 6, 7, 8, 8, 7, 6, 6, 7, 8, 8],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6]]\n )\n\n assert_array_equal(a, b)\n\n def test_check_large_pad_odd(self):\n a = [[4, 5, 6], [6, 7, 8]]\n a = np.pad(a, (5, 7), 'symmetric', reflect_type='odd')\n b = np.array(\n [[-3, -2, -2, -1, 0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6],\n [-3, -2, -2, -1, 0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6],\n [-1, 0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8],\n [-1, 0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8],\n [ 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 10],\n\n [ 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 10],\n [ 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 10, 11, 12, 12],\n\n [ 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 10, 11, 12, 12],\n [ 5, 6, 6, 7, 8, 8, 9, 10, 10, 11, 12, 12, 13, 14, 14],\n [ 5, 6, 6, 7, 8, 8, 9, 10, 10, 11, 12, 12, 13, 14, 14],\n [ 7, 8, 8, 9, 10, 10, 11, 12, 12, 13, 14, 14, 15, 16, 16],\n [ 7, 8, 8, 9, 10, 10, 11, 12, 12, 13, 14, 14, 15, 16, 16],\n [ 9, 10, 10, 11, 12, 12, 13, 14, 14, 15, 16, 16, 17, 18, 18],\n [ 9, 10, 10, 11, 12, 12, 13, 14, 14, 15, 16, 16, 17, 18, 18]]\n )\n assert_array_equal(a, b)\n\n def test_check_shape(self):\n a = [[4, 5, 6]]\n a = np.pad(a, (5, 7), 'symmetric')\n b = np.array(\n [[5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],\n [5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6]]\n )\n assert_array_equal(a, b)\n\n def test_check_01(self):\n a = np.pad([1, 2, 3], 2, 'symmetric')\n b = np.array([2, 1, 1, 2, 3, 3, 2])\n assert_array_equal(a, b)\n\n def test_check_02(self):\n a = np.pad([1, 2, 3], 3, 'symmetric')\n b = np.array([3, 2, 1, 1, 2, 3, 3, 2, 1])\n assert_array_equal(a, b)\n\n def test_check_03(self):\n a = np.pad([1, 2, 3], 6, 'symmetric')\n b = np.array([1, 2, 3, 3, 2, 1, 1, 2, 3, 3, 2, 1, 1, 2, 3])\n assert_array_equal(a, b)\n\n\nclass TestWrap(object):\n def test_check_simple(self):\n a = np.arange(100)\n a = np.pad(a, (25, 20), 'wrap')\n b = np.array(\n [75, 76, 77, 78, 79, 80, 81, 82, 83, 84,\n 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,\n 95, 96, 97, 98, 99,\n\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,\n 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,\n 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,\n 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,\n 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,\n 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,\n 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,\n\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\n )\n assert_array_equal(a, b)\n\n def test_check_large_pad(self):\n a = np.arange(12)\n a = np.reshape(a, (3, 4))\n a = np.pad(a, (10, 12), 'wrap')\n b = np.array(\n [[10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10,\n 11, 8, 9, 10, 11, 8, 9, 10, 11],\n [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2,\n 3, 0, 1, 2, 3, 0, 1, 2, 3],\n [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6,\n 7, 4, 5, 6, 7, 4, 5, 6, 7],\n [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10,\n 11, 8, 9, 10, 11, 8, 9, 10, 11],\n [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2,\n 3, 0, 1, 2, 3, 0, 1, 2, 3],\n [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6,\n 7, 4, 5, 6, 7, 4, 5, 6, 7],\n [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10,\n 11, 8, 9, 10, 11, 8, 9, 10, 11],\n [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2,\n 3, 0, 1, 2, 3, 0, 1, 2, 3],\n [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6,\n 7, 4, 5, 6, 7, 4, 5, 6, 7],\n [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10,\n 11, 8, 9, 10, 11, 8, 9, 10, 11],\n\n [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2,\n 3, 0, 1, 2, 3, 0, 1, 2, 3],\n [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6,\n 7, 4, 5, 6, 7, 4, 5, 6, 7],\n [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10,\n 11, 8, 9, 10, 11, 8, 9, 10, 11],\n\n [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2,\n 3, 0, 1, 2, 3, 0, 1, 2, 3],\n [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6,\n 7, 4, 5, 6, 7, 4, 5, 6, 7],\n [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10,\n 11, 8, 9, 10, 11, 8, 9, 10, 11],\n [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2,\n 3, 0, 1, 2, 3, 0, 1, 2, 3],\n [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6,\n 7, 4, 5, 6, 7, 4, 5, 6, 7],\n [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10,\n 11, 8, 9, 10, 11, 8, 9, 10, 11],\n [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2,\n 3, 0, 1, 2, 3, 0, 1, 2, 3],\n [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6,\n 7, 4, 5, 6, 7, 4, 5, 6, 7],\n [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10,\n 11, 8, 9, 10, 11, 8, 9, 10, 11],\n [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2,\n 3, 0, 1, 2, 3, 0, 1, 2, 3],\n [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6,\n 7, 4, 5, 6, 7, 4, 5, 6, 7],\n [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10,\n 11, 8, 9, 10, 11, 8, 9, 10, 11]]\n )\n assert_array_equal(a, b)\n\n def test_check_01(self):\n a = np.pad([1, 2, 3], 3, 'wrap')\n b = np.array([1, 2, 3, 1, 2, 3, 1, 2, 3])\n assert_array_equal(a, b)\n\n def test_check_02(self):\n a = np.pad([1, 2, 3], 4, 'wrap')\n b = np.array([3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1])\n assert_array_equal(a, b)\n\n def test_pad_with_zero(self):\n a = np.ones((3, 5))\n b = np.pad(a, (0, 5), mode=\"wrap\")\n assert_array_equal(a, b[:-5, :-5])\n\n def test_repeated_wrapping(self):\n \"\"\"\n Check wrapping on each side individually if the wrapped area is longer\n than the original array.\n \"\"\"\n a = np.arange(5)\n b = np.pad(a, (12, 0), mode=\"wrap\")\n assert_array_equal(np.r_[a, a, a, a][3:], b)\n\n a = np.arange(5)\n b = np.pad(a, (0, 12), mode=\"wrap\")\n assert_array_equal(np.r_[a, a, a, a][:-3], b)\n\n\nclass TestEdge(object):\n def test_check_simple(self):\n a = np.arange(12)\n a = np.reshape(a, (4, 3))\n a = np.pad(a, ((2, 3), (3, 2)), 'edge')\n b = np.array(\n [[0, 0, 0, 0, 1, 2, 2, 2],\n [0, 0, 0, 0, 1, 2, 2, 2],\n\n [0, 0, 0, 0, 1, 2, 2, 2],\n [3, 3, 3, 3, 4, 5, 5, 5],\n [6, 6, 6, 6, 7, 8, 8, 8],\n [9, 9, 9, 9, 10, 11, 11, 11],\n\n [9, 9, 9, 9, 10, 11, 11, 11],\n [9, 9, 9, 9, 10, 11, 11, 11],\n [9, 9, 9, 9, 10, 11, 11, 11]]\n )\n assert_array_equal(a, b)\n\n def test_check_width_shape_1_2(self):\n # Check a pad_width of the form ((1, 2),).\n # Regression test for issue gh-7808.\n a = np.array([1, 2, 3])\n padded = np.pad(a, ((1, 2),), 'edge')\n expected = np.array([1, 1, 2, 3, 3, 3])\n assert_array_equal(padded, expected)\n\n a = np.array([[1, 2, 3], [4, 5, 6]])\n padded = np.pad(a, ((1, 2),), 'edge')\n expected = np.pad(a, ((1, 2), (1, 2)), 'edge')\n assert_array_equal(padded, expected)\n\n a = np.arange(24).reshape(2, 3, 4)\n padded = np.pad(a, ((1, 2),), 'edge')\n expected = np.pad(a, ((1, 2), (1, 2), (1, 2)), 'edge')\n assert_array_equal(padded, expected)\n\n\nclass TestEmpty(object):\n def test_simple(self):\n arr = np.arange(24).reshape(4, 6)\n result = np.pad(arr, [(2, 3), (3, 1)], mode=\"empty\")\n assert result.shape == (9, 10)\n assert_equal(arr, result[2:-3, 3:-1])\n\n def test_pad_empty_dimension(self):\n arr = np.zeros((3, 0, 2))\n result = np.pad(arr, [(0,), (2,), (1,)], mode=\"empty\")\n assert result.shape == (3, 4, 4)\n\n\ndef test_legacy_vector_functionality():\n def _padwithtens(vector, pad_width, iaxis, kwargs):\n vector[:pad_width[0]] = 10\n vector[-pad_width[1]:] = 10\n\n a = np.arange(6).reshape(2, 3)\n a = np.pad(a, 2, _padwithtens)\n b = np.array(\n [[10, 10, 10, 10, 10, 10, 10],\n [10, 10, 10, 10, 10, 10, 10],\n\n [10, 10, 0, 1, 2, 10, 10],\n [10, 10, 3, 4, 5, 10, 10],\n\n [10, 10, 10, 10, 10, 10, 10],\n [10, 10, 10, 10, 10, 10, 10]]\n )\n assert_array_equal(a, b)\n\n\ndef test_unicode_mode():\n a = np.pad([1], 2, mode=u'constant')\n b = np.array([0, 0, 1, 0, 0])\n assert_array_equal(a, b)\n\n\[email protected](\"mode\", [\"edge\", \"symmetric\", \"reflect\", \"wrap\"])\ndef test_object_input(mode):\n # Regression test for issue gh-11395.\n a = np.full((4, 3), fill_value=None)\n pad_amt = ((2, 3), (3, 2))\n b = np.full((9, 8), fill_value=None)\n assert_array_equal(np.pad(a, pad_amt, mode=mode), b)\n\n\nclass TestPadWidth(object):\n @pytest.mark.parametrize(\"pad_width\", [\n (4, 5, 6, 7),\n ((1,), (2,), (3,)),\n ((1, 2), (3, 4), (5, 6)),\n ((3, 4, 5), (0, 1, 2)),\n ])\n @pytest.mark.parametrize(\"mode\", _all_modes.keys())\n def test_misshaped_pad_width(self, pad_width, mode):\n arr = np.arange(30).reshape((6, 5))\n match = \"operands could not be broadcast together\"\n with pytest.raises(ValueError, match=match):\n np.pad(arr, pad_width, mode)\n\n @pytest.mark.parametrize(\"mode\", _all_modes.keys())\n def test_misshaped_pad_width_2(self, mode):\n arr = np.arange(30).reshape((6, 5))\n match = (\"input operand has more dimensions than allowed by the axis \"\n \"remapping\")\n with pytest.raises(ValueError, match=match):\n np.pad(arr, (((3,), (4,), (5,)), ((0,), (1,), (2,))), mode)\n\n @pytest.mark.parametrize(\n \"pad_width\", [-2, (-2,), (3, -1), ((5, 2), (-2, 3)), ((-4,), (2,))])\n @pytest.mark.parametrize(\"mode\", _all_modes.keys())\n def test_negative_pad_width(self, pad_width, mode):\n arr = np.arange(30).reshape((6, 5))\n match = \"index can't contain negative values\"\n with pytest.raises(ValueError, match=match):\n np.pad(arr, pad_width, mode)\n\n @pytest.mark.parametrize(\"pad_width, dtype\", [\n (\"3\", None),\n (\"word\", None),\n (None, None),\n (object(), None),\n (3.4, None),\n (((2, 3, 4), (3, 2)), object),\n (complex(1, -1), None),\n (((-2.1, 3), (3, 2)), None),\n ])\n @pytest.mark.parametrize(\"mode\", _all_modes.keys())\n def test_bad_type(self, pad_width, dtype, mode):\n arr = np.arange(30).reshape((6, 5))\n match = \"`pad_width` must be of integral type.\"\n if dtype is not None:\n # avoid DeprecationWarning when not specifying dtype\n with pytest.raises(TypeError, match=match):\n np.pad(arr, np.array(pad_width, dtype=dtype), mode)\n else:\n with pytest.raises(TypeError, match=match):\n np.pad(arr, pad_width, mode)\n with pytest.raises(TypeError, match=match):\n np.pad(arr, np.array(pad_width), mode)\n\n def test_pad_width_as_ndarray(self):\n a = np.arange(12)\n a = np.reshape(a, (4, 3))\n a = np.pad(a, np.array(((2, 3), (3, 2))), 'edge')\n b = np.array(\n [[0, 0, 0, 0, 1, 2, 2, 2],\n [0, 0, 0, 0, 1, 2, 2, 2],\n\n [0, 0, 0, 0, 1, 2, 2, 2],\n [3, 3, 3, 3, 4, 5, 5, 5],\n [6, 6, 6, 6, 7, 8, 8, 8],\n [9, 9, 9, 9, 10, 11, 11, 11],\n\n [9, 9, 9, 9, 10, 11, 11, 11],\n [9, 9, 9, 9, 10, 11, 11, 11],\n [9, 9, 9, 9, 10, 11, 11, 11]]\n )\n assert_array_equal(a, b)\n\n @pytest.mark.parametrize(\"pad_width\", [0, (0, 0), ((0, 0), (0, 0))])\n @pytest.mark.parametrize(\"mode\", _all_modes.keys())\n def test_zero_pad_width(self, pad_width, mode):\n arr = np.arange(30).reshape(6, 5)\n assert_array_equal(arr, np.pad(arr, pad_width, mode=mode))\n\n\[email protected](\"mode\", _all_modes.keys())\ndef test_kwargs(mode):\n \"\"\"Test behavior of pad's kwargs for the given mode.\"\"\"\n allowed = _all_modes[mode]\n not_allowed = {}\n for kwargs in _all_modes.values():\n if kwargs != allowed:\n not_allowed.update(kwargs)\n # Test if allowed keyword arguments pass\n np.pad([1, 2, 3], 1, mode, **allowed)\n # Test if prohibited keyword arguments of other modes raise an error\n for key, value in not_allowed.items():\n match = \"unsupported keyword arguments for mode '{}'\".format(mode)\n with pytest.raises(ValueError, match=match):\n np.pad([1, 2, 3], 1, mode, **{key: value})\n\n\ndef test_constant_zero_default():\n arr = np.array([1, 1])\n assert_array_equal(np.pad(arr, 2), [0, 0, 1, 1, 0, 0])\n\n\[email protected](\"mode\", [1, \"const\", object(), None, True, False])\ndef test_unsupported_mode(mode):\n match= \"mode '{}' is not supported\".format(mode)\n with pytest.raises(ValueError, match=match):\n np.pad([1, 2, 3], 4, mode=mode)\n\n\[email protected](\"mode\", _all_modes.keys())\ndef test_non_contiguous_array(mode):\n arr = np.arange(24).reshape(4, 6)[::2, ::2]\n result = np.pad(arr, (2, 3), mode)\n assert result.shape == (7, 8)\n assert_equal(result[2:-3, 2:-3], arr)\n\n\[email protected](\"mode\", _all_modes.keys())\ndef test_memory_layout_persistence(mode):\n \"\"\"Test if C and F order is preserved for all pad modes.\"\"\"\n x = np.ones((5, 10), order='C')\n assert np.pad(x, 5, mode).flags[\"C_CONTIGUOUS\"]\n x = np.ones((5, 10), order='F')\n assert np.pad(x, 5, mode).flags[\"F_CONTIGUOUS\"]\n\n\[email protected](\"dtype\", _numeric_dtypes)\[email protected](\"mode\", _all_modes.keys())\ndef test_dtype_persistence(dtype, mode):\n arr = np.zeros((3, 2, 1), dtype=dtype)\n result = np.pad(arr, 1, mode=mode)\n assert result.dtype == dtype\n" ]
[ [ "numpy.lib.pad", "numpy.testing.assert_equal", "numpy.pad", "numpy.reshape", "numpy.arange", "numpy.ndarray", "numpy.full", "numpy.testing.assert_array_equal", "numpy.ones", "numpy.testing.assert_allclose", "numpy.lib.arraypad._as_pairs", "numpy.array", "numpy.zeros", "numpy.empty" ] ]
haskie-lambda/DALLE-pytorch
[ "3c59dc9864cc900cefd656f73772e151af4fb97f" ]
[ "dalle_pytorch/vae.py" ]
[ "import io\nimport sys\nimport os, sys\nimport requests\nimport PIL\nimport warnings\nimport os\nimport hashlib\nimport urllib\nimport yaml\nfrom pathlib import Path\nfrom tqdm import tqdm\nfrom math import sqrt\nfrom omegaconf import OmegaConf\nfrom taming.models.vqgan import VQModel\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nfrom einops import rearrange\n\n# constants\n\nCACHE_PATH = os.path.expanduser(\"~/.cache/dalle\")\n\nOPENAI_VAE_ENCODER_PATH = 'https://cdn.openai.com/dall-e/encoder.pkl'\nOPENAI_VAE_DECODER_PATH = 'https://cdn.openai.com/dall-e/decoder.pkl'\n\nVQGAN_VAE_PATH = 'https://heibox.uni-heidelberg.de/f/140747ba53464f49b476/?dl=1'\nVQGAN_VAE_CONFIG_PATH = 'https://heibox.uni-heidelberg.de/f/6ecf2af6c658432c8298/?dl=1'\n\n# helpers methods\n\ndef exists(val):\n return val is not None\n\ndef default(val, d):\n return val if exists(val) else d\n\ndef load_model(path):\n with open(path, 'rb') as f:\n return torch.load(f, map_location = torch.device('cpu'))\n\ndef map_pixels(x, eps = 0.1):\n return (1 - 2 * eps) * x + eps\n\ndef unmap_pixels(x, eps = 0.1):\n return torch.clamp((x - eps) / (1 - 2 * eps), 0, 1)\n\ndef download(url, filename = None, root = CACHE_PATH):\n os.makedirs(root, exist_ok = True)\n filename = default(filename, os.path.basename(url))\n\n download_target = os.path.join(root, filename)\n download_target_tmp = os.path.join(root, f'tmp.{filename}')\n\n if os.path.exists(download_target) and not os.path.isfile(download_target):\n raise RuntimeError(f\"{download_target} exists and is not a regular file\")\n\n if os.path.isfile(download_target):\n return download_target\n\n with urllib.request.urlopen(url) as source, open(download_target_tmp, \"wb\") as output:\n with tqdm(total=int(source.info().get(\"Content-Length\")), ncols=80) as loop:\n while True:\n buffer = source.read(8192)\n if not buffer:\n break\n\n output.write(buffer)\n loop.update(len(buffer))\n\n os.rename(download_target_tmp, download_target)\n return download_target\n\n# pretrained Discrete VAE from OpenAI\n\nclass OpenAIDiscreteVAE(nn.Module):\n def __init__(self):\n super().__init__()\n\n self.enc = load_model(download(OPENAI_VAE_ENCODER_PATH))\n self.dec = load_model(download(OPENAI_VAE_DECODER_PATH))\n\n self.num_layers = 3\n self.image_size = 256\n self.num_tokens = 8192\n\n @torch.no_grad()\n def get_codebook_indices(self, img):\n img = map_pixels(img)\n z_logits = self.enc(img)\n z = torch.argmax(z_logits, dim = 1)\n return rearrange(z, 'b h w -> b (h w)')\n\n def decode(self, img_seq):\n b, n = img_seq.shape\n img_seq = rearrange(img_seq, 'b (h w) -> b h w', h = int(sqrt(n)))\n\n z = F.one_hot(img_seq, num_classes = self.num_tokens)\n z = rearrange(z, 'b h w c -> b c h w').float()\n x_stats = self.dec(z).float()\n x_rec = unmap_pixels(torch.sigmoid(x_stats[:, :3]))\n return x_rec\n\n def forward(self, img):\n raise NotImplemented\n\n# VQGAN from Taming Transformers paper\n# https://arxiv.org/abs/2012.09841\n\nclass VQGanVAE1024(nn.Module):\n def __init__(self):\n super().__init__()\n\n model_filename = 'vqgan.1024.model.ckpt'\n config_filename = 'vqgan.1024.config.yml'\n\n download(VQGAN_VAE_CONFIG_PATH, config_filename)\n download(VQGAN_VAE_PATH, model_filename)\n\n config = OmegaConf.load(str(Path(CACHE_PATH) / config_filename))\n model = VQModel(**config.model.params)\n\n state = torch.load(str(Path(CACHE_PATH) / model_filename), map_location = 'cpu')['state_dict']\n model.load_state_dict(state, strict = False)\n\n self.model = model\n\n self.num_layers = 4\n self.image_size = 256\n self.num_tokens = 1024\n\n @torch.no_grad()\n def get_codebook_indices(self, img):\n b = img.shape[0]\n img = (2 * img) - 1\n _, _, [_, _, indices] = self.model.encode(img)\n return rearrange(indices, '(b n) () -> b n', b = b)\n\n def decode(self, img_seq):\n b, n = img_seq.shape\n one_hot_indices = F.one_hot(img_seq, num_classes = self.num_tokens).float()\n z = (one_hot_indices @ self.model.quantize.embedding.weight)\n\n z = rearrange(z, 'b (h w) c -> b c h w', h = int(sqrt(n)))\n img = self.model.decode(z)\n\n img = (img.clamp(-1., 1.) + 1) * 0.5\n return img\n\n def forward(self, img):\n raise NotImplemented\n" ]
[ [ "torch.sigmoid", "torch.no_grad", "torch.nn.functional.one_hot", "torch.device", "torch.clamp", "torch.argmax" ] ]
hsupengbo/201800130086_spring_NNML
[ "c51d074c2d33650cc923ccc4297ecbce31c83df7" ]
[ "Codes/recognition/lib/models/crnn.py" ]
[ "import torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass BidirectionalLSTM(nn.Module):\n # Inputs hidden units Out\n def __init__(self, nIn, nHidden, nOut):\n super(BidirectionalLSTM, self).__init__()\n\n self.rnn = nn.LSTM(nIn, nHidden, bidirectional=True)\n self.embedding = nn.Linear(nHidden * 2, nOut)\n\n def forward(self, input):\n recurrent, _ = self.rnn(input)\n T, b, h = recurrent.size()\n t_rec = recurrent.view(T * b, h)\n\n output = self.embedding(t_rec) # [T * b, nOut]\n output = output.view(T, b, -1)\n\n return output\n\n\nclass CRNN(nn.Module):\n def __init__(self, imgH, nc, nclass, nh, n_rnn=2, leakyRelu=False):\n super(CRNN, self).__init__()\n assert imgH % 16 == 0, 'imgH has to be a multiple of 16'\n\n ks = [3, 3, 3, 3, 3, 3, 2]\n ps = [1, 1, 1, 1, 1, 1, 0]\n ss = [1, 1, 1, 1, 1, 1, 1]\n nm = [64, 128, 256, 256, 512, 512, 512]\n\n cnn = nn.Sequential()\n\n def convRelu(i, batchNormalization=False):\n nIn = nc if i == 0 else nm[i - 1]\n nOut = nm[i]\n cnn.add_module('conv{0}'.format(i),\n nn.Conv2d(nIn, nOut, ks[i], ss[i], ps[i]))\n if batchNormalization:\n cnn.add_module('batchnorm{0}'.format(i), nn.BatchNorm2d(nOut))\n if leakyRelu:\n cnn.add_module('relu{0}'.format(i),\n nn.LeakyReLU(0.2, inplace=True))\n else:\n cnn.add_module('relu{0}'.format(i), nn.ReLU(True))\n\n convRelu(0)\n cnn.add_module('pooling{0}'.format(0), nn.MaxPool2d(2, 2)) # 64x16x64\n convRelu(1)\n cnn.add_module('pooling{0}'.format(1), nn.MaxPool2d(2, 2)) # 128x8x32\n convRelu(2, True)\n convRelu(3)\n cnn.add_module('pooling{0}'.format(2),\n nn.MaxPool2d((2, 2), (2, 1), (0, 1))) # 256x4x16\n convRelu(4, True)\n convRelu(5)\n cnn.add_module('pooling{0}'.format(3),\n nn.MaxPool2d((2, 2), (2, 1), (0, 1))) # 512x2x16\n convRelu(6, True) # 512x1x16\n\n self.cnn = cnn\n self.rnn = nn.Sequential(\n BidirectionalLSTM(512, nh, nh),\n BidirectionalLSTM(nh, nh, nclass))\n\n def forward(self, input):\n\n # conv features\n conv = self.cnn(input)\n b, c, h, w = conv.size()\n #print(conv.size())\n assert h == 1, \"the height of conv must be 1\"\n conv = conv.squeeze(2) # b *512 * width\n conv = conv.permute(2, 0, 1) # [w, b, c]\n output = F.log_softmax(self.rnn(conv), dim=2)\n\n return output\n\n\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n m.weight.data.normal_(0.0, 0.02)\n elif classname.find('BatchNorm') != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n\n\ndef get_crnn(config):\n model = CRNN(config.MODEL.IMAGE_SIZE.H, 1, config.MODEL.NUM_CLASSES + 1, config.MODEL.NUM_HIDDEN)\n model.apply(weights_init)\n\n return model\n" ]
[ [ "torch.nn.Sequential", "torch.nn.LSTM", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.MaxPool2d", "torch.nn.LeakyReLU", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ] ]
kadekillary/pandas
[ "f6a5dd4b8c450d73f3bec964b05cca32cef4bb71" ]
[ "pandas/core/arrays/numpy_.py" ]
[ "import numbers\n\nimport numpy as np\nfrom numpy.lib.mixins import NDArrayOperatorsMixin\n\nfrom pandas._libs import lib\nfrom pandas.compat.numpy import function as nv\nfrom pandas.util._decorators import Appender\nfrom pandas.util._validators import validate_fillna_kwargs\n\nfrom pandas.core.dtypes.dtypes import ExtensionDtype\nfrom pandas.core.dtypes.generic import ABCIndexClass, ABCSeries\nfrom pandas.core.dtypes.inference import is_array_like, is_list_like\nfrom pandas.core.dtypes.missing import isna\n\nfrom pandas import compat\nfrom pandas.core import nanops\nfrom pandas.core.algorithms import searchsorted, take, unique\nfrom pandas.core.construction import extract_array\nfrom pandas.core.missing import backfill_1d, pad_1d\n\nfrom .base import ExtensionArray, ExtensionOpsMixin\n\n\nclass PandasDtype(ExtensionDtype):\n \"\"\"\n A Pandas ExtensionDtype for NumPy dtypes.\n\n .. versionadded:: 0.24.0\n\n This is mostly for internal compatibility, and is not especially\n useful on its own.\n\n Parameters\n ----------\n dtype : numpy.dtype\n \"\"\"\n\n _metadata = (\"_dtype\",)\n\n def __init__(self, dtype):\n dtype = np.dtype(dtype)\n self._dtype = dtype\n self._name = dtype.name\n self._type = dtype.type\n\n def __repr__(self):\n return \"PandasDtype({!r})\".format(self.name)\n\n @property\n def numpy_dtype(self):\n \"\"\"The NumPy dtype this PandasDtype wraps.\"\"\"\n return self._dtype\n\n @property\n def name(self):\n return self._name\n\n @property\n def type(self):\n return self._type\n\n @property\n def _is_numeric(self):\n # exclude object, str, unicode, void.\n return self.kind in set(\"biufc\")\n\n @property\n def _is_boolean(self):\n return self.kind == \"b\"\n\n @classmethod\n def construct_from_string(cls, string):\n return cls(np.dtype(string))\n\n def construct_array_type(cls):\n return PandasArray\n\n @property\n def kind(self):\n return self._dtype.kind\n\n @property\n def itemsize(self):\n \"\"\"The element size of this data-type object.\"\"\"\n return self._dtype.itemsize\n\n\nclass PandasArray(ExtensionArray, ExtensionOpsMixin, NDArrayOperatorsMixin):\n \"\"\"\n A pandas ExtensionArray for NumPy data.\n\n .. versionadded :: 0.24.0\n\n This is mostly for internal compatibility, and is not especially\n useful on its own.\n\n Parameters\n ----------\n values : ndarray\n The NumPy ndarray to wrap. Must be 1-dimensional.\n copy : bool, default False\n Whether to copy `values`.\n\n Attributes\n ----------\n None\n\n Methods\n -------\n None\n \"\"\"\n\n # If you're wondering why pd.Series(cls) doesn't put the array in an\n # ExtensionBlock, search for `ABCPandasArray`. We check for\n # that _typ to ensure that that users don't unnecessarily use EAs inside\n # pandas internals, which turns off things like block consolidation.\n _typ = \"npy_extension\"\n __array_priority__ = 1000\n\n # ------------------------------------------------------------------------\n # Constructors\n\n def __init__(self, values, copy=False):\n if isinstance(values, type(self)):\n values = values._ndarray\n if not isinstance(values, np.ndarray):\n raise ValueError(\"'values' must be a NumPy array.\")\n\n if values.ndim != 1:\n raise ValueError(\"PandasArray must be 1-dimensional.\")\n\n if copy:\n values = values.copy()\n\n self._ndarray = values\n self._dtype = PandasDtype(values.dtype)\n\n @classmethod\n def _from_sequence(cls, scalars, dtype=None, copy=False):\n if isinstance(dtype, PandasDtype):\n dtype = dtype._dtype\n\n result = np.asarray(scalars, dtype=dtype)\n if copy and result is scalars:\n result = result.copy()\n return cls(result)\n\n @classmethod\n def _from_factorized(cls, values, original):\n return cls(values)\n\n @classmethod\n def _concat_same_type(cls, to_concat):\n return cls(np.concatenate(to_concat))\n\n # ------------------------------------------------------------------------\n # Data\n\n @property\n def dtype(self):\n return self._dtype\n\n # ------------------------------------------------------------------------\n # NumPy Array Interface\n\n def __array__(self, dtype=None):\n return np.asarray(self._ndarray, dtype=dtype)\n\n _HANDLED_TYPES = (np.ndarray, numbers.Number)\n\n def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):\n # Lightly modified version of\n # https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/\\\n # numpy.lib.mixins.NDArrayOperatorsMixin.html\n # The primary modification is not boxing scalar return values\n # in PandasArray, since pandas' ExtensionArrays are 1-d.\n out = kwargs.get(\"out\", ())\n for x in inputs + out:\n # Only support operations with instances of _HANDLED_TYPES.\n # Use PandasArray instead of type(self) for isinstance to\n # allow subclasses that don't override __array_ufunc__ to\n # handle PandasArray objects.\n if not isinstance(x, self._HANDLED_TYPES + (PandasArray,)):\n return NotImplemented\n\n # Defer to the implementation of the ufunc on unwrapped values.\n inputs = tuple(x._ndarray if isinstance(x, PandasArray) else x for x in inputs)\n if out:\n kwargs[\"out\"] = tuple(\n x._ndarray if isinstance(x, PandasArray) else x for x in out\n )\n result = getattr(ufunc, method)(*inputs, **kwargs)\n\n if type(result) is tuple and len(result):\n # multiple return values\n if not lib.is_scalar(result[0]):\n # re-box array-like results\n return tuple(type(self)(x) for x in result)\n else:\n # but not scalar reductions\n return result\n elif method == \"at\":\n # no return value\n return None\n else:\n # one return value\n if not lib.is_scalar(result):\n # re-box array-like results, but not scalar reductions\n result = type(self)(result)\n return result\n\n # ------------------------------------------------------------------------\n # Pandas ExtensionArray Interface\n\n def __getitem__(self, item):\n if isinstance(item, type(self)):\n item = item._ndarray\n\n result = self._ndarray[item]\n if not lib.is_scalar(item):\n result = type(self)(result)\n return result\n\n def __setitem__(self, key, value):\n value = extract_array(value, extract_numpy=True)\n\n if not lib.is_scalar(key) and is_list_like(key):\n key = np.asarray(key)\n\n if not lib.is_scalar(value):\n value = np.asarray(value)\n\n values = self._ndarray\n t = np.result_type(value, values)\n if t != self._ndarray.dtype:\n values = values.astype(t, casting=\"safe\")\n values[key] = value\n self._dtype = PandasDtype(t)\n self._ndarray = values\n else:\n self._ndarray[key] = value\n\n def __len__(self):\n return len(self._ndarray)\n\n @property\n def nbytes(self):\n return self._ndarray.nbytes\n\n def isna(self):\n return isna(self._ndarray)\n\n def fillna(self, value=None, method=None, limit=None):\n # TODO(_values_for_fillna): remove this\n value, method = validate_fillna_kwargs(value, method)\n\n mask = self.isna()\n\n if is_array_like(value):\n if len(value) != len(self):\n raise ValueError(\n \"Length of 'value' does not match. Got ({}) \"\n \" expected {}\".format(len(value), len(self))\n )\n value = value[mask]\n\n if mask.any():\n if method is not None:\n func = pad_1d if method == \"pad\" else backfill_1d\n new_values = func(self._ndarray, limit=limit, mask=mask)\n new_values = self._from_sequence(new_values, dtype=self.dtype)\n else:\n # fill with value\n new_values = self.copy()\n new_values[mask] = value\n else:\n new_values = self.copy()\n return new_values\n\n def take(self, indices, allow_fill=False, fill_value=None):\n result = take(\n self._ndarray, indices, allow_fill=allow_fill, fill_value=fill_value\n )\n return type(self)(result)\n\n def copy(self):\n return type(self)(self._ndarray.copy())\n\n def _values_for_argsort(self):\n return self._ndarray\n\n def _values_for_factorize(self):\n return self._ndarray, -1\n\n def unique(self):\n return type(self)(unique(self._ndarray))\n\n # ------------------------------------------------------------------------\n # Reductions\n\n def _reduce(self, name, skipna=True, **kwargs):\n meth = getattr(self, name, None)\n if meth:\n return meth(skipna=skipna, **kwargs)\n else:\n msg = \"'{}' does not implement reduction '{}'\"\n raise TypeError(msg.format(type(self).__name__, name))\n\n def any(self, axis=None, out=None, keepdims=False, skipna=True):\n nv.validate_any((), dict(out=out, keepdims=keepdims))\n return nanops.nanany(self._ndarray, axis=axis, skipna=skipna)\n\n def all(self, axis=None, out=None, keepdims=False, skipna=True):\n nv.validate_all((), dict(out=out, keepdims=keepdims))\n return nanops.nanall(self._ndarray, axis=axis, skipna=skipna)\n\n def min(self, axis=None, out=None, keepdims=False, skipna=True):\n nv.validate_min((), dict(out=out, keepdims=keepdims))\n return nanops.nanmin(self._ndarray, axis=axis, skipna=skipna)\n\n def max(self, axis=None, out=None, keepdims=False, skipna=True):\n nv.validate_max((), dict(out=out, keepdims=keepdims))\n return nanops.nanmax(self._ndarray, axis=axis, skipna=skipna)\n\n def sum(\n self,\n axis=None,\n dtype=None,\n out=None,\n keepdims=False,\n initial=None,\n skipna=True,\n min_count=0,\n ):\n nv.validate_sum(\n (), dict(dtype=dtype, out=out, keepdims=keepdims, initial=initial)\n )\n return nanops.nansum(\n self._ndarray, axis=axis, skipna=skipna, min_count=min_count\n )\n\n def prod(\n self,\n axis=None,\n dtype=None,\n out=None,\n keepdims=False,\n initial=None,\n skipna=True,\n min_count=0,\n ):\n nv.validate_prod(\n (), dict(dtype=dtype, out=out, keepdims=keepdims, initial=initial)\n )\n return nanops.nanprod(\n self._ndarray, axis=axis, skipna=skipna, min_count=min_count\n )\n\n def mean(self, axis=None, dtype=None, out=None, keepdims=False, skipna=True):\n nv.validate_mean((), dict(dtype=dtype, out=out, keepdims=keepdims))\n return nanops.nanmean(self._ndarray, axis=axis, skipna=skipna)\n\n def median(\n self, axis=None, out=None, overwrite_input=False, keepdims=False, skipna=True\n ):\n nv.validate_median(\n (), dict(out=out, overwrite_input=overwrite_input, keepdims=keepdims)\n )\n return nanops.nanmedian(self._ndarray, axis=axis, skipna=skipna)\n\n def std(self, axis=None, dtype=None, out=None, ddof=1, keepdims=False, skipna=True):\n nv.validate_stat_ddof_func(\n (), dict(dtype=dtype, out=out, keepdims=keepdims), fname=\"std\"\n )\n return nanops.nanstd(self._ndarray, axis=axis, skipna=skipna, ddof=ddof)\n\n def var(self, axis=None, dtype=None, out=None, ddof=1, keepdims=False, skipna=True):\n nv.validate_stat_ddof_func(\n (), dict(dtype=dtype, out=out, keepdims=keepdims), fname=\"var\"\n )\n return nanops.nanvar(self._ndarray, axis=axis, skipna=skipna, ddof=ddof)\n\n def sem(self, axis=None, dtype=None, out=None, ddof=1, keepdims=False, skipna=True):\n nv.validate_stat_ddof_func(\n (), dict(dtype=dtype, out=out, keepdims=keepdims), fname=\"sem\"\n )\n return nanops.nansem(self._ndarray, axis=axis, skipna=skipna, ddof=ddof)\n\n def kurt(self, axis=None, dtype=None, out=None, keepdims=False, skipna=True):\n nv.validate_stat_ddof_func(\n (), dict(dtype=dtype, out=out, keepdims=keepdims), fname=\"kurt\"\n )\n return nanops.nankurt(self._ndarray, axis=axis, skipna=skipna)\n\n def skew(self, axis=None, dtype=None, out=None, keepdims=False, skipna=True):\n nv.validate_stat_ddof_func(\n (), dict(dtype=dtype, out=out, keepdims=keepdims), fname=\"skew\"\n )\n return nanops.nanskew(self._ndarray, axis=axis, skipna=skipna)\n\n # ------------------------------------------------------------------------\n # Additional Methods\n def to_numpy(self, dtype=None, copy=False):\n \"\"\"\n Convert the PandasArray to a :class:`numpy.ndarray`.\n\n By default, this requires no coercion or copying of data.\n\n Parameters\n ----------\n dtype : numpy.dtype\n The NumPy dtype to pass to :func:`numpy.asarray`.\n copy : bool, default False\n Whether to copy the underlying data.\n\n Returns\n -------\n ndarray\n \"\"\"\n result = np.asarray(self._ndarray, dtype=dtype)\n if copy and result is self._ndarray:\n result = result.copy()\n\n return result\n\n @Appender(ExtensionArray.searchsorted.__doc__)\n def searchsorted(self, value, side=\"left\", sorter=None):\n return searchsorted(self.to_numpy(), value, side=side, sorter=sorter)\n\n # ------------------------------------------------------------------------\n # Ops\n\n def __invert__(self):\n return type(self)(~self._ndarray)\n\n @classmethod\n def _create_arithmetic_method(cls, op):\n def arithmetic_method(self, other):\n if isinstance(other, (ABCIndexClass, ABCSeries)):\n return NotImplemented\n\n elif isinstance(other, cls):\n other = other._ndarray\n\n with np.errstate(all=\"ignore\"):\n result = op(self._ndarray, other)\n\n if op is divmod:\n a, b = result\n return cls(a), cls(b)\n\n return cls(result)\n\n return compat.set_function_name(\n arithmetic_method, \"__{}__\".format(op.__name__), cls\n )\n\n _create_comparison_method = _create_arithmetic_method\n\n\nPandasArray._add_arithmetic_ops()\nPandasArray._add_comparison_ops()\n" ]
[ [ "numpy.asarray", "pandas._libs.lib.is_scalar", "numpy.dtype", "numpy.concatenate", "pandas.core.nanops.nanprod", "pandas.core.dtypes.inference.is_list_like", "pandas.core.nanops.nanmin", "pandas.core.nanops.nanall", "pandas.core.nanops.nanstd", "pandas.core.nanops.nansum", "pandas.core.algorithms.unique", "pandas.core.nanops.nanany", "pandas.core.nanops.nanmedian", "pandas.core.dtypes.inference.is_array_like", "pandas.util._decorators.Appender", "pandas.core.nanops.nansem", "numpy.errstate", "pandas.core.nanops.nankurt", "pandas.core.nanops.nanskew", "pandas.util._validators.validate_fillna_kwargs", "pandas.core.nanops.nanmean", "numpy.result_type", "pandas.core.dtypes.missing.isna", "pandas.core.nanops.nanmax", "pandas.core.algorithms.take", "pandas.core.construction.extract_array", "pandas.core.nanops.nanvar" ] ]
zyuerugou/tf-faster-rcnn
[ "6d1e3d9691ad3dd570e56a77304fc307969dc0f3" ]
[ "lib/datasets/voc_eval.py" ]
[ "# --------------------------------------------------------\n# Fast/er R-CNN\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Bharath Hariharan\n# --------------------------------------------------------\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport xml.etree.ElementTree as ET\nimport os\nimport pickle\nimport numpy as np\n\n\ndef parse_rec(filename):\n \"\"\" Parse a PASCAL VOC xml file \"\"\"\n # When data/{dataset}/annotations_cache is not exist,\n # This function will be call.\n tree = ET.parse(filename)\n objects = []\n print('obj class:')\n for obj in tree.findall('object'):\n obj_struct = {}\n obj_struct['name'] = obj.find('name').text.lower()\n #---------------------------------------------------------------\n # user added\n # to sure the data parsed is not Null\n #---------------------------------------------------------------\n print(obj_struct['name'])\n #---------------------------------------------------------------\n obj_struct['pose'] = obj.find('pose').text\n obj_struct['truncated'] = int(obj.find('truncated').text)\n obj_struct['difficult'] = int(obj.find('difficult').text)\n bbox = obj.find('bndbox')\n obj_struct['bbox'] = [int(bbox.find('xmin').text),\n int(bbox.find('ymin').text),\n int(bbox.find('xmax').text),\n int(bbox.find('ymax').text)]\n objects.append(obj_struct)\n\n return objects\n\n\ndef voc_ap(rec, prec, use_07_metric=False):\n \"\"\" ap = voc_ap(rec, prec, [use_07_metric])\n Compute VOC AP given precision and recall.\n If use_07_metric is true, uses the\n VOC 07 11 point method (default:False).\n \"\"\"\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 # correct AP calculation\n # first append sentinel values at the end\n mrec = np.concatenate(([0.], rec, [1.]))\n mpre = np.concatenate(([0.], prec, [0.]))\n\n # compute the precision envelope\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (\\Delta recall) * prec\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n\ndef voc_eval(detpath,\n annopath,\n imagesetfile,\n classname,\n cachedir,\n ovthresh=0.5,\n use_07_metric=False,\n use_diff=False):\n \"\"\"rec, prec, ap = voc_eval(detpath,\n annopath,\n imagesetfile,\n classname,\n [ovthresh],\n [use_07_metric])\n\n Top level function that does the PASCAL VOC evaluation.\n\n detpath: Path to detections\n detpath.format(classname) should produce the detection results file.\n annopath: Path to annotations\n annopath.format(imagename) should be the xml annotations file.\n imagesetfile: Text file containing the list of images, one image per line.\n classname: Category name (duh)\n cachedir: Directory for caching the annotations\n [ovthresh]: Overlap threshold (default = 0.5)\n [use_07_metric]: Whether to use VOC07's 11 point AP computation\n (default False)\n \"\"\"\n # assumes detections are in detpath.format(classname)\n # assumes annotations are in annopath.format(imagename)\n # assumes imagesetfile is a text file with each line an image name\n # cachedir caches the annotations in a pickle file\n\n # first load gt\n if not os.path.isdir(cachedir):\n os.mkdir(cachedir)\n cachefile = os.path.join(cachedir, '%s_annots.pkl' % imagesetfile.split(\"/\")[-1].split(\".\")[0])\n # read list of images\n with open(imagesetfile, 'r') as f:\n lines = f.readlines()\n imagenames = [x.strip() for x in lines]\n \n #-----------------------------------------------------\n # user added\n #-----------------------------------------------------\n print('cachefile:')\n print(cachefile)\n #-----------------------------------------------------\n\n if not os.path.isfile(cachefile):\n # load annotations\n recs = {}\n for i, imagename in enumerate(imagenames):\n recs[imagename] = parse_rec(annopath.format(imagename))\n if i % 100 == 0:\n print('Reading annotation for {:d}/{:d}'.format(\n i + 1, len(imagenames)))\n # save\n print('Saving cached annotations to {:s}'.format(cachefile))\n with open(cachefile, 'wb') as f:\n pickle.dump(recs, f)\n else:\n # load\n with open(cachefile, 'rb') as f:\n try:\n recs = pickle.load(f)\n except:\n recs = pickle.load(f, encoding='bytes')\n\n # extract gt objects for this class\n class_recs = {}\n npos = 0\n for imagename in imagenames:\n #------------------------------------------------------------------------\n # default\n #------------------------------------------------------------------------\n #R = [obj for obj in recs[imagename] if obj['name'] == classname]\n #------------------------------------------------------------------------\n #------------------------------------------------------------------------\n # user changed\n #------------------------------------------------------------------------\n R = []\n for obj in recs[imagename]:\n #print('obj class:' + obj['name'])\n #print('class name:' + classname)\n if obj['name'] == classname:\n R.append(obj)\n #-------------------------------------------------------------------------\n bbox = np.array([x['bbox'] for x in R])\n if use_diff:\n difficult = np.array([False for x in R]).astype(np.bool)\n else:\n difficult = np.array([x['difficult'] for x in R]).astype(np.bool)\n det = [False] * len(R)\n npos = npos + sum(~difficult)\n class_recs[imagename] = {'bbox': bbox,\n 'difficult': difficult,\n 'det': det}\n\n # read dets\n detfile = detpath.format(classname)\n with open(detfile, 'r') as f:\n lines = f.readlines()\n\n splitlines = [x.strip().split(' ') for x in lines]\n image_ids = [x[0] for x in splitlines]\n confidence = np.array([float(x[1]) for x in splitlines])\n BB = np.array([[float(z) for z in x[2:]] for x in splitlines])\n\n nd = len(image_ids)\n tp = np.zeros(nd)\n fp = np.zeros(nd)\n\n if BB.shape[0] > 0:\n # sort by confidence\n sorted_ind = np.argsort(-confidence)\n sorted_scores = np.sort(-confidence)\n BB = BB[sorted_ind, :]\n image_ids = [image_ids[x] for x in sorted_ind]\n\n # go down dets and mark TPs and FPs\n for d in range(nd):\n R = class_recs[image_ids[d]]\n bb = BB[d, :].astype(float)\n ovmax = -np.inf\n BBGT = R['bbox'].astype(float)\n\n if BBGT.size > 0:\n # compute overlaps, IOU\n # intersection\n ixmin = np.maximum(BBGT[:, 0], bb[0])\n iymin = np.maximum(BBGT[:, 1], bb[1])\n ixmax = np.minimum(BBGT[:, 2], bb[2])\n iymax = np.minimum(BBGT[:, 3], bb[3])\n iw = np.maximum(ixmax - ixmin + 1., 0.)\n ih = np.maximum(iymax - iymin + 1., 0.)\n inters = iw * ih\n\n # union\n uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) +\n (BBGT[:, 2] - BBGT[:, 0] + 1.) *\n (BBGT[:, 3] - BBGT[:, 1] + 1.) - inters)\n\n overlaps = inters / uni\n ovmax = np.max(overlaps)\n jmax = np.argmax(overlaps)\n\n if ovmax > ovthresh:\n if not R['difficult'][jmax]:\n if not R['det'][jmax]:\n tp[d] = 1.\n R['det'][jmax] = 1\n \n else:\n fp[d] = 1.\n else:\n fp[d] = 1.\n\n # compute precision recall\n fp = np.cumsum(fp)\n tp = np.cumsum(tp)\n rec = tp / float(npos)\n # avoid divide by zero in case the first detection matches a difficult\n # ground truth\n prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)\n ap = voc_ap(rec, prec, use_07_metric)\n\n return rec, prec, ap\n" ]
[ [ "numpy.maximum", "numpy.minimum", "numpy.arange", "numpy.cumsum", "numpy.sort", "numpy.finfo", "numpy.concatenate", "numpy.max", "numpy.argmax", "numpy.where", "numpy.argsort", "numpy.array", "numpy.zeros", "numpy.sum" ] ]
AJarman/pycaret
[ "e96fefbf95c9e0195ec07ea63ebe25a8ce98baf3" ]
[ "pycaret/tests/test_time_series_tune_base.py" ]
[ "\"\"\"Module to test time_series \"tune_model\" BASE functionality\n\"\"\"\n\nimport pytest\nimport numpy as np\nimport pandas as pd\n\nfrom pycaret.internal.pycaret_experiment import TimeSeriesExperiment\n\nfrom .time_series_test_utils import _ALL_METRICS\n\n\n##########################\n#### Tests Start Here ####\n##########################\n\ndef test_tune_custom_grid_and_choose_better(load_pos_and_neg_data):\n \"\"\"Tests\n (1) passing a custom grid to tune_model, and\n (2) choose_better=True\n \"\"\"\n\n exp = TimeSeriesExperiment()\n\n fh = np.arange(1, 13)\n fold = 2\n data = load_pos_and_neg_data\n\n exp.setup(\n data=data,\n fh=fh,\n fold=fold,\n fold_strategy=\"expanding\",\n verbose=False,\n session_id=42,\n )\n\n model = exp.create_model(\"naive\")\n\n # Custom Grid\n only_strategy = \"mean\"\n custom_grid = {\"strategy\": [only_strategy]}\n\n # By default choose_better = True\n tuned_model1 = exp.tune_model(model, custom_grid=custom_grid)\n\n # Choose Better = False\n tuned_model2 = exp.tune_model(model, custom_grid=custom_grid, choose_better=False)\n\n # Same strategy should be chosen since choose_better = True by default\n assert tuned_model1.strategy == model.strategy\n # should pick only value in custom grid\n assert tuned_model2.strategy == only_strategy\n # tuned model does improve score (verified manually), and choose_better\n # set to False. So pick worse value itself.\n assert tuned_model2.strategy != model.strategy\n\n\ndef test_tune_model_custom_folds(load_pos_and_neg_data):\n \"\"\"test custom folds in tune_model\"\"\"\n exp = TimeSeriesExperiment()\n setup_fold = 3\n exp.setup(\n data=load_pos_and_neg_data,\n fold=setup_fold,\n fh=12,\n fold_strategy=\"sliding\",\n verbose=False,\n )\n\n #######################################\n ## Test Tune Model with custom folds ##\n #######################################\n model = exp.create_model(\"naive\")\n _ = exp.tune_model(model)\n metrics1 = exp.pull()\n\n custom_fold = 5\n _ = exp.tune_model(model, fold=5)\n metrics2 = exp.pull()\n\n assert len(metrics1) == setup_fold + 2 # + 2 for Mean and SD\n assert len(metrics2) == custom_fold + 2 # + 2 for Mean and SD\n\n\[email protected](\"metric\", _ALL_METRICS)\ndef test_tune_model_alternate_metric(load_pos_and_neg_data, metric):\n \"\"\"tests model selection using non default metric\"\"\"\n exp = TimeSeriesExperiment()\n fh = 12\n fold = 2\n\n exp.setup(data=load_pos_and_neg_data, fold=fold, fh=fh, fold_strategy=\"sliding\")\n\n model_obj = exp.create_model(\"naive\")\n\n tuned_model_obj = exp.tune_model(model_obj, optimize=metric)\n y_pred = exp.predict_model(tuned_model_obj)\n assert isinstance(y_pred, pd.Series)\n\n expected_period_index = load_pos_and_neg_data.iloc[-fh:].index\n assert np.all(y_pred.index == expected_period_index)\n\n\ndef test_tune_model_raises(load_pos_and_neg_data):\n \"\"\"Tests conditions that raise an error due to lack of data\"\"\"\n\n exp = TimeSeriesExperiment()\n\n fh = np.arange(1, 13)\n fold = 2\n data = load_pos_and_neg_data\n\n exp.setup(\n data=data,\n fh=fh,\n fold=fold,\n fold_strategy=\"expanding\",\n verbose=False,\n session_id=42,\n )\n\n model = exp.create_model(\"naive\")\n with pytest.raises(ValueError) as errmsg:\n search_algorithm = \"wrong_algorithm\"\n _ = exp.tune_model(model, search_algorithm=search_algorithm)\n\n exceptionmsg = errmsg.value.args[0]\n\n assert (\n exceptionmsg\n == f\"`search_algorithm` must be one of 'None, random, grid'. You passed '{search_algorithm}'.\"\n )\n" ]
[ [ "numpy.all", "numpy.arange" ] ]
kiddkyd1412/find_av_by_face
[ "e6071b9edbfb6a6ae1c833b13988b6262cc9aa55" ]
[ "my_dlib/tsdlib.py" ]
[ "# -*- coding: utf-8 -*-\nimport base64\nimport json\nimport sys\nimport time\nimport warnings\nfrom concurrent.futures import ThreadPoolExecutor, wait, as_completed\nfrom operator import itemgetter\n\nimport dlib\nimport cv2\nimport os\nimport glob\n\nimport numpy as np\n\nfrom iface import IFace\n\n\nclass FaceDlib(IFace):\n def __init__(self):\n super().__init__()\n self.current_path = os.getcwd() # 获取根路径\n self.predictor_path = self.current_path + \"/my_dlib/model/shape_predictor_68_face_landmarks.dat\"\n self.face_rec_model_path = self.current_path + \"/my_dlib/model/dlib_face_recognition_resnet_model_v1.dat\"\n self.dataPath = self.current_path + \"/my_dlib/cache_data/\"\n # 读入模型\n self.detector = dlib.get_frontal_face_detector()\n self.shape_predictor = dlib.shape_predictor(self.predictor_path)\n self.face_rec_model = dlib.face_recognition_model_v1(self.face_rec_model_path)\n\n self.executor = ThreadPoolExecutor(max_workers=8)\n self.result_min_value = 0.5 # 至少要少于0.6才是相似\n\n def init(self, source_img_info, target_img_list, result_list):\n os.makedirs(os.path.join(self.current_path, 'my_dlib/cache_data/'), exist_ok=True)\n\n self.result_list = result_list\n self.source_img_info = source_img_info\n self.target_img_list = target_img_list\n self.source_img_data = self.__get_tezheng(source_img_info)\n\n self.error_list = []\n self.thread_list = []\n\n return self\n\n def working(self):\n try:\n print('开始处理数据,总共:' + str(len(self.target_img_list)) + '条')\n self.__start_thread(self.target_img_list)\n self.__show_thread_log()\n\n if len(self.result_list) > 0:\n self.result_list.sort(key=itemgetter(2))\n print('---------任务结束------------')\n except Exception as ex:\n info = sys.exc_info()\n msg = '{}:{}'.format(info[0], info[1])\n warnings.warn(msg)\n finally:\n self.executor.shutdown(False)\n self.save_log(self.source_img_info['imgurl'].split('/')[-1].split('.')[0], self.result_list, \"dlib\")\n self.save_error_log(self.error_list)\n\n def __chk_photo_for(self, target_info):\n result = self.__compare_data(self.source_img_data, self.__get_tezheng(target_info))\n if result < self.result_min_value:\n self.result_list.append((target_info['imgurl'], target_info['username'], result))\n\n # 开始构建线程进行工作\n def __start_thread(self, work_list):\n self.thread_list.clear()\n for img_info in work_list:\n self.thread_list.append(self.executor.submit(self.__chk_photo_for, img_info))\n\n # 显示线程日志\n def __show_thread_log(self):\n for i, future in enumerate(as_completed(self.thread_list)):\n print('完成:' + str(i + 1))\n print('---------线程结束------------')\n\n def __get_tezheng(self, img_info):\n\n # 检查是否有缓存数据\n filePath = self.dataPath + img_info['imgurl'].split('/')[-1].split('.')[0] + '_' + img_info[\"username\"] + '.npy'\n if os.path.isfile(filePath):\n vectors = np.load(filePath)\n if vectors.size > 0:\n return vectors\n\n # 没有的话,就构建并存起来\n img_data = base64.b64decode(img_info['buf'])\n img_array = np.fromstring(img_data, np.uint8)\n img = cv2.imdecode(img_array, cv2.COLOR_BGR2RGB)\n dets = self.detector(img, 1) # 人脸标定\n\n if len(dets) is not 1:\n warnings.warn(\"图片检测的人脸数为: {}\".format(len(dets)))\n self.error_list.append((img_info['username'], img_info['imgurl']))\n return np.array([])\n\n face = dets[0]\n shape = self.shape_predictor(img, face)\n vectors = np.array([])\n for i, num in enumerate(self.face_rec_model.compute_face_descriptor(img, shape)):\n vectors = np.append(vectors, num)\n np.save(filePath, vectors)\n return vectors\n\n # 计算欧式距离,判断是否是同一个人\n def __compare_data(self, data1, data2):\n diff = 0\n # for v1, v2 in data1, data2:\n # diff += (v1 - v2)**2\n for i in range(len(data1)):\n diff += (data1[i] - data2[i]) ** 2\n diff = np.sqrt(diff)\n return diff\n" ]
[ [ "numpy.sqrt", "numpy.save", "numpy.append", "numpy.fromstring", "numpy.load", "numpy.array" ] ]
EnzoItaliano/calculoNumericoEmPython
[ "be3161b823955620be71e0f94a3421288fd28ef0" ]
[ "Lista2.py" ]
[ "import math\nimport matplotlib.pyplot as plt\nfrom prettytable import PrettyTable\nfrom sympy import *\nimport numpy as np\nx = symbols('x')\n#Raízes de Equações\n##Método da Bissecção\ndef plot2d(f, inicio, fim):\n z = np.arange(inicio,fim,0.1)\n \n y = []\n for i in range(len(z)):\n y.append(f.subs(x,z[i]))\n \n fig, ax = plt.subplots()\n ax.set(title='Gráfico função f(x)='+str(f))\n ax.plot(z,y)\n ax.grid()\n plt.show()\n\ndef bisseccao(f, e, a, b):\n fa = f.subs(x,a)\n fb = f.subs(x,b)\n if fa * fb >= 0:\n print(\"Não atende ao critério f(a) * f(b) < 0\")\n return\n \n k = 0\n ak = []\n bk = []\n xk = []\n fak = []\n fbk = []\n xk = []\n fxk = []\n xk_x = []\n ak.append(a)\n bk.append(b)\n\n kf = math.log((b-a)/e,2)-1\n times = math.ceil(kf) + 1\n\n for k in range(times):\n if k == 0:\n y = ak[len(ak)-1]\n fak.append(round(f.subs(x,y),9))\n y = bk[len(bk)-1]\n fbk.append(round(f.subs(x,y),9))\n xk.append((ak[len(ak)-1] + bk[len(bk)-1])/2)\n y = xk[len(xk)-1]\n fxk.append(round(f.subs(x,y),9))\n xk_x.append('-')\n else:\n if (fak[len(fak)-1] < 0 and fxk[len(fxk)-1] < 0) or (fak[len(fak)-1] > 0 and fxk[len(fxk)-1] > 0):\n ak.append(xk[len(xk)-1])\n bk.append(bk[len(bk)-1])\n else:\n ak.append(ak[len(ak)-1])\n bk.append(xk[len(xk)-1])\n\n y = ak[len(ak)-1]\n fak.append(round(f.subs(x,y),9))\n y = bk[len(bk)-1]\n fbk.append(round(f.subs(x,y),9))\n xk.append((ak[len(ak)-1] + bk[len(bk)-1])/2)\n y = xk[len(xk)-1]\n fxk.append(round(f.subs(x,y),9))\n temp = xk[len(xk)-1] - xk[len(xk)-2]\n if temp < 0:\n temp = temp * -1\n xk_x.append(temp)\n\n Table = PrettyTable([\"k\", \"a\", \"b\", \"f(a)\", \"f(b)\", \"x\", \"f(x)\", \"|x(k) - x(k-1)|\"])\n for k in range(times):\n Table.add_row([k, ak[k], bk[k], fak[k], fbk[k], xk[k], fxk[k], xk_x[k]])\n\n print(Table)\n print(\"Donde \\u03B5 é aproximadamente \" + str(xk[len(xk)-1]))\n\n# def f(x): return pow(x,2)-3\n# plot2d(f(x), 0, 2)\n# bisseccao(f(x), 0.01, 1, 2)\n\n## Método do Ponto Fixo\ndef pontoFixo(f,e,xi):\n xk = []\n xk.append(xi)\n xk_x = []\n xk_x.append(\"-\")\n end_condition = 0\n while not end_condition:\n xk.append(f.subs(x,xk[len(xk)-1]))\n xk_x.append(abs(xk[len(xk)-1]-xk[len(xk)-2]))\n if xk_x[len(xk_x)-1] < e:\n end_condition = 1\n \n Table = PrettyTable([\"k\", \"xk\", \"|x(k) - x(k-1)|\"])\n for k in range(0, len(xk)):\n Table.add_row([k, xk[k], xk_x[k]])\n \n print(Table)\n print(\"Donde \\u03B5 é aproximadamente \" + str(xk[len(xk)-1]))\n\n\n# def f(x): return cos(x)\n# pontoFixo(f(x),10**(-2), math.pi/4)\n\n## Método de Newton\ndef newton(f, e, a, b):\n xk = []\n xk.append(b)\n xk_x = []\n xk_x.append(0)\n end_condition = 0\n\n if f.subs(x,xk[len(xk)-1]) * diff(diff(f,x),x).subs(x,xk[len(xk)-1]) > 0:\n while not end_condition:\n func = f.subs(x,xk[len(xk)-1])\n derivate = diff(f,x).subs(x,xk[len(xk)-1])\n temp = xk[len(xk)-1] - func/derivate\n xk.append(N(temp))\n\n temp2 = xk[len(xk)-2] - xk[len(xk)-1]\n if temp2 < 0:\n temp2 = temp2 * -1\n\n xk_x.append(N(temp2))\n if xk_x[len(xk_x)-1] < e:\n end_condition = 1\n \n Table = PrettyTable([\"k\", \"xk\", \"|x(k) - x(k-1)|\"])\n for k in range(1, len(xk)):\n Table.add_row([k, xk[k], xk_x[k]])\n \n print(Table)\n\n print(\"Donde \\u03B5 é aproximadamente \" + str(xk[len(xk)-1]))\n\n# def f(x): return x**2-2\n# newton(f(x), 0.00005, 1, 2)\n\n## Método da Secante\ndef secante(f, e, a, b):\n xk = []\n xk.append(a)\n xk.append(b)\n xk_x = []\n xk_x.append(0)\n xk_x.append(0)\n end_condition = 0\n\n while not end_condition:\n temp = f.subs(x, xk[len(xk)-1]) * (xk[len(xk)-1] - xk[len(xk)-2])\n temp2 = f.subs(x, xk[len(xk)-1]) - f.subs(x,xk[len(xk)-2])\n temp3 = xk[len(xk)-1] - (temp/temp2)\n xk.append(temp3)\n\n temp4 = xk[len(xk)-1] - xk[len(xk)-2]\n \n if temp4 < 0:\n temp4 = temp4 * -1\n\n xk_x.append(temp4)\n\n if xk_x[len(xk_x)-1] < e:\n end_condition = 1\n\n Table = PrettyTable([\"k\", \"xk\", \"|x(k+1) - x(k)|\"])\n for k in range(2, len(xk)):\n Table.add_row([k, xk[k], xk_x[k]])\n \n print(Table)\n print(\"Donde \\u03B5 é aproximadamente \" + str(xk[len(xk)-1]))\n\nprint(\"Secante\\n\")\ndef f(x): return 2*x**3-5*x**2-10*x+20\nsecante(f(x), 10**(-5), 1.2, 1.7)\n\n## Método Regula Falsi\ndef regulaFalsi(f, e, a, b):\n xk = []\n xk_x = []\n\n x0 = a\n x1 = b\n print(f.subs(x,a))\n print(f.subs(x,b))\n end_condition = 0\n\n while not end_condition:\n temp = x1 - f.subs(x, x1) * (x1 - x0) / (f.subs(x, x1) - f.subs(x, x0))\n\n temp2 = temp - x1\n \n if temp2 < 0:\n temp2 = temp2 * -1\n\n if temp2 < e:\n xk.append(temp)\n xk_x.append(temp2)\n end_condition = 1\n continue\n\n k = f.subs(x, temp)\n\n if k*f.subs(x, x1) < 0:\n x0 = x1\n\n x1 = temp\n xk.append(temp)\n xk_x.append(temp2)\n \n\n Table = PrettyTable([\"k\", \"xk\", \"|x(k) - x(k-1)|\"])\n for k in range(len(xk)):\n Table.add_row([k+2, xk[k], xk_x[k]])\n \n print(Table)\n print(\"Donde \\u03B5 é aproximadamente \" + str(xk[len(xk)-1]))\n\nprint(\"\\nRegula Falsi\\n\")\ndef f(x): return 2*x**3-5*x**2-10*x+20\nregulaFalsi(f(x), 0.0001, 1.2, 1.7)\n" ]
[ [ "numpy.arange", "matplotlib.pyplot.show", "matplotlib.pyplot.subplots" ] ]
jbathmann/ogs
[ "a79e95d7521a841ffebd441a6100562847e03ab5" ]
[ "Tests/Data/Parabolic/T/3D_3BHEs_array/bcs_tespy.py" ]
[ "###\n# Copyright(c) 2012 - 2019, OpenGeoSys Community(http://www.opengeosys.org)\n# Distributed under a Modified BSD License.\n# See accompanying file LICENSE.txt or\n# http://www.opengeosys.org/project/license\n###\n\nimport sys\nprint(sys.version)\nimport os\nimport numpy as np\nfrom pandas import read_csv\nimport OpenGeoSys\nfrom tespy import cmp, con, nwk, hlp, cmp_char\nfrom tespy import nwkr\n\n# User setting +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# parameters\n# refrigerant parameters\nrefrig_density = 992.92 # kg/m3\n# switch for special boundary conditions\n# 'on','off', switch of the function for dynamic thermal demand from consumer\nswitch_dyn_demand = 'on'\n# 'on','off', switch of the function for dynamic flowrate in BHE\nswitch_dyn_frate = 'off'\n\n\n# timecurve setting\ndef timerange(t):\n # month for closed network\n timerange_nw_off_month = [-9999] # No month for closed network\n nw_status = 'on'\n # t-1 to avoid the calculation problem at special time point,\n # e.g. t = 2592000.\n t_trans = int((t - 1) / 86400 / 30) + 1\n t_trans_month = t_trans\n if t_trans_month > 12:\n t_trans_month = t_trans - 12 * (int(t_trans / 12))\n if t_trans_month in timerange_nw_off_month:\n nw_status = 'off'\n return t_trans, t_trans_month, nw_status\n\n\n# consumer thermal load\n# month demand\ndef consumer_demand(t): # dynamic thermal demand from consumer\n # thermal demand in each month (assumed specific heat extraction rate*\n # length of BHE* number of BHE)\n month_demand = [\n -25 * 50 * 3, -25 * 50 * 3, -25 * 50 * 3, -25 * 50 * 3, -25 * 50 * 3,\n -25 * 50 * 3, -25 * 50 * 3, -25 * 50 * 3, -25 * 50 * 3, -25 * 50 * 3,\n -25 * 50 * 3, -25 * 50 * 3\n ]\n return month_demand[t - 1]\n\n\n# dynamic hydraulic flow rate\n# month demand\ndef dyn_frate(t): # dynamic flowrate in BHE\n # flow rate in kg / s time curve in month\n month_frate = [-9999]\n return month_frate[t - 1]\n\n\n# End User setting+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\n# create network dataframe\ndef create_dataframe():\n # return dataframe\n df_nw = read_csv('./pre/bhe_network.csv',\n delimiter=';',\n index_col=[0],\n dtype={'data_index': str})\n return (df_nw)\n\n\n# TESPy hydraulic calculation process\ndef get_hydraulics(t_trans):\n # if network exist dynamic flowrate\n if switch_dyn_frate == 'on':\n cur_frate = dyn_frate(t_trans)\n localVars['inlet_name'].set_attr(m=cur_frate)\n # solve imported network\n nw.solve(mode='design')\n # get flowrate #kg / s\n for i in range(n_BHE):\n for c in nw.conns.index:\n if c.t.label == data_index[i]: # t:inlet comp, s:outlet comp\n df.loc[df.index[i], 'flowrate'] = c.get_attr('m').val_SI\n # convert flowrate to velocity : #m ^ 3 / s\n for i in range(n_BHE):\n df.loc[df.index[i],\n 'f_velocity'] = df.loc[df.index[i], 'flowrate'] / refrig_density\n return df\n\n\n# TESPy Thermal calculation process\ndef get_thermal(t):\n # bhe network thermal re parametrization\n if switch_dyn_demand == 'on':\n # consumer thermal load:\n cur_month_demand = consumer_demand(t)\n # print('cur_month_demand', cur_month_demand)\n nw.busses[bus_name].set_attr(P=cur_month_demand)\n # T_out:\n for i in range(n_BHE):\n localVars['outlet_BHE' + str(i + 1)].set_attr(T=df.loc[data_index[i],\n 'Tout_val'])\n # print('Tout=', df.loc[data_index[i], 'Tout_val'])\n # solving network\n nw.solve(mode='design')\n # get Tin_val\n for i in range(n_BHE):\n df.loc[df.index[i],\n 'Tin_val'] = localVars['inlet_BHE' +\n str(i + 1)].get_attr('T').val_SI\n # print('Tin=', df.loc[df.index[i], 'Tin_val'])\n return df['Tin_val'].tolist()\n\n\n# OGS setting\n# Dirichlet BCs\nclass BC(OpenGeoSys.BHENetwork):\n def initializeDataContainer(self):\n # convert dataframe to column list\n t = 0 # 'initial time'\n data_col_1 = df['Tin_val'].tolist() # 'Tin_val'\n data_col_2 = df['Tout_val'].tolist() # 'Tout_val'\n data_col_3 = df['Tout_node_id'].astype(int).tolist() # 'Tout_node_id'\n get_hydraulics(0)\n data_col_4 = df['f_velocity'].tolist() # 'BHE flow rate'\n return (t, data_col_1, data_col_2, data_col_3, data_col_4)\n\n def tespyThermalSolver(self, t, Tin_val, Tout_val):\n # current time, network status:\n t_trans, t_trans_month, nw_status = timerange(t)\n # if network closed:\n # print('nw_status = ', nw_status)\n if nw_status == 'off':\n return (True, True, Tout_val)\n else:\n # read Tout_val to dataframe\n for i in range(n_BHE):\n df.loc[df.index[i], 'Tout_val'] = Tout_val[i]\n # TESPy solver\n cur_cal_Tin_val = get_thermal(t_trans_month)\n # check norm if network achieves the converge\n if_success = False\n pre_cal_Tin_val = Tin_val\n norm = np.linalg.norm(\n abs(np.asarray(pre_cal_Tin_val) - np.asarray(cur_cal_Tin_val)))\n if norm < 10e-6:\n if_success = True\n # return to OGS\n return (True, if_success, cur_cal_Tin_val)\n\n def tespyHydroSolver(self, t):\n if_dyn_frate = False\n data_f_velocity = df['f_velocity'].tolist()\n if switch_dyn_frate == 'on':\n if_dyn_frate = True\n # current time, network status:\n t_trans, t_trans_month, nw_status = timerange(t)\n if nw_status == 'off':\n for i in range(n_BHE):\n df.loc[df.index[i], 'f_velocity'] = 0\n data_f_velocity = df['f_velocity'].tolist()\n else:\n dataframe = get_hydraulics(t_trans)\n data_f_velocity = dataframe['f_velocity'].tolist()\n # return to OGS\n return (if_dyn_frate, data_f_velocity)\n\n\n# main\n# initialize the tespy model of the bhe network\n# load path of network model:\n# loading the TESPy model\nproject_dir = os.getcwd()\nprint(\"Project dir is: \", project_dir)\nnw = nwkr.load_nwk('./pre/tespy_nw')\n# set if print the information of the network\nnw.set_printoptions(print_level='none')\n\n# create bhe dataframe of the network system from bhe_network.csv\ndf = create_dataframe()\nn_BHE = np.size(df.iloc[:, 0])\n\n# create local variables of the components label and connections label in\n# network\nlocalVars = locals()\ndata_index = df.index.tolist()\nfor i in range(n_BHE):\n for c in nw.conns.index:\n # bhe inlet and outlet conns\n if c.t.label == data_index[i]: # inlet conns of bhe\n localVars['inlet_BHE' + str(i + 1)] = c\n if c.s.label == data_index[i]: # outlet conns of bhe\n localVars['outlet_BHE' + str(i + 1)] = c\n\n# time depended consumer thermal demand\nif switch_dyn_demand == 'on':\n # import the name of bus from the network csv file\n bus_name = read_csv('./pre/tespy_nw/comps/bus.csv',\n delimiter=';',\n index_col=[0]).index[0]\n\n# time depended flowrate\nif switch_dyn_frate == 'on':\n # import the name of inlet connection from the network csv file\n inlet_name = read_csv('./pre/tespy_nw/conn.csv',\n delimiter=';',\n index_col=[0]).iloc[0,0]\n for c in nw.conns.index:\n # bhe inflow conns\n if c.s.label == inlet_name: # inlet conns of bhe\n localVars['inlet_name'] = c\n\n# instantiate BC objects referenced in OpenGeoSys\nbc_bhe = BC()\n" ]
[ [ "numpy.asarray", "numpy.size", "pandas.read_csv" ] ]
897741007/EIAA
[ "94a071687eb387f199f9d8a82848a40ef2a6f5d7" ]
[ "GAT_prediction.py" ]
[ "import torch\nfrom torch import nn\nimport numpy as np\nfrom Smi2Graph import SMI_grapher\nfrom time import time\nimport os\n\nclass GAT_predictor(nn.Module):\n def __init__(self, hidden_dim, layer_num, head_num, dict_size, dropout=0, bond_influence=0, prediction_class=2, device='cuda'):\n # param : bond_influence --> how to merge the influence of bond in the attention\n # 0: ingore the influence of bond\n # 1: add the embedding of bond to K\n # 2: mul the embedding of bond to K\n # param : prediction_class --> the number of classification labels\n # 1: the task is a regression task\n # n(n>1): the task is a classification task \n super(GAT_predictor, self).__init__()\n self.hidden_dim = hidden_dim\n self.layer_num = layer_num\n self.head_num = head_num\n self.dict_size = dict_size\n assert dropout < 1\n self.dropout = dropout\n assert bond_influence in (0, 1, 2)\n self.bond_influence = bond_influence\n self.prediction_class = prediction_class\n self.scale = np.sqrt(hidden_dim)\n self.sp_dim = int(hidden_dim/head_num)\n self.device = device\n self.GAT_init()\n \n def GAT_init(self):\n self.atom_embedding_layer = nn.Embedding(self.dict_size, self.hidden_dim).to(self.device)\n # bond type: non-link, self-link, single-bond, double-bond, trible-bond, π-adj, π-meta, π-para\n if self.bond_influence:\n # N(0, 1), if the influence of bond is add to the weight matrix, the distribution of embedding ~ N(0,1)\n bond_embedding_weight = torch.randn(8, self.hidden_dim, device=self.device)\n if self.bond_influence==2:\n # N(1, 1), if the influence of bond is mul to the weight matrix, the distribution of embedding ~ N(1,1)\n bond_embedding_weight = bond_embedding_weight + torch.ones_like(bond_embedding_weight, device=self.device)\n self.bond_embedding_layer = nn.Embedding(8, self.hidden_dim,_weight=bond_embedding_weight).to(self.device)\n\n self.q_layers = nn.ModuleList()\n self.k_layers = nn.ModuleList()\n self.v_layers = nn.ModuleList()\n self.ew_layers = nn.ModuleList()\n self.stack_head_layers = nn.ModuleList()\n self.FNN_layers = nn.ModuleList()\n for _ in range(self.layer_num):\n self.q_layers.append(nn.Linear(self.hidden_dim, self.hidden_dim, bias=False).to(self.device))\n self.k_layers.append(nn.Linear(self.hidden_dim, self.hidden_dim, bias=False).to(self.device))\n self.v_layers.append(nn.Linear(self.hidden_dim, self.hidden_dim, bias=False).to(self.device))\n self.ew_layers.append(nn.Linear(self.hidden_dim, self.hidden_dim, bias=False).to(self.device))\n self.stack_head_layers.append(nn.Linear(self.hidden_dim, self.hidden_dim, bias=False).to(self.device))\n self.FNN_layers.append(nn.ModuleList([nn.Linear(self.hidden_dim, self.hidden_dim*4, bias=False).to(self.device), \n nn.Linear(self.hidden_dim*4, self.hidden_dim, bias=False).to(self.device)]))\n self.output_layer = nn.Sequential(nn.Linear(self.hidden_dim, self.hidden_dim, bias=False).to(self.device),\n nn.Tanh().to(self.device))\n self.predictor_layer = nn.Linear(self.hidden_dim, self.prediction_class).to(self.device)\n if self.prediction_class > 1:\n self.predictor_softmax = nn.Softmax(dim=-1)\n\n def weighted_qkmm(self, q, k, w):\n # q.shape : [batch_size, head_num, token_len, split_dim]\n # k.shape : [batch_size, head_num, token_len, split_dim]\n # w.shape : [batch_size, head_num, token_len, token_len, split_dim]\n q = q.unsqueeze(-2).expand(w.shape)\n k = k.unsqueeze(-3).expand(w.shape)\n if self.bond_influence == 1:\n k = k + w\n else:\n k = torch.mul(k, w)\n sim_s = torch.mul(q, k)\n sim = sim_s.sum(-1)\n return sim\n \n def edge_attention(self, attn_out, w):\n # update the feature of edge according to edge and the linked atoms\n # new_edge : sum(Softmax(edge*atom_0, edge*edge, edge*atom_1) * (atom_0, edge, atom_1))\n # atten_out.shape : [batch_size, token_len, hidden_dim]\n # w.shape : [batch_size, token_len, token_len, hidden_dim]\n ew_0 = w.unsqueeze(-2)\n ew_1 = w.unsqueeze(-1)\n ew_s = torch.matmul(ew_0, ew_1).squeeze(-2)\n # atom_0 * edge\n aw_0 = attn_out.unsqueeze(2).expand_as(w).unsqueeze(-1)\n aw_0s = torch.matmul(ew_0, aw_0).squeeze(-2)\n # atom_1 * edge\n aw_1 = attn_out.unsqueeze(1).expand_as(w).unsqueeze(-1)\n aw_1s = torch.matmul(ew_0, aw_1).squeeze(-2)\n # Softmax\n weight = torch.cat((ew_s, aw_0s, aw_1s), dim=-1)\n weight = weight/self.scale\n weight = nn.Softmax(dim=-1)(weight).unsqueeze(-2)\n # weighted sum\n hidden = torch.cat((ew_1, aw_0, aw_1), dim=-1).permute((0,1,2,4,3))\n new_e = torch.matmul(weight, hidden).squeeze(-2)\n return new_e\n\n def split_head(self, tensor):\n # split the head into n heads\n k = tensor.shape\n if len(k) == 4:\n return tensor\n else:\n split_tensor = tensor.reshape(k[0], k[1], self.head_num, self.sp_dim)\n split_tensor = split_tensor.permute(0,2,1,3)\n return split_tensor\n \n def split_bond_embedding(self, bond_embedding):\n # split the bond embedding into n heads\n # bond_embedding shape : [batch_size, tensor_length, tensor_length, embedding_dim]\n # splited_bond_embedding shape : [batch_size, head_num, tensor_length, tensor_length, splited_dim]\n k = bond_embedding.shape\n split_bond_embedding = bond_embedding.reshape(k[0], k[1], k[2], self.head_num, self.sp_dim)\n split_bond_embedding = split_bond_embedding.permute(0,3,1,2,4)\n return split_bond_embedding\n\n def combine_head(self, tensor):\n # combine the split heads into one head\n k = tensor.shape\n if len(k) == 3:\n return tensor\n else:\n combine_tensor = tensor.permute(0,2,1,3)\n combine_tensor = combine_tensor.reshape(k[0], k[2], self.hidden_dim)\n return combine_tensor\n \n def attention_mask(self, logits, adjacency_matrix):\n # mask attention weights to control the range of attention\n # each atom can only see the atoms it linked and the atom itself\n # different type of bonds are regard as the same bonds\n multi_head_adjacency_matrix = adjacency_matrix.unsqueeze(1).expand(logits.shape)\n #logits[multi_head_adjacency_matrix<0.5] = -np.inf\n #logits[multi_head_adjacency_matrix<0.5] = -1e9\n attn_scores = torch.zeros_like(multi_head_adjacency_matrix, dtype=torch.float)\n attn_scores[multi_head_adjacency_matrix==0] = -np.inf\n logits = logits + attn_scores\n #torch.save(logits, 'test_logits.pkl')\n return logits\n \n def multi_head_attention_layer(self, q, k, v, idx, bond_embedding, attn_mask_template):\n # scaled dot multi head-attention\n # parameter : attn_mask_template ---> the template of masking the attention\n if self.bond_influence:\n logits = self.weighted_qkmm(q, k, bond_embedding)\n else:\n logits = torch.matmul(q, k.permute(0, 1, 3, 2))\n logits = logits/self.scale\n logits = self.attention_mask(logits, attn_mask_template)\n weights = nn.Softmax(dim=-1)(logits)\n if self.dropout:\n weights = nn.Dropout(self.dropout)(weights)\n #torch.save(weights, 'test_weights.pkl')\n out_pre = torch.matmul(weights, v)\n out = self.combine_head(out_pre)\n out = self.stack_head_layers[idx](out)\n return out\n\n def FNN(self, idx, input_batch):\n # feed forward layer\n # consists of two linear layers, the activation only occurs after the first linear layer\n fnn_hidden_tensor = self.FNN_layers[idx][0](input_batch)\n fnn_hidden_tensor = nn.ReLU()(fnn_hidden_tensor)\n if self.dropout:\n fnn_hidden_tensor = nn.Dropout(self.dropout)(fnn_hidden_tensor)\n fnn_output = self.FNN_layers[idx][1](fnn_hidden_tensor)\n return fnn_output\n\n def GAT_layer_0(self, input_batch, adj_m, idx, bond_embedding):\n # attention layer in Graph Attention\n input_batch = nn.LayerNorm(self.hidden_dim).to(self.device)(input_batch)\n q = self.split_head(self.q_layers[idx](input_batch))\n k = self.split_head(self.k_layers[idx](input_batch))\n v = self.split_head(self.v_layers[idx](input_batch))\n ew = None\n if self.bond_influence:\n #ew = self.split_bond_embedding(self.ew_layers[idx](bond_embedding))\n ew = self.split_bond_embedding(bond_embedding)\n attn_out = self.multi_head_attention_layer(q, k, v, idx, ew, adj_m)\n\n if self.dropout:\n attn_out = nn.Dropout(self.dropout)(attn_out)\n # the first residual\n attn_resid = attn_out + input_batch\n # the first layer normalization\n #LN_attn_resid = self.transformer_LNs[idx][0](attn_resid)\n LN_attn_resid = nn.LayerNorm(self.hidden_dim).to(self.device)(attn_resid)\n # feed forward layer\n FNN_out = self.FNN(idx, LN_attn_resid)\n if self.dropout:\n FNN_out = nn.Dropout(self.dropout)(FNN_out)\n # the second residual\n #FNN_resid = FNN_out + LN_attn_resid\n transformer_output = FNN_out + attn_resid\n # the second layer normalization\n #transformer_output = self.transformer_LNs[idx][1](FNN_resid)\n #transformer_output = nn.LayerNorm(self.hidden_dim).to(self.device)(FNN_resid)\n\n return transformer_output\n\n def GAT_layer_0e(self, input_batch, adj_m, idx, bond_embedding):\n # attention layer in Graph Attention\n # combination of node attention and edge attention\n input_batch = nn.LayerNorm(self.hidden_dim).to(self.device)(input_batch)\n q = self.split_head(self.q_layers[idx](input_batch))\n k = self.split_head(self.k_layers[idx](input_batch))\n v = self.split_head(self.v_layers[idx](input_batch))\n ew = self.ew_layers[idx](bond_embedding)\n attn_out = self.multi_head_attention_layer(q, k, v, idx, self.split_bond_embedding(ew), adj_m)\n if self.dropout:\n attn_out = nn.Dropout(self.dropout)(attn_out)\n # the first residual\n attn_resid = attn_out + input_batch\n # the first layer normalization\n LN_attn_resid = nn.LayerNorm(self.hidden_dim).to(self.device)(attn_resid)\n # feed forward layer\n FNN_out = self.FNN(idx, LN_attn_resid)\n if self.dropout:\n FNN_out = nn.Dropout(self.dropout)(FNN_out)\n # the second residual\n transformer_output = FNN_out + attn_resid\n # edge attention\n #print(transformer_output.shape)\n #print(ew.shape)\n edge_output = self.edge_attention(transformer_output, ew)\n return transformer_output, edge_output\n\n def GAT_layer_1(self, input_batch, adj_m, idx, bond_embedding):\n # attention layer in Graph Attention\n q = self.split_head(self.q_layers[idx](input_batch))\n k = self.split_head(self.k_layers[idx](input_batch))\n v = self.split_head(self.v_layers[idx](input_batch))\n attn_out = self.multi_head_attention_layer(q, k, v, idx, bond_embedding, adj_m)\n if self.dropout:\n attn_out = nn.Dropout(self.dropout)(attn_out)\n # the first residual\n attn_resid = attn_out + input_batch\n # the first layer normalization\n LN_attn_resid = nn.LayerNorm(self.hidden_dim).to(self.device)(attn_resid)\n # feed forward layer\n FNN_out = self.FNN(idx, LN_attn_resid)\n if self.dropout:\n FNN_out = nn.Dropout(self.dropout)(FNN_out)\n # the second residual\n FNN_resid = FNN_out + LN_attn_resid\n # the second layer normalization\n transformer_output = nn.LayerNorm(self.hidden_dim).to(self.device)(FNN_resid)\n\n return transformer_output\n\n def get_cls(self, gat_output):\n # get the [CLS] of each mol-graph in the batch\n cls_vector = gat_output[:, 0, :]\n cls_output = self.output_layer(cls_vector)\n cls_output = nn.Dropout(p=0.1)(cls_output)\n cls_output = self.predictor_layer(cls_output)\n if self.prediction_class > 1:\n cls_output = self.predictor_softmax(cls_output)\n #else:\n #cls_output = cls_output.reshape(-1)\n return cls_output\n\n def forward_(self, input_batch, adj_m):\n # forward propagation without edge attention\n # parameter : input_batch ---> Atom information\n # parameter : adj_m ---> Adjacency matrix\n atom_embedding = self.atom_embedding_layer(input_batch)\n if self.bond_influence:\n bond_embedding = self.bond_embedding_layer(adj_m)\n #bond_embedding = self.split_bond_embedding(bond_embedding)\n else:\n bond_embedding = None\n g_layer_output = self.GAT_layer_0(atom_embedding, adj_m, 0, bond_embedding)\n for layer_idx in range(1, self.layer_num):\n g_layer_output = self.GAT_layer_0(g_layer_output, adj_m, layer_idx, bond_embedding)\n prediction = self.get_cls(g_layer_output)\n return prediction\n \n def forward(self, input_batch, adj_m):\n # forward propagation with edge attention\n # parameter : input_batch ---> Atom information\n # parameter : adj_m ---> Adjacency matrix\n atom_embedding = self.atom_embedding_layer(input_batch)\n bond_embedding = self.bond_embedding_layer(adj_m)\n g_layer_output, g_layer_egde = self.GAT_layer_0e(atom_embedding, adj_m, 0, bond_embedding)\n for layer_idx in range(1, self.layer_num):\n g_layer_output, g_layer_egde = self.GAT_layer_0e(g_layer_output, adj_m, layer_idx, g_layer_egde)\n prediction = self.get_cls(g_layer_output)\n return prediction\n\nif __name__ == '__main__':\n hidden_dim = 512\n layer_num = 12\n head_num = 8\n dropout = 0.2\n bond_influence = 1\n prediction_class = 2\n device = 'cuda'\n graph_provider = SMI_grapher(for_predictor=True, device=device)\n graph_provider.fit_new(batch_smis)\n GAT_model = GAT_predictor(hidden_dim, layer_num, head_num, grapher_provider.dict_size, dropout, bond_influence, prediction_class, device)\n" ]
[ [ "torch.nn.Softmax", "torch.nn.Dropout", "numpy.sqrt", "torch.cat", "torch.randn", "torch.nn.ModuleList", "torch.zeros_like", "torch.nn.Embedding", "torch.nn.Tanh", "torch.nn.LayerNorm", "torch.matmul", "torch.nn.Linear", "torch.mul", "torch.nn.ReLU", "torch.ones_like" ] ]
Neotriple/differentiable-robot-model
[ "7b3887b5d80ad7d99379962f9f46aabfd4a1c46d" ]
[ "differentiable_robot_model/spatial_vector_algebra.py" ]
[ "from __future__ import annotations\nimport torch\nimport hydra\nimport math\nfrom . import utils\nfrom .utils import cross_product\n\n\ndef x_rot(angle):\n if len(angle.shape) == 0:\n angle = angle.unsqueeze(0)\n angle = utils.convert_into_at_least_2d_pytorch_tensor(angle).squeeze(1)\n batch_size = angle.shape[0]\n R = torch.zeros((batch_size, 3, 3))\n R[:, 0, 0] = torch.ones(batch_size)\n R[:, 1, 1] = torch.cos(angle)\n R[:, 1, 2] = -torch.sin(angle)\n R[:, 2, 1] = torch.sin(angle)\n R[:, 2, 2] = torch.cos(angle)\n return R\n\n\ndef y_rot(angle):\n if len(angle.shape) == 0:\n angle = angle.unsqueeze(0)\n angle = utils.convert_into_at_least_2d_pytorch_tensor(angle).squeeze(1)\n batch_size = angle.shape[0]\n R = torch.zeros((batch_size, 3, 3))\n R[:, 0, 0] = torch.cos(angle)\n R[:, 0, 2] = torch.sin(angle)\n R[:, 1, 1] = torch.ones(batch_size)\n R[:, 2, 0] = -torch.sin(angle)\n R[:, 2, 2] = torch.cos(angle)\n return R\n\n\ndef z_rot(angle):\n if len(angle.shape) == 0:\n angle = angle.unsqueeze(0)\n angle = utils.convert_into_at_least_2d_pytorch_tensor(angle).squeeze(1)\n batch_size = angle.shape[0]\n R = torch.zeros((batch_size, 3, 3))\n R[:, 0, 0] = torch.cos(angle)\n R[:, 0, 1] = -torch.sin(angle)\n R[:, 1, 0] = torch.sin(angle)\n R[:, 1, 1] = torch.cos(angle)\n R[:, 2, 2] = torch.ones(batch_size)\n return R\n\n\nclass CoordinateTransform(object):\n def __init__(self, rot=None, trans=None):\n\n if rot is None:\n self._rot = torch.eye(3)\n else:\n self._rot = rot\n if len(self._rot.shape) == 2:\n self._rot = self._rot.unsqueeze(0)\n\n if trans is None:\n self._trans = torch.zeros(3)\n else:\n self._trans = trans\n if len(self._trans.shape) == 1:\n self._trans = self._trans.unsqueeze(0)\n\n def set_translation(self, t):\n self._trans = t\n if len(self._trans.shape) == 1:\n self._trans = self._trans.unsqueeze(0)\n return\n\n def set_rotation(self, rot):\n self._rot = rot\n if len(self._rot.shape) == 2:\n self._rot = self._rot.unsqueeze(0)\n return\n\n def rotation(self):\n return self._rot\n\n def translation(self):\n return self._trans\n\n def inverse(self):\n rot_transpose = self._rot.transpose(-2, -1)\n return CoordinateTransform(rot_transpose, -(rot_transpose @ self._trans.unsqueeze(2)).squeeze(2))\n\n def multiply_transform(self, coordinate_transform):\n new_rot = self._rot @ coordinate_transform.rotation()\n new_trans = (self._rot @ coordinate_transform.translation().unsqueeze(2)).squeeze(2) + self._trans\n return CoordinateTransform(new_rot, new_trans)\n\n def trans_cross_rot(self):\n return utils.vector3_to_skew_symm_matrix(self._trans) @ self._rot\n\n def get_quaternion(self):\n batch_size = self._rot.shape[0]\n M = torch.zeros((batch_size, 4, 4)).to(self._rot.device)\n M[:, :3, :3] = self._rot\n M[:, :3, 3] = self._trans\n M[:, 3, 3] = 1\n q = torch.empty((batch_size, 4)).to(self._rot.device)\n t = torch.einsum('bii->b', M) #torch.trace(M)\n for n in range(batch_size):\n tn = t[n]\n if tn > M[n, 3, 3]:\n q[n, 3] = tn\n q[n, 2] = M[n, 1, 0] - M[n, 0, 1]\n q[n, 1] = M[n, 0, 2] - M[n, 2, 0]\n q[n, 0] = M[n, 2, 1] - M[n, 1, 2]\n else:\n i, j, k = 0, 1, 2\n if M[n, 1, 1] > M[n, 0, 0]:\n i, j, k = 1, 2, 0\n if M[n, 2, 2] > M[n, i, i]:\n i, j, k = 2, 0, 1\n tn = M[n, i, i] - (M[n, j, j] + M[n, k, k]) + M[n, 3, 3]\n q[n, i] = tn\n q[n, j] = M[n, i, j] + M[n, j, i]\n q[n, k] = M[n, k, i] + M[n, i, k]\n q[n, 3] = M[n, k, j] - M[n, j, k]\n #q = q[[3, 0, 1, 2]]\n q[n, :] *= 0.5 / math.sqrt(tn * M[n, 3, 3])\n return q\n\n def to_matrix(self):\n mat = torch.zeros((6, 6))\n t = torch.zeros((3, 3))\n t[0, 1] = -self._trans[0, 2]\n t[0, 2] = self._trans[0, 1]\n t[1, 0] = self._trans[0, 2]\n t[1, 2] = -self._trans[0, 0]\n t[2, 0] = -self._trans[0, 1]\n t[2, 1] = self._trans[0, 0]\n _Erx = self._rot[0].transpose(-2, 1).matmul(t)\n\n mat[:3, :3] = self._rot[0].transpose(-2, 1)\n mat[3:, 0:3] = -_Erx\n mat[3:, 3:] = self._rot[0].transpose(-2, 1)\n return mat\n\n def to_matrix_transpose(self):\n mat = torch.zeros((6, 6))\n t = torch.zeros((3, 3))\n t[0, 1] = -self._trans[0, 2]\n t[0, 2] = self._trans[0, 1]\n t[1, 0] = self._trans[0, 2]\n t[1, 2] = -self._trans[0, 0]\n t[2, 0] = -self._trans[0, 1]\n t[2, 1] = self._trans[0, 0]\n _Erx = self._rot[0].matmul(t)\n\n mat[:3, :3] = self._rot[0].transpose(1, 0)\n mat[3:, 0:3] = -_Erx.transpose(1, 0)\n mat[3:, 3:] = self._rot[0].transpose(1, 0)\n return mat\n\n\nclass SpatialMotionVec(object):\n\n def __init__(self,\n lin_motion: torch.Tensor = torch.zeros((1, 3)),\n ang_motion: torch.Tensor = torch.zeros((1, 3))\n ):\n self.lin = lin_motion\n self.ang = ang_motion\n\n def add_motion_vec(self, smv: SpatialMotionVec) -> SpatialMotionVec:\n r\"\"\"\n Args:\n smv: spatial motion vector\n Returns:\n the sum of motion vectors\n \"\"\"\n\n return SpatialMotionVec(self.lin + smv.lin, self.ang + smv.ang)\n\n def cross_motion_vec(self, smv: SpatialMotionVec) -> SpatialMotionVec:\n r\"\"\"\n Args:\n smv: spatial motion vector\n Returns:\n the cross product between motion vectors\n \"\"\"\n new_ang = cross_product(self.ang, smv.ang)\n new_lin = cross_product(self.ang, smv.lin) + cross_product(self.lin, smv.ang)\n return SpatialMotionVec(new_lin, new_ang)\n\n def cross_force_vec(self, sfv: SpatialForceVec) -> SpatialForceVec:\n r\"\"\"\n Args:\n sfv: spatial force vector\n Returns:\n the cross product between motion (self) and force vector\n \"\"\"\n new_ang = cross_product(self.ang, sfv.ang) + cross_product(self.lin, sfv.lin)\n new_lin = cross_product(self.ang, sfv.lin)\n return SpatialForceVec(new_lin, new_ang)\n\n def transform(self, transform: CoordinateTransform) -> SpatialMotionVec:\n r\"\"\"\n Args:\n transform: a coordinate transform object\n Returns:\n the motion vector (self) transformed by the coordinate transform\n \"\"\"\n new_ang = (transform.rotation() @ self.ang.unsqueeze(2)).squeeze(2)\n new_lin = (transform.trans_cross_rot() @ self.ang.unsqueeze(2)).squeeze(2)\n new_lin += (transform.rotation() @ self.lin.unsqueeze(2)).squeeze(2)\n return SpatialMotionVec(new_lin, new_ang)\n\n def get_vector(self):\n return torch.cat([self.ang, self.lin], dim=1)\n\n def multiply(self, v):\n batch_size = self.lin.shape[0]\n return SpatialForceVec(self.lin*v.view(batch_size, 1), self.ang*v.view(batch_size, 1))\n\n def dot(self, smv):\n batch_size, n_d = self.ang.shape\n tmp1 = torch.bmm(self.ang.view(batch_size, 1, n_d), smv.ang.view(batch_size, n_d, 1)).squeeze()\n tmp2 = torch.bmm(self.lin.view(batch_size, 1, n_d), smv.lin.view(batch_size, n_d, 1)).squeeze()\n return tmp1 + tmp2\n #return self.ang[0].dot(smv.ang[0]) + self.lin[0].dot(smv.lin[0])\n\n\nclass SpatialForceVec(object):\n def __init__(self,\n lin_force: torch.Tensor = torch.zeros((1, 3)),\n ang_force: torch.Tensor = torch.zeros((1, 3))\n ):\n self.lin = lin_force\n self.ang = ang_force\n\n def add_force_vec(self, sfv: SpatialForceVec) -> SpatialForceVec:\n r\"\"\"\n Args:\n sfv: spatial force vector\n Returns:\n the sum of force vectors\n \"\"\"\n return SpatialForceVec(self.lin + sfv.lin, self.ang + sfv.ang)\n\n def transform(self, transform: CoordinateTransform) -> SpatialForceVec:\n r\"\"\"\n Args:\n transform: a coordinate transform object\n Returns:\n the force vector (self) transformed by the coordinate transform\n \"\"\"\n new_lin = (transform.rotation() @ self.lin.unsqueeze(2)).squeeze(2)\n new_ang = (transform.trans_cross_rot() @ self.lin.unsqueeze(2)).squeeze(2)\n new_ang += (transform.rotation() @ self.ang.unsqueeze(2)).squeeze(2)\n return SpatialForceVec(new_lin, new_ang)\n\n def get_vector(self):\n return torch.cat([self.ang, self.lin], dim=1)\n\n def multiply(self, v):\n batch_size = self.lin.shape[0]\n return SpatialForceVec(self.lin*v.view(batch_size, 1), self.ang*v.view(batch_size, 1))\n\n def dot(self, smv):\n #return self.ang[0].dot(smv.ang[0]) + self.lin[0].dot(smv.lin[0])\n batch_size, n_d = self.ang.shape\n tmp1 = torch.bmm(self.ang.view(batch_size, 1, n_d), smv.ang.view(batch_size, n_d, 1)).squeeze()\n tmp2 = torch.bmm(self.lin.view(batch_size, 1, n_d), smv.lin.view(batch_size, n_d, 1)).squeeze()\n return tmp1 + tmp2\n\n\nclass DifferentiableSpatialRigidBodyInertia(torch.nn.Module):\n\n def __init__(self, rigid_body_params):\n super().__init__()\n self.mass = rigid_body_params[\"mass\"]\n self.com = rigid_body_params[\"com\"]\n self.inertia_mat = rigid_body_params[\"inertia_mat\"]\n\n def _get_parameter_values(self):\n return self.mass, self.com, self.inertia_mat\n\n def multiply_motion_vec(self, smv):\n mass, com, inertia_mat = self._get_parameter_values()\n mcom = com * mass\n com_skew_symm_mat = utils.vector3_to_skew_symm_matrix(com)\n inertia = inertia_mat + mass * (\n com_skew_symm_mat @ com_skew_symm_mat.transpose(-2, -1)\n )\n\n batch_size = smv.lin.shape[0]\n\n new_lin_force = mass * smv.lin - utils.cross_product(\n mcom.repeat(batch_size, 1), smv.ang\n )\n new_ang_force = (inertia.repeat(batch_size, 1, 1) @ smv.ang.unsqueeze(2)).squeeze(\n 2\n ) + utils.cross_product(mcom.repeat(batch_size, 1), smv.lin)\n\n return SpatialForceVec(new_lin_force, new_ang_force)\n\n def get_spatial_mat(self):\n mass, com, inertia_mat = self._get_parameter_values()\n mcom = mass * com\n com_skew_symm_mat = utils.vector3_to_skew_symm_matrix(com)\n inertia = inertia_mat + mass * (\n com_skew_symm_mat @ com_skew_symm_mat.transpose(-2, -1)\n )\n mat = torch.zeros((6, 6))\n mat[:3, :3] = inertia\n mat[3, 0] = 0; mat[3, 1] = mcom[0, 2]; mat[3, 2] = -mcom[0, 1]\n mat[4, 0] = -mcom[0, 2]; mat[4, 1] = 0.0; mat[4, 2] = mcom[0, 0]\n mat[5, 0] = mcom[0, 1]; mat[5, 1] = -mcom[0, 0]; mat[5, 2] = 0.0\n\n mat[0, 3] = 0; mat[0, 4] = -mcom[0, 2]; mat[0, 5] = mcom[0, 1]\n mat[1, 3] = mcom[0, 2]; mat[1, 4] = 0.0; mat[1, 5] = -mcom[0, 0]\n mat[2, 3] = -mcom[0, 1]; mat[2, 4] = mcom[0, 0]; mat[2, 5] = 0.0\n\n mat[3, 3] = mass\n mat[4, 4] = mass\n mat[5, 5] = mass\n return mat\n\n\nclass LearnableSpatialRigidBodyInertia(DifferentiableSpatialRigidBodyInertia):\n def __init__(self, learnable_rigid_body_config, rigid_body_params):\n super().__init__(rigid_body_params)\n\n # we overwrite dynamics parameters\n if \"mass\" in learnable_rigid_body_config.learnable_dynamics_params:\n self.mass_fn = hydra.utils.instantiate(\n learnable_rigid_body_config.mass_parametrization\n )\n else:\n self.mass_fn = lambda: self.mass\n\n if \"com\" in learnable_rigid_body_config.learnable_dynamics_params:\n self.com_fn = hydra.utils.instantiate(\n learnable_rigid_body_config.com_parametrization\n )\n else:\n self.com_fn = lambda: self.com\n\n if \"inertia_mat\" in learnable_rigid_body_config.learnable_dynamics_params:\n self.inertia_mat_fn = hydra.utils.instantiate(learnable_rigid_body_config.inertia_parametrization)\n else:\n self.inertia_mat_fn = lambda: self.inertia_mat\n\n def _get_parameter_values(self):\n return self.mass_fn(), self.com_fn(), self.inertia_mat_fn()\n\n\n" ]
[ [ "torch.ones", "torch.empty", "torch.sin", "torch.zeros", "torch.einsum", "torch.cat", "torch.eye", "torch.cos" ] ]
Luger-Lab/Cryo-EM
[ "3eb62434181d6ce438190230758f6ce0e6b20af8" ]
[ "cryolo_relion_wrapper/cryolo_wrapper_library.py" ]
[ "#!/usr/bin/env python\n'''\nOriginal version written by Samuel Bowerman (6/22/2021)\n'''\n\nimport os,sys,glob,datetime,itertools,subprocess,shutil\nimport numpy as np\n\ndef do_denoise(args,logfile):\n starttime = datetime.datetime.now().strftime(\"%Y-%m-%d, %H:%M:%S\")\n logfile.write(\"Beginning 'Denoise' task at \"+starttime+\"\\n\\n\")\n\n mics_star_path = args.in_mics\n #Extract list of .mrc files from input .star file\n mics_star_file = open(mics_star_path,'r')\n star_lines = mics_star_file.readlines()\n mics_star_file.close()\n\n #We will also use the mic_file_list later to build the output .star file\n mic_file_list = []\n star_line_list= []\n denoised_out_star = open(os.path.join(args.o,\"micrographs_denoised.star\"),'w')\n denoised_star_header_complete = False\n\n for line in star_lines:\n first_column = line.split(\" \")[0] #the mrc image should consistently be the first thing in the list, if the line describes a micrograph (either from MotCorr or from CtfFind job\n if \"MotionCorr\" in first_column: #Will always be the first column, if in a correct row\n mic_file_list.append(first_column)\n if not denoised_star_header_complete:\n denoised_out_star.write(\"_rlnDenoisedMicrograph #\"+str(rln_idx+1)+\"\\n\")\n denoised_star_header_complete = True\n #We don't want to include the \"new line\" character (the \"-1\"th index) because we are adding to the line\n #denoised_out_star.write(line[:-1]+\"\\t\")\n star_line_list.append(line[:-1]+\" \")\n else:\n denoised_out_star.write(line)\n if \"_rln\" in line: #Need to keep track of how many _rlnColumns we have\n rln_idx = int(line.split(\" \")[-2].replace(\"#\",\"\")) #The \"-1\" idx is the new line character, so the \"-2\" idx will be \"#[rln_idx]\" string\n\n\n #Randomly pick args.nmic number of files to denoise etc.\n mic_idx = np.arange(len(mic_file_list))\n denoise_idxs = np.random.choice(mic_idx,size=args.nmic,replace=False)\n denoise_list = np.array(mic_file_list)[denoise_idxs]\n denoise_star_lines = np.array(star_line_list)[denoise_idxs]\n for idx in range(args.nmic):\n mic_basename = os.path.basename(denoise_list[idx])\n denoised_mic = os.path.join(args.o,\"denoised/for_picking/\"+mic_basename)\n denoised_out_star.write(denoise_star_lines[idx]+denoised_mic+\"\\n\")\n denoised_out_star.close()\n\n #Create a folder to house the mic list for denoising/manual picking\n for_pick_folder = os.path.join(args.o,\"for_picking\")\n if not os.path.isdir(for_pick_folder):\n logfile.write(datetime.datetime.now().strftime(\"%Y-%m-%d, %H:%M:%S\")+\": creating folder = \"+for_pick_folder+\"\\n\")\n os.mkdir(for_pick_folder)\n #If the folder does exist, get rid of old symlinks\n else:\n for FILE in glob.glob(os.path.join(for_pick_folder,\"*.*\")):\n os.unlink(FILE)\n\n #This folder will hold the post-denoising mics\n after_denoise_folder = os.path.join(args.o,\"denoised\")\n if not os.path.isdir(after_denoise_folder):\n logfile.write(datetime.datetime.now().strftime(\"%Y-%m-%d, %H:%M:%S\")+\": creating folder = \"+after_denoise_folder+\"\\n\")\n os.mkdir(after_denoise_folder)\n\n #put symbolic links to the randomly-selected micrographs in to the \"for_picking\" folder\n for FILE in denoise_list:\n #Call os.path.basename to remove the prefix path (maintained by glob.glob call)\n link_path = os.path.join(for_pick_folder,os.path.basename(FILE))\n logfile.write(datetime.datetime.now().strftime(\"%Y-%m-%d, %H:%M:%S\")+\": creating symbolic link for micrograph: \"+FILE+\" -> \"+link_path)\n os.symlink(os.path.join(os.getcwd(),FILE),link_path)\n\n #Now that the preparation work has been done, start denoising micrographs\n function_call = \"janni_denoise.py denoise -ol 24 -bs 4 -g 0 \"+for_pick_folder+\" \" +after_denoise_folder+\" \"+args.n_model\n logfile.write(datetime.datetime.now().strftime(\"%Y-%m-%d, %H:%M:%S\")+\": Sending function call = \"+function_call+\"\\n\")\n #Need to split the program and inputs in subprocess call (needs to be list, not string)\n function_call_split = function_call.split(\" \")\n subprocess.call(function_call_split)\n\n #Need to make pipeline .star file information\n out_nodes_star = open(os.path.join(args.o,\"RELION_OUTPUT_NODES.star\"),'w')\n out_nodes_star.write(\"data_output_nodes\\n\")\n out_nodes_star.write(\"loop_\\n\")\n out_nodes_star.write(\"_rlnPipeLineNodeName #1\\n\")\n out_nodes_star.write(\"_rlnPipeLineNodeType #2\\n\")\n out_nodes_star.write(os.path.join(args.o,\"micrographs_denoised.star\")+\"\\t1\\n\")\n out_nodes_star.close()\n\ndef do_manual_pick(args,logfile):\n starttime = datetime.datetime.now().strftime(\"%Y-%m-%d, %H:%M:%S\")\n logfile.write(\"Beginning 'Manual Pick' task at \"+starttime+\"\\n\\n\")\n\n logfile.write(\"Opening input micrographs star file: \"+args.in_mics+\"\\n\")\n denoised_star = open(args.in_mics,'r')\n denoised_star_lines = denoised_star.readlines()\n denoised_star.close()\n\n #Generate a folder within the job to link the mics for picking\n denoise_mic_folder = os.path.join(args.o,\"denoised_folder\")\n raw_mic_folder= os.path.join(args.o,\"raw_image_folder\")\n manual_pick_folder = os.path.join(args.o,\"boxes\")\n\n #If folders don't exist, then make them\n logfile.write(\"Generating folders for symbolic links and particle picks: %s; %s; %s\\n\" % (denoise_mic_folder, raw_mic_folder, manual_pick_folder))\n if not os.path.isdir(denoise_mic_folder):\n os.mkdir(denoise_mic_folder)\n if not os.path.isdir(raw_mic_folder):\n os.mkdir(raw_mic_folder)\n if not os.path.isdir(manual_pick_folder):\n os.mkdir(manual_pick_folder)\n\n #look for lines containing micrograph information, denoised images will be final column\n logfile.write(\"Determining raw and denoised micrographs for manual picking from \"+args.in_mics+\"\\n\")\n for LINE in denoised_star_lines:\n LINE = LINE.replace(\"\\n\",\"\").replace(\"\\t\",\"\") #Things got weird around the new-line character, so I just got rid of it\n if \"MotionCorr\" in LINE: #The micrograph lines will just bet the ones with \"MotionCorr\" in the first column\n\n split_line = LINE.split(\" \")\n #The original motion-corrected file will be the first column, the denoised version the last column\n link_path_prefix = os.getcwd()\n\n raw_rel_path = split_line[0]\n raw_basename = os.path.basename(raw_rel_path)\n raw_link_src = os.path.join(link_path_prefix,raw_rel_path)\n raw_link_dest= os.path.join(raw_mic_folder,raw_basename)\n\n currtime= datetime.datetime.now().strftime(\"%Y-%m-%d, %H:%M:%S\")\n if not os.path.exists(raw_link_dest):\n if os.path.exists(raw_link_src):\n logfile.write(currtime+\" = creating symbolic link \"+raw_link_src+\" -> \"+raw_link_dest+\"\\n\")\n os.symlink(raw_link_src,raw_link_dest)\n else:\n logfile.write(currtime+\" = could not find source for symbolic link (\"+raw_link_src+\" -> \"+raw_link_dest+\")\\n\")\n else:\n logfile.write(currtime+\" = Symbolic link already present at destination (\"+raw_link_dest+\")\\n\")\n denoise_rel_path = split_line[-1] #For some reason, \"-1\" isn't the new line character for .star files written through this python wrapper?\n denoise_basename = os.path.basename(denoise_rel_path)\n denoise_link_src = os.path.join(link_path_prefix,denoise_rel_path)\n denoise_link_dest= os.path.join(denoise_mic_folder,denoise_basename)\n \n if not os.path.exists(denoise_link_dest):\n currtime = datetime.datetime.now().strftime(\"%Y-%m-%d, %H:%M:%S\")\n if os.path.exists(denoise_link_src):\n logfile.write(currtime+\" = creating symbolic link \"+denoise_link_src+\" -> \"+denoise_link_dest+\"\\n\")\n os.symlink(denoise_link_src,denoise_link_dest)\n else:\n logfile.write(currtime+\" = could not find source for symbolic link (\"+denoise_link_src+\" -> \"+denoise_link_dest+\")\\n\")\n else:\n logfile.write(currtime+\" = Symbolic link already present at destination (\"+denoise_link_dest+\")\\n\")\n \n function_call = \"cryolo_boxmanager.py -i \"+denoise_mic_folder\n function_call_split = function_call.split(\" \")\n\n logfile.write(datetime.datetime.now().strftime(\"%Y-%m-%d, %H:%M:%S\")+\": sending function call = \"+function_call+\"\\n\")\n subprocess.call(function_call_split)\n\n #Need to code-in some kind of pipeline.star file for information for training\n train_star = open(os.path.join(args.o,\"micrographs_train_metadata.star\"),'w')\n #The first row will define the path to \"train_images\"\n train_star.write(os.path.join(args.o,\"raw_image_folder\")+\"\\n\")\n #The second row will define the path to the \"train_boxes\" folder\n train_star.write(os.path.join(args.o,\"boxes\")+\"\\n\")\n train_star.close()\n\n #Star file for managing relion pipeline flow\n out_nodes_star = open(os.path.join(args.o,\"RELION_OUTPUT_NODES.star\"),'w')\n out_nodes_star.write(\"data_output_nodes\\n\")\n out_nodes_star.write(\"loop_\\n\")\n out_nodes_star.write(\"_rlnPipeLineNodeName #1\\n\")\n out_nodes_star.write(\"_rlnPipeLineNodeType #2\\n\")\n out_nodes_star.write(os.path.join(args.o,\"micrographs_train_metadata.star\")+\" 1\\n\")\n out_nodes_star.close()\n\n\ndef do_train(args,logfile):\n starttime = get_time()\n logfile.write(\"Beginning 'Training' task at \"+starttime+\"\\n\\n\")\n \n train_paths_star = open(args.in_mics,'r')\n train_folders = train_paths_star.readlines()\n train_images = train_folders[0].replace(\"\\n\",\"\")\n train_boxes = train_folders[1].replace(\"\\n\",\"\")\n config_path = train_folders[2].replace(\"\\n\",\"\")\n model_name = train_folders[3].replace(\"\\n\",\"\")\n\n function_call = \"cryolo_gui.py train -c \"+config_path+\" -nc \"+args.j+\" -w 5\"\n this_time = get_time()\n logfile.write(this_time+\" = sending function call: \"+function_call+\"\\n\")\n function_call_split = function_call.split(\" \")\n subprocess.call(function_call_split)\n\n #Copy the output picking model to the folder, to prevent potential over-writing by future trainings\n shutil.copyfile(model_name,os.path.join(args.o,model_name))\n \n #Pipeline STAR\n out_nodes_star = open(os.path.join(args.o,\"RELION_OUTPUT_NODES.star\"),'w')\n out_nodes_star.write(\"data_output_nodes\\n\")\n out_nodes_star.write(\"loop_\\n\")\n out_nodes_star.write(\"_rlnPipeLineNodeName #1\\n\")\n out_nodes_star.write(\"_rlnPipeLineNodeType #2\\n\")\n out_nodes_star.write(os.path.join(args.o,\"particles_model.star\")+\" 3\\n\")\n out_nodes_star.close()\n\n #STAR file containing meta-data for picking\n trained_star = open(os.path.join(args.o,\"particles_model.star\"),'w')\n trained_star.write(os.path.join(args.o,model_name)+\"\\n\")\n trained_star.write(config_path+\"\\n\")\n trained_star.close()\n\n\ndef do_predict(args,logfile):\n starttime = get_time()\n logfile.write(\"Beginning 'Predict' task at \"+starttime+\"\\n\\n\")\n\n mic_ctf_star = open(args.in_mics, 'r')\n cryolo_star = open(args.in_parts,'r')\n cryolo_lines = cryolo_star.readlines()\n model_path = cryolo_lines[0].replace(\"\\n\",\"\")\n config_path = cryolo_lines[1].replace(\"\\n\",\"\")\n\n this_time = get_time()\n logfile.write(this_time+\" = Using model \"+model_path+\" to pick particles on micrographs in \"+args.in_mics+\"\\n\")\n\n out_box_folder = os.path.join(args.o,\"particles\")\n \n #Find the micrograph folder from CTF path\n mic_ctf_star_lines = mic_ctf_star.readlines()\n #In case there are multiple runs joined together, we are going to look for unique CtfFind/micrographs folders, instead of just using the first we find\n ctf_mic_path_list = []\n CTFcol = 2 #Assume .star file follows default order but still explicitly identify below, just in case\n for LINE in mic_ctf_star_lines:\n if \"_rlnCtfImage\" in LINE:\n #Have to fix weird spacing issue\n LINE = LINE.replace(\" \\n\",\"\")\n CTFcol = int(LINE.split(\" \")[-1].replace(\"#\",\"\")) - 1 #Relion is 1-indexed, python is 0-indexed\n if \"MotionCorr\" in LINE:\n while \" \" in LINE: #since we are splitting by \" \", we need to make sure there aren't any multi-\" \" left\n LINE = LINE.replace(\" \",\" \")\n split_line = LINE.split(\" \")\n CTF_full_path = split_line[CTFcol].replace(\":mrc\",\"\") #Remove the weird nomenclature from .star file\n CTF_mic_folder= os.path.split(CTF_full_path)[0]\n ctf_mic_path_list.append(CTF_mic_folder)\n\n #Pull only the unique CTF/micrographs folders\n unique_paths = np.unique(np.array(ctf_mic_path_list))\n this_time = get_time()\n logfile.write(this_time+\" = Identified the following micrograph path(s): \"+str(unique_paths)+\"\\n\")\n \n #We need to make symbolic links to a unified folder\n mic_folder = os.path.join(args.o,\"micrographs\")\n if not os.path.exists(mic_folder):\n os.mkdir(mic_folder)\n for mic_path in unique_paths:\n full_path = os.path.join(os.getcwd(),mic_path)\n mic_list = glob.glob(os.path.join(full_path,\"*.mrc\"))\n for MIC in mic_list:\n link_path = os.path.join(mic_folder,os.path.basename(MIC))\n if os.path.exists(link_path):\n os.unlink(link_path)\n os.symlink(MIC,link_path)\n\n #Make a folder for storing particle picks\n out_box_folder = os.path.join(args.o,\"boxes\")\n if not os.path.exists(out_box_folder):\n os.mkdir(out_box_folder)\n\n function_call = \"cryolo_gui.py predict -c \"+config_path+\" -w \"+model_path+\" -i \"+mic_folder+\" -o \"+out_box_folder+\" -t \"+str(args.threshold)+\" -d \"+str(args.distance)+\" -nc \"+args.j\n this_time = get_time()\n logfile.write(this_time+\" = sending function call: \"+function_call+\"\\n\")\n function_call_split = function_call.split(\" \")\n subprocess.call(function_call_split)\n\n\n #Pipeline STAR\n out_nodes_star = open(os.path.join(args.o,\"RELION_OUTPUT_NODES.star\"),'w')\n out_nodes_star.write(\"data_output_nodes\\n\")\n out_nodes_star.write(\"loop_\\n\")\n out_nodes_star.write(\"_rlnPipeLineNodeName #1\\n\")\n out_nodes_star.write(\"_rlnPipeLineNodeType #2\\n\")\n out_nodes_star.write(os.path.join(args.o,\"coords_suffix_cryolo.star\")+\" 2\\n\")\n out_nodes_star.close()\n \n #Relion requires you to define coordinate suffixes for filenames (in this case \"cryolo\")\n suffix_star = open(os.path.join(args.o,\"coords_suffix_cryolo.star\"),'w')\n suffix_star.write(args.in_mics+\"\\n\")\n suffix_star.close()\n \n #Take the .star files from cryolo and put them in relion-type arrangement\n star_list = glob.glob(os.path.join(args.o,\"boxes/STAR/*.star\"))\n for STAR in star_list:\n full_star_path = os.path.join(os.getcwd(),STAR)\n link_path = os.path.join(args.o,\"micrographs/\"+os.path.basename(STAR)).replace(\".star\",\"_cryolo.star\")\n link_path.replace(\".star\",\"_cryolo.star\") # have to do the swap defined by suffix above\n if os.path.exists(link_path):\n os.unlink(link_path)\n os.symlink(full_star_path,link_path)\n\n \ndef do_config_setup(args,logfile):\n starttime = get_time()\n logfile.write(\"Beginning 'Config Setup' task at \"+starttime+\"\\n\\n\")\n \n this_time = get_time()\n logfile.write(this_time+\" = Getting training micrographs and boxes from \"+args.in_mics+\"\\n\")\n train_paths_star = open(args.in_mics,'r')\n train_folders = train_paths_star.readlines()\n train_images = train_folders[0].replace(\"\\n\",\"\")\n train_boxes = train_folders[1].replace(\"\\n\",\"\")\n this_time = get_time()\n logfile.write(this_time+\" = Train images (\"+train_images+\") and training boxes (\"+train_boxes+\") folders identified.\\n\")\n\n this_time = get_time()\n logfile.write(this_time+\" = Getting box size from training boxes .box files\\n\")\n train_box_files = glob.glob(os.path.join(train_boxes,\"*.box\"))\n x_coord,y_coord,xbox,ybox = np.genfromtxt(train_box_files[0],dtype=int,unpack=True)\n boxsize = np.copy(np.unique(xbox)[0])\n config_path = os.path.join(args.o,\"config_cryolo.json\")\n \n function_call = \"cryolo_gui.py config --train_image_folder \"+train_images+\" --train_annot_folder \"+train_boxes+\" --saved_weights_name \"+args.p_model+\" --filter JANNI --janni_model \"+args.n_model+\" --log_path \"+os.path.join(args.o,\"cryolo_log.log \"+config_path+\" \"+str(boxsize))\n this_time = get_time()\n logfile.write(this_time+\" = Sending function call: \"+function_call+\"\\n\")\n function_call_split = function_call.split(\" \")\n subprocess.call(function_call_split)\n\n #Copy the manually-picked training details to this job, which will then feed to the actual train job\n box_src = os.path.join(os.getcwd(),train_boxes)\n box_dest= os.path.join(args.o,\"train_boxes\")\n if os.path.exists(box_dest):\n os.unlink(box_dest)\n os.symlink(box_src,box_dest)\n mic_src = os.path.join(os.getcwd(),train_images)\n mic_dest= os.path.join(args.o,\"train_images\")\n if os.path.exists(mic_dest):\n os.unlink(mic_dest)\n os.symlink(mic_src,mic_dest)\n\n #Put the metadata in a dummy star file, like before\n config_star_path = os.path.join(args.o,\"micrographs_config.star\")\n config_star = open(config_star_path,'w')\n config_star.write(os.path.join(args.o,\"train_images\")+\"\\n\")\n config_star.write(os.path.join(args.o,\"train_boxes\")+\"\\n\")\n config_star.write(config_path+\"\\n\")\n config_star.write(args.p_model+\"\\n\")\n config_star.close()\n\n #Set up the relion pipeline info\n out_nodes_star = open(os.path.join(args.o,\"RELION_OUTPUT_NODES.star\"),'w')\n out_nodes_star.write(\"data_output_nodes\\n\")\n out_nodes_star.write(\"loop_\\n\")\n out_nodes_star.write(\"_rlnPipeLineNodeName #1\\n\")\n out_nodes_star.write(\"_rlnPipeLineNodeType #2\\n\")\n out_nodes_star.write(os.path.join(args.o,\"micrographs_config.star\")+\" 1\\n\")\n out_nodes_star.close()\n\n #Symlink the config_cryolo.json file to the main project directory, so that the auto-pipeline can see that it doesn't need to repeat this step again\n config_basename = os.path.basename(config_path)\n if os.path.exists(config_basename):\n os.unlink(config_basename)\n os.symlink(os.path.join(os.getcwd(),config_path),config_basename)\n\ndef get_time():\n this_time = datetime.datetime.now().strftime(\"%Y-%m-%d, %H:%M:%S\")\n return this_time\n\n" ]
[ [ "numpy.array", "numpy.unique", "numpy.genfromtxt", "numpy.random.choice" ] ]
SooluThomas/qiskit-finance
[ "3e25551b55cdfebfeba1b3889a1cb930b83e57e3" ]
[ "test/circuit/test_european_call_pricing_objective.py" ]
[ "# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2020, 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\" Test EuropeanCallPricingObjective\"\"\"\n\nimport unittest\nfrom test import QiskitFinanceTestCase\n\nimport numpy as np\n\nfrom qiskit.utils import algorithm_globals, QuantumInstance\nfrom qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem\nfrom qiskit.circuit.library import LinearAmplitudeFunction, TwoLocal\nfrom qiskit.quantum_info import Operator\nfrom qiskit_finance.circuit.library import EuropeanCallPricingObjective, NormalDistribution\n\n\nclass TestEuropeanCallExpectedValue(QiskitFinanceTestCase):\n \"\"\"Tests EuropeanCallPricingObjective.\"\"\"\n\n def setUp(self):\n super().setUp()\n self.seed = 457\n algorithm_globals.random_seed = self.seed\n\n def test_ecev_circuit(self):\n \"\"\"Test the expected circuit.\n\n If it equals the correct ``LinearAmplitudeFunction`` we know the circuit is correct.\n \"\"\"\n num_qubits = 3\n rescaling_factor = 0.1\n strike_price = 0.5\n bounds = (0, 2)\n ecev = EuropeanCallPricingObjective(num_qubits, strike_price, rescaling_factor, bounds)\n\n breakpoints = [0, strike_price]\n slopes = [0, 1]\n offsets = [0, 0]\n image = (0, 2 - strike_price)\n domain = (0, 2)\n linear_function = LinearAmplitudeFunction(\n num_qubits,\n slopes,\n offsets,\n domain=domain,\n image=image,\n breakpoints=breakpoints,\n rescaling_factor=rescaling_factor,\n )\n\n self.assertTrue(Operator(ecev).equiv(linear_function))\n\n def test_application(self):\n \"\"\"Test an end-to-end application.\"\"\"\n try:\n from qiskit import (\n Aer,\n ) # pylint: disable=unused-import,import-outside-toplevel\n except ImportError as ex: # pylint: disable=broad-except\n self.skipTest(\"Aer doesn't appear to be installed. Error: '{}'\".format(str(ex)))\n return\n\n bounds = np.array([0.0, 7.0])\n num_qubits = 3\n\n # the distribution circuit is a normal distribution plus a QGAN-trained ansatz circuit\n dist = NormalDistribution(num_qubits, mu=1, sigma=1, bounds=bounds)\n\n ansatz = TwoLocal(num_qubits, \"ry\", \"cz\", reps=1, entanglement=\"circular\")\n trained_params = [\n 0.29399714,\n 0.38853322,\n 0.9557694,\n 0.07245791,\n 6.02626428,\n 0.13537225,\n ]\n ansatz.assign_parameters(trained_params, inplace=True)\n\n dist.compose(ansatz, inplace=True)\n\n # create the European call expected value\n strike_price = 2\n rescaling_factor = 0.25\n european_call = EuropeanCallPricingObjective(\n num_state_qubits=num_qubits,\n strike_price=strike_price,\n rescaling_factor=rescaling_factor,\n bounds=bounds,\n )\n\n # create the state preparation circuit\n state_preparation = european_call.compose(dist, front=True)\n\n problem = EstimationProblem(\n state_preparation=state_preparation,\n objective_qubits=[num_qubits],\n post_processing=european_call.post_processing,\n )\n\n q_i = QuantumInstance(\n Aer.get_backend(\"aer_simulator\"), seed_simulator=125, seed_transpiler=80\n )\n iae = IterativeAmplitudeEstimation(epsilon_target=0.01, alpha=0.05, quantum_instance=q_i)\n result = iae.estimate(problem)\n self.assertAlmostEqual(result.estimation_processed, 1.0127253837345427)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.array" ] ]
olihawkins/penguin-models
[ "fabecdf6336390fc50e67cfd8494ade69fc3ef7f" ]
[ "plots.py" ]
[ "# -*- coding: utf-8 -*-\n\n\"\"\"A module for plotting penguins data for modelling with scikit-learn.\"\"\"\n\n# Imports ---------------------------------------------------------------------\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n# Constants -------------------------------------------------------------------\n\nSPECIES_COLORS = {\n 'Adelie': '#4daf4a', \n 'Gentoo': '#ffb000', \n 'Chinstrap': '#0084f7'\n}\n\nX_AXIS = [30, 60]\nY_AXIS = [12, 22]\n\n# Set style -------------------------------------------------------------------\n\n# Load the style from a file\nplt.style.use('./style/eda.mplstyle')\n\n# Alternatively, load the style from the library in ~/.matplotlib/stylelib\n# plt.style.use(['eda'])\n\n# Functions -------------------------------------------------------------------\n\ndef get_contour_data(model, pipeline, n_points=1000):\n\n \"\"\"Create the data used to show the boundary of the decision function.\"\"\"\n \n x0s = np.linspace(X_AXIS[0], X_AXIS[1], n_points)\n x1s = np.linspace(Y_AXIS[0], Y_AXIS[1], n_points)\n x0, x1 = np.meshgrid(x0s, x1s)\n X = np.c_[x0.ravel(), x1.ravel()]\n df_X = pd.DataFrame(X, columns=['bill_length_mm', 'bill_depth_mm'])\n X = pipeline.transform(df_X)\n y_pred = model.predict(X).reshape(x0.shape)\n y_decision = model.decision_function(X).reshape(x0.shape)\n return x0, x1, y_pred, y_decision\n\n\ndef get_target_colors(target):\n\n \"\"\"Create a dictionary of colors to use in binary classification plots.\"\"\"\n \n return {\n target : '#984ea3',\n 'Other': '#ff7f00'\n }\n\n# Plots -----------------------------------------------------------------------\n\ndef plot_example():\n\n plt.style.reload_library()\n plt.style.use(['eda'])\n fig, ax = plt.subplots()\n ax.set_title('Some random words of the title')\n ax.scatter(np.random.normal(0,1,10), np.random.normal(0,1,10))\n fig.savefig('plots/test.svg', format='svg')\n fig.savefig('plots/test.png', format='png')\n plt.close()\n\n\ndef plot_target_by_features(df):\n\n \"\"\"Plot the different target species.\"\"\"\n\n fig, ax = plt.subplots()\n\n ax.set_title(\n label='Palmer penguins by species and bill characteristics', \n loc='center')\n\n ax.get_xaxis().set_major_formatter(\n mpl.ticker.FormatStrFormatter('%.0f'))\n ax.set_xlim(X_AXIS[0], X_AXIS[1])\n ax.set_xlabel('Bill length (mm)')\n\n ax.get_yaxis().set_major_formatter(\n mpl.ticker.FormatStrFormatter('%.0f'))\n ax.set_ylim(Y_AXIS[0], Y_AXIS[1])\n ax.set_ylabel('Bill depth (mm)')\n \n grouped = df.groupby('species')\n for key, group in grouped:\n ax.scatter(\n group['bill_length_mm'], \n group['bill_depth_mm'], \n c=SPECIES_COLORS[key],\n s=40,\n label=key,\n alpha=0.55)\n \n ax.legend(loc='lower left', handletextpad=0.2)\n fig.savefig('plots/target-by-features.png', format='png')\n plt.close()\n\n\ndef plot_model(df, model, pipeline, f_score, target, title, filename):\n\n \"\"\"Plot the results of a binary classification model.\"\"\"\n\n fig, ax = plt.subplots()\n\n ax.set_title(title, loc='center')\n\n ax.get_xaxis().set_major_formatter(\n mpl.ticker.FormatStrFormatter('%.0f'))\n ax.set_xlim(X_AXIS[0], X_AXIS[1])\n ax.set_xlabel('Bill length (mm)')\n\n ax.get_yaxis().set_major_formatter(\n mpl.ticker.FormatStrFormatter('%.0f'))\n ax.set_ylim(Y_AXIS[0], Y_AXIS[1])\n ax.set_ylabel('Bill depth (mm)')\n\n # Plot the boundary of the decision function\n x0, x1, y_pred, y_decision = get_contour_data(model, pipeline)\n ax.contourf(x0, x1, y_pred, cmap=plt.cm.PuOr, alpha=0.2)\n\n # This plots the decision score, if needed\n # ax.contourf(x0, x1, y_decision, cmap=plt.cm.PuOr, alpha=0.1)\n\n df = df.copy()\n df['species'] = df['target'].apply(lambda t: target if t == 1 else 'Other')\n\n colors = get_target_colors(target)\n\n grouped = df.groupby('species')\n for key, group in grouped:\n ax.scatter(\n group['bill_length_mm'], \n group['bill_depth_mm'], \n c=colors[key],\n s=40,\n label=key, \n alpha=0.55)\n \n ax.legend(loc='lower left', handletextpad=0.2)\n\n bbox_style = {\n 'boxstyle': 'round', \n 'facecolor': '#ffffff', \n 'edgecolor': '#d4d4d4', \n 'alpha': 0.8\n }\n\n ax.text(53, 12.415, '$F_1$ score: {0}'.format(f_score), bbox=bbox_style)\n \n fig.savefig('plots/{0}.png'.format(filename), format='png')\n plt.close()" ]
[ [ "numpy.linspace", "matplotlib.pyplot.subplots", "pandas.DataFrame", "numpy.random.normal", "matplotlib.pyplot.close", "matplotlib.ticker.FormatStrFormatter", "numpy.meshgrid", "matplotlib.pyplot.style.use", "matplotlib.pyplot.style.reload_library" ] ]
CurryEleison/lambda-metrics
[ "0954273a1aec0f8c8ea867383e33a9acc9c785cf" ]
[ "lambda/s3trigger.py" ]
[ "import boto3\nimport numpy as np\nimport logging\nimport pandas as pd\nimport datetime\nfrom AwsElbLogUtil import LogDataFrame\nfrom CloudWatchUtil import CustomMetricSender\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n\n\ndef send_random(event, context):\n data = np.random.randn(5)\n logging.info(data)\n\n\ndef send_metrics_tpltest(event, context):\n objlist = []\n \n client = boto3.resource('s3')\n for record in event['Records']:\n objlist.append(\n client.ObjectSummary(\n record['s3']['bucket']['name'], \n record['s3']['object']['key']\n )\n )\n # bucket = record['s3']['bucket']['name']\n # keds.append(record['s3']['object']['key'])\n #download_path = '/tmp/{}{}'.format(uuid.uuid4(), key)\n #s3_client.download_file(bucket, key, download_path)\n dfmaker = LogDataFrame(client)\n for s3objsummary in objlist:\n logging.info(s3objsummary.key)\n df = dfmaker.make_dataframe(objlist, lambda l: hasattr(l, 'path') and l.path.startswith('/tpltest'))\n # urltimetaken = df[['path', 'servertime']].groupby('path').sum().sort_values('servertime', ascending=False) #.agg({'servertime', 'sum'})\n # print urltimetaken.head(10)\n df['roundedtime'] = df['utctime'].apply(lambda dt: datetime.datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute)) \n df = df.assign(mintime = df.servertime).assign(maxtime = df.servertime).assign(sumtime = df.servertime).assign(reccount = df.method) \n summary = df.groupby('roundedtime').agg( \n { \n 'maxtime': 'max', \n 'mintime': 'min', \n 'sumtime': 'sum', \n 'reccount': 'count' \n } \n ) \n sender = CustomMetricSender('ExperimentalCustom', 'TpltestTimings')\n for index, item in summary.iterrows():\n logging.info(\"At {4} Min: {0}, Max: {1}, Sum: {2}, Count: {3}\".format(item['mintime'], item['maxtime'], item['sumtime'], item['reccount'], index))\n resp = sender.senddataaggregate(datatime = index, datalength = item['reccount'],\n datasum = item['sumtime'], datamin = item['mintime'], datamax = item['maxtime'])\n logging.info(resp)\n\n" ]
[ [ "numpy.random.randn" ] ]
skully-coder/COVID-19_TLSTM
[ "7ae6b3e1d8edbcb593b1c5f70001e075b7d29c0f" ]
[ "baselines/DT.py" ]
[ "from math import log\nimport operator\nimport pickle\nimport numpy as np\n\n\ndef load_pkl(path):\n with open(path, 'rb') as f:\n obj = pickle.load(f)\n return obj\n\n\ndef calcShannonEnt(dataSet):\n numEntries = len(dataSet)\n labelCounts = {}\n for featVec in dataSet:\n currentLabel = featVec[-1]\n print(currentLabel)\n if currentLabel not in labelCounts.keys():\n labelCounts[currentLabel] = 0\n labelCounts[currentLabel] += 1\n shannonEnt = 0\n for key in labelCounts:\n prob = float(labelCounts[key])/numEntries\n shannonEnt -= prob*log(prob, 2)\n return shannonEnt\n\n\ndef splitDataSet(dataSet, axis, value):\n retDataSet = []\n for featVec in dataSet:\n if featVec[axis] == value:\n reducedFeatVec = featVec[:axis]\n reducedFeatVec.extend(featVec[axis+1:])\n retDataSet.append(reducedFeatVec)\n return retDataSet\n\n\ndef chooseBestFeatureToSplit(dataSet):\n numFeatures = len(dataSet[0])-1\n baseEntropy = calcShannonEnt(dataSet)\n bestInfoGain = 0\n bestFeature = -1\n for i in range(numFeatures):\n featList = [example[i] for example in dataSet]\n uniqueVals = set(featList)\n newEntropy = 0\n for value in uniqueVals:\n subDataSet = splitDataSet(dataSet, i, value)\n prob = len(subDataSet)/float(len(dataSet))\n newEntropy += prob*calcShannonEnt(subDataSet)\n infoGain = baseEntropy - newEntropy\n if (infoGain > bestInfoGain):\n bestInfoGain = infoGain\n bestFeature = i\n return bestFeature\n\n\ndef majorityCnt(classList):\n classCount = {}\n for vote in classList:\n if vote not in classCount.keys():\n classCount[vote] = 0\n classCount[vote] += 1\n sortedClassCount = sorted(\n classCount.items(), key=operator.itemgetter(1), reverse=True)\n return sortedClassCount[0][0]\n\n\ndef createTree(dataSet, labels):\n classList = [example[-1] for example in dataSet]\n if classList.count(classList[0]) == len(classList):\n return classList[0]\n if len(dataSet[0]) == 1:\n return majorityCnt(classList)\n bestFeat = chooseBestFeatureToSplit(dataSet)\n bestFeatLabel = labels[bestFeat]\n myTree = {bestFeatLabel: {}}\n del(labels[bestFeat])\n featValues = [example[bestFeat] for example in dataSet]\n uniqueVals = set(featValues)\n for value in uniqueVals:\n subLabels = labels[:]\n myTree[bestFeatLabel][value] = createTree(splitDataSet\n (dataSet, bestFeat, value), subLabels)\n return myTree\n\n\nif __name__ == \"__main__\":\n path = 'BatchData'\n # train data\n path_string = path + '/TrainData.seqs'\n data_train_batches = load_pkl(path_string)\n path_string = path + '/TrainLabel.seqs'\n labels_train_batches = load_pkl(path_string)\n\n number_train_batches = len(data_train_batches)\n\n input_dim = np.array(data_train_batches[0]).shape[2]\n output_dim = np.array(labels_train_batches[0]).shape[1]\n\n print(\"Train data is loaded!\")\n print(data_train_batches)\n path_string = path + '/TestData.seqs'\n data_test_batches = load_pkl(path_string)\n\n path_string = path + '/TestLabel.seqs'\n labels_test_batches = load_pkl(path_string)\n\n number_test_batches = len(data_test_batches)\n\n print(\"Test data is loaded!\")\n\n print(createTree(data_train_batches, labels_train_batches))\n" ]
[ [ "numpy.array" ] ]
theblackfly/protoflow
[ "02a77e59f6afc8d462a738874d06eca810911166" ]
[ "protoflow/utils/data.py" ]
[ "\"\"\"ProtoFlow data utilities.\"\"\"\n\nimport hashlib\nimport os\nimport shutil\nimport tarfile\nimport zipfile\n\nimport requests\nimport six\nfrom six.moves.urllib.error import HTTPError, URLError\nfrom tensorflow.python.keras.utils.io_utils import path_to_string\nfrom tqdm import tqdm\n\n\ndef _extract_archive(file_path, path=\".\", archive_format=\"auto\"):\n \"\"\"Extracts an archive if it matches tar, tar.gz, tar.bz, or zip formats.\n\n Arguments:\n file_path: path to the archive file\n path: path to extract the archive file\n archive_format: Archive format to try for extracting the file.\n Options are \"auto\", \"tar\", \"zip\", and None.\n \"tar\" includes tar, tar.gz, and tar.bz files.\n The default \"auto\" is [\"tar\", \"zip\"].\n None or an empty list will return no matches found.\n\n Returns:\n True if a match was found and an archive extraction was completed,\n False otherwise.\n \"\"\"\n if archive_format is None:\n return False\n if archive_format == \"auto\":\n archive_format = [\"tar\", \"zip\"]\n if isinstance(archive_format, six.string_types):\n archive_format = [archive_format]\n\n file_path = path_to_string(file_path)\n path = path_to_string(path)\n\n for archive_type in archive_format:\n if archive_type == \"tar\":\n open_fn = tarfile.open\n is_match_fn = tarfile.is_tarfile\n if archive_type == \"zip\":\n open_fn = zipfile.ZipFile\n is_match_fn = zipfile.is_zipfile\n\n if is_match_fn(file_path):\n with open_fn(file_path) as archive:\n try:\n archive.extractall(path)\n except (tarfile.TarError, RuntimeError, KeyboardInterrupt):\n if os.path.exists(path):\n if os.path.isfile(path):\n os.remove(path)\n else:\n shutil.rmtree(path)\n raise\n return True\n return False\n\n\ndef _hash_file(fpath, algorithm=\"sha256\", chunk_size=65535):\n \"\"\"Calculates a file sha256 or md5 hash.\n\n Example:\n\n ```python\n _hash_file(\"/path/to/file.zip\")\n \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\"\n ```\n\n Arguments:\n fpath: path to the file being validated\n algorithm: hash algorithm, one of `\"auto\"`, `\"sha256\"`, or `\"md5\"`.\n The default `\"auto\"` detects the hash algorithm in use.\n chunk_size: Bytes to read at a time, important for large files.\n\n Returns:\n The file hash\n \"\"\"\n if (algorithm == \"sha256\") or (algorithm == \"auto\" and len(hash) == 64):\n hasher = hashlib.sha256()\n else:\n hasher = hashlib.md5()\n\n with open(fpath, \"rb\") as fpath_file:\n for chunk in iter(lambda: fpath_file.read(chunk_size), b\"\"):\n hasher.update(chunk)\n\n return hasher.hexdigest()\n\n\ndef _validate_file(fpath, file_hash, algorithm=\"auto\", chunk_size=65535):\n \"\"\"Validates a file against a sha256 or md5 hash.\n\n Arguments:\n fpath: path to the file being validated\n file_hash: The expected hash string of the file.\n The sha256 and md5 hash algorithms are both supported.\n algorithm: Hash algorithm, one of \"auto\", \"sha256\", or \"md5\".\n The default \"auto\" detects the hash algorithm in use.\n chunk_size: Bytes to read at a time, important for large files.\n\n Returns:\n Whether the file is valid\n \"\"\"\n if (algorithm == \"sha256\") or (algorithm == \"auto\"\n and len(file_hash) == 64):\n hasher = \"sha256\"\n else:\n hasher = \"md5\"\n\n if str(_hash_file(fpath, hasher, chunk_size)) == str(file_hash):\n return True\n else:\n return False\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 get_file_from_google(fname,\n file_id,\n untar=False,\n md5_hash=None,\n file_hash=None,\n cache_subdir=\"datasets\",\n hash_algorithm=\"auto\",\n extract=False,\n archive_format=\"auto\",\n cache_dir=None):\n if cache_dir is None:\n cache_dir = os.path.join(os.path.expanduser(\"~\"), \".keras\")\n if md5_hash is not None and file_hash is None:\n file_hash = md5_hash\n hash_algorithm = \"md5\"\n datadir_base = os.path.expanduser(cache_dir)\n if not os.access(datadir_base, os.W_OK):\n datadir_base = os.path.join(\"/tmp\", \".keras\")\n datadir = os.path.join(datadir_base, cache_subdir)\n os.makedirs(datadir, exist_ok=True)\n\n fname = path_to_string(fname)\n\n if untar:\n untar_fpath = os.path.join(datadir, fname)\n fpath = untar_fpath + \".tar.gz\"\n else:\n fpath = os.path.join(datadir, fname)\n\n download = False\n if os.path.exists(fpath):\n # File found; verify integrity if a hash was provided.\n if file_hash is not None:\n if not _validate_file(fpath, file_hash, algorithm=hash_algorithm):\n print(\"A local file was found, but it seems to be \"\n \"incomplete or outdated because the \" + hash_algorithm +\n \" file hash does not match the original value of \" +\n file_hash + \" so we will re-download the data.\")\n download = True\n else:\n download = True\n\n if download:\n print(\"Downloading data from Google Drive...\")\n\n error_msg = \"Failed on https://drive.google.com/file/d/{}: {} -- {}\"\n try:\n try:\n url = \"https://docs.google.com/uc?export=download\"\n session = requests.Session()\n\n response = session.get(url,\n params={\"id\": file_id},\n 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 except HTTPError as e:\n raise Exception(error_msg.format(file_id, e.code, e.msg))\n except URLError as e:\n raise Exception(error_msg.format(file_id, e.errno, e.reason))\n except (Exception, KeyboardInterrupt) as e:\n if os.path.exists(fpath):\n os.remove(fpath)\n raise e\n\n if untar:\n if not os.path.exists(untar_fpath):\n _extract_archive(fpath, datadir, archive_format=\"tar\")\n return untar_fpath\n\n if extract:\n _extract_archive(fpath, datadir, archive_format)\n\n return fpath\n" ]
[ [ "tensorflow.python.keras.utils.io_utils.path_to_string" ] ]
johnharveymath/fetchers-python
[ "1f5fc7b64f43142991ad0d901b0840b3e8ef1382" ]
[ "src/plugins/EU_ZH/fetcher.py" ]
[ "# Copyright (C) 2020 University of Oxford\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport pandas as pd\nimport os\nimport sys\n\n__all__ = ('EU_ZH_Fetcher',)\n\nfrom utils.fetcher.base_epidemiology import BaseEpidemiologyFetcher\n\nlogger = logging.getLogger(__name__)\n\n\"\"\"\n site-location: https://github.com/covid19-eu-zh/covid19-eu-data\n COVID19 data for European countries created and maintained by covid19-eu-zh\n Data originally from\n Austria's Sozial Ministerium https://www.sozialministerium.at/Informationen-zum-Coronavirus/Neuartiges-Coronavirus-(2019-nCov).html\n Czech Ministry of Health https://onemocneni-aktualne.mzcr.cz/covid-19\n Germany's Robert Koch Institute https://www.rki.de/DE/Content/InfAZ/N/Neuartiges_Coronavirus/Fallzahlen.html\n Hungary's Office of the Prime Minister https://koronavirus.gov.hu/\n Ireland's Health Protection Surveillance Centre https://www.hpsc.ie/a-z/respiratory/coronavirus/novelcoronavirus/casesinireland/\n Poland - Government https://www.gov.pl/web/koronawirus/wykaz-zarazen-koronawirusem-sars-cov-2\n Sweden's Public Health Authority https://www.folkhalsomyndigheten.se/smittskydd-beredskap/utbrott/aktuella-utbrott/covid-19/aktuellt-epidemiologiskt-lage/\n Slovenia's Government Communications Office https://www.gov.si/en/topics/coronavirus-disease-covid-19/\n Belgian institute for health: https://epistat.wiv-isp.be/Covid/\n\"\"\"\n\n\nclass EU_ZH_Fetcher(BaseEpidemiologyFetcher):\n LOAD_PLUGIN = True\n SOURCE = 'EU_ZH'\n\n def fetch(self, url):\n return pd.read_csv(url)\n\n # Certain regions have excess characters in some source files\n def clean_string(self, input):\n if isinstance(input, str):\n return input.replace('­', '')\n else:\n return input\n\n def parse_int(self, data):\n if pd.isna(data):\n return None\n\n if isinstance(data, str):\n data = data.replace('*', '')\n\n return int(data)\n\n def country_fetcher(self, region, country, code_3, code_2):\n\n logger.info(\"Processing number of cases in \" + country)\n\n if code_3 == 'NOR':\n logger.warning(\"These GIDs not entirely accurate due to change in Norway's county boundaries, 2020.\")\n if code_3 == 'BEL':\n logger.warning(\"These GIDs has MISSING region due to unknown data resourses, 2020.\")\n url = 'https://github.com/covid19-eu-zh/covid19-eu-data/raw/master/dataset/covid-19-' + code_2 + '.csv'\n df = self.fetch(url)\n\n for index, record in df.iterrows():\n # date Y-m-d or Y-m-dTH:M:S\n date = record['datetime'].split('T')[0]\n adm_area_2 = None\n\n # If no region is reported then all data is national\n if not hasattr(record, region):\n adm_area_1 = None\n gid = [code_3]\n # Ignore two known corrupted lines in the Polish data\n elif str(record[region])[:4] == 'http':\n continue\n elif pd.isna(record[region]) and code_3 == 'POL':\n continue\n # Austria's national data is reported with a blank region\n elif pd.isna(record[region]) and code_3 == 'AUT':\n adm_area_1 = None\n gid = [code_3]\n elif region == 'nuts_2' and code_3 == 'BEL':\n if self.clean_string(record['nuts_1']) == 'MISSING' or pd.isna(record[region]):\n continue\n\n success, adm_area_1, adm_area_2, adm_area_3, gid = self.adm_translator.tr(\n input_adm_area_1=self.clean_string(record['nuts_1']),\n input_adm_area_2=self.clean_string(record[region]),\n return_original_if_failure=True,\n suppress_exception=True\n )\n # If the region appears cleanly, then we can translate to obtain GID\n elif region == 'nuts_1' and code_3 == 'BEL':\n if pd.notna(record['nuts_2']):\n continue\n\n success, adm_area_1, adm_area_2, adm_area_3, gid = self.adm_translator.tr(\n input_adm_area_1=self.clean_string(record[region]),\n return_original_if_failure=True,\n suppress_exception=True\n )\n else:\n success, adm_area_1, adm_area_2, adm_area_3, gid = self.adm_translator.tr(\n input_adm_area_1=self.clean_string(record[region]),\n return_original_if_failure=True,\n suppress_exception=True\n )\n\n upsert_obj = {\n 'source': self.SOURCE,\n 'date': date,\n 'country': country,\n 'countrycode': code_3,\n 'adm_area_1': adm_area_1,\n 'adm_area_2': adm_area_2,\n 'adm_area_3': None,\n 'gid': gid\n }\n\n # add the epidemiological properties to the object if they exist\n if hasattr(record, 'tests'):\n upsert_obj['tested'] = self.parse_int(record['tests'])\n if hasattr(record, 'cases'):\n upsert_obj['confirmed'] = self.parse_int(record['cases'])\n if hasattr(record, 'tests_positive'):\n upsert_obj['confirmed'] = self.parse_int(record['tests_positive'])\n if hasattr(record, 'recovered'):\n upsert_obj['recovered'] = self.parse_int(record['recovered'])\n if hasattr(record, 'deaths'):\n upsert_obj['dead'] = self.parse_int(record['deaths'])\n if hasattr(record, 'hospitalized'):\n upsert_obj['hospitalised'] = self.parse_int(record['hospitalized'])\n if hasattr(record, 'intensive_care'):\n upsert_obj['hospitalised_icu'] = self.parse_int(record['intensive_care'])\n if hasattr(record, 'quarantine'):\n upsert_obj['quarantined'] = self.parse_int(record['quarantine'])\n\n self.upsert_data(**upsert_obj)\n\n # read the list of countries from a csv file in order to fetch each one\n def load_countries_to_fetch(self):\n input_csv_fname = getattr(self.__class__, 'INPUT_CSV', \"input.csv\")\n path = os.path.dirname(sys.modules[self.__class__.__module__].__file__)\n csv_fname = os.path.join(path, input_csv_fname)\n if not os.path.exists(csv_fname):\n return None\n colnames = ['country', 'code_3', 'code_2', 'region']\n input_pd = pd.read_csv(csv_fname)\n input_pd.columns = colnames\n input_pd = input_pd.where((pd.notnull(input_pd)), None)\n return input_pd\n\n def run(self):\n countries = self.load_countries_to_fetch()\n for index, record in countries.iterrows():\n self.country_fetcher(record['region'], record['country'], record['code_3'], record['code_2'])\n" ]
[ [ "pandas.notnull", "pandas.notna", "pandas.isna", "pandas.read_csv" ] ]
SpatialMetabolomics/pyMS
[ "52c4dce2c4c0eba3c6d447565f3296252f882f9e" ]
[ "pyMSpec/test/test_mass_spectrum.py" ]
[ "\"\"\"\nCreated on 27.08.2015\n\n@author: Dominik Fay\n\"\"\"\nimport unittest\n\nimport numpy\nfrom numpy.ma.testutils import assert_array_equal\n\nfrom .. import mass_spectrum\n\n\nclass MassSpectrumTest(unittest.TestCase):\n def test_init(self):\n \"\"\"Check that spectrum is empty on initialization.\"\"\"\n ms = mass_spectrum.MassSpectrum()\n mzs, ints = ms.get_spectrum()\n assert_array_equal([], mzs)\n assert_array_equal([], ints)\n\n def test_copy_if_empty(self):\n \"\"\"Check that get_spectrum creates a new numpy array if the spectrum has not been set.\"\"\"\n ms = mass_spectrum.MassSpectrum()\n mzs1, ints1 = ms.get_spectrum()\n mzs2, ints2 = ms.get_spectrum()\n\n self.assertFalse(mzs1 is mzs2)\n self.assertFalse(ints1 is ints2)\n\n def test_copy_if_list(self):\n \"\"\"Check that get_spectrum creates a new numpy array if the spectrum has been set as list.\"\"\"\n ms = mass_spectrum.MassSpectrum()\n\n mzs_list = [1, 2, 3]\n ints_list = [2, 4, 6]\n ms.add_spectrum(mzs_list, ints_list)\n mzs_array, ints_array = ms.get_spectrum()\n\n self.assertFalse(mzs_list is mzs_array)\n self.assertFalse(ints_list is ints_array)\n\n def test_no_copy_if_array(self):\n \"\"\"Check that get_spectrum does not create a new numpy array if the spectrum has been set as array.\"\"\"\n ms = mass_spectrum.MassSpectrum()\n\n mzs_array1 = numpy.array([1, 2, 3])\n ints_array1 = numpy.array([2, 4, 6])\n ms.add_spectrum(mzs_array1, ints_array1)\n mzs_array2, ints_array2 = ms.get_spectrum()\n\n self.assertTrue(mzs_array1 is mzs_array2)\n self.assertTrue(ints_array1 is ints_array2)\n\n def test_use_centroid_if_given(self):\n \"\"\"Check that get_spectrum returns the centroids if they have been set.\"\"\"\n ms = mass_spectrum.MassSpectrum()\n\n mzs_profile1 = numpy.array([1, 2, 3])\n ints_profile1 = numpy.array([2, 6, 4])\n mzs_centroid1 = numpy.array([2.2])\n ints_centroid1 = numpy.array([12])\n ms.add_spectrum(mzs_profile1, ints_profile1)\n ms.add_centroids(mzs_centroid1, ints_centroid1)\n mzs_profile2, ints_profile2 = ms.get_spectrum(source='profile')\n mzs_centroid2, ints_centroid2 = ms.get_spectrum(source='centroids')\n\n self.assertTrue(mzs_profile1 is mzs_profile2)\n self.assertTrue(ints_profile1 is ints_profile2)\n self.assertTrue(mzs_centroid1 is mzs_centroid2)\n self.assertTrue(ints_centroid1 is ints_centroid2)\n\n def test_IOError_if_unknown_kwarg(self):\n \"\"\"Check that get_spectrum raises an IOError when an unknown value of the kwarg 'source' is passed.\"\"\"\n ms = mass_spectrum.MassSpectrum()\n self.assertRaises(IOError, ms.get_spectrum, source='asdf')\n\n def test_IOError_if_different_arr_sizes(self):\n \"\"\"Check that add_spectrum and add_centroids raise an IOError when the size of the m/z array and the\n intensity array differ.\n \"\"\"\n ms = mass_spectrum.MassSpectrum()\n test_cases = (\n ([], [1]), ([-7.4], []), ([2968.2395, 29305.23, -23698.5, 1, 2 ** 28], range(2)),\n (range(198), range(102958)))\n\n for case in test_cases:\n self.assertRaises(IOError, ms.add_spectrum, *case)\n self.assertRaises(IOError, ms.add_centroids, *case)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.array", "numpy.ma.testutils.assert_array_equal" ] ]
benmontet/K2-noise
[ "a4b682cdf33f85d2dffc4cef115dcedacfccb4b4" ]
[ "diff_movie.py" ]
[ "#Create a movie of the frames\n\nimport numpy as np\nfrom utils_simple import TIME, FLUX, QUALITY\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.cm import get_cmap\n\n#Limit ourselves 10-40 for more detail\nFLUX = FLUX[:, 15:35, 15:35]\n\ntime = TIME - 1860\ndiffs = np.diff(FLUX, axis=0)\n\nbase = \"frames/{:0>3d}.png\"\n\nbin = get_cmap(\"binary\")\ndiv = get_cmap(\"bwr\")\n\ndef update_qual(qual):\n if qual == 0:\n qual_ant.set_text(\"\")\n else:\n qual_ant.set_text(\"{:d}\".format(qual))\n qual_ant.set_color(\"red\")\n\nfig, ax = plt.subplots(ncols=2, figsize=(8, 4))\nimg0 = ax[0].imshow(FLUX[1], cmap=bin, origin=\"upper\", interpolation=\"none\", extent=[15, 35, 35, 15])\nax[0].set_title(\"Frame\")\ncb0 = plt.colorbar(img0, ax=ax[0])\nimg1 = ax[1].imshow(diffs[0], cmap=div, origin=\"upper\", interpolation=\"none\", extent=[15, 35, 35, 15])\nscale = np.max(np.abs(diffs[0]))\nimg1.set_clim(-scale, scale)\nax[1].set_title(\"Difference\")\ncb1 = plt.colorbar(img1, ax=ax[1])\nant = ax[0].annotate(\"{:.4f} [BJD - 2456684]\".format(time[0]), (17,17), size=\"x-small\")\nqual_ant = ax[0].annotate(\"\", (31,17), size=\"x-small\")\nupdate_qual(QUALITY[0])\nfig.canvas.draw_idle()\nfig.savefig(base.format(0))\n\nfor i, (flux, diff, time, qual) in enumerate(zip(FLUX[1:], diffs, time[1:], QUALITY[1:])):\n img0.set_data(flux)\n img0.autoscale()\n ant.set_text(\"{:.4f} [BJD - 2456684]\".format(time))\n\n img1.set_data(diff)\n scale = np.max(np.abs(diff))\n img1.set_clim(-scale, scale)\n update_qual(qual)\n\n fig.canvas.draw_idle()\n fig.savefig(base.format(i+1))" ]
[ [ "numpy.abs", "matplotlib.pyplot.subplots", "matplotlib.pyplot.colorbar", "numpy.diff", "matplotlib.cm.get_cmap" ] ]
shivamvats/autolab_core
[ "cda081d2e07e3fe6cc9f3e8c86eea92330910d20" ]
[ "autolab_core/dual_quaternion.py" ]
[ "\"\"\"\nClass to handle dual quaternions and their interpolations\nImplementation details inspired by Ben Kenwright's \"A Beginners Guide to\nDual-Quaternions\"\nhttp://cs.gmu.edu/~jmlien/teaching/cs451/uploads/Main/dual-quaternion.pdf\nAuthor: Jacky Liang\n\"\"\"\nfrom numbers import Number\nimport numpy as np\n\nfrom .transformations import quaternion_multiply, quaternion_conjugate\n\n\nclass DualQuaternion(object):\n \"\"\"Class for handling dual quaternions and their interpolations.\n\n Attributes\n ----------\n qr : :obj:`numpy.ndarray` of float\n A 4-entry quaternion in wxyz format.\n\n qd : :obj:`numpy.ndarray` of float\n A 4-entry quaternion in wxyz format.\n\n conjugate : :obj:`DualQuaternion`\n The conjugate of this DualQuaternion.\n\n norm : :obj:`tuple` of :obj:`numpy.ndarray`\n The normalized vectors for qr and qd, respectively.\n\n normalized : :obj:`DualQuaternion`\n This quaternion with qr normalized.\n \"\"\"\n\n def __init__(\n self, qr=[1, 0, 0, 0], qd=[0, 0, 0, 0], enforce_unit_norm=True\n ):\n \"\"\"Initialize a dual quaternion.\n\n Parameters\n ----------\n qr : :obj:`numpy.ndarray` of float\n A 4-entry quaternion in wxyz format.\n\n qd : :obj:`numpy.ndarray` of float\n A 4-entry quaternion in wxyz format.\n\n enforce_unit_norm : bool\n If true, raises a ValueError when the quaternion is not normalized.\n\n Raises\n ------\n ValueError\n If enforce_unit_norm is True and the norm of qr is not 1.\n \"\"\"\n self.qr = qr\n self.qd = qd\n\n if enforce_unit_norm:\n norm = self.norm\n if not np.allclose(norm[0], [1]):\n raise ValueError(\n \"Dual quaternion does not have norm 1! Got {0}\".format(\n norm[0]\n )\n )\n\n @property\n def qr(self):\n \"\"\":obj:`numpy.ndarray` of float: A 4-entry quaternion in\n wxyz format.\"\"\"\n qr_wxyz = np.roll(self._qr, 1)\n return qr_wxyz\n\n @qr.setter\n def qr(self, qr_wxyz):\n qr_wxyz = np.array([n for n in qr_wxyz])\n qr_xyzw = np.roll(qr_wxyz, -1)\n self._qr = qr_xyzw\n\n @property\n def qd(self):\n \"\"\":obj:`numpy.ndarray` of float: A 4-entry quaternion in\n wxyz format.\"\"\"\n qd_wxyz = np.roll(self._qd, 1)\n return qd_wxyz\n\n @qd.setter\n def qd(self, qd_wxyz):\n qd_wxyz = np.array([n for n in qd_wxyz])\n if qd_wxyz[0] != 0:\n raise ValueError(\n \"Invalid dual quaternion! First value of Qd must be 0. \"\n f\"Got {qd_wxyz[0]}\"\n )\n qd_xyzw = np.roll(qd_wxyz, -1)\n self._qd = qd_xyzw\n\n @property\n def conjugate(self):\n \"\"\":obj:`DualQuaternion`: The conjugate of this quaternion.\"\"\"\n qr_c_xyzw = quaternion_conjugate(self._qr)\n qd_c_xyzw = quaternion_conjugate(self._qd)\n\n qr_c_wxyz = np.roll(qr_c_xyzw, 1)\n qd_c_wxyz = np.roll(qd_c_xyzw, 1)\n return DualQuaternion(qr_c_wxyz, qd_c_wxyz)\n\n @property\n def norm(self):\n \"\"\":obj:`tuple` of :obj:`numpy.ndarray`: The normalized vectors for qr\n and qd, respectively.\"\"\"\n qr_c = quaternion_conjugate(self._qr)\n qd_c = quaternion_conjugate(self._qd)\n\n qr_norm = np.linalg.norm(quaternion_multiply(self._qr, qr_c))\n qd_norm = np.linalg.norm(\n quaternion_multiply(self._qr, qd_c)\n + quaternion_multiply(self._qd, qr_c)\n )\n\n return (qr_norm, qd_norm)\n\n @property\n def normalized(self):\n \"\"\":obj:`DualQuaternion`: This quaternion with qr normalized.\"\"\"\n qr = self.qr / 1.0 / np.linalg.norm(self.qr)\n return DualQuaternion(qr, self.qd, True)\n\n def copy(self):\n \"\"\"Return a copy of this quaternion.\n\n Returns\n -------\n :obj:`DualQuaternion`\n The copied DualQuaternion.\n \"\"\"\n return DualQuaternion(self.qr.copy(), self.qd.copy())\n\n @staticmethod\n def interpolate(dq0, dq1, t):\n \"\"\"Return the interpolation of two DualQuaternions.\n\n This uses the Dual Quaternion Linear Blending Method as described by\n Matthew Smith's 'Applications of Dual Quaternions in Three Dimensional\n Transformation and Interpolation'\n https://www.cosc.canterbury.ac.nz/research/reports/HonsReps/2013/hons_1305.pdf\n\n Parameters\n ----------\n dq0 : :obj:`DualQuaternion`\n The first DualQuaternion.\n\n dq1 : :obj:`DualQuaternion`\n The second DualQuaternion.\n\n t : float\n The interpolation step in [0,1]. When t=0, this returns dq0, and\n when t=1, this returns dq1.\n\n Returns\n -------\n :obj:`DualQuaternion`\n The interpolated DualQuaternion.\n\n Raises\n ------\n ValueError\n If t isn't in [0,1].\n \"\"\"\n if not 0 <= t <= 1:\n raise ValueError(\n \"Interpolation step must be between 0 and 1! Got {0}\".format(t)\n )\n\n dqt = dq0 * (1 - t) + dq1 * t\n return dqt.normalized\n\n def __mul__(self, val):\n \"\"\"Multiplies the dual quaternion by another dual quaternion or a\n scalar.\n\n Parameters\n ----------\n val : :obj:`DualQuaternion` or number\n The value by which to multiply this dual quaternion.\n\n Returns\n -------\n :obj:`DualQuaternion`\n A new DualQuaternion that results from the multiplication.\n\n Raises\n ------\n ValueError\n If val is not a DualQuaternion or Number.\n \"\"\"\n if isinstance(val, DualQuaternion):\n new_qr_xyzw = quaternion_multiply(self._qr, val._qr)\n new_qd_xyzw = quaternion_multiply(\n self._qr, val._qd\n ) + quaternion_multiply(self._qd, val._qr)\n\n new_qr_wxyz = np.roll(new_qr_xyzw, 1)\n new_qd_wxyz = np.roll(new_qd_xyzw, 1)\n\n return DualQuaternion(new_qr_wxyz, new_qd_wxyz)\n elif isinstance(val, Number):\n new_qr_wxyz = val * self.qr\n new_qd_wxyz = val * self.qd\n\n return DualQuaternion(new_qr_wxyz, new_qd_wxyz, False)\n\n raise ValueError(\n \"Cannot multiply dual quaternion with object of type {0}\".format(\n type(val)\n )\n )\n\n def __add__(self, val):\n \"\"\"Adds the dual quaternion to another dual quaternion.\n\n Parameters\n ----------\n val : :obj:`DualQuaternion`\n The DualQuaternion to add to this one.\n\n Returns\n -------\n :obj:`DualQuaternion`\n A new DualQuaternion that results from the addition..\n\n Raises\n ------\n ValueError\n If val is not a DualQuaternion.\n \"\"\"\n if not isinstance(val, DualQuaternion):\n raise ValueError(\n \"Cannot add dual quaternion with object of type {0}\".format(\n type(val)\n )\n )\n\n new_qr_wxyz = self.qr + val.qr\n new_qd_wxyz = self.qd + val.qd\n new_qr_wxyz = new_qr_wxyz / np.linalg.norm(new_qr_wxyz)\n\n return DualQuaternion(new_qr_wxyz, new_qd_wxyz, False)\n\n def __str__(self):\n return \"{0}+{1}e\".format(self.qr, self.qd)\n\n def __repr__(self):\n return \"DualQuaternion({0},{1})\".format(repr(self.qr), repr(self.qd))\n" ]
[ [ "numpy.array", "numpy.linalg.norm", "numpy.roll", "numpy.allclose" ] ]
GauravKParmar/Disaster-Response-Pipeline
[ "740aaa9e2062662841add2daa981d5177abda021" ]
[ "data/process_data.py" ]
[ "import sys\nimport pandas as pd\nfrom sqlalchemy import create_engine\n\ndef load_data(messages_filepath, categories_filepath):\n \n \"\"\" \n Loads data from given filepaths and merges them. \n \n Parameters: \n messages_filepath (str): messages filepath\n categories_filepath (str): categories filepath\n \n Returns: \n df (DataFrame): combined dataframe\n \n \"\"\"\n \n # reading csv files using pandas\n messages = pd.read_csv(messages_filepath)\n categories = pd.read_csv(categories_filepath)\n \n # merging the two dataframes\n df = pd.merge(messages, categories, on=\"id\")\n \n return df\n\ndef clean_data(df):\n \n \"\"\" \n Creates new individual category columns by splitting values \n from categories column and drops duplicate rows.\n \n Parameters: \n df (DataFrame): dataframe to be cleaned.\n \n Returns: \n df (DataFrame): cleaned dataframe with new columns.\n \n \"\"\"\n \n # creating a dataframe of the 36 individual category columns\n categories = df['categories'].str.split(';', expand=True)\n \n # selecting the first row of the categories dataframe to extract column names\n row = categories.iloc[0,:]\n \n # creating a list of category column names\n category_colnames = row.apply(lambda x : x[:-2])\n \n # renaming the columns of 'categories' dataframe\n categories.columns = category_colnames\n \n for column in categories:\n # set each value to be the last character of the string\n categories[column] = categories[column].astype(str).str[-1]\n \n # convert column from string to numeric\n categories[column] = pd.to_numeric(categories[column])\n \n # replacing categories column in df with new category columns.\n df.drop('categories', inplace=True, axis=1)\n \n # concatenating the original dataframe with the new 'categories' dataframe\n df = pd.concat([df, categories], axis=1)\n \n # removing duplicates\n df.drop_duplicates(inplace=True)\n \n return df\n\ndef save_data(df, database_filename):\n \n \"\"\" \n Saves the dataframe to a database.\n \n Parameters: \n df (DataFrame): dataframe to be stored.\n database_filename (str) : database filename.\n \n \"\"\"\n \n # initiating SQLAlchemy Engine\n engine = create_engine('sqlite:///'+database_filename)\n \n # using pandas to save the DataFrame to the database\n df.to_sql(database_filename[:-3], engine, index=False) \n\n \ndef main():\n if len(sys.argv) == 4:\n\n messages_filepath, categories_filepath, database_filepath = sys.argv[1:]\n\n print('Loading data...\\n MESSAGES: {}\\n CATEGORIES: {}'\n .format(messages_filepath, categories_filepath))\n df = load_data(messages_filepath, categories_filepath)\n\n print('Cleaning data...')\n df = clean_data(df)\n \n print('Saving data...\\n DATABASE: {}'.format(database_filepath))\n save_data(df, database_filepath)\n \n print('Cleaned data saved to database!')\n \n else:\n print('Please provide the filepaths of the messages and categories '\\\n 'datasets as the first and second argument respectively, as '\\\n 'well as the filepath of the database to save the cleaned data '\\\n 'to as the third argument. \\n\\nExample: python process_data.py '\\\n 'disaster_messages.csv disaster_categories.csv '\\\n 'DisasterResponse.db')\n\n\nif __name__ == '__main__':\n main()" ]
[ [ "pandas.merge", "pandas.read_csv", "pandas.to_numeric", "pandas.concat" ] ]
CyrilShch/persona-training-scripts
[ "8f026fe29b35b7f217fbb58445181dc0569f3321" ]
[ "Personalization/script_BolCom.py" ]
[ "# imports\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.common.exceptions import TimeoutException\nimport pandas as pd\nimport numpy as np\nimport time\nimport re\nfrom tqdm import tqdm\nimport argparse\nimport warnings\nfrom user_agents import parse\nwarnings.simplefilter(\"ignore\")\n\n\n# SCRIPT USAGE:\n### without user-agent:\n# python Personalization/script_BolCom.py\n# --exp_name BC_first_exp1\n# --items_list sneakers parfum sandalen horloge rugzak zonnebril kostuum trainingspak badpak jurk overhemd mantel laarzen koptelefoon yogamat sjaal badjas halsketting portemonnee\n# --web_page https://www.bol.com/\n# --exec_path Personalization/geckodriver.exe\n\n### with user-agent:\n# python Personalization/script_BolCom.py\n# --exp_name BC_second_exp2\n# --items_list sneakers parfum sandalen horloge rugzak zonnebril kostuum trainingspak badpak jurk overhemd mantel laarzen koptelefoon yogamat sjaal badjas halsketting portemonnee\n# --web_page https://www.bol.com/\n# --exec_path Personalization/geckodriver.exe\n# --ua_string \"Mozilla/5.0 (Linux; U; Android 4.0.4; en-gb; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30\"\n\n# LIST OF UA STRING:\n### iPhone's user agent string\n# ua_string = 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3'\n### Samsung Galaxy S3\n# ua_string = 'Mozilla/5.0 (Linux; U; Android 4.0.4; en-gb; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'\n### non touch Blackberry device\n# ua_string = 'BlackBerry9700/5.0.0.862 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/331 UNTRUSTED/1.0 3gpp-gba'\n### iPad's user agent string\n# ua_string = 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10'\n### Kindle Fire's user agent string\n# ua_string = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true'\n### Touch capable Windows 8 device\n# ua_string = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0; Touch)'\n\ndef get_parser():\n # parse parameters\n parser = argparse.ArgumentParser(description='Scrape Lidl website')\n parser.add_argument(\"--exp_name\", type=str, default=\"\", help=\"Experiment name\")\n parser.add_argument(\"--items_list\", nargs='+', default=\"\", help=\"List of products to search\")\n parser.add_argument(\"--web_page\", type=str, default=\"\", help=\"Website url\")\n parser.add_argument(\"--exec_path\", type=str, default=\"\", help=\"Path to execute the webdriver\")\n parser.add_argument(\"--ua_string\", type=str, default=\"\", help=\"User agent string to specify to identify/detect devices and browsers\")\n parser.add_argument(\"--proxy\", type=str, default=\"\", help=\"Proxy to mimic IP Address Geolocation\")\n\n return parser\n\n\ndef iteration(driver, item, delays, collected_data):\n # banner button BolCom click to update the search bar\n banner_button = driver.find_element_by_class_name('omniture_main_logo')\n # randomly choose a delay and freeze the execution to mimic a person usage\n delay = np.random.choice(delays)\n time.sleep(delay)\n banner_button.click() # press ENTER\n\n delay = np.random.choice(delays)\n time.sleep(delay)\n\n # put a query in the search bar\n search = driver.find_element_by_name(\"searchtext\")\n search.send_keys(item) # put it in the search field\n search.submit() # press ENTER\n\n time.sleep(5)\n\n timeout = 30\n try:\n main = WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.ID, 'js_items_content')))\n time.sleep(5)\n articles = main.find_elements_by_class_name('product-item--row') # get all products from the page\n\n for article in tqdm(articles):\n price_header = article.find_elements_by_class_name('price-block__price') # get a price object\n\n if len(price_header) != 0:\n # process price text\n price = re.sub(r'[\\n\\r]+', '.', price_header[0].text) # get a price text\n price = re.sub(\"\\-\", \"00\", price)\n\n product_header = article.find_elements_by_class_name('product-title') # get a product name\n\n # get a seller name\n try:\n seller = article.find_elements_by_class_name('product-seller__name')\n assert seller\n except:\n seller = article.find_elements_by_class_name('product-seller')\n\n if len(seller) == 0: # case if there is no seller specified\n _seller = 'NaN'\n else:\n _seller = seller[0].text # get a seller name text\n\n # temporary dictionary of the product data\n temp = {\n 'item': item,\n 'product': product_header[0].text,\n 'seller': _seller,\n 'price': price}\n\n collected_data.append(temp) # append the data\n\n except TimeoutException:\n # driver.quit()\n print(\"driver has not found products on the webpage\")\n\n\ndef main(params):\n # initialize a list of the possible delays to mimic user interaction with websites\n delays = [1, 2, 3, 4, 5]\n\n # initialize a list where we store all collected data\n collected_data = []\n\n # list of items to search\n items_list = params.items_list\n\n # initalize webdriver options\n profile = webdriver.FirefoxProfile()\n if params.ua_string != '':\n # user agent string\n ua_string = params.ua_string\n # initialize user agent\n user_agent = parse(ua_string)\n print(f\"Current user-agent: {user_agent}\")\n profile.set_preference(\"general.useragent.override\", ua_string)\n\n PROXY = params.proxy\n if PROXY != '':\n webdriver.DesiredCapabilities.FIREFOX['proxy'] = {\n \"httpProxy\": PROXY,\n \"ftpProxy\": PROXY,\n \"sslProxy\": PROXY,\n \"proxyType\": \"MANUAL\",\n }\n # initialize a webdriver\n driver = webdriver.Firefox(profile, executable_path=params.exec_path)\n # get the url\n driver.get(params.web_page)\n\n # time to wait a response from the page\n timeout = 30\n # press the button to accept cookies\n try:\n cookies = WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.CLASS_NAME, \"js-confirm-button\")))\n\n delay = np.random.choice(delays)\n time.sleep(delay)\n\n cookies.send_keys(Keys.RETURN) # press ENTER\n\n except TimeoutException:\n print(\"Didn't found the button accept cookies.\")\n pass\n\n # initialize a list with failed items\n skipped_items = []\n\n # collect the data\n for item in tqdm(items_list):\n print(\"================\")\n print(item)\n print(\"================\")\n print(\"\\n\")\n\n try:\n try:\n try:\n _ = iteration(driver, item, delays, collected_data)\n\n except:\n _ = iteration(driver, item, delays, collected_data)\n\n except:\n try:\n _ = iteration(driver, item, delays, collected_data)\n\n except:\n _ = iteration(driver, item, delays, collected_data)\n\n except:\n print(f\"{item} was skipped\")\n skipped_items.append(item)\n pass\n\n print(\"Writing csv file...\")\n df = pd.DataFrame(collected_data)\n df.to_csv(f'{params.exp_name}.csv', index=False)\n print(\"Writing finished.\")\n\n # close the driver\n driver.quit()\n\nif __name__ == '__main__':\n parser = get_parser()\n params, unknown = parser.parse_known_args()\n\n # run the script\n main(params)\n\n" ]
[ [ "pandas.DataFrame", "numpy.random.choice" ] ]
sam1373/glow-tts
[ "e38e9f0d149c55d3726b059802971145746d99cd" ]
[ "train.py" ]
[ "import os\nimport json\nimport argparse\nimport math\nimport torch\nfrom torch import nn, optim\nfrom torch.nn import functional as F\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nimport torch.multiprocessing as mp\nimport torch.distributed as dist\nfrom apex.parallel import DistributedDataParallel as DDP\nfrom apex import amp\n\nfrom data_utils import TextMelLoader, TextMelCollate\nimport models\nimport commons\nimport utils\nfrom text.symbols import symbols\n \n\nglobal_step = 0\n\n\ndef main():\n \"\"\"Assume Single Node Multi GPUs Training Only\"\"\"\n assert torch.cuda.is_available(), \"CPU training is not allowed.\"\n\n n_gpus = torch.cuda.device_count()\n os.environ['MASTER_ADDR'] = 'localhost'\n os.environ['MASTER_PORT'] = '80000'\n\n hps = utils.get_hparams()\n mp.spawn(train_and_eval, nprocs=n_gpus, args=(n_gpus, hps,))\n\n\ndef train_and_eval(rank, n_gpus, hps):\n global global_step\n if rank == 0:\n logger = utils.get_logger(hps.model_dir)\n logger.info(hps)\n utils.check_git_hash(hps.model_dir)\n writer = SummaryWriter(log_dir=hps.model_dir)\n writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, \"eval\"))\n\n dist.init_process_group(backend='nccl', init_method='env://', world_size=n_gpus, rank=rank)\n torch.manual_seed(hps.train.seed)\n torch.cuda.set_device(rank)\n\n train_dataset = TextMelLoader(hps.data.training_files, hps.data)\n train_sampler = torch.utils.data.distributed.DistributedSampler(\n train_dataset,\n num_replicas=n_gpus,\n rank=rank,\n shuffle=True)\n collate_fn = TextMelCollate(1)\n train_loader = DataLoader(train_dataset, num_workers=8, shuffle=False,\n batch_size=hps.train.batch_size, pin_memory=True,\n drop_last=True, collate_fn=collate_fn, sampler=train_sampler)\n if rank == 0:\n val_dataset = TextMelLoader(hps.data.validation_files, hps.data)\n val_loader = DataLoader(val_dataset, num_workers=8, shuffle=False,\n batch_size=hps.train.batch_size, pin_memory=True,\n drop_last=True, collate_fn=collate_fn)\n\n #print(len(train_dataset))\n #print(len(train_loader))\n print(symbols)\n print(len(symbols))\n\n generator = models.FlowGenerator(\n n_vocab=len(symbols), \n out_channels=hps.data.n_mel_channels, \n **hps.model).cuda(rank)\n optimizer_g = commons.Adam(generator.parameters(), scheduler=hps.train.scheduler, dim_model=hps.model.hidden_channels, warmup_steps=hps.train.warmup_steps, lr=hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps)\n if hps.train.fp16_run:\n generator, optimizer_g._optim = amp.initialize(generator, optimizer_g._optim, opt_level=\"O1\")\n generator = DDP(generator)\n try:\n _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, \"G_*.pth\"), generator, optimizer_g)\n epoch_str += 1\n optimizer_g.step_num = (epoch_str - 1) * len(train_loader)\n optimizer_g._update_learning_rate()\n global_step = (epoch_str - 1) * len(train_loader)\n except:\n if hps.train.ddi and os.path.isfile(os.path.join(hps.model_dir, \"ddi_G.pth\")):\n _ = utils.load_checkpoint(os.path.join(hps.model_dir, \"ddi_G.pth\"), generator, optimizer_g)\n epoch_str = 1\n global_step = 0\n\n \n for epoch in range(epoch_str, hps.train.epochs + 1):\n if rank==0:\n train(rank, epoch, hps, generator, optimizer_g, train_loader, logger, writer)\n evaluate(rank, epoch, hps, generator, optimizer_g, val_loader, logger, writer_eval)\n if epoch % hps.train.save_every == 0:\n utils.save_checkpoint(generator, optimizer_g, hps.train.learning_rate, epoch, os.path.join(hps.model_dir, \"G_{}.pth\".format(epoch)))\n else:\n train(rank, epoch, hps, generator, optimizer_g, train_loader, None, None)\n\n\ndef train(rank, epoch, hps, generator, optimizer_g, train_loader, logger, writer):\n train_loader.sampler.set_epoch(epoch)\n global global_step\n\n generator.train()\n for batch_idx, (x, x_lengths, y, y_lengths) in enumerate(train_loader):\n x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True)\n y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True)\n\n # Train Generator\n optimizer_g.zero_grad()\n \n (z, y_m, y_logs, logdet), attn, logw, logw_, x_m, x_logs = generator(x, x_lengths, y, y_lengths, gen=False)\n l_mle = 0.5 * math.log(2 * math.pi) + (torch.sum(y_logs) + 0.5 * torch.sum(torch.exp(-2 * y_logs) * (z - y_m)**2)) / (torch.sum(y_lengths // hps.model.n_sqz) * hps.model.n_sqz * hps.data.n_mel_channels)\n l_length = torch.sum((logw - logw_)**2) / torch.sum(x_lengths)\n\n loss_gs = [l_mle, l_length]\n loss_g = sum(loss_gs)\n\n if hps.train.fp16_run:\n with amp.scale_loss(loss_g, optimizer_g._optim) as scaled_loss:\n scaled_loss.backward()\n grad_norm = commons.clip_grad_value_(amp.master_params(optimizer_g._optim), 5)\n else:\n loss_g.backward()\n grad_norm = commons.clip_grad_value_(generator.parameters(), 5)\n optimizer_g.step()\n \n if rank==0:\n if batch_idx % hps.train.log_interval == 0:\n (y_gen, *_), *_ = generator.module(x[:1], x_lengths[:1], gen=True)\n logger.info('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(x), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader),\n loss_g.item()))\n logger.info([x.item() for x in loss_gs] + [global_step, optimizer_g.get_lr()])\n \n scalar_dict = {\"loss/g/total\": loss_g, \"learning_rate\": optimizer_g.get_lr(), \"grad_norm\": grad_norm}\n scalar_dict.update({\"loss/g/{}\".format(i): v for i, v in enumerate(loss_gs)})\n utils.summarize(\n writer=writer,\n global_step=global_step, \n images={\"y_org\": utils.plot_spectrogram_to_numpy(y[0].data.cpu().numpy()), \n \"y_gen\": utils.plot_spectrogram_to_numpy(y_gen[0].data.cpu().numpy()), \n \"attn\": utils.plot_alignment_to_numpy(attn[0,0].data.cpu().numpy()),\n },\n scalars=scalar_dict)\n global_step += 1\n \n if rank == 0:\n logger.info('====> Epoch: {}'.format(epoch))\n\n \ndef evaluate(rank, epoch, hps, generator, optimizer_g, val_loader, logger, writer_eval):\n if rank == 0:\n global global_step\n generator.eval()\n losses_tot = []\n with torch.no_grad():\n for batch_idx, (x, x_lengths, y, y_lengths) in enumerate(val_loader):\n x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True)\n y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True)\n\n \n (z, y_m, y_logs, logdet), attn, logw, logw_, x_m, x_logs = generator(x, x_lengths, y, y_lengths, gen=False)\n l_mle = 0.5 * math.log(2 * math.pi) + (torch.sum(y_logs) + 0.5 * torch.sum(torch.exp(-2 * y_logs) * (z - y_m)**2) - torch.sum(logdet)) / (torch.sum(y_lengths // hps.model.n_sqz) * hps.model.n_sqz * hps.data.n_mel_channels)\n l_length = torch.sum((logw - logw_)**2) / torch.sum(x_lengths)\n loss_gs = [l_mle, l_length]\n loss_g = sum(loss_gs)\n\n if batch_idx == 0:\n losses_tot = loss_gs\n else:\n losses_tot = [x + y for (x, y) in zip(losses_tot, loss_gs)]\n\n if batch_idx % hps.train.log_interval == 0:\n logger.info('Eval Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(x), len(val_loader.dataset),\n 100. * batch_idx / len(val_loader),\n loss_g.item()))\n logger.info([x.item() for x in loss_gs])\n \n \n losses_tot = [x/len(val_loader) for x in losses_tot]\n loss_tot = sum(losses_tot)\n scalar_dict = {\"loss/g/total\": loss_tot}\n scalar_dict.update({\"loss/g/{}\".format(i): v for i, v in enumerate(losses_tot)})\n utils.summarize(\n writer=writer_eval,\n global_step=global_step, \n scalars=scalar_dict)\n logger.info('====> Epoch: {}'.format(epoch))\n\n \nif __name__ == \"__main__\":\n main()\n" ]
[ [ "torch.distributed.init_process_group", "torch.multiprocessing.spawn", "torch.cuda.set_device", "torch.utils.data.distributed.DistributedSampler", "torch.manual_seed", "torch.utils.data.DataLoader", "torch.sum", "torch.exp", "torch.no_grad", "torch.utils.tensorboard.SummaryWriter", "torch.cuda.is_available", "torch.cuda.device_count" ] ]
askap-vast/forced_phot
[ "8f4307825781743755d189418a9cb9111aaf0b63" ]
[ "tests/test_forced_phot_inject.py" ]
[ "import time\nimport warnings\nfrom astropy import units as u, constants as c\nfrom astropy.coordinates import SkyCoord\nfrom astropy.io import fits\nfrom astropy.io.fits.verify import VerifyWarning\nfrom astropy.table import Table\nimport astropy.wcs\nfrom astropy.utils.exceptions import AstropyWarning\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nimport forced_phot\n\n# suppress FITS verification warnings\nwarnings.simplefilter(\"ignore\", category=AstropyWarning)\n\nimage = \"image.i.SB9668.cont.VAST_0341-50A.linmos.taylor.0.restored.fits\"\nbackground = \"meanMap.image.i.SB9668.cont.VAST_0341-50A.linmos.taylor.0.restored.fits\"\nnoise = \"noiseMap.image.i.SB9668.cont.VAST_0341-50A.linmos.taylor.0.restored.fits\"\n\nFP = forced_phot.ForcedPhot(image, background, noise)\n\nn = 500\nt = time.time()\n\nx = (np.random.random_sample((n,)) - 0.5) * 8000 + 7046.5\ny = (np.random.random_sample((n,)) - 0.5) * 8000 + 7046.5\nP_inj = astropy.wcs.utils.pixel_to_skycoord(x, y, FP.w)\nflux_inj = np.random.random_sample((n,)) * 100e-3 + 0.5e-3\n\n# inject with a wider kernel than recovery\nFP.inject(flux_inj, P_inj, nbeam=15)\nflux_recover, flux_err_recover, *_ = FP.measure(P_inj, cluster_threshold=None)\n\nprint(time.time() - t)\nplt.clf()\nplt.errorbar(flux_inj, (flux_recover - flux_inj), yerr=flux_err_recover, fmt=\"o\")\nplt.plot([0, flux_inj.max()], [0, 0], \"k--\")\nplt.xlabel(\"Injected flux density (Jy)\")\nplt.ylabel(\"(Recovered - injected (Jy)\")\nplt.title(\n r\"$\\chi^2=%.1f$ (%d DOF)\"\n % ((((flux_recover - flux_inj) / flux_err_recover) ** 2).sum(), n)\n)\n" ]
[ [ "numpy.random.random_sample", "matplotlib.pyplot.clf", "matplotlib.pyplot.errorbar", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.ylabel" ] ]
quincy-125/DigiPath_CLAM_TF
[ "8b7ab50caaca13f666268b0f4e071d123e190978", "8b7ab50caaca13f666268b0f4e071d123e190978" ]
[ "MODEL/model_bag_classifier.py", "MODEL/model_attention.py" ]
[ "import tensorflow as tf\nimport numpy as np\n\n\nclass S_Bag(tf.keras.Model):\n def __init__(self, dim_compress_features=512, n_class=2):\n super(S_Bag, self).__init__()\n self.dim_compress_features = dim_compress_features\n self.n_class = n_class\n\n self.s_bag_model = tf.keras.models.Sequential()\n self.s_bag_layer = tf.keras.layers.Dense(\n units=1, activation='linear', input_shape=(self.n_class, self.dim_compress_features),\n name='Bag_Classifier_Layer'\n )\n self.s_bag_model.add(self.s_bag_layer)\n\n def bag_classifier(self):\n return self.s_bag_model\n\n def h_slide(self, A, h):\n # compute the slide-level representation aggregated per the attention score distribution for the mth class\n SAR = list()\n for i in range(len(A)):\n sar = tf.linalg.matmul(tf.transpose(A[i]), h[i]) # shape be (2,512)\n SAR.append(sar)\n slide_agg_rep = tf.math.add_n(SAR) # return h_[slide,m], shape be (2,512)\n\n return slide_agg_rep\n\n def call(self, bag_label, A, h):\n slide_agg_rep = self.h_slide(A, h)\n bag_classifier = self.bag_classifier()\n slide_score_unnorm = bag_classifier(slide_agg_rep)\n slide_score_unnorm = tf.reshape(slide_score_unnorm, (1, self.n_class))\n Y_hat = tf.math.top_k(slide_score_unnorm, 1)[1][-1]\n Y_prob = tf.math.softmax(\n tf.reshape(slide_score_unnorm, (1, self.n_class))) # shape be (1,2), predictions for each of the classes\n predict_slide_label = np.argmax(Y_prob.numpy())\n\n Y_true = tf.one_hot([bag_label], 2)\n\n return slide_score_unnorm, Y_hat, Y_prob, predict_slide_label, Y_true\n\n\nclass M_Bag(tf.keras.Model):\n def __init__(self, dim_compress_features=512, n_class=2):\n super(M_Bag, self).__init__()\n self.dim_compress_features = dim_compress_features\n self.n_class = n_class\n\n self.m_bag_models = list()\n self.m_bag_model = tf.keras.models.Sequential()\n self.m_bag_layer = tf.keras.layers.Dense(units=1, activation='linear',\n input_shape=(1, self.dim_compress_features),\n name='Bag_Classifier_Layer')\n self.m_bag_model.add(self.m_bag_layer)\n for i in range(self.n_class):\n self.m_bag_models.append(self.m_bag_model)\n\n def bag_classifier(self):\n return self.m_bag_models\n\n def h_slide(self, A, h):\n # compute the slide-level representation aggregated per the attention score distribution for the mth class\n SAR = list()\n for i in range(len(A)):\n sar = tf.linalg.matmul(tf.transpose(A[i]), h[i]) # shape be (2,512)\n SAR.append(sar)\n\n SAR_Branch = list()\n for i in range(self.n_class):\n sar_branch = list()\n for j in range(len(SAR)):\n sar_c = tf.reshape(SAR[j][i], (1, self.dim_compress_features))\n sar_branch.append(sar_c)\n SAR_Branch.append(sar_branch)\n\n slide_agg_rep = list()\n for k in range(self.n_class):\n slide_agg_rep.append(tf.math.add_n(SAR_Branch[k]))\n\n return slide_agg_rep\n\n def call(self, bag_label, A, h):\n slide_agg_rep = self.h_slide(A, h)\n\n # return s_[slide,m] (slide-level prediction scores)\n ssus = list()\n for i in range(self.n_class):\n bag_classifier = self.bag_classifier()[i]\n ssu = bag_classifier(slide_agg_rep[i])\n ssus.append(ssu[0][0])\n\n slide_score_unnorm = tf.convert_to_tensor(ssus)\n slide_score_unnorm = tf.reshape(slide_score_unnorm, (1, self.n_class))\n\n Y_hat = tf.math.top_k(slide_score_unnorm, 1)[1][-1]\n Y_prob = tf.math.softmax(slide_score_unnorm)\n predict_slide_label = np.argmax(Y_prob.numpy())\n\n Y_true = tf.one_hot([bag_label], 2)\n\n return slide_score_unnorm, Y_hat, Y_prob, predict_slide_label, Y_true", "import tensorflow as tf\n\n\nclass NG_Att_Net(tf.keras.Model):\n def __init__(self, dim_features=1024, dim_compress_features=512, n_hidden_units=256, n_class=2,\n dropout=False, dropout_rate=.25):\n super(NG_Att_Net, self).__init__()\n self.dim_features = dim_features\n self.dim_compress_features = dim_compress_features\n self.n_hidden_units = n_hidden_units\n self.n_class = n_class\n self.dropout = dropout\n self.dropout_rate = dropout_rate\n\n self.compression_model = tf.keras.models.Sequential()\n self.model = tf.keras.models.Sequential()\n\n self.fc_compress_layer = tf.keras.layers.Dense(units=dim_compress_features,\n activation='relu',\n input_shape=(dim_features,),\n kernel_initializer='glorot_normal',\n bias_initializer='zeros',\n name='Fully_Connected_Layer')\n\n self.compression_model.add(self.fc_compress_layer)\n\n self.att_layer1 = tf.keras.layers.Dense(units=n_hidden_units,\n activation='linear',\n input_shape=(dim_compress_features,),\n kernel_initializer='glorot_normal',\n bias_initializer='zeros',\n name='Attention_layer1')\n\n self.att_layer2 = tf.keras.layers.Dense(units=n_hidden_units,\n activation='tanh',\n input_shape=(dim_compress_features,),\n kernel_initializer='glorot_normal',\n bias_initializer='zeros',\n name='Attention_Layer2')\n\n self.att_layer3 = tf.keras.layers.Dense(units=n_class,\n activation='linear',\n input_shape=(n_hidden_units,),\n kernel_initializer='glorot_normal',\n bias_initializer='zeros',\n name='Attention_Layer3')\n\n self.model.add(self.att_layer1)\n self.model.add(self.att_layer2)\n\n if dropout:\n self.model.add(tf.keras.layers.Dropout(dropout_rate, name='Dropout_Layer'))\n\n self.model.add(self.att_layer3)\n\n def att_model(self):\n attention_model = [self.compression_model, self.model]\n return attention_model\n\n def call(self, img_features):\n h = list()\n A = list()\n\n for i in img_features:\n c_imf = self.att_model()[0](i)\n h.append(c_imf)\n\n for j in h:\n a = self.att_model()[1](j)\n A.append(a)\n return h, A\n\n\nclass G_Att_Net(tf.keras.Model):\n def __init__(self, dim_features=1024, dim_compress_features=512, n_hidden_units=256, n_class=2,\n dropout=False, dropout_rate=.25):\n super(G_Att_Net, self).__init__()\n self.dim_features = dim_features\n self.dim_compress_features = dim_compress_features\n self.n_hidden_units = n_hidden_units\n self.n_class = n_class\n self.dropout = dropout\n self.dropout_rate = dropout_rate\n\n self.compression_model = tf.keras.models.Sequential()\n self.model_v = tf.keras.models.Sequential()\n self.model_u = tf.keras.models.Sequential()\n self.model = tf.keras.models.Sequential()\n\n self.fc_compress_layer = tf.keras.layers.Dense(units=dim_compress_features,\n activation='relu',\n input_shape=(dim_features,),\n kernel_initializer='glorot_normal',\n bias_initializer='zeros',\n name='Fully_Connected_Layer')\n\n self.compression_model.add(self.fc_compress_layer)\n\n self.att_v_layer1 = tf.keras.layers.Dense(units=n_hidden_units,\n activation='linear',\n input_shape=(dim_compress_features,),\n kernel_initializer='glorot_normal',\n bias_initializer='zeros',\n name='Attention_V_Layer1')\n\n self.att_v_layer2 = tf.keras.layers.Dense(units=n_hidden_units,\n activation='tanh',\n input_shape=(dim_compress_features,),\n kernel_initializer='glorot_normal',\n bias_initializer='zeros',\n name='Attention_V_Layer2')\n\n self.att_u_layer1 = tf.keras.layers.Dense(units=n_hidden_units,\n activation='linear',\n input_shape=(dim_compress_features,),\n kernel_initializer='glorot_normal',\n bias_initializer='zeros',\n name='Attention_U_Layer1')\n\n self.att_u_layer2 = tf.keras.layers.Dense(units=n_hidden_units,\n activation='sigmoid',\n input_shape=(dim_compress_features,),\n kernel_initializer='glorot_normal',\n bias_initializer='zeros',\n name='Attention_U_Layer2')\n\n self.att_layer_f = tf.keras.layers.Dense(units=n_class,\n activation='linear',\n input_shape=(n_hidden_units,),\n kernel_initializer='glorot_normal',\n bias_initializer='zeros',\n name='Attention_Gated_Final_Layer')\n\n self.model_v.add(self.att_v_layer1)\n self.model_v.add(self.att_v_layer2)\n\n self.model_u.add(self.att_u_layer1)\n self.model_u.add(self.att_u_layer2)\n\n if dropout:\n self.model_v.add(tf.keras.layers.Dropout(dropout_rate, name='Dropout_V_Layer'))\n self.model_u.add(tf.keras.layers.Dropout(dropout_rate, name='Dropout_U_Layer'))\n\n self.model.add(self.att_layer_f)\n\n def att_model(self):\n attention_model = [self.compression_model, self.model_v, self.model_u, self.model]\n return attention_model\n\n def call(self, img_features):\n h = list()\n A = list()\n\n for i in img_features:\n c_imf = self.att_model()[0](i)\n h.append(c_imf)\n\n for j in h:\n att_v_output = self.att_model()[1](j)\n att_u_output = self.att_model()[2](j)\n att_input = tf.math.multiply(att_v_output, att_u_output)\n a = self.att_model()[3](att_input)\n A.append(a)\n\n return h, A" ]
[ [ "tensorflow.convert_to_tensor", "tensorflow.transpose", "tensorflow.keras.layers.Dense", "tensorflow.reshape", "tensorflow.math.add_n", "tensorflow.one_hot", "tensorflow.math.softmax", "tensorflow.math.top_k", "tensorflow.keras.models.Sequential" ], [ "tensorflow.math.multiply", "tensorflow.keras.layers.Dense", "tensorflow.keras.models.Sequential", "tensorflow.keras.layers.Dropout" ] ]
HaldexBrake/ReducedOrderModeling
[ "d56917f52018dabd317c1a9a583efe0b90cc9e7b" ]
[ "dmd/dmd.py" ]
[ "\"\"\"\n\n\"\"\"\nfrom pyfmi import load_fmu\nimport numpy as np\nfrom scipy.linalg import eig\nfrom numpy.linalg import svd, solve, inv, norm\nimport matplotlib.pyplot as plt\nfrom sympy import symbols, lambdify\n\n\ndef create_input_vec(time_vec, inp_type='sin', amp=10.0, freq=1.0, delta_time=1.0, duration=1):\n \"\"\"Constructs an input vector either as a sine wave, Dirac pulse or chirp signal.\n\n Args:\n time_vec (ndarray): Time vector.\n inp_type (str): What kind input is wanted. Must be `sin`, `delta` or `inc_freq`.\n amp (double): Amplitude of the sine wave or the Dirac pulse.\n freq (double): Frequency of the sine wave.\n delta_time (double): Time at which the pulse starts.\n duration (int): Duration in time steps of the Dirac pulse.\n\n Returns:\n ndarray: The input vector.\n\n Raises:\n ValueError: If specified input type is non-existing.\n\n \"\"\"\n if amp == 0:\n u = None\n elif inp_type == 'sin':\n u = amp*np.sin((freq*2*np.pi)*time_vec)\n elif inp_type == 'delta':\n u = np.zeros_like(time_vec)\n idx = np.argmax(time_vec>delta_time)\n u[idx:idx+duration] = np.array(duration*[amp])\n elif inp_type == 'inc_freq':\n freq = np.linspace(0,1,len(time_vec))\n u = amp*np.sin((freq*2*np.pi)*time_vec)\n else:\n raise ValueError('inp must be either \\'sin\\', \\'inc_freq\\' or \\'delta\\'.')\n return u\n\n\ndef get_snapshots_damped_dual_mass(t_start, t_stop, ncp, input_force=None, time_vec=None, states=['mass1.s','mass1.v','mass2.s','mass2.v']):\n \"\"\"Simulates the FMU of the damped dual mass system and returns the\n snapshots as a matrix.\n\n Args:\n t_start (double): Simulation start time.\n t_stop (double): Simulation stop time.\n ncp (int): Number of communication points, i.e. number of time steps\n excluding the initial conndition.\n input_force (ndarray): Input signal of same length as `time_vec`.\n time_vec (ndarray): Time vector of same length as `input_force`.\n states (list): The states of the fmu that should be included in the\n snapshots.\n\n Returns:\n ndarray: The matrix of snapshots, where row i corresponds to state i\n in states and time evovles along the columns.\n\n Raises:\n ValueError: If `input_force` is given without time vector.\n\n \"\"\"\n # Load the FMU\n model = load_fmu('../fmu/DampedDualMassSystem.fmu')\n\n # Specify number of comuncation points (ncp)\n opts = model.simulate_options()\n opts['ncp'] = ncp\n\n # Create input object\n if input_force is not None:\n if time_vec is None:\n raise ValueError('Specify time vector plz.')\n input_object = ('F', np.transpose(np.vstack((time_vec,input_force))))\n else:\n input_object = None\n\n # Simulate the FMU\n res = model.simulate(start_time=t_start, final_time=t_stop, input=input_object, options=opts)\n\n # If no states are given, return all\n if states is None or len(states) == 0:\n states = res.keys()\n\n # Extract simulation result\n snapshots = np.zeros((len(states),ncp+1))\n for i, state in enumerate(states):\n snapshots[i,:] = res[state]\n\n return snapshots\n\n\ndef get_snapshots_stop_friction(t_start, t_stop, ncp, input_force=None, time_vec=None, states=['mass1.s','mass1.v','mass2.s','mass2.v']):\n \"\"\"Simulates the FMU of the damped dual mass system with stop and friction\n and returns the snapshots as a matrix.\n\n Args:\n t_start (double): Simulation start time.\n t_stop (double): Simulation stop time.\n ncp (int): Number of communication points, i.e. number of time steps\n excluding the initial conndition.\n input_force (ndarray): Input signal of same length as `time_vec`.\n time_vec (ndarray): Time vector of same length as `input_force`.\n states (list): The states of the FMU that should be included in the\n snapshots.\n\n Returns:\n ndarray: The matrix of snapshots, where row i corresponds to state i\n in states and time evovles along the columns.\n\n Raises:\n ValueError: If `input_force` is given without time vector.\n\n \"\"\"\n # Load the FMU\n model = load_fmu('../fmu/DampedDualMassSystemStopFriction.fmu')\n\n # Specify number of comuncation points (ncp)\n opts = model.simulate_options()\n opts['ncp'] = ncp\n\n # Create input object\n if input_force is not None:\n if time_vec is None:\n raise ValueError('Specify time vector plz.')\n input_object = ('F', np.transpose(np.vstack((time_vec,input_force))))\n else:\n input_object = None\n\n # Simulate the FMU\n res = model.simulate(start_time=t_start, final_time=t_stop, input=input_object, options=opts)\n\n # Find mask to extract the solution at the specified communication points, i.e. not at\n # the additional state events points.\n mask = len(res['time'])*[True]\n i = 0\n for el in time_vec:\n while abs(el-res['time'][i])>1e-12:\n mask[i] = False\n i += 1\n if i == len(res['time']):\n break\n i += 1\n\n # If no states are given, return all\n if states is None or len(states)==0:\n states = res.keys()\n\n # Extract simulation result\n snapshots = np.zeros((len(states),ncp+1))\n for i, state in enumerate(states):\n snapshots[i,:] = res[state][mask]\n\n return snapshots\n\n\ndef get_koopman_snapshots_stop_friction(t_start, t_stop, ncp, observables, input_force=None, time_vec=None):\n \"\"\"Simulates the FMU of the damped dual mass system with stop and friction\n and returns the snapshots as a matrix where observables have been applied\n to the result.\n\n Args:\n t_start (double): Simulation start time.\n t_stop (double): Simulation stop time.\n ncp (int): Number of communication points, i.e. number of time steps\n excluding the initial conndition.\n observables (list of SymPy expressions): The observable functions used\n to extract states.\n input_force (ndarray): Input signal of same length as `time_vec`.\n time_vec (ndarray): Time vector of same length as `input_force`.\n\n Returns:\n ndarray: The matrix of snapshots, where row i corresponds to state i\n in states and time evovles along the columns.\n\n Raises:\n ValueError: If `input_force` is given without time vector.\n\n \"\"\"\n # Wrapper function to be able to call the function `func` with\n # arguments inside a list\n def _wrapper(func, args):\n return func(*args)\n\n # Load the FMU\n model = load_fmu('../fmu/DampedDualMassSystemStopFriction.fmu')\n\n # Specify number of comuncation points (ncp)\n opts = model.simulate_options()\n opts['ncp'] = ncp\n\n # Create input object\n if input_force is not None:\n if time_vec is None:\n raise ValueError('Please specify time vector.')\n input_object = ('F', np.transpose(np.vstack((time_vec,input_force))))\n else:\n input_object = None\n\n # Simulate the FMU\n res = model.simulate(start_time=t_start, final_time=t_stop, input=input_object, options=opts)\n\n # Find mask for extracting the solution at the correct points, i.e. not at\n # the additional state events\n mask = len(res['time'])*[True]\n i = 0\n for t in time_vec:\n while abs(t-res['time'][i])>1e-12:\n mask[i] = False\n i += 1\n if i == len(res['time']):\n break\n i += 1\n\n # Extract simulation result\n snapshots = np.zeros((len(observables),ncp+1))\n for i, obs in enumerate(observables):\n syms = obs.free_symbols # Get args in this observable\n states = [sym.name for sym in list(syms)] # Get the names of the args, i.e. our states\n f = lambdify(syms, obs, 'numpy') # Vectorize the observable function\n values = [res[state][mask] for state in states] # Get simulation result for each state\n val = _wrapper(f, values) # Computes g_i(x)\n snapshots[i,:] = val\n\n return snapshots\n\n\ndef get_analytical_snapshots_damped_dual_mass(t_start, t_stop, ncp, input_force=None):\n \"\"\"Generates snapshots for the damped dual mass system from the analytical\n solution to the system.\n\n Args:\n t_start (double): Simulation start time.\n t_stop (double): Simulation stop time.\n ncp (int): Number of communication points, i.e. number of time steps\n excluding the initial conndition.\n input_force (ndarray): Input signal of same length as `time_vec`.\n\n Returns:\n ndarray: The matrix of snapshots, where row i corresponds to state i\n in states and time evovles along the columns. The states are:\n position and veclocity of mass 1, position and veclocity of mass 2\n\n \"\"\"\n # Analytical solution to the damped dual mass system\n # Set the values of constants\n k1,k2,m1,m2,c_damp = 250, 1000, 3, 2, np.sqrt(500)\n\n # Construct system matrix s.t. dot{x} = Ax\n A = np.array([[0,1,0,0],\n [-(k1+k2)/m1,-c_damp/m1,k2/m1,c_damp/m1],\n [0,0,0,1],\n [k2/m2,c_damp/m2,-k2/m2,-c_damp/m2]])\n\n # Eigendecomposition of A\n lam_A,V = eig(A) # eigenvals as elements of lam, eigenvecs as columns in V\n\n # Exponential matrix of a for the given time step\n dt = (t_stop-t_start)/ncp # step size\n expAdt = [email protected](np.exp(dt*lam_A))@inv(V)\n expAdt = np.real(expAdt)\n\n # Setup for time-stepping\n X = np.zeros((4,ncp+1)) # Construct matrix for storage\n X[:,0] = np.array([0, 0, 0.1, -0.2]) # Set initial values\n B = solve(A, expAdt-np.eye(4)) # Help matrix for more efficient calculations\n b = B[:,-1] # Extract the needed column\n\n # Iterate solution forward in time\n # States at time k (given states up to k-1) are given by\n # X[:,k] = expAdt@X[:,k-1] + A_inv@(expAdt - np.eye(4))@np.array([0,input_force[k-1]/m2,0,0])\n if input_force is None:\n for k in range(1,ncp+1):\n X[:,k] = expAdt@X[:,k-1]\n else:\n for k in range(1,ncp+1):\n X[:,k] = expAdt@X[:,k-1] + input_force[k-1]/m2*b\n\n return X\n\n\ndef get_data_matrices(data, m_stop=None, u=None, q=0):\n \"\"\"Creates the X and Y data matrices.\n\n Args:\n data (ndarray): Simulation result.\n m_stop (int): Number of columns of the data matrices.\n u (ndarray): Input vector.\n q (int): Number of time-delay embeddings.\n\n Returns:\n tuple: (X,Y). The X and Y data matrices.\n\n Raises:\n ValueError: If `m_stop` is not valid.\n\n \"\"\"\n if m_stop is None:\n m_stop = data.shape[1]\n elif m_stop == 0:\n raise ValueError('m_stop must be greater than zero')\n elif m_stop <= q+1:\n raise ValueError('m_stop at least = q+2')\n\n # Construct data matrices (If statement not required. More effective to create X directly and not stack vectors)\n if q>0:\n if u is None:\n X = data[:,:m_stop-(q+1)]\n for i in range(q,0,-1):\n X = np.vstack([X,data[:,(q+1-i):m_stop-i]])\n Y = np.vstack([X[data.shape[0]:,:],data[:,(q+1):m_stop]])\n else:\n zero_vec = np.zeros(m_stop-(q+1))\n X = np.vstack([data[:,:m_stop-(q+1)],u[:m_stop-(q+1)]])\n Y = np.vstack([data[:,1:m_stop-q],zero_vec])\n for i in range(q,0,-1):\n X = np.vstack([X,data[:,(q+1-i):m_stop-i],u[(q+1-i):m_stop-i]])\n Y = np.vstack([Y,data[:,(q+1-(i-1)):m_stop-(i-1)],zero_vec])\n else:\n if u is None:\n X = data[:,:m_stop-1]\n Y = data[:,1:m_stop]\n else:\n X = np.vstack([data[:,:m_stop-1],u[:m_stop-1]])\n Y = np.vstack([data[:,1:m_stop],np.zeros((m_stop-1,))])\n\n return X.astype(np.float64),Y.astype(np.float64)\n\n\ndef get_dmd_modes(X, Y, n_trunc=None, plot=False):\n \"\"\"Computes the DMD modes `v` and eigenvalues `lam` of the data matrices `X`,`Y`.\n\n Args:\n X (ndarray): First data matrix.\n Y (ndarray): Second data matrix.\n n_trunc (int): Truncates `X` to rank `n_trunc`.\n plot (bool): Plots the singular values, eigenvalues and some columns of V.\n\n Returns:\n tuple: (lam,w,v,A). Eigenvalues, left eigenvectors, right eigenvectors and the matrix A or A_tilde.\n\n \"\"\"\n U,S,VH = svd(X,full_matrices=False)\n\n if n_trunc is None:\n # Compute A_hat and make eigendecomposition\n A = [email protected]@np.diag(1/S)@U.T\n # Add some dust to the diagonal (singular values) if needed\n # A = [email protected]@np.diag(S/(S*S + 1e-2))@U.T\n lam,w,v = eig(A,left=True,right=True)\n else:\n # Truncate\n U = U[:,0:n_trunc]\n S_trunc = S[0:n_trunc]\n VH = VH[0:n_trunc,:]\n\n # Similarity transform to matrix A_tilde and eigendecomposition\n A = np.conj(U.T)@[email protected](VH.T)@np.diag(1/S_trunc)\n lam,w_tilde,v_tilde = eig(A,left=True,right=True)\n\n # Project eigenvectors so we get correct DMD modes\n w = ([email protected](U.T)).T\n v = U@v_tilde\n\n if plot:\n # Singular values\n plt.figure()\n nnz_s = S > 1e-12\n x = np.arange(len(S))\n plt.semilogy(x[nnz_s],S[nnz_s], 'bx')\n plt.semilogy(x[nnz_s==False],S[nnz_s==False], 'rx')\n plt.xlim([1,len(S)])\n if n_trunc is not None:\n plt.axvline(x=n_trunc, color='k', linestyle='-',linewidth=1)\n plt.grid(True)\n plt.xlabel('Index')\n plt.ylabel('Singular value')\n\n # Eigenvalues in complex plane\n plt.figure()\n mask = np.abs(lam) > 1\n plt.plot(np.real(lam[mask==False]),np.imag(lam[mask==False]),'bx')\n plt.plot(np.real(lam[mask]),np.imag(lam[mask]),'rx')\n plt.plot(np.cos(np.linspace(0,2*np.pi)),np.sin(np.linspace(0,2*np.pi)),'--k')\n plt.xlabel('Re($\\lambda$)')\n plt.ylabel('Im($\\lambda$)')\n plt.grid(True)\n plt.axis('equal')\n\n # Columns in V\n plt.figure()\n plt.plot(np.conj(VH.T)[:,0:6])\n plt.xlim([0,VH.shape[1]])\n plt.title('Columns in V')\n plt.grid(True)\n\n plt.plot()\n\n return lam.astype(np.complex128),w.astype(np.complex128),v.astype(np.complex128),A\n\n\ndef one_step_pred(xk, lam, wH, v, norm_vec):\n \"\"\"Performs a one-step prediction of the system represented by its DMD.\n\n Args:\n xk (ndarray): Solution (states) at time step k.\n lam (ndarray): DMD eigenvalues.\n wH (ndarray): Complex conjugated left eigenvectors from DMD.\n v (ndarray): DMD modes.\n norm_vec (ndarray): Normalization vector.\n\n Returns:\n ndarray: Prediction of the states of the system at time step k+1.\n\n \"\"\"\n return np.real(np.sum(((lam*(wH@xk))*norm_vec)*v,axis=1))\n\n\ndef predict(lam, w, v, X0, N, u=None, q=0):\n \"\"\"Predict the future dynamics of the system given an initial value `X0`. Result is returned\n as a matrix where rows correspond to states and columns to time.\n\n Args:\n lam (ndarray): DMD eigenvalues.\n w (ndarray): Left eigenvectors from DMD.\n v (ndarray): DMD modes.\n X0 (ndarray): Initial value of the system.\n N (int): Number of time steps to predict.\n u (ndarray): Input signal.\n q (int): Number of time-delay embeddings.\n\n Returns:\n ndarray: Prediction of the states of the system for N time steps into the future.\n\n \"\"\"\n # Construct matrix for predictions and set initial values\n n = X0.shape[0]\n Yhat = np.zeros((n,N+1-q),dtype=np.float64)\n Yhat[:,0] = X0\n\n # Add input in the correct rows and construct a mask for prediction\n n_x = n//(q+1)\n if u is not None:\n if q>0:\n mask = np.array((q+1)*((n_x-1)*[True]+[False]))\n len_u = len(u)\n Yhat[mask==False,:] = np.vstack([u[i:len_u-(q-i)] for i in range(0,q+1)])\n else:\n mask = (n-1)*[True] + [False]\n Yhat[-1,:] = u # Add input\n else:\n mask = n*[True]\n\n # For efficient calculations\n wH = np.conj(w).T\n norm_vec = 1/(np.diag(wH@v))\n\n # Prediction\n for i in range(1,N+1-q):\n yhat = one_step_pred(Yhat[:,i-1],lam,wH,v,norm_vec)\n Yhat[mask,i] = yhat[mask]\n\n # Extract predictions\n res = np.zeros((n_x,N+1),dtype=np.float64)\n res[:,:N+1-q] = Yhat[:n_x,:]\n for i in range(q):\n res[:,N+1-q+i] = Yhat[(i+1)*n_x:(i+2)*n_x,-1]\n\n return res\n" ]
[ [ "numpy.diag", "numpy.imag", "numpy.sqrt", "numpy.linspace", "matplotlib.pyplot.plot", "numpy.zeros_like", "numpy.exp", "numpy.linalg.svd", "numpy.eye", "numpy.sin", "numpy.real", "numpy.argmax", "matplotlib.pyplot.axis", "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "numpy.linalg.inv", "numpy.array", "numpy.sum", "scipy.linalg.eig", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.semilogy", "matplotlib.pyplot.axvline", "numpy.conj", "numpy.abs", "matplotlib.pyplot.xlim", "matplotlib.pyplot.grid", "matplotlib.pyplot.xlabel", "numpy.vstack" ] ]
thomas-mazumder/project5
[ "b8f2eda71dcfb550d030a2ee2d9b136005198aca" ]
[ "cluster/silhouette.py" ]
[ "import numpy as np\nfrom scipy.spatial.distance import cdist\n\nclass Silhouette:\n def __init__(self, metric: str = \"euclidean\"):\n \"\"\"\n inputs:\n metric: str\n the name of the distance metric to use\n \"\"\"\n self._metric = metric \n\n def score(self, X: np.ndarray, y: np.ndarray) -> np.ndarray:\n \"\"\"\n calculates the silhouette score for each of the observations\n\n inputs:\n X: np.ndarray\n A 2D matrix where the rows are observations and columns are features. \n\n y: np.ndarray\n a 1D array representing the cluster labels for each of the observations in `X`\n\n outputs:\n np.ndarray\n a 1D array with the silhouette scores for each of the observations in `X`\n \"\"\"\n s = np.zeros(X.shape[0])\n distances = cdist(X, X, self._metric)\n for i in range(X.shape[0]):\n a = self._calculate_a(distances, y, i)\n b = self._calculate_b(distances, y, i)\n s[i] = (b - a)/np.max([a, b])\n return s\n\n def _calculate_a(self, distances, y, i):\n \"\"\"\n Calculate the intra cluster distance for a data point\n \"\"\"\n distances = distances[i,y == y[i]]\n return np.sum(distances)/(np.sum(y == y[i]) - 1)\n\n def _calculate_b(self, distances, y, i):\n \"\"\"\n Calculate the inter cluster distance for a data point\n \"\"\"\n inter_distances = np.ones(np.max(y)) * np.inf\n for j in range(np.max(y)):\n if j != y[i]:\n inter_distances[j] = np.sum(distances[i,y == j])/np.sum(y == j)\n return np.min(inter_distances)\n\n" ]
[ [ "numpy.min", "scipy.spatial.distance.cdist", "numpy.max", "numpy.zeros", "numpy.sum" ] ]
ArpanBose11/Music_Recogniser_Omega
[ "584ca1e77436a54ac2589bb9be839ec392b8b2c2" ]
[ "recognize-from-microphone.py" ]
[ "#!/usr/bin/python\nimport argparse\nimport sys\nfrom argparse import RawTextHelpFormatter\nfrom itertools import zip_longest as izip_longest\n\nimport numpy as np\nfrom termcolor import colored\n\nimport libs.fingerprint as fingerprint\nfrom libs.config import get_config\nfrom libs.db_sqlite import SqliteDatabase\nfrom libs.reader_microphone import MicrophoneReader\nfrom libs.visualiser_console import VisualiserConsole as visual_peak\nfrom libs.visualiser_plot import VisualiserPlot as visual_plot\nfrom contextlib import redirect_stdout\n\n\n# from libs.db_mongo import MongoDatabase\n\ndef writeTofile(data, filename):\n with open(filename, 'wb') as file:\n file.write(data)\n print(\"Stored blob data into: \", filename, \"\\n\")\n\ndef align_matches(matches):\n diff_counter = {}\n largest = 0\n largest_count = 0\n song_id = -1\n\n\n for tup in matches:\n sid, diff = tup\n\n if diff not in diff_counter:\n diff_counter[diff] = {}\n\n if sid not in diff_counter[diff]:\n diff_counter[diff][sid] = 0\n\n diff_counter[diff][sid] += 1\n\n if diff_counter[diff][sid] > largest_count:\n largest = diff\n largest_count = diff_counter[diff][sid]\n song_id = sid\n\n songM = db.get_song_by_id(song_id)\n #genreM= db.get_song_by_id(song_id)\n #artistM=db.get_song_by_id(song_id)\n\n\n\n\n nseconds = round(float(largest) / fingerprint.DEFAULT_FS *\n fingerprint.DEFAULT_WINDOW_SIZE *\n fingerprint.DEFAULT_OVERLAP_RATIO, 5)\n\n return {\n \"SONG_ID\": song_id,\n \"SONG_NAME\": songM[1],\n \"CONFIDENCE\": largest_count,\n \"OFFSET\": int(largest),\n \"OFFSET_SECS\": nseconds,\n \"GENRE\": songM[3],\n \"ARTIST\":songM[4],\n \"ART\":songM[5],\n \"ALBUM\": songM[6]\n\n }\n\n\ndef grouper(iterable, n, fillvalue=None):\n args = [iter(iterable)] * n\n return (filter(None, values)\n for values in izip_longest(fillvalue=fillvalue, *args))\n\n\ndef find_matches(samples, Fs=fingerprint.DEFAULT_FS):\n hashes = fingerprint.fingerprint(1,samples, Fs=Fs)\n return return_matches(hashes)\n\n\ndef return_matches(hashes):\n mapper = {}\n for hash, offset in hashes:\n mapper[hash.upper()] = offset\n values = mapper.keys()\n\n # https://www.sqlite.org/limits.html\n # To prevent excessive memory allocations,\n # the maximum value of a host parameter number is SQLITE_MAX_VARIABLE_NUMBER, which defaults to 999 for SQLites\n for split_values in map(list, grouper(values, 999)):\n # @todo move to db related files\n query = \"\"\"\n SELECT upper(hash), song_fk, offset\n FROM fingerprints\n WHERE upper(hash) IN (%s)\n \"\"\"\n query = query % ', '.join('?' * len(split_values))\n\n x = db.executeAll(query, split_values)\n matches_found = len(x)\n\n if matches_found > 0:\n msg = ' ** found %d hash matches (step %d/%d)'\n #print(colored(msg, 'green') % (\n #matches_found,\n #len(split_values),\n #len(values)\n #))\n pass\n else:\n msg = ' ** not matches found (step %d/%d)'\n #print(colored(msg, 'red') % (len(split_values), len(values)))\n\n for hash_code, sid, offset in x:\n # (sid, db_offset - song_sampled_offset)\n if isinstance(offset, bytes):\n # offset come from fingerprint.py and numpy extraction/processing\n offset = np.frombuffer(offset, dtype=np.int)[0]\n yield sid, offset - mapper[hash_code]\n\n\nif __name__ == '__main__':\n sys.stdout = open(\"out.txt\", \"w\")\n config = get_config()\n\n db = SqliteDatabase()\n\n\n\n seconds = 6\n\n chunksize = 2 ** 12 # 4096\n channels = 1 # int(config['channels']) # 1=mono, 2=stereo\n\n record_forever = False\n visualise_console = bool(config['mic.visualise_console'])\n visualise_plot = bool(config['mic.visualise_plot'])\n\n reader = MicrophoneReader(None)\n\n reader.start_recording(seconds=seconds,\n chunksize=chunksize,\n channels=channels)\n\n msg = ' * started recording..'\n #print(colored(msg, attrs=['dark']))\n\n while True:\n bufferSize = int(reader.rate / reader.chunksize * seconds)\n\n for i in range(0, bufferSize):\n nums = reader.process_recording()\n\n if visualise_console:\n msg = colored(' %05d', attrs=['dark']) + colored(' %s', 'green')\n #print(msg % visual_peak.calc(nums))\n else:\n msg = ' processing %d of %d..' % (i, bufferSize)\n #print(colored(msg, attrs=['dark']))\n\n if not record_forever:\n break\n\n if visualise_plot:\n data = reader.get_recorded_data()[0]\n visual_plot.show(data)\n\n reader.stop_recording()\n\n msg = ' * recording has been stopped'\n #print(colored(msg, attrs=['dark']))\n\n data = reader.get_recorded_data()\n\n msg = ' * recorded %d samples'\n #print(colored(msg, attrs=['dark']) % len(data[0]))\n\n # reader.save_recorded('test.wav')\n\n Fs = fingerprint.DEFAULT_FS\n channel_amount = len(data)\n\n result = set()\n matches = []\n\n for channeln, channel in enumerate(data):\n # TODO: Remove prints or change them into optional logging.\n msg = ' fingerprinting channel %d/%d'\n #print(colored(msg, attrs=['dark']) % (channeln + 1, channel_amount))\n\n matches.extend(find_matches(channel))\n\n msg = ' finished channel %d/%d, got %d hashes'\n #print(colored(msg, attrs=['dark']) % (channeln + 1,\n # channel_amount, len(matches)))\n\n total_matches_found = len(matches)\n\n #print('')\n\n if total_matches_found > 0:\n msg = ' ** totally found %d hash matches'\n #print(colored(msg, 'green') % total_matches_found)\n\n song = align_matches(matches)\n\n msg = ' \\n=> Song: %s \\n'\n #msg += ' offset: %d (%d secs)\\n'\n #msg += ' confidence: %d\\n'\n msg += ' Genre: %s\\n'\n msg += ' Artist: %s\\n'\n msg += ' Album:%s\\n'\n msg += '%s\\n'\n\n\n\n\n\n print(colored(msg, 'green') % (song['SONG_NAME'],\n #song['SONG_ID'],\n #song['OFFSET'], song['OFFSET_SECS'],\n #song['CONFIDENCE'],\n song['GENRE'],\n song['ARTIST'],\n song['ALBUM'],\n song['SONG_NAME'] + song['ARTIST']))\n photo=song['ART']\n photoPath = \"example\" + \".jpg\"\n\n writeTofile(photo, photoPath)\n\n else:\n msg = ' \\n\\nNo matches found\\n\\n\\n '\n print(colored(msg, 'red'))\n\n sys.stdout.close()\n\n\n\n\n\n" ]
[ [ "numpy.frombuffer" ] ]
hoossainalik/goodreads-reviewer
[ "b4f47856b5c0e88f9bd5bc55b91f2cba8909ef27" ]
[ "BookReviewsSentimentAnalyzer.py" ]
[ "\"\"\"-------------------------------------------\r\nPackage Name: BookReviewsSentimentAnalyzer\r\nAuthor: Hussain Ali Khan\r\nVersion: 1.0.1\r\nLast Modified: 12/02/2018\r\n-------------------------------------------\r\n\"\"\"\r\n\r\nimport sys\r\nfrom PyQt5.QtWidgets import QDialog, QApplication, QMainWindow, QMessageBox, QDesktopWidget\r\nfrom PyQt5.uic import loadUi\r\nfrom PyQt5.QtCore import pyqtSlot, QTimer\r\nimport goodreads_api_client as gr\r\nfrom PyQt5 import QtWidgets, QtGui\r\nimport requests\r\nfrom requests import HTTPError\r\nfrom bs4 import BeautifulSoup\r\nimport re\r\nimport pandas as pd\r\n\r\n\r\nclass BookProfiler(QMainWindow):\r\n def __init__(self):\r\n super(BookProfiler, self).__init__()\r\n loadUi('book.ui', self)\r\n qt_rectangle = self.frameGeometry()\r\n center_point = QDesktopWidget().availableGeometry().center()\r\n qt_rectangle.moveCenter(center_point)\r\n self.move(qt_rectangle.topLeft())\r\n self.search_btn.clicked.connect(self.search_book)\r\n self.export_to_csv_btn.clicked.connect(self.export)\r\n self.search_txt.setText(\"\")\r\n self.client = gr.Client(developer_key='NqaQK91zheH4ofJYuTmpA')\r\n self.search_tbl.resizeRowsToContents()\r\n self.search_tbl.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)\r\n self.label_default_style = 'color: red; font-size: 16px; background-color: none; text-align: justify;'\r\n self.book_data = {}\r\n self.book_review_data = {}\r\n self.clear_fields()\r\n\r\n @pyqtSlot()\r\n def search_book(self):\r\n\r\n self.clear_fields()\r\n\r\n book_isbn = self.search_txt.text()\r\n\r\n if book_isbn != \"\":\r\n\r\n if (len(book_isbn) == 10 or len(book_isbn) == 13) and book_isbn.isnumeric():\r\n try:\r\n book = self.get_book(book_isbn)\r\n\r\n keys_wanted = ['id', 'title', 'isbn', 'isbn13', 'num_pages', 'authors', 'format',\r\n 'edition_information',\r\n 'publisher', 'publication_day', 'publication_month', 'publication_year',\r\n 'description']\r\n\r\n reduced_book = {k: v for k, v in book.items() if k in keys_wanted}\r\n\r\n book_id = \"\"\r\n\r\n if reduced_book[\"id\"] is not None:\r\n book_id = reduced_book[\"id\"]\r\n\r\n authors = \"N/A\"\r\n\r\n if len(reduced_book[\"authors\"][\"author\"]) > 0:\r\n try:\r\n authors = reduced_book[\"authors\"][\"author\"][\"name\"]\r\n except TypeError:\r\n author_names = []\r\n for author in reduced_book[\"authors\"][\"author\"]:\r\n if author is not None:\r\n author_names.append(author[\"name\"])\r\n authors = ', '.join(author_names)\r\n\r\n date_published = \"N/A\"\r\n\r\n if reduced_book[\"publication_day\"] is not None:\r\n if reduced_book[\"publication_month\"] is not None:\r\n if reduced_book[\"publication_year\"] is not None:\r\n date_published = reduced_book[\"publication_day\"] + \"/\" + reduced_book[\r\n \"publication_month\"] + \"/\" + \\\r\n reduced_book[\"publication_year\"]\r\n elif reduced_book[\"publication_month\"] is not None:\r\n if reduced_book[\"publication_year\"] is not None:\r\n date_published = reduced_book[\"publication_month\"] + \"/\" + reduced_book[\"publication_year\"]\r\n\r\n isbn = \"N/A\"\r\n\r\n if reduced_book[\"isbn\"] is not None:\r\n isbn = reduced_book[\"isbn\"]\r\n\r\n reviews = self.get_reviews(isbn)\r\n\r\n self.book_review_data = reviews\r\n\r\n isbn13 = \"N/A\"\r\n\r\n if reduced_book[\"isbn13\"] is not None:\r\n isbn13 = reduced_book[\"isbn13\"]\r\n\r\n edition = \"N/A\"\r\n\r\n if reduced_book[\"edition_information\"] is not None:\r\n edition = reduced_book[\"edition_information\"]\r\n\r\n book_format = \"N/A\"\r\n\r\n if reduced_book[\"format\"] is not None:\r\n book_format = reduced_book[\"format\"]\r\n\r\n publisher = \"N/A\"\r\n\r\n if reduced_book[\"publisher\"] is not None:\r\n publisher = reduced_book[\"publisher\"]\r\n\r\n pages = \"N/A\"\r\n\r\n if reduced_book[\"num_pages\"] is not None:\r\n pages = reduced_book[\"num_pages\"]\r\n\r\n title = \"N/A\"\r\n\r\n if reduced_book[\"title\"] is not None:\r\n title = reduced_book[\"title\"]\r\n\r\n description = \"N/A\"\r\n\r\n if reduced_book[\"description\"] is not None:\r\n description = reduced_book[\"description\"]\r\n\r\n book_info = {\r\n \"isbn\": isbn,\r\n \"isbn13\": isbn13,\r\n \"title\": title,\r\n \"authors\": authors,\r\n \"pages\": pages,\r\n \"date_published\": date_published,\r\n \"edition\": edition,\r\n \"format\": book_format,\r\n \"publisher\": publisher,\r\n \"description\": description\r\n }\r\n\r\n self.book_data = book_info\r\n\r\n self.show_information(book_info, reviews)\r\n\r\n except HTTPError:\r\n print(\"ISBN isn't Valid\")\r\n self.show_message(\"ISBN Not Found On Goodreads.com\", \"Error! ISBN Not Found!!\")\r\n\r\n else:\r\n self.show_message(\"Please Enter A Valid ISBN Number\", \"Error! Invalid ISBN Entered!!\")\r\n\r\n else:\r\n self.show_message(\"Please Enter ISBN Number To Search\", \"Error! Empty ISBN\")\r\n\r\n def get_book(self, isbn):\r\n book = self.client.Book.show_by_isbn(str(isbn))\r\n return book\r\n\r\n def clear_fields(self):\r\n self.book_isbn.setText(\"\")\r\n self.book_isbn13.setText(\"\")\r\n self.book_title.setText(\"\")\r\n self.book_authors.setText(\"\")\r\n self.book_pages.setText(\"\")\r\n self.book_date_published.setText(\"\")\r\n self.book_edition.setText(\"\")\r\n self.book_format.setText(\"\")\r\n self.book_publisher.setText(\"\")\r\n self.book_description.setText(\"\")\r\n self.search_tbl.setRowCount(0)\r\n\r\n def get_reviews(self, isbn):\r\n\r\n key = \"NqaQK91zheH4ofJYuTmpA\"\r\n\r\n endpoint = \"https://www.goodreads.com/api/reviews_widget_iframe?did=\" + key +\\\r\n \"&amp;format=html&amp;isbn=\" + isbn + \\\r\n \"&amp;links=660&amp;review_back=fff&amp;stars=000&amp;text=000\"\r\n\r\n r = requests.get(url=endpoint)\r\n\r\n soup = BeautifulSoup(r.content, \"html.parser\")\r\n\r\n reviews = soup.find_all('div', attrs={\"itemprop\": \"reviews\"})\r\n\r\n review_by = []\r\n review_rating = []\r\n review_text = []\r\n\r\n for review in reviews:\r\n\r\n reviewer = review.find(\"span\", attrs={\"class\": \"gr_review_by\"})\r\n\r\n if reviewer is not None:\r\n reviewer = reviewer.a\r\n if reviewer is not None:\r\n review_by.append(reviewer.text)\r\n else:\r\n review_by.append(\"N/A\")\r\n\r\n rating = review.find(\"span\", attrs={\"class\": \"gr_rating\"})\r\n\r\n if rating is not None:\r\n review_rating.append(self.get_rating(rating.text))\r\n else:\r\n review_rating.append(\"N/A\")\r\n\r\n rev = review.find(\"div\", attrs={\"class\": \"gr_review_text\"})\r\n\r\n if rev is not None:\r\n review_text.append(self.clean_text(rev.text))\r\n else:\r\n review_text.append(\"N/A\")\r\n\r\n revs = {\"reviewer\": review_by, \"rating\": review_rating, \"review\": review_text}\r\n return revs\r\n\r\n def show_information(self, book_info, reviews):\r\n\r\n if reviews is not None:\r\n reviewers = reviews[\"reviewer\"]\r\n ratings = reviews[\"rating\"]\r\n reviews_text = reviews[\"review\"]\r\n\r\n for rev in range(len(reviewers)):\r\n pos = self.search_tbl.rowCount()\r\n self.search_tbl.insertRow(pos)\r\n self.search_tbl.setItem(pos, 0, QtWidgets.QTableWidgetItem(reviewers[rev]))\r\n self.search_tbl.setItem(pos, 1, QtWidgets.QTableWidgetItem(str(ratings[rev])+\"/5\"))\r\n self.search_tbl.setItem(pos, 2, QtWidgets.QTableWidgetItem(reviews_text[rev]))\r\n self.search_tbl.resizeColumnsToContents()\r\n\r\n self.book_isbn.setText(book_info[\"isbn\"])\r\n self.book_isbn.setStyleSheet(self.label_default_style)\r\n self.book_isbn13.setText(book_info[\"isbn13\"])\r\n self.book_isbn13.setStyleSheet(self.label_default_style)\r\n self.book_title.setText(book_info[\"title\"])\r\n self.book_title.setStyleSheet(self.label_default_style)\r\n self.book_authors.setText(book_info[\"authors\"])\r\n self.book_authors.setStyleSheet(self.label_default_style)\r\n self.book_pages.setText(book_info[\"pages\"])\r\n self.book_pages.setStyleSheet(self.label_default_style)\r\n self.book_date_published.setText(book_info[\"date_published\"])\r\n self.book_date_published.setStyleSheet(self.label_default_style)\r\n self.book_edition.setText(book_info[\"edition\"])\r\n self.book_edition.setStyleSheet(self.label_default_style)\r\n self.book_format.setText(book_info[\"format\"])\r\n self.book_format.setStyleSheet(self.label_default_style)\r\n self.book_publisher.setText(book_info[\"publisher\"])\r\n self.book_publisher.setStyleSheet(self.label_default_style)\r\n self.book_description.setText(book_info[\"description\"])\r\n self.book_description.setStyleSheet(self.label_default_style)\r\n\r\n def show_message(self, message, title):\r\n choice = QMessageBox.question(self, title, message, QMessageBox.Ok)\r\n if choice == QMessageBox.Ok:\r\n print(\"OK\")\r\n else:\r\n pass\r\n\r\n def clean_text(self, review):\r\n review = review.replace(\"\\n\", \"\")\r\n review = review.replace(\"...\", \" \")\r\n review = review.replace(\"more\", \" \")\r\n review = re.sub('\\s+', ' ', review).strip()\r\n return review\r\n\r\n def get_rating(self, stars):\r\n rating_scale = {\"★★★★★\": 5, \"★★★★☆\": 4, \"★★★☆☆\": 3, \"★★☆☆☆\": 2, \"★☆☆☆☆\": 1}\r\n return rating_scale[stars]\r\n\r\n @pyqtSlot()\r\n def export(self):\r\n self.export_as_csv()\r\n\r\n def export_as_csv(self):\r\n book_df = pd.DataFrame(self.book_data, index=[0])\r\n book_df.to_csv(\"Books/\"+self.book_data[\"isbn\"]+\"_details.csv\")\r\n review_df = pd.DataFrame(self.book_review_data)\r\n review_df.to_csv(\"Reviews/\"+self.book_data[\"isbn\"]+\"_reviews.csv\")\r\n self.show_message(\"Exported Book And Review Details To CSV\", \"Data Exported!!\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app = QApplication(sys.argv)\r\n window = BookProfiler()\r\n window.show()\r\n sys.exit(app.exec_())\r\n" ]
[ [ "pandas.DataFrame" ] ]
MAC-AutoML/XNAS
[ "2c54ceb09b255cbcabd67f3c39fc777c4b2403f4" ]
[ "search/DrNAS/nb201space_progressive.py" ]
[ "import os\nimport torch\nimport torch.nn as nn\nimport torch.utils\nimport torch.backends.cudnn as cudnn\n\nimport xnas.core.logging as logging\nimport xnas.core.config as config\nimport xnas.core.meters as meters\nimport xnas.search_space.DrNAS.utils as utils\nfrom xnas.core.builders import build_loss_fun, DrNAS_builder\nfrom xnas.core.config import cfg\nfrom xnas.core.timer import Timer\nfrom xnas.core.trainer import setup_env, test_epoch\nfrom xnas.datasets.loader import construct_loader\nfrom xnas.search_algorithm.DrNAS import Architect\n\nfrom torch.utils.tensorboard import SummaryWriter\nfrom nas_201_api import NASBench201API as API\n\n\n# Load config and check\nconfig.load_cfg_fom_args()\nconfig.assert_and_infer_cfg()\ncfg.freeze()\n# Tensorboard supplement\nwriter = SummaryWriter(log_dir=os.path.join(cfg.OUT_DIR, \"tb\"))\n\nlogger = logging.get_logger(__name__)\n\n\ndef distill(result):\n result = result.split(\"\\n\")\n cifar10 = result[5].replace(\" \", \"\").split(\":\")\n cifar100 = result[7].replace(\" \", \"\").split(\":\")\n imagenet16 = result[9].replace(\" \", \"\").split(\":\")\n\n cifar10_train = float(cifar10[1].strip(\",test\")[-7:-2].strip(\"=\"))\n cifar10_test = float(cifar10[2][-7:-2].strip(\"=\"))\n cifar100_train = float(cifar100[1].strip(\",valid\")[-7:-2].strip(\"=\"))\n cifar100_valid = float(cifar100[2].strip(\",test\")[-7:-2].strip(\"=\"))\n cifar100_test = float(cifar100[3][-7:-2].strip(\"=\"))\n imagenet16_train = float(imagenet16[1].strip(\",valid\")[-7:-2].strip(\"=\"))\n imagenet16_valid = float(imagenet16[2].strip(\",test\")[-7:-2].strip(\"=\"))\n imagenet16_test = float(imagenet16[3][-7:-2].strip(\"=\"))\n\n return (\n cifar10_train,\n cifar10_test,\n cifar100_train,\n cifar100_valid,\n cifar100_test,\n imagenet16_train,\n imagenet16_valid,\n imagenet16_test,\n )\n\n\ndef main():\n\n setup_env()\n # follow DrNAS settings.\n torch.set_num_threads(3)\n cudnn.benchmark = True\n\n if not \"debug\" in cfg.OUT_DIR:\n api = API(\"./data/NAS-Bench-201-v1_1-096897.pth\")\n\n criterion = build_loss_fun().cuda()\n\n assert cfg.DRNAS.METHOD in [\"snas\", \"dirichlet\", \"darts\"], \"method not supported.\"\n\n if cfg.DRNAS.METHOD == \"snas\":\n # Create the decrease step for the gumbel softmax temperature\n # cfg.OPTIM.MAX_EPOCH = 100\n [tau_min, tau_max] = cfg.DRNAS.TAU\n # Create the decrease step for the gumbel softmax temperature\n tau_step = (tau_min - tau_max) / cfg.OPTIM.MAX_EPOCH\n tau_epoch = tau_max\n\n model = DrNAS_builder().cuda()\n\n logger.info(\"param size = %fMB\", utils.count_parameters_in_MB(model))\n\n optimizer = torch.optim.SGD(\n model.get_weights(),\n cfg.OPTIM.BASE_LR,\n momentum=cfg.OPTIM.MOMENTUM,\n weight_decay=cfg.OPTIM.WEIGHT_DECAY,\n )\n\n train_loader, valid_loader = construct_loader(\n cfg.SEARCH.DATASET,\n cfg.SEARCH.SPLIT,\n cfg.SEARCH.BATCH_SIZE,\n cfg.SEARCH.DATAPATH,\n num_workers=cfg.DATA_LOADER.NUM_WORKERS,\n )\n\n architect = Architect(model, cfg)\n\n # configure progressive parameter\n epoch = 0\n ks = [4, 2]\n num_keeps = [5, 3]\n train_epochs = [2, 2] if \"debug\" in cfg.OUT_DIR else [50, 50]\n\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(\n optimizer, float(sum(train_epochs)), eta_min=cfg.OPTIM.MIN_LR\n )\n\n train_meter = meters.TrainMeter(len(train_loader))\n val_meter = meters.TestMeter(len(valid_loader))\n\n # train_timer = Timer()\n for i, current_epochs in enumerate(train_epochs):\n for e in range(current_epochs):\n lr = scheduler.get_lr()[0]\n logger.info(\"epoch %d lr %e\", epoch, lr)\n genotype = model.genotype()\n logger.info(\"genotype = %s\", genotype)\n model.show_arch_parameters(logger)\n\n # training\n # train_timer.tic()\n top1err = train_epoch(\n train_loader,\n valid_loader,\n model,\n architect,\n criterion,\n optimizer,\n lr,\n train_meter,\n e,\n )\n logger.info(\"Top1 err:%f\", top1err)\n # train_timer.toc()\n # print(\"epoch time:{}\".format(train_timer.diff))\n\n # validation\n test_epoch(valid_loader, model, val_meter, epoch, writer)\n\n if not \"debug\" in cfg.OUT_DIR:\n # nasbench201\n result = api.query_by_arch(model.genotype())\n logger.info(\"{:}\".format(result))\n (\n cifar10_train,\n cifar10_test,\n cifar100_train,\n cifar100_valid,\n cifar100_test,\n imagenet16_train,\n imagenet16_valid,\n imagenet16_test,\n ) = distill(result)\n logger.info(\"cifar10 train %f test %f\", cifar10_train, cifar10_test)\n logger.info(\n \"cifar100 train %f valid %f test %f\",\n cifar100_train,\n cifar100_valid,\n cifar100_test,\n )\n logger.info(\n \"imagenet16 train %f valid %f test %f\",\n imagenet16_train,\n imagenet16_valid,\n imagenet16_test,\n )\n\n # tensorboard\n writer.add_scalars(\n \"nasbench201/cifar10\",\n {\"train\": cifar10_train, \"test\": cifar10_test},\n epoch,\n )\n writer.add_scalars(\n \"nasbench201/cifar100\",\n {\n \"train\": cifar100_train,\n \"valid\": cifar100_valid,\n \"test\": cifar100_test,\n },\n epoch,\n )\n writer.add_scalars(\n \"nasbench201/imagenet16\",\n {\n \"train\": imagenet16_train,\n \"valid\": imagenet16_valid,\n \"test\": imagenet16_test,\n },\n epoch,\n )\n\n utils.save_checkpoint(\n {\n \"epoch\": epoch + 1,\n \"state_dict\": model.state_dict(),\n \"optimizer\": optimizer.state_dict(),\n \"alpha\": model.arch_parameters(),\n },\n False,\n cfg.OUT_DIR,\n )\n\n epoch += 1\n scheduler.step()\n if cfg.DRNAS.METHOD == \"snas\":\n # Decrease the temperature for the gumbel softmax linearly\n tau_epoch += tau_step\n logger.info(\"tau %f\", tau_epoch)\n model.set_tau(tau_epoch)\n\n if not i == len(train_epochs) - 1:\n model.pruning(num_keeps[i + 1])\n # architect.pruning([model._mask])\n model.wider(ks[i + 1])\n optimizer = utils.configure_optimizer(\n optimizer,\n torch.optim.SGD(\n model.get_weights(),\n cfg.OPTIM.BASE_LR,\n momentum=cfg.OPTIM.MOMENTUM,\n weight_decay=cfg.OPTIM.WEIGHT_DECAY,\n ),\n )\n scheduler = utils.configure_scheduler(\n scheduler,\n torch.optim.lr_scheduler.CosineAnnealingLR(\n optimizer, float(sum(train_epochs)), eta_min=cfg.OPTIM.MIN_LR\n ),\n )\n logger.info(\"pruning finish, %d ops left per edge\", num_keeps[i + 1])\n logger.info(\"network wider finish, current pc parameter %d\", ks[i + 1])\n\n genotype = model.genotype()\n logger.info(\"genotype = %s\", genotype)\n model.show_arch_parameters(logger)\n writer.close()\n\n\ndef train_epoch(\n train_loader,\n valid_loader,\n model,\n architect,\n criterion,\n optimizer,\n lr,\n train_meter,\n cur_epoch,\n):\n train_meter.iter_tic()\n cur_step = cur_epoch * len(train_loader)\n writer.add_scalar(\"train/lr\", lr, cur_step)\n\n valid_loader_iter = iter(valid_loader)\n\n for cur_iter, (trn_X, trn_y) in enumerate(train_loader):\n model.train()\n try:\n (val_X, val_y) = next(valid_loader_iter)\n except StopIteration:\n valid_loader_iter = iter(valid_loader)\n (val_X, val_y) = next(valid_loader_iter)\n # Transfer the data to the current GPU device\n trn_X, trn_y = trn_X.cuda(), trn_y.cuda(non_blocking=True)\n val_X, val_y = val_X.cuda(), val_y.cuda(non_blocking=True)\n\n if cur_epoch >= 10:\n architect.step(\n trn_X, trn_y, val_X, val_y, lr, optimizer, unrolled=cfg.DRNAS.UNROLLED\n )\n optimizer.zero_grad()\n architect.optimizer.zero_grad()\n\n logits = model(trn_X)\n loss = criterion(logits, trn_y)\n\n loss.backward()\n nn.utils.clip_grad_norm_(model.parameters(), cfg.OPTIM.GRAD_CLIP)\n optimizer.step()\n optimizer.zero_grad()\n architect.optimizer.zero_grad()\n\n top1_err, top5_err = meters.topk_errors(logits, trn_y, [1, 5])\n loss, top1_err, top5_err = loss.item(), top1_err.item(), top5_err.item()\n train_meter.iter_toc()\n\n # Update and log stats\n # TODO: multiply with NUM_GPUS are disabled before appling parallel\n # mb_size = trn_X.size(0) * cfg.NUM_GPUS\n mb_size = trn_X.size(0)\n train_meter.update_stats(top1_err, top5_err, loss, lr, mb_size)\n train_meter.log_iter_stats(cur_epoch, cur_iter)\n train_meter.iter_tic()\n # write to tensorboard\n writer.add_scalar(\"train/loss\", loss, cur_step)\n writer.add_scalar(\"train/top1_error\", top1_err, cur_step)\n writer.add_scalar(\"train/top5_error\", top5_err, cur_step)\n cur_step += 1\n # Log epoch stats\n train_meter.log_epoch_stats(cur_epoch)\n train_meter.reset()\n return top1_err\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "torch.set_num_threads" ] ]
GT-RIPL/UNO-IC
[ "6a95f2c6bc52ad80bfb1da53fd046a3d4db310d0" ]
[ "classification/rebalancing.py" ]
[ "import torch\n\ndef prior_recbalancing(logit,beta,s_prior,t_prior=None):\n\t# logit (b,c,h,w): pre-softmax network output\n\t# beta (1,): user controlled hyperparameter \n\t# s_prior (1,c): source (training) data prior\n\t# t_prior (1,c): target (test) data prior (most likely uniform)\n\n prob = torch.nn.Softmax(dim=1)(logit) \n\n inv_prior = 1/s_prior\n inv_prior[inv_prior == float(\"inf\")] = 0\n inv_prior = inv_prior.unsqueeze(0).float()\n\n if t_prior is None:\n prob_r = prob*inv_prior\n else:\n prob_r = prob*inv_prior*t_prior\n\n prob_r = prob_r/prob_r.sum(1).unsqueeze(1) # nomalize to make valid prob\n \n outputs = prob**(1-beta) * prob_r**beta\n outputs = outputs/outputs.sum(1).unsqueeze(1) # nomalize to make valid prob\n return outputs" ]
[ [ "torch.nn.Softmax" ] ]
alvarochiqui/edem
[ "d28861b04d9053848e26c24056395e5381ed398e" ]
[ "1. FUNDAMENTOS/3. PROGRAMACION ESTADISTICA CON PYTHON/3. my project/Part 1/heart.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 16 18:17:34 2021\n\n@author: alvar\n\"\"\"\n#Importamos todas las librerias necesarias para el proyecto\n\nimport os #sistema operativo\nimport pandas as pd #gestionar datframes\nimport numpy as np #numeric python vectores\nimport matplotlib.pyplot as plt #graficos estadisticos\n\n\n#Mencionamos carpeta donde se encuentra nuestro csv y lo mencionamos con el nombre \"heart\"\nos.chdir(r'C:\\Users\\alvar\\Desktop\\EDEM\\2. GITHUB\\edem\\Estadistica Python\\my project')\nheart = pd.read_csv ('heart.csv', sep=',')\nos.getcwd()\n\n#A continuación comprobamos que se ejecuta\nprint(heart)\n\n#Sacamos datos estadísticos como la media, desviacion tipica y quartile\nprint(heart.head(4))\n#Hacemos describe para las variables nominales identificadas\nprint(heart.Sex.describe())\nprint(heart.ChestPainType.describe())\nprint(heart.RestingECG.describe())\nprint(heart.ExerciseAngina.describe())\nprint(heart.ST_Slope.describe())\n\n#Hacemos describe para las variables cuantitativas identificadas\nAge = heart.Age.describe()\nprint(heart.Age.describe())\nm_age=Age[1]\nsd_age=Age[2]\nprint(m_age)\n\nprint(heart.RestingBP.describe())\n\nCholesterol = heart.Cholesterol.describe()\nprint(heart.Cholesterol.describe())\nm_cho=Cholesterol[1]\nsd_cho=Cholesterol[2]\n\nprint(heart.FastingBS.describe())\nprint(heart.MaxHR.describe())\nprint(heart.Oldpeak.describe())\nprint(heart.HeartDisease.describe())\n\n\n#TABLAS\n#Creamos una tabla para 3 variables nominales\n#Nominal tipo Sex\nmytablesex = heart.groupby(['Sex']).size()\nprint(mytablesex)\nn=mytablesex.sum()\n\n#Sacamos la tabla con porcentajes\nmytablesex2 = (mytablesex/n)*100\nprint(mytablesex2)\n\n#Redondeamos los porcentajes\nmytablesex3 = round(mytablesex2,1)\nprint(mytablesex3)\n\n#Nominal tipo: ChestPainType\nmytablechest = heart.groupby(['ChestPainType']).size()\nprint(mytablechest)\nn=mytablechest.sum()\n\n#Sacamos la tabla con porcentajes\nmytablechest2 = (mytablechest/n)*100\nprint(mytablechest2)\n\n#Redondeamos los porcentajes\nmytablechest3 = round(mytablechest2,1)\nprint(mytablechest3)\n\n#Identificamos y elegimos la variable Sexo como nominal\n#Creamos una tabla con la variable Sexo\nmytable = heart.groupby(['Sex']).size()\nprint(mytable)\nn=mytable.sum()\n\n#Sacamos la tabla con porcentajes\nmytable2 = (mytable/n)*100\nprint(mytable2)\n\n#Redondeamos los porcentajes\nmytable3 = round(mytable2,1)\nprint(mytable3)\n\n#Una vez creada la tabla, creamos su plot\nn=mytable.sum()\n\nbar_list = ['ASY', 'ATA', 'NAP', 'TA']\nplt.bar(bar_list, mytablechest3, edgecolor='black')\nplt.ylabel('Percentage')\nplt.xlabel('Chest Pain Type')\nplt.title('Figure 4. Percentage of Chest Pain Type')\nprops = dict(boxstyle='round', facecolor='white', lw=0.5)\ntextstr = '$\\mathrm{n}=%.0f$'%(n)\nplt.text(1.6, 50,'n:918')\n\n\n\nplt.savefig('Figure 4.svg')\n\n#Para evitar que se junten dos gráficas, ejecutamos otra vez:\nplt.show()\n\n#Una vez creada la tabla, creamos su plot\nn=mytable.sum()\nbar_list = ['Female', 'Male']\nplt.bar(bar_list, mytablesex3, edgecolor='black')\nplt.ylabel('Percentage')\nplt.xlabel('Sex')\nplt.title('Figure 3. Percentage of Female and Male')\nplt.text(1.5, 50,'n:918')\n#Observamos visualmente en el plot como:\n#las Mujeres son el 21% y hombres el 79% del sample de 918 pacientes\nplt.savefig('Figure 3.svg')\n\n#Para evitar que se junten dos gráficas, ejecutamos otra vez:\nplt.show()\n\n#Ahora elegimos una variable(Edad) cuantitativa para crear un histograma\n#Edad(x) y vemos cuanto se repite(y=frecuencia) para cada franja(step=5)\n#Sabiendo que el MIN es 28 y MAX es 77(del Age.decribe anterior)...\n#he decidido usar np.arange(25,85)\nx=heart['Age']\nplt.hist(x,edgecolor='black',bins=20)\nplt.xticks(np.arange(25,85, step=5))\nplt.title(\"Figura 1. Edades\")\nplt.ylabel('Frequency')\nplt.xlabel('Age')\nplt.axvline(x=m_age, linewidth=1, linestyle= 'solid', color=\"red\", label='Mean')\nplt.axvline(x=m_age-sd_age, linewidth=1, linestyle= 'dashed', color=\"green\", label='- 1 S.D.')\nplt.axvline(x=m_age + sd_age, linewidth=1, linestyle= 'dashed', color=\"green\", label='+ 1 S.D.')\n\nplt.savefig('Figure 1.svg')\n\n#Para evitar que se junten dos gráficas, ejecutamos otra vez:\nplt.show()\n\n#Ahora elegimos una variable(Edad) cuantitativa para crear un histograma\n#Edad(x) y vemos cuanto se repite(y=frecuencia) para cada franja(step=5)\n#Sabiendo que el MIN es 28 y MAX es 77(del Age.decribe anterior)...\n#he decidido usar np.arange(25,85)\nx=heart['Cholesterol']\nplt.hist(x,edgecolor='black',bins=20)\nplt.xticks(np.arange(0,610, step=50))\nplt.title(\"Figura 2. Colesterol\")\nplt.ylabel('Frequency')\nplt.xlabel('Cholesterol level')\nplt.axvline(x=m_cho, linewidth=1, linestyle= 'solid', color=\"red\", label='Mean')\nplt.axvline(x=m_cho-sd_cho, linewidth=1, linestyle= 'dashed', color=\"green\", label='- 1 S.D.')\nplt.axvline(x=m_cho + sd_cho, linewidth=1, linestyle= 'dashed', color=\"green\", label='+ 1 S.D.')\n\n\nplt.savefig('Figure 2.svg')" ]
[ [ "pandas.read_csv", "matplotlib.pyplot.axvline", "matplotlib.pyplot.title", "numpy.arange", "matplotlib.pyplot.savefig", "matplotlib.pyplot.bar", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.text", "matplotlib.pyplot.show", "matplotlib.pyplot.hist", "matplotlib.pyplot.ylabel" ] ]
Zhas1ke/Captcha_Generator
[ "72be27f298b8475643f037082b06b453a2dc9b78" ]
[ "captcha.py" ]
[ "import numpy as np\nimport cv2\nimport string\nimport math\nimport os\nimport uuid\nimport random\n\n##############################################\ngrad_img = cv2.imread('grad.png')\ndef sp_noise(image,prob):\n '''\n Add salt and pepper noise to image\n prob: Probability of the noise\n '''\n output = np.zeros(image.shape,np.uint8)\n thres = 1 - prob \n for i in range(image.shape[0]):\n for j in range(image.shape[1]):\n rdn = random.random()\n if rdn < prob:\n output[i][j] = (np.random.randint(0, 256), np.random.randint(0, 256), np.random.randint(0, 256))\n else:\n output[i][j] = image[i][j]\n return output\n##############################################\n\nwd, _ = os.path.split(os.path.abspath(__file__))\n\nCAPTCHA_LENGTH = 6\nWIDTH = 300 # 120\nHEIGHT = 100 # 36\n\n# RGB\n# font_colors = {\n# 'dark-green':(0, 150, 0),\n # (241, 145, 241)\n# 'red':(230, 70, 50),\n# 'violet':(135, 80, 250),\n# 'light-green':(65, 235, 100)\n# }\n# BGR\nfont_colors = {\n 'dark-green':(0, 150, 0),\n 'red':(50, 70, 230),\n 'violet':(250, 80, 135),\n 'light-green':(100, 235, 65)\n}\n\nclass Captcha:\n def __init__(self, width, high, ls=None, lc=CAPTCHA_LENGTH, fs=None,\n # folder=os.path.join(wd, 'samples'),\n folder='samples',\n debug=False):\n \"\"\"\n :param ls: letter set, all\n :param fs: font set\n :param lc: letter count in one pic\n :param folder: the folder to save img\n :param debug: debug mode\n \"\"\"\n\n if fs is None:\n fs = ['FONT_HERSHEY_SIMPLEX', 'FONT_ITALIC']\n\n self.fs = fs\n\n if ls is None:\n ls = string.ascii_uppercase + string.digits\n if isinstance(ls, str):\n self.letter = [i for i in ls]\n elif isinstance(ls, list):\n self.letter = ls\n\n self.lc = lc\n self.width, self.high = width, high\n self.debug = debug\n self.folder = folder\n if not self.debug and folder:\n if not os.path.exists(self.folder):\n os.makedirs(self.folder)\n\n def _tilt_img(self, img):\n tmp_img = img.copy()\n tmp_img.fill(255)\n tile_angle = np.random.randint(\n 100*-math.pi/6, 0\n ) / 100\n high, width, _ = img.shape\n for y in range(width):\n for x in range(high):\n new_y = int(y + (x-high/2)*math.tanh(tile_angle))\n try:\n tmp_img[x, new_y, :] = img[x, y, :]\n except IndexError:\n pass\n img[:, :, :] = tmp_img[:, :, :]\n\n def _shake_img(self, img, outer_top_left, outer_bottom_right,\n inner_top_left, inner_bottom_right):\n (x1, y1), (x2, y2) = outer_top_left, outer_bottom_right\n (i1, j1), (i2, j2) = inner_top_left, inner_bottom_right\n delta_x = np.random.randint(x1-i1, x2-i2)\n delta_y = np.random.randint(y1-j1, y2-j2)\n area = img[y1:y2, x1:x2, :]\n area_high, area_width, _ = area.shape\n tmp_area = area.copy()\n tmp_area.fill(255)\n\n for index_y in range(area_high):\n for index_x in range(area_width):\n new_x, new_y = index_x + delta_x, index_y + delta_y\n if new_x < area_width and new_y < area_high:\n tmp_area[new_y, new_x, :] = area[index_y, index_x, :]\n\n area[:, :, :] = tmp_area[:, :, :]\n\n def _distort_img(self, img):\n high, width, _ = img.shape\n tmp_img = img.copy()\n tmp_img.fill(255)\n\n coef_vertical = np.random.randint(1, 5)\n coef_horizontal = np.random.choice([2, 3, 4]) * math.pi / width\n scale_biase = np.random.randint(0, 360) * math.pi / 180\n\n def new_coordinate(x, y):\n return int(x+coef_vertical*math.sin(coef_horizontal*y+scale_biase))\n\n for y in range(width):\n for x in range(high):\n new_x = new_coordinate(x, y)\n try:\n tmp_img[x, y, :] = img[new_x, y, :]\n except IndexError:\n pass\n\n img[:, :, :] = tmp_img[:, :, :]\n\n def _draw_basic(self, img, text):\n font_scale = 1.6 # 36 px\n max_width = max_high = 0\n\n for i in text:\n for _font_face in [getattr(cv2, self.fs[i]) for i in range(len(self.fs))]:\n for _font_thickness in [5, 6]:\n (width, high), _ = cv2.getTextSize(\n i, _font_face, font_scale, _font_thickness)\n max_width, max_high = max(max_width, width), max(max_high, high)\n\n total_width = max_width * self.lc\n width_delta = np.random.randint(0, self.width - total_width)\n vertical_range = self.high - max_high\n images = list()\n\n font_color = np.random.choice(a=['dark-green', 'red', 'violet', 'light-green'], p=[0.91, 0.03, 0.03, 0.03])\n font_color = font_colors[font_color]\n\n delta_high = np.random.randint(\n int(2*vertical_range/5), int(3*vertical_range/5)\n )\n\n for index, letter in enumerate(text):\n font_face = getattr(cv2, np.random.choice(self.fs))\n font_thickness = np.random.choice([5, 6])\n tmp_img = img.copy()\n\n bottom_left_coordinate = (\n index*max_width + width_delta,\n self.high - delta_high\n )\n cv2.putText(tmp_img, letter, bottom_left_coordinate, font_face,\n font_scale, font_color, font_thickness)\n self._tilt_img(tmp_img)\n\n # cv2.imshow(text, tmp_img)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n\n images.append(tmp_img)\n\n high, width, _ = img.shape\n for y in range(width):\n for x in range(high):\n r, g, b = 0, 0, 0\n for tmp_img in images:\n r += tmp_img[x, y, 0] + 1\n g += tmp_img[x, y, 1] + 1\n b += tmp_img[x, y, 2] + 1\n r, g, b = r % 256, g % 256, b % 256\n img[x, y, :] = (r, g, b)\n\n for y in range(width):\n for x in range(high):\n if (img[x,y,0] + img[x,y,1] + img[x,y,2]) % 256 == 0:\n img[x,y,0] = img[x,y,1] = img[x,y,2] = 255\n\n def _draw_line(self, img):\n left_x = np.random.randint(0, self.width//4)\n left_y = np.random.randint(self.high)\n right_x = np.random.randint(self.width*3//4, self.width)\n right_y = np.random.randint(self.high)\n start, end = (left_x, left_y), (right_x, right_y)\n line_color = tuple(int(np.random.choice(range(0, 156)))\n for _ in range(3))\n line_thickness = np.random.randint(1, 3)\n cv2.line(img, start, end, line_color, line_thickness)\n\n def _put_noise(self, img):\n for i in range(600):\n x = np.random.randint(self.width)\n y = np.random.randint(self.high)\n dot_color = tuple(int(np.random.choice(range(0, 156)))\n for _ in range(3))\n img[y, x, :] = dot_color\n\n def save_img(self, text):\n img = np.zeros((self.high, self.width, 3), np.uint8)\n img.fill(255)\n\n # img = cv2.imread('grad.png')\n\n # cv2.imshow(text, img)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n\n self._draw_basic(img, text)\n # self._put_noise(img)\n # self._distort_img(img)\n # self._draw_line(img)\n\n noise_grad_img = sp_noise(grad_img,0.15)\n \n img = cv2.addWeighted(img, 0.5,noise_grad_img,0.5,0)\n\n # cv2.imshow(text, dst)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n\n if self.debug:\n cv2.imshow(text, img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n else:\n fn = text + ('_'+str(uuid.uuid1())[4: 8])\n cv2.imwrite('{}\\\\{}.jpg'.format(self.folder, fn), img)\n\n\n\n\n def batch_create_img(self, number=5):\n exits = set()\n while(len(exits)) < number:\n word = ''.join(np.random.choice(self.letter, self.lc))\n if word not in exits:\n exits.add(word)\n self.save_img(word)\n if not self.debug:\n if len(exits) % 10 == 0:\n print('{} generated.'.format(len(exits)))\n if not self.debug:\n print('{} captchas saved into {}.'.format(len(exits), self.folder))\n\nif __name__ == '__main__':\n letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']\n c = Captcha(WIDTH, HEIGHT, letters, fs=['FONT_HERSHEY_SIMPLEX', 'FONT_ITALIC'], debug=False)\n c.batch_create_img(19995)\n\n'''\n font_scale = 1.5\n font = cv2.FONT_HERSHEY_PLAIN\n\n # set the rectangle background to white\n rectangle_bgr = (255, 255, 255)\n # make a black image\n img = np.zeros((500, 500))\n # set some text\n text = \"Some text in a box!\"\n # get the width and height of the text box\n (text_width, text_height) = cv2.getTextSize(text, font, fontScale=font_scale, thickness=1)[0]\n # set the text start position\n text_offset_x = 10\n text_offset_y = img.shape[0] - 25\n # make the coords of the box with a small padding of two pixels\n box_coords = ((text_offset_x, text_offset_y), (text_offset_x + text_width + 2, text_offset_y - text_height - 2))\n cv2.rectangle(img, box_coords[0], box_coords[1], rectangle_bgr, cv2.FILLED)\n cv2.putText(img, text, (text_offset_x, text_offset_y), font, fontScale=font_scale, color=(0, 0, 0), thickness=1)\n cv2.imshow(\"A box!\", img)\n cv2.waitKey(0)\n'''" ]
[ [ "numpy.zeros", "numpy.random.choice", "numpy.random.randint" ] ]
ia-flash/matchvec
[ "e418c55c55a273f6a73fc048b3259967960c7e4f" ]
[ "aws_lambda/lambda_function.py" ]
[ "import io\nimport re\nfrom os import listdir, getenv\nimport json\nimport base64\nimport numpy as np\nimport cv2\nfrom PIL import Image\nfrom matchvec import predict_class, predict_objects, predict_anonym\nfrom urllib.request import urlopen\nfrom requests_toolbelt.multipart import decoder\n\npattern = re.compile('(?<=form-data; name=\").*?(?=\")')\n\n\ndef lambda_handler_classification(event, context):\n print(\"ENV\", getenv('BACKEND'))\n print(\"ENV\", getenv('DETECTION_THRESHOLD'))\n print(\"LISTDIR\", listdir('/tmp'))\n res = list()\n if event.get('httpMethod') == 'OPTIONS':\n return {\n 'headers': {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n \"Access-Control-Allow-Methods\": \"OPTIONS\"\n },\n 'statusCode': 200\n }\n assert event.get('httpMethod') == 'POST'\n try:\n event['body'] = base64.b64decode(event['body'])\n except:\n return {\n 'headers': {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n \"Access-Control-Allow-Methods\": \"POST\"\n },\n 'statusCode': 400,\n 'body': json.dumps(res)\n }\n\n if event['path'] == '/predict':\n infer_func = predict_class\n elif event['path'] == '/object_detection':\n infer_func = predict_objects\n elif event['path'] == '/anonym':\n infer_func = predict_anonym\n else:\n return {\n 'headers': {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n \"Access-Control-Allow-Methods\": \"POST\"\n },\n 'statusCode': 404,\n 'body': json.dumps(res)\n }\n\n content_type = event.get('headers', {\"content-type\": ''}).get('content-type')\n if 'multipart/form-data' in content_type:\n\n # convert to bytes if need\n if type(event['body']) is str:\n event['body'] = bytes(event['body'], 'utf-8')\n\n multipart_data = decoder.MultipartDecoder(event['body'], content_type)\n for part in multipart_data.parts:\n content_disposition = part.headers.get(b'Content-Disposition', b'').decode('utf-8')\n search_field = pattern.search(content_disposition)\n if search_field:\n if search_field.group(0) == 'image':\n try:\n img_io = io.BytesIO(part.content)\n img_io.seek(0)\n img = Image.open(img_io)\n img = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB)\n res.append(infer_func(img))\n except Exception as e:\n print(e)\n res.append([])\n\n elif search_field.group(0) == 'url':\n try:\n resp = urlopen(part.content.decode('utf-8'))\n img = np.asarray(bytearray(resp.read()), dtype=\"uint8\")\n img = cv2.imdecode(img, cv2.IMREAD_COLOR)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n res.append(infer_func(img))\n except Exception as e:\n print(e)\n res.append([])\n else:\n print('Bad field name in form-data')\n\n return {\n 'headers': {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n \"Access-Control-Allow-Methods\": \"OPTIONS,POST\"\n },\n 'statusCode': 200,\n 'body': json.dumps(res)\n }\n" ]
[ [ "numpy.array" ] ]
heytitle/Syllable-based-Neural-Thai-Word-Segmentation
[ "bb8a4f0dbabe31a65f9bfa1fd784000544e3e7f5" ]
[ "scripts/writing/hyperopt-model-tables.py" ]
[ "# This generates model hyperopt tables for Appendix\n\nimport yaml\nimport pandas as pd\nfrom attacut import utils\n\nOUTPUT = \"./writing/tables/hyperopt-model-tables.tex\"\n\ntable = r\"\"\"\n\\begin{table*}\n\n\\centering\n\\begin{tabular}{lc}\n\\toprule\n\\textbf{Average training duration} & %(avg_training).0f minutes \\\\\n\\textbf{Average validation word-level $F_1$} & %(avg_val_f1)2.2f$\\pm$%(std_val_f1).2f\\%% \\\\\n\\textbf{Best validation word-level $F_1$} & %(best_val_f1)2.2f\\%% \\\\\n\\textbf{Best model's number of trainable parameters} & %(best_num_params)s \\\\\n\\bottomrule\t\n\\end{tabular}\n\n\\begin{tabular}{rccc}\n\\toprule\n\\textbf{Hyperparameter} & \\textbf{Search Space} & \\textbf{Best Assignment} \\\\\nlearning rate & \\textit{loguniform(1e-4, 1e-3)}& %(lr).2e \\\\\nweight decay & \\textit{loguniform(1e-6, 1e-3)} & %(weight_decay).2e \\\\\n%(family_params)s\n\\bottomrule\n\\end{tabular}\n\n\\caption{Best hyperparameter and search space for %(name)s.}\n\\label{tab:appendix-hyperopt-%(ref)s}\n\\end{table*}\n\"\"\"\n\nfamily_specific_param = {\n \"ID-CNN\": r\"\"\"\nconvolution filters & \\textit{uniform-interger(128, 256)} & %(conv)d \\\\\nlinear layer & \\textit{uniform-interger(16, 48)} & %(l1)d \\\\\ndropout & \\textit{uniform(0, 0.5)} & %(do).4f \\\\\n\"\"\",\n \"BiLSTM\": r\"\"\"\nLSTM cells & \\textit{uniform-interger(128, 512)} & %(cells)d \\\\\nlinear layer & \\textit{uniform-interger(16, 48)} & %(l1)d \\\\\ndropout & \\textit{uniform(0, 0.5)} & %(do).4f \\\\\n\"\"\",\n}\n\nif __name__ == \"__main__\":\n with open(\"./hyperopt-results.yml\", \"r\") as fh, open(OUTPUT, \"w\") as fw:\n data = yaml.safe_load(fh)\n\n for i, row in enumerate(data):\n path = row[\"path\"]\n df = pd.read_csv(path)\n\n print(f\"loading {path}\")\n\n max_val_f1 = df[\"best-val:word_level:f1\"].max()\n best_model = df[df[\"best-val:word_level:f1\"] == max_val_f1].to_dict(\"row\")[0]\n arch_config = utils.parse_model_params(best_model[\"params\"])\n\n if \"ID-CNN-XL\" in row[\"name\"]:\n fam_param_tmp = family_specific_param[\"ID-CNN-XL\"]\n elif \"ID-CNN\" in row[\"name\"]:\n fam_param_tmp = family_specific_param[\"ID-CNN\"] \n elif \"BiLSTM-XL\" in row[\"name\"]:\n fam_param_tmp = family_specific_param[\"BiLSTM-XL\"] \n elif \"BiLSTM\" in row[\"name\"]:\n fam_param_tmp = family_specific_param[\"BiLSTM\"] \n else:\n raise ValueError(row[\"name\"], \"doesn't exist!\")\n \n fam_param = fam_param_tmp % arch_config\n\n tt = table % dict(\n best_val_f1=max_val_f1*100,\n best_num_params=\"{:,}\".format(best_model[\"num_trainable_params\"]),\n avg_training=(df[\"training_took\"] / 60).mean(),\n avg_val_f1=(df[\"best-val:word_level:f1\"]).mean() * 100,\n std_val_f1=(df[\"best-val:word_level:f1\"]).std() * 100,\n name=row[\"name\"],\n lr=best_model[\"lr\"],\n weight_decay=best_model[\"weight_decay\"],\n family_params=fam_param,\n ref=\"last\" if i == len(data)-1 else i\n )\n\n fw.write(f\"{tt} \\n\\n\\n\")" ]
[ [ "pandas.read_csv" ] ]
vengalraoguttha/EGG
[ "e4f8412f197543ec7f1f00cf89b5a364b038dc57" ]
[ "tests/test_agent_wrappers.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\nimport sys\nfrom pathlib import Path\n\nimport torch\nfrom torch.nn import functional as F\n\nimport egg.core as core\n\nsys.path.insert(0, Path(__file__).parent.parent.resolve().as_posix())\n\nBATCH_X = torch.eye(8)\nBATCH_Y = torch.tensor([0, 0, 0, 0, 1, 1, 1, 1]).long()\n\n\nclass Dataset:\n def __iter__(self):\n return iter([(BATCH_X, BATCH_Y)])\n\n\nclass ToyAgent(torch.nn.Module):\n def __init__(self):\n super(ToyAgent, self).__init__()\n self.fc1 = torch.nn.Linear(8, 2, bias=False)\n\n def forward(self, x, _aux_input=None):\n x = self.fc1(x)\n return F.log_softmax(x, dim=1)\n\n\nclass Receiver(torch.nn.Module):\n def __init__(self):\n super(Receiver, self).__init__()\n\n def forward(self, x, _input=None, _aux_input=None):\n return x\n\n\ndef test_toy_agent_gs():\n core.init()\n agent = core.GumbelSoftmaxWrapper(ToyAgent())\n\n agent.eval()\n output = agent(BATCH_X)\n assert output.size() == torch.Size((8, 2))\n assert (output > 0).sum() == 8\n\n agent.train()\n agent.temperature = 10.0\n output = agent(BATCH_X, {})\n assert output.size() == torch.Size((8, 2))\n assert (output > 0).sum() == 16\n\n agent.temperature = 0.5\n\n optimizer = torch.optim.Adam(agent.parameters())\n\n for _ in range(1000):\n optimizer.zero_grad()\n out = agent(BATCH_X, {})\n loss = F.cross_entropy(out, BATCH_Y)\n loss.backward()\n\n optimizer.step()\n\n assert (agent.agent.fc1.weight.t().argmax(dim=1) == BATCH_Y).all()\n\n\ndef test_game_gs():\n core.init()\n sender = core.GumbelSoftmaxWrapper(ToyAgent())\n receiver = Receiver()\n loss = lambda sender_input, message, receiver_input, receiver_output, labels, aux_input: (\n F.cross_entropy(receiver_output, labels),\n {},\n )\n\n game = core.SymbolGameGS(sender, receiver, loss)\n optimizer = torch.optim.Adam(game.parameters())\n\n data = Dataset()\n trainer = core.Trainer(game, optimizer, train_data=data, validation_data=None)\n trainer.train(1000)\n\n assert (sender.agent.fc1.weight.t().argmax(dim=1).cpu() == BATCH_Y).all()\n\n\ndef test_toy_agent_reinforce():\n core.init()\n agent = core.ReinforceWrapper(ToyAgent())\n\n optimizer = torch.optim.Adam(agent.parameters())\n\n for _ in range(1000):\n optimizer.zero_grad()\n output, log_prob, entropy = agent(BATCH_X, {})\n loss = -((output == BATCH_Y).float() * log_prob).mean()\n loss.backward()\n\n optimizer.step()\n\n assert (agent.agent.fc1.weight.t().argmax(dim=1).cpu() == BATCH_Y).all()\n\n\ndef test_game_reinforce():\n core.init()\n sender = core.ReinforceWrapper(ToyAgent())\n receiver = core.ReinforceDeterministicWrapper(Receiver())\n\n loss = lambda sender_input, message, receiver_input, receiver_output, labels, aux_input: (\n -(receiver_output == labels).float(),\n {},\n )\n\n game = core.SymbolGameReinforce(\n sender, receiver, loss, sender_entropy_coeff=1e-1, receiver_entropy_coeff=0.0\n )\n optimizer = torch.optim.Adagrad(game.parameters(), lr=1e-1)\n\n data = Dataset()\n trainer = core.Trainer(game, optimizer, train_data=data, validation_data=None)\n trainer.train(5000)\n\n assert (sender.agent.fc1.weight.t().argmax(dim=1).cpu() == BATCH_Y).all(), str(\n sender.agent.fc1.weight\n )\n\n\ndef test_symbol_wrapper():\n core.init()\n\n receiver = core.SymbolReceiverWrapper(Receiver(), vocab_size=15, agent_input_size=5)\n\n # when trained with REINFORCE, the message would be encoded as long ids\n message_rf = torch.randint(high=15, size=(16,)).long()\n output_rf = receiver(message_rf)\n\n assert output_rf.size() == torch.Size((16, 5))\n\n # when trained with Gumbel-Softmax, the message would be encoded as one-hots\n message_gs = torch.zeros((16, 15))\n message_gs.scatter_(\n 1, message_rf.unsqueeze(1), 1.0\n ) # same message, one-hot-encoded\n output_gs = receiver(message_gs)\n\n assert output_rf.eq(output_gs).all().item() == 1\n" ]
[ [ "torch.Size", "torch.randint", "torch.nn.functional.log_softmax", "torch.zeros", "torch.nn.functional.cross_entropy", "torch.eye", "torch.tensor", "torch.nn.Linear" ] ]
Kyl67899/python-labs
[ "aafc6fc94837ee43c9ef2e1b103d86f80dfc9814" ]
[ "WX272_lab4_thkn.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 14 15:20:21 2020\n\n@author: parsotak\n\"\"\"\n# import datasets\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom netCDF4 import Dataset\nfrom mpl_toolkits.basemap import Basemap\n\n#Define input file\n\ninfile = '/wx/storage/halpea17/wx272/20170909_erai.nc'\n\n#Read in the file\n\nf = Dataset(infile, 'r')\n\n#read in geo height contours at 00z 1000-500mb\n\ngpot_1000mb = f['HGT_GDS0_ISBL'][2, 3, :, :]\n\ngpot_500mb = f['HGT_GDS0_ISBL'][2, 3, :, :]\n\n#Read in lat. and long.\n\nlats = f['g0_lat_1'][:]\n\nlons = f['g0_lon_2'][:]\n\nprint(lats.shape)\n\nprint(lons.shape)\n\n#getting the thickness of the two mb Convert mb to dams\n\nthkns = (gpot_500mb - gpot_1000mb)/ 10 \n\n#Using the heights to find the temps. from 1000-500mb at 12z and convert to C\n\ntempsK = (10 * thkns) / 29.3 * (np.log(1000/500))\n\ntempsC = tempsK - 273.15\n\n#calculate the average temp from 1000 mb to 500 mb\n\n#temp_avg = np.mean()\n\n#from 1D to 2D to plot to a map\n\nlon2d, lat2d = np.meshgrid(lons, lats)\n\n#Define a figure\n\nfig = plt.figure(figsize = (12,8))\n\nax = fig.add_axes([0.1,0.1,0.8,0.8])\n\n#Define basemap \n\nm = Basemap(llcrnrlon = 200., llcrnrlat = 20., urcrnrlon = 320., urcrnrlat = 65., resolution = 'l', projection = 'merc', ax = ax)\n\nxi, yi = m(lon2d, lat2d)\n\nm.drawcoastlines()\n\nm.drawstates()\n\nm.drawcountries()\n\n#lat are 20 N - 65 N every 10 ;lons are 160 W - 40 W every 20.\n\nm.drawparallels(np.arange(-80., 81., 10.), labels = [1, 0, 0, 0], fontsize = 12)\n\nm.drawmeridians(np.arange(0., 359., 20.), labels = [0, 0 ,0, 1], fontsize = 12)\n\n#range of temps avg\n\nrange_tempsavg = np.arange(-30, 21, 5)\n\n#range for the avg contour \n\nrange_contour = np.arange(510, 601, 6)\n\n#contours for temps\n\ncontour_temps1 = m.contourf(xi, yi, tempsC, range_tempsavg) # range_tempsavg is either not being read in and not being averaged \n#not printing contours \n\n#contours for the thinkness\n\ncontour_thkns = m.contour(xi, yi, thkns, range_contour)\n\n#contour thinkness less than equal to 540 blue\n\n\n#contour thinkness greater than 540 red\n\n#Add colorbar for temps \n\ncbar = plt.colorbar(contour_temps1, orientation = 'horizontal', pad = 0.05, shrink = 0.75, ax = ax, ticks = range_tempsavg)\n\n#plot contours from each range with the color to define the differences in thinkness levels\n\n\n#increase size of labels \n\ncbar.ax.tick_params(labelsize = 14)\n\ncbar.set_label('1000-500 mb average temperature ($^{o}$C)', fontsize = 14)\n\n#add a title \n\nax.set_title('1000-500 mb thickness (dam) and average temperature $^{o}$C on 20151107 at 00Z', fontsize = 12)\n\n#save png\n\nplt.savefig(\"parsotak_lab4_thkn.png\")\n\nplt.show()" ]
[ [ "numpy.log", "numpy.arange", "matplotlib.pyplot.savefig", "matplotlib.pyplot.colorbar", "numpy.meshgrid", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
mikhail-tsir/vespa-exloration
[ "9bebc00acb43021fa60c6e144fe4f1fa1d7719fc" ]
[ "text-video-search/src/python/embedding.py" ]
[ "import os\nimport glob\nimport ntpath\nfrom collections import Counter\n\nimport numpy as np\nimport imageio\n\n\nfrom vespa.package import ApplicationPackage, Field, HNSW, RankProfile, QueryTypeField\nfrom vespa.application import Vespa\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision.transforms import ToPILImage\nimport clip\nfrom tenacity import retry, wait_exponential, stop_after_attempt\n\n\ndef translate_model_names_to_valid_vespa_field_names(model_name):\n return model_name.replace(\"/\", \"_\").replace(\"-\", \"_\").lower()\n\n\ndef sample_images(images, number_to_sample):\n \"\"\"\n Sample equally spaced frames from a list of image frames\n\n :param images: a list of image frames.\n :param number_to_sample: int representing the number os frames to sample.\n\n :return: a numpy array containing the sample of frames.\n \"\"\"\n if number_to_sample < len(images):\n idx = np.round(np.linspace(0, len(images) - 1, number_to_sample)).astype(int)\n return np.array(images)[idx]\n else:\n return np.array(images)\n\n\ndef extract_images(video_path, number_frames):\n \"\"\"\n Extract equally spaced frames from a video.\n\n :param video_path: Full .mp4 video path.\n :param number_frames: Number of frames to sample.\n\n :return: a numpy array containing the sample of frames.\n \"\"\"\n reader = imageio.get_reader(video_path, fps=1)\n frames = []\n for i, im in enumerate(reader):\n frames.append(im)\n return sample_images(frames, number_frames)\n\n\nclass VideoFeedDataset(Dataset):\n def __init__(self, video_dir, model_name, number_frames_per_video):\n \"\"\"\n PyTorch Dataset to compute video embeddings and return pyvespa-compatible feed data.\n\n :param video_dir: Folder containing .mp4 video files.\n :param model_name: CLIP model name.\n :param number_frames_per_video: Number of embeddings per video.\n \"\"\"\n self.video_dir = video_dir\n self.number_frames_per_video = number_frames_per_video\n valid_vespa_model_name = translate_model_names_to_valid_vespa_field_names(\n model_name\n )\n self.from_tensor_to_PIL = ToPILImage()\n self.model, self.preprocess = clip.load(model_name)\n self.video_file_names = glob.glob(os.path.join(video_dir, \"*.mp4\"))\n self.image_embedding_name = valid_vespa_model_name + \"_image\"\n\n def _from_image_to_vector(self, x):\n \"\"\"\n From image to embedding.\n\n :param x: PIL images\n :return: normalized image embeddings.\n \"\"\"\n with torch.no_grad():\n image_features = self.model.encode_image(\n self.preprocess(x).unsqueeze(0)\n ).float()\n image_features /= image_features.norm(dim=-1, keepdim=True)\n return image_features\n\n def __len__(self):\n return len(self.video_file_names)\n\n def __getitem__(self, idx):\n video_file_name = self.video_file_names[idx]\n images = extract_images(\n video_path=video_file_name, number_frames=self.number_frames_per_video\n )\n pil_images = [self.from_tensor_to_PIL(x) for x in images]\n frames = []\n for idx, image in enumerate(pil_images):\n image = self._from_image_to_vector(image)\n video_base_name = ntpath.basename(video_file_name)\n frames.append(\n {\n \"id\": video_base_name.split(\".mp4\")[0] + \"_{}\".format(idx),\n \"fields\": {\n \"video_file_name\": video_base_name,\n self.image_embedding_name: {\"values\": image.tolist()[0]},\n },\n \"create\": True,\n }\n )\n return frames\n\n\n@retry(wait=wait_exponential(multiplier=1), stop=stop_after_attempt(3))\ndef send_video_embeddings(app, batch):\n \"\"\"\n Send pyvespa-compatible batch to Vespa app.\n\n :param app: pyvespa connection to a Vespa instance\n :param batch: pyvespa-compatible list of data points to be updated.\n :return: None\n \"\"\"\n responses = app.update_batch(batch=batch)\n status_code_summary = Counter([x.status_code for x in responses])\n if status_code_summary[200] != len(batch):\n print([response.json for response in responses if response.status_code != 200])\n raise ValueError(\"Failed to send data.\")\n print(\"Successfully sent {} data points.\".format(status_code_summary[200]))\n\n\ndef compute_and_send_video_embeddings(\n app, batch_size, clip_model_names, number_frames_per_video, video_dir, num_workers=0\n):\n \"\"\"\n Loop through video folder, compute embeddings and send to Vespa app.\n\n :param app: pyvespa connection to a Vespa instance\n :param batch_size: Number of images to process per iteration.\n :param clip_model_names: CLIP models names. It will generate one image embedding per model name.\n :param number_frames_per_video: Number of frames to use per video.\n :param video_dir: Complete path of the folder containing .mp4 video files.\n :param num_workers: Number of workers to use (refers to the DataLoader parallelization)\n :return: None\n \"\"\"\n for model_name in clip_model_names:\n video_dataset = VideoFeedDataset(\n video_dir=video_dir, # Folder containing image files\n model_name=model_name, # CLIP model name used to convert image into vector\n number_frames_per_video=number_frames_per_video,\n )\n dataloader = DataLoader(\n video_dataset,\n batch_size=batch_size,\n shuffle=False,\n collate_fn=lambda x: [item for sublist in x for item in sublist],\n num_workers=num_workers,\n )\n for idx, batch in enumerate(dataloader):\n print(\n \"Model name: {}. Iteration: {}/{}\".format(\n model_name, idx, len(dataloader)\n )\n )\n send_video_embeddings(app=app, batch=batch)\n\n\nclass TextProcessor(object):\n def __init__(self, model_name):\n \"\"\"\n Python-based text processor.\n\n :param model_name: CLIP model name to use embedding text.\n \"\"\"\n self.model, _ = clip.load(model_name)\n self.model_name = model_name\n\n def embed(self, text):\n \"\"\"\n Convert text to (normalized) embedding\n\n :param text: a string to be embedded.\n :return: Normalized embedding vector.\n \"\"\"\n text_tokens = clip.tokenize(text)\n with torch.no_grad():\n text_features = self.model.encode_text(text_tokens).float()\n text_features /= text_features.norm(dim=-1, keepdim=True)\n return text_features.tolist()[0]\n\n\ndef create_text_video_app(model_info):\n \"\"\"\n Create text to video search app based on a variety of CLIP models\n\n :param model_info: dict containing model names as keys and embedding size as values.\n Check `clip.available_models()` to check which models are available.\n\n :return: A Vespa application package.\n \"\"\"\n app_package = ApplicationPackage(name=\"video_search\")\n\n app_package.schema.add_fields(\n Field(name=\"video_file_name\", type=\"string\", indexing=[\"summary\", \"attribute\"]),\n )\n for model_name, embedding_size in model_info.items():\n model_name = translate_model_names_to_valid_vespa_field_names(model_name)\n app_package.schema.add_fields(\n Field(\n name=model_name + \"_image\",\n type=\"tensor<float>(x[{}])\".format(embedding_size),\n indexing=[\"attribute\", \"index\"],\n ann=HNSW(\n distance_metric=\"euclidean\",\n max_links_per_node=16,\n neighbors_to_explore_at_insert=500,\n ),\n )\n )\n app_package.schema.add_rank_profile(\n RankProfile(\n name=model_name + \"_similarity\",\n inherits=\"default\",\n first_phase=\"closeness({})\".format(model_name + \"_image\"),\n )\n )\n app_package.query_profile_type.add_fields(\n QueryTypeField(\n name=\"ranking.features.query({})\".format(model_name + \"_text\"),\n type=\"tensor<float>(x[{}])\".format(embedding_size),\n )\n )\n return app_package\n\n\ndef create_vespa_query(query, text_processor, number_videos):\n \"\"\"\n Create the body of a Vespa query.\n\n :param query: a string representing the query.\n :param text_processor: an instance of `TextProcessor` to convert string to embedding.\n :param number_videos: Number of videos to return.\n :return: body of a Vespa query request.\n \"\"\"\n valid_vespa_model_name = translate_model_names_to_valid_vespa_field_names(\n text_processor.model_name\n )\n image_field_name = valid_vespa_model_name + \"_image\"\n text_field_name = valid_vespa_model_name + \"_text\"\n ranking_name = valid_vespa_model_name + \"_similarity\"\n\n return {\n \"yql\": 'select * from sources * where ({{\"targetNumHits\":100}}nearestNeighbor({},{})) | all(group(video_file_name) max({}) order(-max(relevance())) each( max(1) each(output(summary())) as(frame)) as(video))'.format(\n image_field_name, text_field_name, number_videos\n ),\n \"hits\": 0,\n \"ranking.features.query({})\".format(text_field_name): text_processor.embed(\n query\n ),\n \"ranking.profile\": ranking_name,\n \"timeout\": 10,\n }\n\n\ndef search_video_file_names(app, query, text_processor, number_videos):\n \"\"\"\n Parse the output of the Vespa query.\n\n Parse the output of the Vespa query to return a list with the video file name and\n relevance score for each hit.\n\n :param app: The pyvespa Vespa connection to the app.\n :param query: The text query to be sent.\n :param text_processor: An instance of the TextProcessor to turn text into embedding.\n :param number_videos: The number of videos to be retrieved.\n :return: a list with the video file name and relevance score for each hit.\n \"\"\"\n\n result = app.query(\n body=create_vespa_query(\n query=query, text_processor=text_processor, number_videos=number_videos\n )\n )\n parsed_results = [\n {\n \"video_file_name\": video[\"children\"][0][\"children\"][0][\"fields\"][\n \"video_file_name\"\n ],\n \"relevance\": video[\"children\"][0][\"children\"][0][\"relevance\"],\n }\n for video in result.json[\"root\"][\"children\"][0][\"children\"][0][\"children\"]\n ]\n return parsed_results\n\n\nclass VideoSearchApp(object):\n def __init__(self, app: Vespa, clip_model_name=None, text_processor=None):\n \"\"\"\n Video search app with custom query for video retrieval.\n\n :param app: The pyvespa Vespa connection to the app.\n :param clip_model_name: CLIP model name to turn text into embedding\n :param text_processor: TextProcessor instance. `clip_model_name` will\n be ignored if an instance is provided.\n \"\"\"\n if text_processor:\n self.text_processor = text_processor\n elif clip_model_name:\n self.text_processor = TextProcessor(clip_model_name)\n else:\n ValueError(\"Provide a clip_model_name or an instance of TextProcessor\")\n self.app = app\n\n def query(self, text, number_videos):\n \"\"\"\n Video search\n\n :param text: Text query describing an action.\n :param number_videos: Number of videos to retrieve.\n :return: a list with the video file name and relevance score for each hit.\n \"\"\"\n return search_video_file_names(\n app=self.app,\n query=text,\n text_processor=self.text_processor,\n number_videos=number_videos,\n )\n" ]
[ [ "torch.no_grad", "numpy.array", "torch.utils.data.DataLoader" ] ]
youngmit/armi
[ "67688e4e67d2a217dfc7b1ccfa64028c20b57a5b" ]
[ "armi/nuclearDataIO/xsCollections.py" ]
[ "# Copyright 2019 TerraPower, LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nCross section collections contain cross sections for a single nuclide or region.\n\nSpecifically, they are used as attributes of :py:class:`~armi.nuclearDataIO.xsNuclides.XSNuclide`, which\nthen are combined as a :py:class:`~armi.nuclearDataIO.xsLibraries.XSLibrary`.\n\nThese may represent microscopic or macroscopic neutron or photon cross sections. When they are macroscopic,\nthey generally represent a whole region with many nuclides, though this is not required.\n\nSee Also\n--------\narmi.nuclearDataIO.xsCollection.XSCollection : object that gets created.\n\nExamples\n--------\n# creating a MicroscopicXSCollection by loading one from ISOTXS.\nmicroLib = armi.nuclearDataIO.ISOTXS('ISOTXS')\nmicros = myLib.nuclides['U235AA'].micros\n\n# creating macroscopic XS:\nmc = MacroscopicCrossSectionCreator()\nmacroCollection = mc.createMacrosFromMicros(microLib, block)\nblocksWithMacros = mc.createMacrosOnBlocklist(microLib, blocks)\n\n\"\"\"\nimport numpy\nfrom scipy import sparse\n\nfrom armi import runLog\nfrom armi.localization import exceptions\nfrom armi.utils import properties\nfrom armi.utils import units\n\n# Basic cross-section types that are represented by a 1-D vector in the multigroup approximation\n# No one is particularly proud of these names...we can claim\n# they have some origin in the ISOTXS file format card 04 definition\n# fmt: off\nNGAMMA = \"nGamma\" # radiative capture\nNAPLHA = \"nalph\" # (n, alpha)\nNP = \"np\" # (n, proton)\nND = \"nd\" # (n, deuteron)\nNT = \"nt\" # (n, triton)\nFISSION_XS = \"fission\" # (n, fission)\nN2N_XS = \"n2n\" # (n,2n)\nNUSIGF = \"nuSigF\" \nNU = \"neutronsPerFission\"\n# fmt: on\nCAPTURE_XS = [NGAMMA, NAPLHA, NP, ND, NT]\n\n# Cross section types that are represented by 2-D matrices in the multigroup approximation\nBASIC_SCAT_MATRIX = [\"elasticScatter\", \"inelasticScatter\", \"n2nScatter\"]\nOTHER_SCAT_MATRIX = [\"totalScatter\", \"elasticScatter1stOrder\"]\nHIGHORDER_SCATTER = \"higherOrderScatter\"\n\n# Subset of vector xs used to evaluate absorption cross-section\nABSORPTION_XS = CAPTURE_XS + [FISSION_XS, N2N_XS]\n\n# Subset of vector xs evaluated by _convertBasicXS\nBASIC_XS = ABSORPTION_XS + [NUSIGF]\n\n# Subset vector xs that are derived from basic cross sections\nDERIVED_XS = [\"absorption\", \"removal\"]\n\n# Total and transport are treated differently since they are 2D (can have multiple moments)\nTOTAL_XS = [\"total\", \"transport\"]\n\n# Subset of all basic cross sections that include removal and scattering\nALL_XS = BASIC_XS + BASIC_SCAT_MATRIX + OTHER_SCAT_MATRIX + DERIVED_XS + TOTAL_XS\n\n# All xs collection data\nALL_COLLECTION_DATA = ALL_XS + [\n \"chi\",\n NU,\n \"strpd\",\n HIGHORDER_SCATTER,\n \"diffusionConstants\",\n]\n\nE_CAPTURE = \"ecapt\"\nE_FISSION = \"efiss\"\n\n\nclass XSCollection(object):\n \"\"\"A cross section collection.\"\"\"\n\n _zeroes = {}\n \"\"\"\n A dict of numpy arrays set to the size of XSLibrary.numGroups.\n\n This is used to initialize cross sections which may not exist for the specific nuclide.\n Consequently, there should never be a situation where a cross section does not exist.\n In addition, they are all pointers to the same array, so we're not generating too much\n unnecessary data.\n\n Notes\n -----\n This is a dict so that it can store multiple 0_g \"matricies\", i.e. vectors. Realistically,\n during any given run there will only be a set of groups, e.g. 33.\n \"\"\"\n\n @classmethod\n def getDefaultXs(cls, numGroups):\n default = cls._zeroes.get(numGroups, None)\n if default is None:\n default = numpy.zeros(numGroups)\n cls._zeroes[numGroups] = default\n return default\n\n def __init__(self, parent):\n \"\"\"\n Construct a NuclideCollection.\n \n Parameters\n ----------\n parent : object\n The parent container, which may be a region, a nuclide, a block, etc.\n \"\"\"\n self.numGroups = None\n self.transport = None\n self.total = None\n self.nGamma = None\n self.fission = None\n self.neutronsPerFission = None\n self.chi = None\n self.nalph = None\n self.np = None\n self.n2n = None\n self.nd = None\n self.nt = None\n self.strpd = None\n self.elasticScatter = None\n self.inelasticScatter = None\n self.n2nScatter = None\n self.elasticScatter1stOrder = None\n self.totalScatter = None\n self.absorption = None\n self.diffusionConstants = None\n self.removal = None\n self.nuSigF = None\n self.higherOrderScatter = {}\n self.source = \"{}\".format(parent)\n\n def __getitem__(self, key):\n \"\"\"\n Access cross sections by key string (e.g. micros['fission'] = micros.fission.\n \n Notes\n -----\n These containers were originally\n dicts, but upgraded to objects with numpy values as specialization\n was needed. This access method could/should be phased out.\n \"\"\"\n return self.__dict__[key]\n\n def __setitem__(self, key, value):\n self.__dict__[key] = value\n\n def get(self, key, default):\n try:\n return self[key]\n except (IndexError, KeyError, TypeError):\n return default\n\n def getAbsorptionXS(self):\n \"\"\"Return total absorption XS, which is the sum of capture + fission + others.\"\"\"\n absXS = [\n self.nGamma,\n self.fission,\n self.nalph,\n self.np,\n self.nd,\n self.nt,\n self.n2n,\n ]\n return absXS\n\n def getTotalScatterMatrix(self):\n \"\"\"\n Sum up scatter matrices to produce total scatter matrix.\n\n Multiply reaction-based n2n scatter matrix by 2.0 to convert to production-based.\n\n .. warning:: Not all lattice codes store (n,2n) matrices consistently. Some are \n production-based and some are absorption-based. If you use an\n absorption-based one, your scatter matrix will be off, generally\n leading to about a percent error in your neutron balance.\n\n Notes\n -----\n The total scattering matrix is produced by summing the elastic, inelastic, and n2n scattering matrices. If a\n specific scattering matrix does not exist for a composition (nuclide or region) then it is skipped and a\n warning is displayed stating that the scattering reaction is not available and is not included in the total\n scattering matrix.\n\n Example: When producing macroscopic cross sections in MC2-3 the code internally merges the elastic and\n inelastic scattering matrices into a single elastic scattering matrix.\n \"\"\"\n scatters = []\n totalScatterComponents = {\n \"elastic\": self.elasticScatter,\n \"inelastic\": self.inelasticScatter,\n \"n2n\": self.n2nScatter * 2.0,\n }\n for sType, sMatrix in totalScatterComponents.items():\n if sMatrix is not None:\n scatters.append(sMatrix)\n else:\n runLog.warning(\n \"{} scattering matrix in {} is not defined. Generating total scattering matrix\"\n \" without this data\".format(sType.title(), self),\n single=True,\n )\n return sum(scatters)\n\n def clear(self):\n \"\"\"Zero out all the cross sections; this is useful for creating dummy cross sections.\"\"\"\n for xsAttr in ALL_XS:\n value = getattr(self, xsAttr)\n # it should either be a list, a numpy array, or a sparse matrix\n if isinstance(value, list):\n value = [0.0] * len(value)\n elif isinstance(value, numpy.ndarray):\n value = numpy.zeros(value.shape)\n elif value is None: # assume it is scipy.sparse\n pass\n elif value.nnz >= 0:\n value = sparse.csr_matrix(value.shape)\n setattr(self, xsAttr, value)\n # need to do the same thing for the higherOrderScatter\n for kk, currentMatrix in self.higherOrderScatter.items():\n self.higherOrderScatter[kk] = sparse.csr_matrix(currentMatrix.shape)\n\n @staticmethod\n def collapseCrossSection(crossSection, weights):\n r\"\"\"\n Collapse a cross section into 1-group.\n\n This is extremely useful for many analyses such as doing a shielding efficacy survey\n or computing one-group reaction rates.\n\n .. math::\n \n \\bar{\\sigma} = \\frac{\\sum_g{\\sigma_g \\phi_g}}{\\sum_g{\\phi_g}}\n\n Parameters\n ----------\n crossSection : list\n Multigroup cross section values\n weights : list\n energy group weights to apply (usually the multigroup flux)\n\n Returns\n -------\n oneGroupXS : float\n The one group cross section in the same units as the input cross section.\n \"\"\"\n mult = numpy.array(crossSection) * numpy.array(weights)\n return sum(mult) / sum(weights)\n\n def compare(self, other, flux, relativeTolerance=0, verbose=False):\n \"\"\"Compare the cross sections between two XSCollections objects.\"\"\"\n equal = True\n for xsName in ALL_COLLECTION_DATA:\n\n myXsData = self.__dict__[xsName]\n theirXsData = other.__dict__[xsName]\n\n if xsName == HIGHORDER_SCATTER:\n for actualList, expectedList in zip(myXsData, theirXsData):\n if actualList != expectedList:\n equal = False\n runLog.important(\n \" {} {:<30} cross section is different.\".format(\n self.source, xsName\n )\n )\n\n elif sparse.issparse(myXsData) and sparse.issparse(theirXsData):\n if not numpy.allclose(\n myXsData.todense(),\n theirXsData.todense(),\n rtol=relativeTolerance,\n atol=0.0,\n ):\n verboseData = (\n \"\"\n if not verbose\n else \"\\n{},\\n\\n{}\".format(myXsData, theirXsData)\n )\n runLog.important(\n \" {} {:<30} cross section is different.{}\".format(\n self.source, xsName, verboseData\n )\n )\n equal = False\n elif isinstance(myXsData, dict) and myXsData != theirXsData:\n # there are no dicts currently so code is untested\n raise NotImplementedError(\"there are no dicts\")\n elif not properties.areEqual(myXsData, theirXsData, relativeTolerance):\n verboseData = (\n \"\" if not verbose else \"\\n{},\\n\\n{}\".format(myXsData, theirXsData)\n )\n runLog.important(\n \" {} {:<30} cross section is different.{}\".format(\n self.source, xsName, verboseData\n )\n )\n equal = False\n return equal\n\n def merge(self, other):\n \"\"\"\n Merge the cross sections of two collections.\n\n Notes\n -----\n 1. This can only merge if one hasn't been assigned at all, because it doesn't try to figure out how to\n account for overlapping cross sections.\n 2. Update the current library (self) with values from the other library if all attributes in the library except\n ones in `attributesToIgnore` are None.\n 3. Libraries are already merged if all attributes in the other library are None (This is nothing to merge!).\n \"\"\"\n attributesToIgnore = [\"source\", HIGHORDER_SCATTER]\n if all(\n v is None for k, v in self.__dict__.items() if k not in attributesToIgnore\n ):\n self.__dict__.update(other.__dict__) # See note 2\n elif all(\n v is None for k, v in other.__dict__.items() if k not in attributesToIgnore\n ):\n pass # See note 3\n else:\n overlappingAttrs = set(\n k for k, v in self.__dict__.items() if v is not None and k != \"source\"\n )\n overlappingAttrs &= set(\n k for k, v in other.__dict__.items() if v is not None and k != \"source\"\n )\n raise exceptions.XSLibraryError(\n \"Cannot merge {} and {}.\\n Cross sections overlap in \"\n \"attributes: {}.\".format(\n self.source, other.source, \", \".join(overlappingAttrs)\n )\n )\n raise exceptions.XSLibraryError(\n \"Cannot merge from and from \\n Cross sections overlap in \"\n \"attributes:.\"\n )\n\n\nclass MacroscopicCrossSectionCreator(object):\n \"\"\"\n Create macroscopic cross sections from micros and number density.\n\n Object encapsulating all high-level methods related to the creation of\n macroscopic cross sections.\n \"\"\"\n\n def __init__(self, buildScatterMatrix=True, buildOnlyCoolant=False):\n self.densities = None\n self.macros = None\n self.micros = None\n self.buildScatterMatrix = buildScatterMatrix\n self.buildOnlyCoolant = (\n buildOnlyCoolant # TODO: this is not implemented yet. is it needed?\n )\n self.block = None\n\n def createMacrosOnBlocklist(\n self, microLibrary, blockList, nucNames=None, libType=\"micros\"\n ):\n for block in blockList:\n block.macros = self.createMacrosFromMicros(\n microLibrary, block, nucNames, libType=libType\n )\n return blockList\n\n def createMacrosFromMicros(\n self, microLibrary, block, nucNames=None, libType=\"micros\"\n ):\n \"\"\"\n Creates a macroscopic cross section set based on a microscopic XS library using a block object\n\n Micro libraries have lots of nuclides, but macros only have 1.\n\n Parameters\n ----------\n microLibrary : xsCollection.XSCollection\n Input micros\n\n block : Block\n Object whos number densities should be used to generate macros\n\n nucNames : list, optional\n List of nuclides to include in the macros. Defaults to all in block.\n\n libType : str, optional\n The block attribute containing the desired microscopic XS for this block:\n either \"micros\" for neutron XS or \"gammaXS\" for gamma XS.\n\n Returns\n -------\n macros : xsCollection.XSCollection\n A new XSCollection full of macroscopic cross sections\n\n \"\"\"\n runLog.debug(\"Building macroscopic cross sections for {0}\".format(block))\n if nucNames is None:\n nucNames = block.getNuclides()\n\n self.microLibrary = microLibrary\n self.block = block\n self.xsSuffix = block.getMicroSuffix()\n self.macros = XSCollection(parent=block)\n self.densities = dict(zip(nucNames, block.getNuclideNumberDensities(nucNames)))\n self.ng = getattr(self.microLibrary, \"numGroups\" + _getLibTypeSuffix(libType))\n\n self._initializeMacros()\n self._convertBasicXS(libType=libType)\n self._computeAbsorptionXS()\n self._convertScatterMatrices(libType=libType)\n self._computeDiffusionConstants()\n self._buildTotalScatterMatrix()\n self._computeRemovalXS()\n self.macros.chi = computeBlockAverageChi(\n b=self.block, isotxsLib=self.microLibrary\n )\n\n return self.macros\n\n def _initializeMacros(self):\n m = self.macros\n for xsName in BASIC_XS + DERIVED_XS:\n setattr(m, xsName, numpy.zeros(self.ng))\n\n for matrixName in BASIC_SCAT_MATRIX:\n # lil_matrices are good for indexing but bad for certain math operations.\n # use csr for faster math\n setattr(m, matrixName, sparse.csr_matrix((self.ng, self.ng)))\n\n def _convertBasicXS(self, libType=\"micros\"):\n \"\"\"\n Converts basic XS such as fission, nGamma, etc.\n\n Parameters\n ----------\n libType : str, optional\n The block attribute containing the desired microscopic XS for this block:\n either \"micros\" for neutron XS or \"gammaXS\" for gamma XS.\n \"\"\"\n reactions = BASIC_XS + TOTAL_XS\n if NUSIGF in reactions:\n reactions.remove(NUSIGF)\n self.macros[NUSIGF] = computeMacroscopicGroupConstants(\n FISSION_XS,\n self.densities,\n self.microLibrary,\n self.xsSuffix,\n libType=libType,\n multConstant=NU,\n )\n\n for reaction in reactions:\n self.macros[reaction] = computeMacroscopicGroupConstants(\n reaction,\n self.densities,\n self.microLibrary,\n self.xsSuffix,\n libType=libType,\n )\n\n def _convertScatterMatrices(self, libType=\"micros\"):\n \"\"\"\n Build macroscopic scatter matrices.\n\n Parameters\n ----------\n libType : str, optional\n The block attribute containing the desired microscopic XS for this block:\n either \"micros\" for neutron XS or \"gammaXS\" for gamma XS.\n \"\"\"\n\n if not self.buildScatterMatrix:\n return\n\n for nuclide in self.microLibrary.getNuclides(self.xsSuffix):\n microCollection = getattr(nuclide, libType)\n nDens = self.densities.get(nuclide.name, 0.0)\n if microCollection.elasticScatter is not None:\n self.macros.elasticScatter += microCollection.elasticScatter * nDens\n if microCollection.inelasticScatter is not None:\n self.macros.inelasticScatter += microCollection.inelasticScatter * nDens\n if microCollection.n2nScatter is not None:\n self.macros.n2nScatter += microCollection.n2nScatter * nDens\n\n def _computeAbsorptionXS(self):\n \"\"\"\n Absorption = sum of all absorption reactions.\n\n Must be called after :py:meth:`_convertBasicXS`.\n \"\"\"\n for absXS in self.macros.getAbsorptionXS():\n self.macros.absorption += absXS\n\n def _computeDiffusionConstants(self):\n self.macros.diffusionConstants = 1.0 / (3.0 * self.macros.transport)\n\n def _buildTotalScatterMatrix(self):\n self.macros.totalScatter = self.macros.getTotalScatterMatrix()\n\n def _computeRemovalXS(self):\n \"\"\"\n Compute removal cross section (things that remove a neutron from this phase space)\n\n This includes all absorptions and outscattering.\n Outscattering is represented by columns of the total scatter matrix.\n Self-scattering (e.g. when g' == g) is not be included. This can be\n handled by summing the columns and then subtracting the diagonal.\n\n within-group n2n is accounted for by simply not including n2n in the removal xs.\n \"\"\"\n self.macros.removal = self.macros.absorption - self.macros.n2n\n # columnSum = self.macros.totalScatter.columnSum(self.ng) # convert to ndarray\n columnSum = self.macros.totalScatter.sum(axis=0).getA1() # convert to ndarray\n # diags = self.macros.totalScatter.diagonal(self.ng)\n diags = self.macros.totalScatter.diagonal()\n self.macros.removal += columnSum - diags\n\n\ndef computeBlockAverageChi(b, isotxsLib):\n r\"\"\"\n Return the block average total chi vector based on isotope chi vectors.\n \n This is defined by eq 3.4b in DIF3D manual [DIF3D]_, which corresponds to 1 in A.HMG4C card.\n\n .. math::\n \n \n \\chi_g = \\frac{\\sum_{n} \\chi_{g,n} N_n V \\sum_{g'}(\\nu_{g'}*\\sigma_{f,g'})}{\\sum_n N_n V \\sum_{g'}(\\nu_{g'}*\\sigma_{f,g'} )}\n \n\n To evaluate efficiently, assume that if :math:`\\chi_{g,n}=0`, there will be no contributions\n\n Volume is not used b/c it is already homogenized in the block.\n \n Parameters\n ----------\n b : object\n Block object\n \n isotxsLib : object\n ISOTXS library object\n \n Notes\n -----\n This methodology is based on option 1 in the HMG4C utility (named total \n fission source weighting).\n \"\"\"\n numGroups = isotxsLib.numGroups\n numerator = numpy.zeros(numGroups)\n denominator = 0.0\n numberDensities = b.getNumberDensities()\n for nucObj in isotxsLib.getNuclides(b.getMicroSuffix()):\n nucMicroXS = nucObj.micros\n nucNDens = numberDensities.get(nucObj.name, 0.0)\n nuFissionTotal = sum(nucMicroXS.neutronsPerFission * nucMicroXS.fission)\n numerator += nucMicroXS.chi * nucNDens * nuFissionTotal\n denominator += nucNDens * nuFissionTotal\n if denominator != 0.0:\n return numerator / denominator\n else:\n return numpy.zeros(numGroups)\n\n\ndef _getLibTypeSuffix(libType):\n if libType == \"micros\":\n libTypeSuffix = \"\"\n elif libType == \"gammaXS\":\n libTypeSuffix = \"Gamma\"\n else:\n libTypeSuffix = None\n runLog.warning(\n \"ARMI currently supports only micro XS libraries of types \"\n '\"micros\" (neutron) and \"gammaXS\" (gamma).'\n )\n\n return libTypeSuffix\n\n\ndef computeNeutronEnergyDepositionConstants(numberDensities, lib, microSuffix):\n \"\"\"\n Compute the macroscopic neutron energy deposition group constants.\n\n These group constants can be multiplied by the flux to obtain energy deposition rates.\n\n Parameters\n ----------\n numberDensities : dict\n nucName keys, number density values (atoms/bn-cm) of all nuclides in the composite for which\n the macroscopic group constants are computed. See composite `getNuclideNumberDensities` method.\n\n lib : library object\n Microscopic cross section library.\n\n microSuffix : str\n Microscopic library suffix (e.g. 'AB') for this composite.\n See composite `getMicroSuffix` method.\n\n Returns\n -------\n energyDepositionConsts : numpy array\n Neutron energy deposition group constants. (J/cm)\n\n Notes\n -----\n PMATRX documentation says units will be eV/s when multiplied by flux but it's eV/s/cm^3.\n (eV/s/cm^3 = eV-bn * 1/cm^2/s * 1/bn-cm.)\n\n Converted here to obtain J/cm (eV-bn * 1/bn-cm * J / eV)\n \"\"\"\n return (\n computeMacroscopicGroupConstants(\n \"neutronHeating\", numberDensities, lib, microSuffix\n )\n * units.JOULES_PER_eV\n )\n\n\ndef computeGammaEnergyDepositionConstants(numberDensities, lib, microSuffix):\n \"\"\"\n Compute the macroscopic gamma energy deposition group constants.\n\n These group constants can be multiplied by the flux to obtain energy deposition rates.\n\n Parameters\n ----------\n numberDensities : dict\n nucName keys, number density values (atoms/bn-cm) of all nuclides in the composite for which\n the macroscopic group constants are computed. See composite `getNuclideNumberDensities` method.\n\n lib : library object\n Microscopic cross section library.\n\n microSuffix : str\n Microscopic library suffix (e.g. 'AB') for this composite.\n See composite `getMicroSuffix` method.\n\n Returns\n -------\n energyDepositionConsts : numpy array\n gamma energy deposition group constants. (J/cm)\n\n Notes\n -----\n PMATRX documentation says units will be eV/s when multiplied by flux but it's eV/s/cm^3.\n (eV/s/cm^3 = eV-bn * 1/cm^2/s * 1/bn-cm.)\n\n Convert here to obtain J/cm (eV-bn * 1/bn-cm * J / eV)\n \"\"\"\n return (\n computeMacroscopicGroupConstants(\n \"gammaHeating\", numberDensities, lib, microSuffix\n )\n * units.JOULES_PER_eV\n )\n\n\ndef computeFissionEnergyGenerationConstants(numberDensities, lib, microSuffix):\n r\"\"\"\n Get the fission energy generation group constant of a block\n\n .. math::\n\n E_{generation_fission} = \\kappa_f \\Sigma_f\n\n Power comes from fission and capture reactions.\n\n Parameters\n ----------\n numberDensities : dict\n nucName keys, number density values (atoms/bn-cm) of all nuclides in the composite for which\n the macroscopic group constants are computed. See composite `getNuclideNumberDensities` method.\n\n lib : library object\n Microscopic cross section library.\n\n microSuffix : str\n Microscopic library suffix (e.g. 'AB') for this composite.\n See composite `getMicroSuffix` method.\n\n Returns\n -------\n fissionEnergyFactor: numpy.array\n Fission energy generation group constants (in Joules/cm)\n \"\"\"\n fissionEnergyFactor = computeMacroscopicGroupConstants(\n FISSION_XS,\n numberDensities,\n lib,\n microSuffix,\n libType=\"micros\",\n multConstant=E_FISSION,\n )\n\n return fissionEnergyFactor\n\n\ndef computeCaptureEnergyGenerationConstants(numberDensities, lib, microSuffix):\n r\"\"\"\n Get the energy generation group constant of a block\n\n .. math::\n\n E_{generation capture} = \\kappa_c \\Sigma_c\n\n\n Typically, one only cares about the flux* this XS (to find total power),\n but the XS itself is required in some sensitivity studies.\n\n Power comes from fission and capture reactions.\n\n Parameters\n ----------\n numberDensities : dict\n nucName keys, number density values (atoms/bn-cm) of all nuclides in the composite for which\n the macroscopic group constants are computed. See composite `getNumberDensities` method.\n\n lib : library object\n Microscopic cross section library.\n\n microSuffix : str\n Microscopic library suffix (e.g. 'AB') for this composite.\n See composite `getMicroSuffix` method.\n\n Returns\n -------\n captureEnergyFactor: numpy.array\n Capture energy generation group constants (in Joules/cm)\n \"\"\"\n captureEnergyFactor = None\n for xs in CAPTURE_XS:\n if captureEnergyFactor is None:\n captureEnergyFactor = numpy.zeros(\n numpy.shape(\n computeMacroscopicGroupConstants(\n xs, numberDensities, lib, microSuffix, libType=\"micros\"\n )\n )\n )\n\n captureEnergyFactor += computeMacroscopicGroupConstants(\n xs,\n numberDensities,\n lib,\n microSuffix,\n libType=\"micros\",\n multConstant=E_CAPTURE,\n )\n\n return captureEnergyFactor\n\n\ndef computeMacroscopicGroupConstants(\n constantName,\n numberDensities,\n lib,\n microSuffix,\n libType=None,\n multConstant=None,\n multLib=None,\n):\n \"\"\"\n Compute any macroscopic group constants given number densities and a microscopic library.\n\n Parameters\n ----------\n constantName : str\n Name of the reaction for which to obtain the group constants. This name should match a\n cross section name or an attribute in the collection.\n\n numberDensities : dict\n nucName keys, number density values (atoms/bn-cm) of all nuclides in the composite for which\n the macroscopic group constants are computed. See composite `getNuclideNumberDensities` method.\n\n lib : library object\n Microscopic cross section library.\n\n microSuffix : str\n Microscopic library suffix (e.g. 'AB') for this composite.\n See composite `getMicroSuffix` method.\n\n libType : str, optional\n The block attribute containing the desired microscopic XS for this block:\n either \"micros\" for neutron XS or \"gammaXS\" for gamma XS.\n\n multConstant : str, optional\n Name of constant by which the group constants will be multiplied. This name should match a\n cross section name or an attribute in the collection.\n\n multLib : library object, optional\n Microscopic cross section nuclide library to obtain the multiplier from.\n If None, same library as base cross section is used.\n\n Returns\n -------\n macroGroupConstant : numpy array\n Macroscopic group constants for the requested reaction.\n \"\"\"\n skippedNuclides = []\n skippedMultNuclides = []\n macroGroupConstants = None\n\n # sort the numberDensities because a summation is being performed that may result in slight\n # differences based on the order.\n for nuclideName, numberDensity in sorted(numberDensities.items()):\n try:\n libNuclide = lib.getNuclide(nuclideName, microSuffix)\n multLibNuclide = libNuclide\n except KeyError:\n skippedNuclides.append(nuclideName) # Nuclide does not exist in the library\n continue\n\n if multLib:\n try:\n multLibNuclide = multLib.getNuclide(nuclideName, microSuffix)\n except KeyError:\n skippedMultNuclides.append(\n nuclideName\n ) # Nuclide does not exist in the library\n continue\n\n microGroupConstants = _getMicroGroupConstants(\n libNuclide, constantName, nuclideName, libType\n )\n\n multiplierVal = _getXsMultiplier(multLibNuclide, multConstant, libType)\n\n if macroGroupConstants is None:\n macroGroupConstants = numpy.zeros(microGroupConstants.shape)\n\n if (\n microGroupConstants.shape != macroGroupConstants.shape\n and not microGroupConstants.any()\n ):\n microGroupConstants = numpy.zeros(macroGroupConstants.shape)\n\n macroGroupConstants += (\n numpy.asarray(numberDensity) * microGroupConstants * multiplierVal\n )\n\n if skippedNuclides:\n runLog.error(\n \"Following nuclides are not in microscopic library {}: {}\".format(\n lib, skippedNuclides\n ),\n single=True,\n )\n raise ValueError(\n \"Specified nuclides are not in microscopic library {}\".format(lib)\n )\n\n if skippedMultNuclides:\n runLog.debug(\n \"Following nuclides are not in multiplier library {}: {}\".format(\n multLib, skippedMultNuclides\n ),\n single=True,\n )\n\n return macroGroupConstants\n\n\ndef _getXsMultiplier(libNuclide, multiplier, libType):\n if multiplier:\n try:\n microCollection = getattr(libNuclide, libType)\n multiplierVal = getattr(microCollection, multiplier)\n except:\n multiplierVal = libNuclide.isotxsMetadata[multiplier]\n else:\n multiplierVal = 1.0\n\n return numpy.asarray(multiplierVal)\n\n\ndef _getMicroGroupConstants(libNuclide, constantName, nuclideName, libType):\n if libType:\n microCollection = getattr(libNuclide, libType)\n else:\n microCollection = libNuclide\n\n microGroupConstants = numpy.asarray(getattr(microCollection, constantName))\n\n if not microGroupConstants.any():\n runLog.debug(\n \"Nuclide {} does no have {} microscopic group constants.\".format(\n nuclideName, constantName\n ),\n single=True,\n )\n\n return microGroupConstants\n" ]
[ [ "scipy.sparse.issparse", "numpy.asarray", "scipy.sparse.csr_matrix", "numpy.array", "numpy.zeros" ] ]
Shuai-Xie/structure_knowledge_distillation
[ "a5a0897f01e16d71dc4e3c77d4ac926fb0cd532d" ]
[ "dataset/datasets.py" ]
[ "import os\r\nimport os.path as osp\r\nimport numpy as np\r\nimport random\r\nimport collections\r\nimport torch\r\nimport torchvision\r\nimport cv2\r\nfrom torch.utils import data\r\n\r\n\r\nclass VOCDataSet(data.Dataset):\r\n def __init__(self, root, list_path, max_iters=None, crop_size=(321, 321), mean=(128, 128, 128), scale=True, mirror=True, ignore_label=255):\r\n self.root = root\r\n self.list_path = list_path\r\n self.crop_h, self.crop_w = crop_size\r\n self.scale = scale\r\n self.ignore_label = ignore_label\r\n self.mean = mean\r\n self.is_mirror = mirror\r\n # self.mean_bgr = np.array([104.00698793, 116.66876762, 122.67891434])\r\n self.img_ids = [i_id.strip() for i_id in open(list_path)]\r\n if not max_iters == None:\r\n self.img_ids = self.img_ids * int(np.ceil(float(max_iters) / len(self.img_ids)))\r\n self.files = []\r\n # for split in [\"train\", \"trainval\", \"val\"]:\r\n for name in self.img_ids:\r\n img_file = osp.join(self.root, \"JPEGImages/%s.jpg\" % name)\r\n label_file = osp.join(self.root, \"SegmentationClassAug/%s.png\" % name)\r\n self.files.append({\r\n \"img\": img_file,\r\n \"label\": label_file,\r\n \"name\": name\r\n })\r\n\r\n def __len__(self):\r\n return len(self.files)\r\n\r\n def generate_scale_label(self, image, label):\r\n f_scale = 0.5 + random.randint(0, 11) / 10.0\r\n image = cv2.resize(image, None, fx=f_scale, fy=f_scale, interpolation=cv2.INTER_LINEAR)\r\n label = cv2.resize(label, None, fx=f_scale, fy=f_scale, interpolation=cv2.INTER_NEAREST)\r\n return image, label\r\n\r\n def __getitem__(self, index):\r\n datafiles = self.files[index]\r\n image = cv2.imread(datafiles[\"img\"], cv2.IMREAD_COLOR)\r\n label = cv2.imread(datafiles[\"label\"], cv2.IMREAD_GRAYSCALE)\r\n size = image.shape\r\n name = datafiles[\"name\"]\r\n if self.scale:\r\n image, label = self.generate_scale_label(image, label)\r\n image = np.asarray(image, np.float32)\r\n image -= self.mean\r\n img_h, img_w = label.shape\r\n pad_h = max(self.crop_h - img_h, 0)\r\n pad_w = max(self.crop_w - img_w, 0)\r\n if pad_h > 0 or pad_w > 0:\r\n img_pad = cv2.copyMakeBorder(image, 0, pad_h, 0,\r\n pad_w, cv2.BORDER_CONSTANT,\r\n value=(0.0, 0.0, 0.0))\r\n label_pad = cv2.copyMakeBorder(label, 0, pad_h, 0,\r\n pad_w, cv2.BORDER_CONSTANT,\r\n value=(self.ignore_label,))\r\n else:\r\n img_pad, label_pad = image, label\r\n\r\n img_h, img_w = label_pad.shape\r\n h_off = random.randint(0, img_h - self.crop_h)\r\n w_off = random.randint(0, img_w - self.crop_w)\r\n # roi = cv2.Rect(w_off, h_off, self.crop_w, self.crop_h);\r\n image = np.asarray(img_pad[h_off: h_off + self.crop_h, w_off: w_off + self.crop_w], np.float32)\r\n label = np.asarray(label_pad[h_off: h_off + self.crop_h, w_off: w_off + self.crop_w], np.float32)\r\n # image = image[:, :, ::-1] # change to BGR\r\n image = image.transpose((2, 0, 1))\r\n if self.is_mirror:\r\n flip = np.random.choice(2) * 2 - 1\r\n image = image[:, :, ::flip]\r\n label = label[:, ::flip]\r\n\r\n return image.copy(), label.copy(), np.array(size), name\r\n\r\n\r\nclass VOCDataTestSet(data.Dataset):\r\n def __init__(self, root, list_path, crop_size=(505, 505), mean=(128, 128, 128)):\r\n self.root = root\r\n self.list_path = list_path\r\n self.crop_h, self.crop_w = crop_size\r\n self.mean = mean\r\n # self.mean_bgr = np.array([104.00698793, 116.66876762, 122.67891434])\r\n self.img_ids = [i_id.strip() for i_id in open(list_path)]\r\n self.files = []\r\n # for split in [\"train\", \"trainval\", \"val\"]:\r\n for name in self.img_ids:\r\n img_file = osp.join(self.root, \"JPEGImages/%s.jpg\" % name)\r\n self.files.append({\r\n \"img\": img_file\r\n })\r\n\r\n def __len__(self):\r\n return len(self.files)\r\n\r\n def __getitem__(self, index):\r\n datafiles = self.files[index]\r\n image = cv2.imread(datafiles[\"img\"], cv2.IMREAD_COLOR)\r\n size = image.shape\r\n name = osp.splitext(osp.basename(datafiles[\"img\"]))[0]\r\n image = np.asarray(image, np.float32)\r\n image -= self.mean\r\n\r\n img_h, img_w, _ = image.shape\r\n pad_h = max(self.crop_h - img_h, 0)\r\n pad_w = max(self.crop_w - img_w, 0)\r\n if pad_h > 0 or pad_w > 0:\r\n image = cv2.copyMakeBorder(image, 0, pad_h, 0,\r\n pad_w, cv2.BORDER_CONSTANT,\r\n value=(0.0, 0.0, 0.0))\r\n image = image.transpose((2, 0, 1))\r\n return image, name, size\r\n\r\n\r\nclass CSDataSet(data.Dataset):\r\n def __init__(self, root, list_path, max_iters=None, crop_size=(321, 321), mean=(128, 128, 128), scale=True, mirror=True, ignore_label=255):\r\n self.root = root\r\n self.list_path = list_path\r\n self.crop_h, self.crop_w = crop_size\r\n self.scale = scale\r\n self.ignore_label = ignore_label\r\n self.mean = mean\r\n self.is_mirror = mirror\r\n # self.mean_bgr = np.array([104.00698793, 116.66876762, 122.67891434])\r\n self.img_ids = [i_id.strip().split() for i_id in open(list_path)]\r\n if not max_iters == None:\r\n self.img_ids = self.img_ids * int(np.ceil(float(max_iters) / len(self.img_ids)))\r\n self.files = []\r\n # for split in [\"train\", \"trainval\", \"val\"]:\r\n for item in self.img_ids:\r\n image_path, label_path = item\r\n name = osp.splitext(osp.basename(label_path))[0]\r\n img_file = osp.join(self.root, image_path)\r\n label_file = osp.join(self.root, label_path)\r\n self.files.append({\r\n \"img\": img_file,\r\n \"label\": label_file,\r\n \"name\": name\r\n })\r\n self.id_to_trainid = {-1: ignore_label, 0: ignore_label, 1: ignore_label, 2: ignore_label,\r\n 3: ignore_label, 4: ignore_label, 5: ignore_label, 6: ignore_label,\r\n 7: 0, 8: 1, 9: ignore_label, 10: ignore_label, 11: 2, 12: 3, 13: 4,\r\n 14: ignore_label, 15: ignore_label, 16: ignore_label, 17: 5,\r\n 18: ignore_label, 19: 6, 20: 7, 21: 8, 22: 9, 23: 10, 24: 11, 25: 12, 26: 13, 27: 14,\r\n 28: 15, 29: ignore_label, 30: ignore_label, 31: 16, 32: 17, 33: 18}\r\n print('{} images are loaded!'.format(len(self.img_ids)))\r\n\r\n def __len__(self):\r\n return len(self.files)\r\n\r\n def generate_scale_label(self, image, label):\r\n f_scale = 0.7 + random.randint(0, 14) / 10.0\r\n image = cv2.resize(image, None, fx=f_scale, fy=f_scale, interpolation=cv2.INTER_LINEAR)\r\n label = cv2.resize(label, None, fx=f_scale, fy=f_scale, interpolation=cv2.INTER_NEAREST)\r\n return image, label\r\n\r\n def id2trainId(self, label, reverse=False):\r\n label_copy = label.copy()\r\n if reverse:\r\n for v, k in self.id_to_trainid.items():\r\n label_copy[label == k] = v\r\n else:\r\n for k, v in self.id_to_trainid.items():\r\n label_copy[label == k] = v\r\n return label_copy\r\n\r\n def __getitem__(self, index):\r\n datafiles = self.files[index]\r\n image = cv2.imread(datafiles[\"img\"], cv2.IMREAD_COLOR)\r\n label = cv2.imread(datafiles[\"label\"], cv2.IMREAD_GRAYSCALE)\r\n label = self.id2trainId(label)\r\n size = image.shape\r\n name = datafiles[\"name\"]\r\n if self.scale:\r\n image, label = self.generate_scale_label(image, label)\r\n image = np.asarray(image, np.float32)\r\n image -= self.mean\r\n img_h, img_w = label.shape\r\n pad_h = max(self.crop_h - img_h, 0)\r\n pad_w = max(self.crop_w - img_w, 0)\r\n if pad_h > 0 or pad_w > 0:\r\n img_pad = cv2.copyMakeBorder(image, 0, pad_h, 0,\r\n pad_w, cv2.BORDER_CONSTANT,\r\n value=(0.0, 0.0, 0.0))\r\n label_pad = cv2.copyMakeBorder(label, 0, pad_h, 0,\r\n pad_w, cv2.BORDER_CONSTANT,\r\n value=(self.ignore_label,))\r\n else:\r\n img_pad, label_pad = image, label\r\n\r\n img_h, img_w = label_pad.shape\r\n h_off = random.randint(0, img_h - self.crop_h)\r\n w_off = random.randint(0, img_w - self.crop_w)\r\n # roi = cv2.Rect(w_off, h_off, self.crop_w, self.crop_h);\r\n image = np.asarray(img_pad[h_off: h_off + self.crop_h, w_off: w_off + self.crop_w], np.float32)\r\n label = np.asarray(label_pad[h_off: h_off + self.crop_h, w_off: w_off + self.crop_w], np.float32)\r\n # image = image[:, :, ::-1] # change to BGR\r\n image = image.transpose((2, 0, 1))\r\n if self.is_mirror:\r\n flip = np.random.choice(2) * 2 - 1\r\n image = image[:, :, ::flip]\r\n label = label[:, ::flip]\r\n\r\n return image.copy(), label.copy(), np.array(size), name\r\n\r\n\r\nclass CSDataTestSet(data.Dataset):\r\n def __init__(self, root, list_path, crop_size=(505, 505), mean=(128, 128, 128)):\r\n self.root = root\r\n self.list_path = list_path\r\n self.crop_h, self.crop_w = crop_size\r\n self.mean = (104.00698793, 116.66876762, 122.67891434)\r\n # self.mean_bgr = np.array([104.00698793, 116.66876762, 122.67891434])\r\n self.img_ids = [i_id.strip().split() for i_id in open(list_path)]\r\n self.files = []\r\n # for split in [\"train\", \"trainval\", \"val\"]:\r\n for item in self.img_ids:\r\n image_path = item[0]\r\n name = osp.splitext(osp.basename(image_path))[0]\r\n img_file = osp.join(self.root, image_path)\r\n self.files.append({\r\n \"img\": img_file\r\n })\r\n\r\n def __len__(self):\r\n return len(self.files)\r\n\r\n def __getitem__(self, index):\r\n datafiles = self.files[index]\r\n image = cv2.imread(datafiles[\"img\"], cv2.IMREAD_COLOR)\r\n size = image.shape\r\n name = osp.splitext(osp.basename(datafiles[\"img\"]))[0]\r\n image = np.asarray(image, np.float32)\r\n image -= self.mean\r\n\r\n img_h, img_w, _ = image.shape\r\n pad_h = max(self.crop_h - img_h, 0)\r\n pad_w = max(self.crop_w - img_w, 0)\r\n if pad_h > 0 or pad_w > 0:\r\n image = cv2.copyMakeBorder(image, 0, pad_h, 0,\r\n pad_w, cv2.BORDER_CONSTANT,\r\n value=(0.0, 0.0, 0.0))\r\n image = image.transpose((2, 0, 1))\r\n return image, size, name\r\n" ]
[ [ "numpy.asarray", "numpy.array", "numpy.random.choice" ] ]
donghaW/RCF-pytorch
[ "6380209ef747abefa87637e60d33369ba423814d" ]
[ "data_loader.py" ]
[ "from os.path import join\n\nimport cv2\nimport numpy as np\nfrom PIL import Image\nfrom torch.utils import data\n\n\ndef prepare_image_PIL(im):\n im = im[:,:,::-1] - np.zeros_like(im) # rgb to bgr\n im -= np.array((104.00698793,116.66876762,122.67891434))\n im = np.transpose(im, (2, 0, 1)) # (H x W x C) to (C x H x W)\n return im\n\n\ndef prepare_image_cv2(im):\n im -= np.array((104.00698793,116.66876762,122.67891434))\n im = np.transpose(im, (2, 0, 1)) # (H x W x C) to (C x H x W)\n return im\n\n\nclass BSDS_RCFLoader(data.Dataset):\n \"\"\"\n Dataloader BSDS500\n \"\"\"\n def __init__(self, root='data/HED-BSDS_PASCAL', split='train', transform=False):\n self.root = root\n self.split = split\n self.transform = transform\n if self.split == 'train':\n self.filelist = join(self.root, 'bsds_pascal_train_pair.lst')\n elif self.split == 'test':\n self.filelist = join(self.root, 'test.lst')\n else:\n raise ValueError(\"Invalid split type!\")\n with open(self.filelist, 'r') as f:\n self.filelist = f.readlines()\n\n def __len__(self):\n return len(self.filelist)\n \n def __getitem__(self, index):\n if self.split == \"train\":\n img_file, lb_file = self.filelist[index].split()\n lb = np.array(Image.open(join(self.root, lb_file)), dtype=np.float32)\n if lb.ndim == 3:\n lb = np.squeeze(lb[:, :, 0])\n assert lb.ndim == 2\n lb = lb[np.newaxis, :, :]\n lb[lb == 0] = 0\n lb[np.logical_and(lb>0, lb<128)] = 2\n lb[lb >= 128] = 1\n \n else:\n img_file = self.filelist[index].rstrip()\n\n if self.split == \"train\":\n img = np.array(cv2.imread(join(self.root, img_file)), dtype=np.float32)\n img = prepare_image_cv2(img)\n return img, lb\n else:\n img = np.array(Image.open(join(self.root, img_file)), dtype=np.float32)\n img = prepare_image_PIL(img)\n return img\n" ]
[ [ "numpy.logical_and", "numpy.squeeze", "numpy.zeros_like", "numpy.transpose", "numpy.array" ] ]
kikei/btc-bot-ai
[ "cb118fa1809ebef472a2025be697c9050e948009" ]
[ "apps/predict/src/predict.py" ]
[ "import datetime\n\n# Numpy\nimport numpy as np\n\n# Matplotlib\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\n\nfrom Plotter import Plotter\nfrom dsp import crosszero\nfrom learningUtils import validated, to2d, zscore, loadModel\nfrom utils import readConfig, getLogger, reportTrend, loadnpy, StopWatch\n\nlogger = getLogger()\nlogger.debug('Start prediction.')\n\n# Measure run time\ntimer = StopWatch()\ntimer.start()\n\nconfig = readConfig('predict.ini')\n\nINPUT_SIZE = config['predict'].getint('fitting.inputsize')\nSAMPLES_PREDICT = config['train'].getint('samples.predict')\n\ndef load(exchanger, unit, ty):\n return loadnpy(config, exchanger, unit, ty, nan=0.)\n\nXbh1 = load('bitflyer', 'hourly', 'askAverage')\nXbh2 = load('bitflyer', 'hourly', 'askMax')\nXbh3 = load('bitflyer', 'hourly', 'askMin')\nXbhb1 = load('bitflyer', 'hourly', 'askAverageBB+2')\nXbhb2 = load('bitflyer', 'hourly', 'askAverageBB-2')\nXbhi1 = load('bitflyer', 'hourly', 'askAverageConv')\nXbhi2 = load('bitflyer', 'hourly', 'askAverageBase')\nXbhi3 = load('bitflyer', 'hourly', 'askAveragePrc1')\nXbhi4 = load('bitflyer', 'hourly', 'askAveragePrc2')\nXbm1 = loadnpy(config, 'bitflyer', 'minutely', 'askAverage')\nXqm1 = loadnpy(config, 'quoine', 'minutely', 'askAverage')\nybh1 = load('bitflyer', 'hourly', 'askCloseTrend')\n\nybh1 = validated(ybh1)\n\nsampleSize = INPUT_SIZE\nfeatureCount = 11\n\navailableSize = len(Xbhi4)\ndataSize = availableSize - sampleSize + 1\nXbh0 = np.zeros((dataSize, sampleSize, featureCount))\nXbh0[:,:,0] = to2d(Xbh1, sampleSize, available=availableSize)\nXbh0[:,:,1] = to2d(Xbh2, sampleSize, available=availableSize)\nXbh0[:,:,2] = to2d(Xbh3, sampleSize, available=availableSize)\nXbh0[:,:,3] = to2d(Xbhb1, sampleSize, available=availableSize)\nXbh0[:,:,4] = to2d(Xbhb2, sampleSize, available=availableSize)\nXbh0[:,:,5] = to2d(Xbhi1, sampleSize, available=availableSize)\nXbh0[:,:,6] = to2d(Xbhi2, sampleSize, available=availableSize)\nXbh0[:,:,7] = to2d(Xbhi3, sampleSize, available=availableSize)\nXbh0[:,:,8] = to2d(Xbhi4, sampleSize, available=availableSize)\n# setup minutely\navailableSizeM = (dataSize - 1) * 60 + sampleSize\nd = datetime.datetime.now()\nminutesToday = d.hour * 60 + d.minute\nXbh0[-1:,:,9] = Xbm1[-sampleSize:]\nXbh0[:-1,:,9] = to2d(Xbm1[:-minutesToday], sampleSize,\n available=availableSizeM, stride=60)\nXbh0[-1:,:,10] = Xqm1[-sampleSize:]\nXbh0[:-1,:,10] = to2d(Xqm1[:-minutesToday], sampleSize,\n available=availableSizeM, stride=60)\n\ndataSize = Xbh0.shape[0]\nXbh = np.zeros((dataSize, Xbh0.shape[1] * Xbh0.shape[2]))\nfor i in range(0, dataSize):\n for j in range(0, featureCount):\n Xbh[i,j*sampleSize:(j+1)*sampleSize] = Xbh0[i,:,j]\n\nybh0 = ybh1[len(ybh1)-availableSize+sampleSize-1:]\n\n# Restore models.\nyModel = loadModel(config, 'trend')\n\n# Prediction\nlogger.debug('Predicting current trend, Xbh.shape={x}...'.format(x=Xbh.shape))\n\nybhPred = yModel.predict(zscore(Xbh))[:,0]\n\ndef smoothPredicted(y, n, z=None):\n if z is None:\n z = lambda i:i/n\n f = np.zeros(n * 2)\n for i in range(0, n):\n f[n+i] = z(i)\n f = f / np.sum(f)\n y = np.convolve(y, f, mode='same')\n return y\n\np = Plotter(plt, subplots=(3, 1), linewidth=0.4)\nXbh1_ = Xbh1[len(Xbh1)-availableSize+sampleSize-1:]\nybhAvr = smoothPredicted(ybhPred, 11)\nybhZero = crosszero(ybhAvr - 0.5, thres=5e-3)\n\nxlim = (Xbh1_.shape[0] - 2000, Xbh1_.shape[0] - 0)\n\nxPlot = np.arange(0, len(Xbh1_), 1)\np.plot(xPlot, Xbh1_, n=0, label='ask avr.')\nfor k, label in [(np.argwhere(ybhZero == -1.), 'short'),\n (np.argwhere(ybhZero == +1.), 'long')]:\n p.scatter(k, Xbh1_[k], n=0, marker='x', linewidth=0.4, label=label)\np.limit(Xbh1_, xlim, n=0)\np.plot(xPlot, ybh0, n=1, label='exp.')\np.plot(xPlot, ybhPred, n=1, label='pred.')\np.plot(xPlot, ybhAvr, n=1, label='avr.')\np.hlines(0.5, 0, len(Xbh1_), n=1, linewidth=0.4)\np.vlines(len(Xbh1_) - SAMPLES_PREDICT, 0, 1, n=1, linewidth=0.4)\np.limit(ybh0, xlim, n=1)\np.plot(xPlot, np.abs(ybh0 - ybhPred), n=2, label='delta')\np.savefig('../figures/predicted.svg')\n\nSHOW_LAST_PREDICTS = 24 * 3\n\nfor i in range(SHOW_LAST_PREDICTS, 0, -1):\n if i == 1:\n logger.warn('Current predicts are trend={trend:0.2f}.'\n .format(trend=ybhPred[-i]))\n else:\n logger.info('Predicts[{i:2.0f}] are trend={trend:0.2f}.'\n .format(i=i, trend=ybhPred[-i]))\n\n# Finished\nseconds = timer.stop()\nlogger.debug('End prediction, elapsed={s:.2f}s'.format(s=seconds))\n\nlogger.debug('Start registering.')\nyTrend = ybhPred[-1].item()\nlogger.debug('Registering trend={trend:.3f}.'.format(trend=yTrend))\nreportTrend(config, yTrend, logger)\nlogger.debug('End registering.')\n" ]
[ [ "numpy.convolve", "numpy.abs", "matplotlib.use", "numpy.argwhere", "numpy.zeros", "numpy.sum" ] ]
AarthiKasirajan/transformer-kgc
[ "d660dce63133f0fd3fa4d909c92b27dad6395153" ]
[ "evaluate.py" ]
[ "import argparse\r\nimport math\r\nfrom tqdm import tqdm\r\nfrom dataset import T5_Dataset\r\nfrom torch.utils.data import DataLoader\r\nfrom utils_accelerate import *\r\nimport numpy as np\r\nfrom typing import Dict\r\nfrom collections import defaultdict\r\n\r\n\r\nclass Evaluator:\r\n def __init__(self, dataset: T5_Dataset, model, args):\r\n self.device = args.device\r\n self.dataset = dataset\r\n self.model = model.to(self.device)\r\n self.num_workers = args.num_workers\r\n self.batch_size = args.batch_size\r\n self.chunk_size = args.chunk_size\r\n self.data_loader = DataLoader(\r\n dataset,\r\n batch_size=self.batch_size,\r\n shuffle=False,\r\n num_workers=self.num_workers,\r\n collate_fn=dataset._collate_eval_2,\r\n )\r\n self.filter_dicts = dict()\r\n self.filter_dicts[\"train\"] = self.create_filter_dict(\"train\")\r\n self.filter_dicts[\"valid\"] = self.create_filter_dict(\"valid\")\r\n self.filter_dicts[\"test\"] = self.create_filter_dict(\"test\")\r\n\r\n def create_filter_dict(self, split: str) -> Dict[str, int]:\r\n data = self.dataset.split(split)\r\n filter_dict = defaultdict(list)\r\n for input, output in zip(data[\"inputs\"], data[\"outputs\"]):\r\n filter_dict[input].append(self.dataset.entity_string_to_id[output])\r\n return filter_dict\r\n\r\n @torch.no_grad()\r\n def eval(self):\r\n self.model.eval()\r\n loader = tqdm(self.data_loader, total=len(self.data_loader), unit=\"batch\")\r\n ranks = {\r\n \"unfiltered\": list(),\r\n \"filtered\": list(),\r\n }\r\n for steps, batch in enumerate(loader):\r\n ranks_in_batch = {\r\n \"unfiltered\": list(),\r\n \"filtered\": list()\r\n }\r\n input_ids, attention_mask, label_strings, input_strings = batch\r\n input_ids = input_ids.to(self.device)\r\n attention_mask = attention_mask.to(self.device)\r\n # labels = labels.to(self.device)\r\n input_ids_repeated = torch.repeat_interleave(\r\n input_ids, len(self.dataset.entity_strings), dim=0\r\n )\r\n attention_mask_repeated = torch.repeat_interleave(\r\n attention_mask, len(self.dataset.entity_strings), dim=0\r\n )\r\n tokenized_entities = self.dataset.tokenized_entities.input_ids.to(\r\n self.device\r\n )\r\n # todo: for filtering we need to use only the filtered entities per triple here\r\n all_entities_repeated = tokenized_entities.repeat([self.batch_size, 1])\r\n summed_logit_chunks = []\r\n # process chunk by chunk\r\n for chunk_number in range(\r\n math.ceil(len(input_ids_repeated) / self.chunk_size)\r\n ):\r\n chunk_start = self.chunk_size * chunk_number\r\n chunk_end = min(\r\n self.chunk_size * (chunk_number + 1), len(input_ids_repeated)\r\n )\r\n current_chunk_size = chunk_end - chunk_start\r\n outputs_chunk = self.model(\r\n input_ids=input_ids_repeated[chunk_start:chunk_end],\r\n attention_mask=attention_mask_repeated[chunk_start:chunk_end],\r\n labels=all_entities_repeated[chunk_start:chunk_end],\r\n )\r\n logits_chunk = outputs_chunk.logits\r\n soft_logits_chunk = torch.log_softmax(logits_chunk, dim=2)\r\n coordinates = all_entities_repeated[chunk_start:chunk_end].view(current_chunk_size, -1, 1)\r\n # set padded logits to zero\r\n padded_mask = (coordinates == 0).squeeze()\r\n soft_logits_chunk[padded_mask] = 0\r\n needed_soft_logits_chunk = torch.gather(\r\n soft_logits_chunk,\r\n 2,\r\n coordinates\r\n ).view(current_chunk_size, -1)\r\n\r\n summed_logits = torch.sum(needed_soft_logits_chunk, dim=1)\r\n summed_logit_chunks.append(summed_logits)\r\n summed_logits = torch.cat(summed_logit_chunks)\r\n for summed_logits_per_triple, input_string, label in zip(\r\n summed_logits.split(len(self.dataset.entity_strings)), input_strings, label_strings\r\n ):\r\n # todo: currently we are calculating best rank on equality\r\n # change to mean\r\n arg_sorted = torch.argsort(summed_logits_per_triple, descending=True)\r\n entity_id = self.dataset.entity_string_to_id[label]\r\n rank = (\r\n (arg_sorted == entity_id)\r\n .nonzero(as_tuple=True)[0]\r\n .item()\r\n )\r\n print(rank)\r\n ranks_in_batch[\"unfiltered\"].append(rank)\r\n\r\n # now filter\r\n true_score = summed_logits_per_triple[entity_id].clone()\r\n for filter_dict in self.filter_dicts.values():\r\n summed_logits_per_triple[filter_dict[input_string]] = -float(\"inf\")\r\n summed_logits_per_triple[entity_id] = true_score\r\n arg_sorted = torch.argsort(summed_logits_per_triple, descending=True)\r\n rank = (\r\n (arg_sorted == entity_id)\r\n .nonzero(as_tuple=True)[0]\r\n .item()\r\n )\r\n print(rank)\r\n ranks_in_batch[\"filtered\"].append(rank)\r\n ranks[\"filtered\"].extend(ranks_in_batch[\"filtered\"])\r\n ranks[\"unfiltered\"].extend(ranks_in_batch[\"unfiltered\"])\r\n for setting, list_of_ranks in ranks.items():\r\n ranks[setting] = np.array(list_of_ranks, dtype=np.float32) + 1\r\n # ranks = np.array(ranks, dtype=np.float32)\r\n # # add 1 to have best rank 1 not 0\r\n # ranks += 1\r\n print(\"MR\", ranks[\"unfiltered\"].mean())\r\n print(\"MR-filtered\", ranks[\"filtered\"].mean())\r\n print(\"MRR\", np.power(ranks[\"unfiltered\"], -1).mean())\r\n print(\"MRR-filtered\", np.power(ranks[\"filtered\"], -1).mean())\r\n print(\"Hits@1\", (ranks[\"unfiltered\"] == 1).sum() / len(self.dataset))\r\n print(\"Hits@1-filtered\", (ranks[\"filtered\"] == 1).sum() / len(self.dataset))\r\n print(\"Hits@10\", (ranks[\"unfiltered\"] <= 10).sum() / len(self.dataset))\r\n print(\"Hits@10-filtered\", (ranks[\"filtered\"] <= 10).sum() / len(self.dataset))\r\n\r\ndef main():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"--prefix\", type=str, default=\"temp\")\r\n parser.add_argument(\"--checkpoint\", type=str)\r\n parser.add_argument(\"--dataset\", type=str, default=\"codex-m\")\r\n parser.add_argument(\"--batch_size\", type=int, default=1)\r\n parser.add_argument(\"--chunk_size\", type=int, default=50)\r\n parser.add_argument(\"--num_beams\", type=int, default=1)\r\n parser.add_argument(\"--num_predictions\", type=int, default=1)\r\n parser.add_argument(\"--length_penalty\", type=float, default=0.6)\r\n parser.add_argument(\"--num_workers\", type=int, default=0)\r\n parser.add_argument(\"--device\", type=str, default=\"cuda\")\r\n parser.add_argument(\"--split\", type=str, default=\"test\")\r\n\r\n args = parser.parse_args()\r\n valid_dataset = T5_Dataset(args.split, dataset_name=args.dataset)\r\n checkpoint_location = \"models/{}/{}.pt\".format(args.prefix, args.checkpoint)\r\n print(\"Using %s\" % checkpoint_location)\r\n\r\n model = load_accelerator_model(checkpoint_location, only_model=True)\r\n evaluator = Evaluator(dataset=valid_dataset, model=model, args=args)\r\n evaluator.eval()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n" ]
[ [ "numpy.array", "torch.utils.data.DataLoader", "numpy.power" ] ]
anguyen216/mTSP-work
[ "47d3b59c83569e9e03c92c9b5140a549d4742bce" ]
[ "solvers_examples.py" ]
[ "# includes examples of how to run solvers\n# Author: Anh Nguyen\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom utils import longLatDistKm, plotPath, plotMultiplePaths\nfrom tsp_solvers.dp_solver import DP_TSP\nfrom tsp_solvers.ILP_solver import ILP_TSP\nfrom tsp_solvers.opt2_solver import OPT2_TSP\nfrom cities import WAYPOINTS, NAMES_DICT\nfrom mtsp_solvers.basic_solver import BASIC_MTSP\nimport time\n\ndef main():\n # SETUP\n N = len(WAYPOINTS)\n opt2_runtime = []\n opt2_costs = []\n opt2_sizes = [i for i in range(3, N, 3)]\n ilp_costs = []\n # dp_runtime = []\n # ilp_runtime = []\n ilp_sizes = [i for i in range(3, 26, 3)]\n # dp_sizes = [i for i in range(3, 13, 3)]\n\n # testing basic mTSP solver\n indices = np.random.choice(40, size=15, replace=False)\n waypoints = [WAYPOINTS[idx] for idx in indices]\n start = np.random.randint(0, len(waypoints))\n bmtsp = BASIC_MTSP(waypoints, longLatDistKm)\n num_v = 2\n colors = ['steelblue', 'orange']\n v_limits = [100000] * num_v\n sol = bmtsp.solve(waypoints[start], num_v, v_limits)\n if sol:\n paths, cost = sol\n print(\"Total distance traveled by all vehicles:\", cost, \"km\")\n pname = \"./plots/sample_mtsp_result.png\"\n plotMultiplePaths(paths, colors, save_plot=True, plot_name=pname)\n\n\n # Check OPT-2 near-optimal solution\n # for s in ilp_sizes:\n # print(s)\n # indices = np.random.randint(0, 26, size=s)\n # waypoints = [WAYPOINTS[idx] for idx in indices]\n # start = np.random.randint(0, s)\n # ilp = ILP_TSP(waypoints, longLatDistKm)\n # opt2 = OPT2_TSP(waypoints, longLatDistKm)\n # ilp_path, ilp_cost = ilp.solve(waypoints[start])\n # opt2_path, opt2_cost = opt2.solve(waypoints[start])\n # opt2_costs.append(opt2_cost)\n # ilp_costs.append(ilp_cost)\n # plt.plot(ilp_sizes, ilp_costs, label='ILP cost')\n # plt.plot(ilp_sizes, opt2_costs, label='OPT-2 cost')\n # plt.xlabel('number of waypoints')\n # plt.ylabel('solution cost in km')\n # plt.legend()\n # plt.title('Check OPT-2 near-optimal solution')\n # plt.savefig(\"plots/opt2_cost_check.png\")\n\n # Plot OPT-2 runtime\n # for s in range(3, N, 3):\n # print(s)\n # indices = np.random.randint(0, N, size=s)\n # waypoints = [WAYPOINTS[idx] for idx in indices]\n # start = np.random.randint(0, s)\n # opt2 = OPT2_TSP(waypoints, longLatDistKm)\n # start_time = time.time()\n # opt2_path, opt2_cost = opt2.solve(waypoints[start])\n # opt2_runtime.append(time.time() - start_time)\n # opt2_costs.append(opt2_cost)\n # plt.plot(opt2_sizes, opt2_runtime)\n # plt.xlabel('number of waypoints')\n # plt.ylabel('runtime in seconds')\n # plt.title('runtime of OPT-2 approximation for TSP problem')\n # plt.savefig(\"plots/opt2_tsp_runtime.png\")\n\n # Plot ILP runtime\n # for s in ilp_sizes:\n # # randomize the waypoints and number of waypoints\n # # pick a random starting point\n # print(s)\n # indices = np.random.randint(0, 26, size=s)\n # waypoints = [WAYPOINTS[idx] for idx in indices]\n # start = np.random.randint(0, len(waypoints))\n # # setup solvers\n # ilp = ILP_TSP(waypoints, longLatDistKm)\n # # time solvers\n # start_time = time.time()\n # ilp_path, ilp_cost = ilp.solve(waypoints[start])\n # ilp_runtime.append(time.time() - start_time)\n # # ILP plot\n # plt.plot(ilp_sizes, ilp_runtime)\n # plt.xlabel('number of waypoints')\n # plt.ylabel('runtime in seconds')\n # plt.title('runtime of ILP solver for TSP problem')\n # plt.savefig(\"plots/ilp_tsp_runtime.png\")\n\n # Plot DP runtime\n # for s in dp_sizes:\n # print(s)\n # indices = np.random.randint(0, 13, size=s)\n # waypoints = [WAYPOINTS[idx] for idx in indices]\n # start = np.random.randint(0, len(waypoints))\n # dp = DP_TSP(waypoints, longLatDistKm)\n # start_time = time.time()\n # dp_path, dp_cost = dp.solve(waypoints[start])\n # dp_runtime.append(time.time() - start_time)\n #\n # # DP plot\n # plt.plot(dp_sizes, dp_runtime)\n # plt.xlabel('number of waypoints')\n # plt.ylabel('runtime in seconds')\n # plt.title('runtime of DP solver for TSP problem')\n # plt.savefig(\"plots/dp_tsp_runtime.png\")\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.random.choice" ] ]
TrackerSB/deepjanus
[ "f715072645b1e6f2cc0c51ec0c3a6296cfb14a1d" ]
[ "DeepJanus-BeamNG/udacity_integration/take-free-screenshot.py" ]
[ "import random\n\nimport numpy as np\n\nfrom beamng_brewer import BeamNGBrewer\nfrom beamng_waypoint import BeamNGWaypoint\nfrom road_storage import RoadStorage\nfrom simulation_data_collector import SimulationDataCollector\nfrom beamng_tig_maps import maps\n\nrandom.seed(42)\nnp.random.seed(42)\n\nmaps.install_map_if_needed()\n\n\ndef get_node_coords(node):\n return node[0], node[1], node[2]\n\n\ndef distance(p1, p2):\n return np.linalg.norm(np.subtract(get_node_coords(p1), get_node_coords(p2)))\n\n\nnodes = RoadStorage().get_road_nodes_by_index(2)\n\nbrewer = BeamNGBrewer(road_nodes=nodes)\nwaypoint_goal = BeamNGWaypoint('waypoint_goal', nodes[40][:3])\nmaps.beamng_map.generated().write_items(brewer.decal_road.to_json() + '\\n' + waypoint_goal.to_json())\nbrewer.vehicle_start_pose = brewer.road_points.vehicle_start_pose(road_point_index=0)\n\nvehicle = brewer.setup_vehicle()\nbrewer.setup_scenario_camera()\nbeamng = brewer.beamng\nsteps = brewer.params.beamng_steps\nsim_data_collector = SimulationDataCollector(vehicle, beamng, brewer.decal_road, brewer.params)\n\nbrewer.bring_up()\nai_aggression = None # 1.0\nsim_save_path = 'screenshot'\n\nif ai_aggression:\n vehicle.ai_set_aggression(ai_aggression)\n vehicle.ai_drive_in_lane(True)\n vehicle.ai_set_waypoint(waypoint_goal.name)\nelse:\n vehicle.ai_set_mode(\"disabled\")\n\n\ndef start():\n for idx in range(1000):\n sim_data_collector.collect_current_data()\n last_state = sim_data_collector.states[-1]\n if distance(last_state.pos, waypoint_goal.position) < 15.0:\n pass\n\n def shot(dir, h=-25):\n brewer.camera.pose.pos = tuple(last_state.pos[:2]) + (h,)\n brewer.camera.pose.rot = dir\n brewer.camera.get_rgb_image().save(f'shot{dir}_h{h}.png')\n\n shot((0, 0, -90), -25)\n shot((0, 0, -90), -20)\n shot((0, 0, -90), -15)\n # brewer.camera.resolution = (800,600)\n break\n beamng.step(steps)\n\n\ntry:\n start()\nfinally:\n sim_data_collector.save()\n beamng.close()\n" ]
[ [ "numpy.random.seed" ] ]
Bhumika0201/autoai
[ "8a1ba4453395798cf694c49ac481ba1d37989fb4" ]
[ "blobcity/utils/ProblemType.py" ]
[ "# Copyright 2021 BlobCity, Inc\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThis Python file consists of Function to identify the problem type either Classification or Regression Type.\n\"\"\"\n\nimport numpy as np\nclass ProType:\n\n def __init__(self):\n pass\n def checkType(self,data):\n\n \"\"\"\n param1: class\n param2: target data\n \n This function identify type of problem to be solved either regression or classification \n on the basis of datatype and uniquiness in target columns\n\n Conditions:\n 1. if datatype is Object/String return problem Type as classification\n 2. else check if it is integer or float type with less then equal to 100 classes then return Classification \n else return Regression as the ProblemType\n \"\"\"\n if(data.dtype in ['object']): return dict({'type':'Classification'})\n else:\n target_length =len(np.unique(data))\n if data.dtype in ['int64','float64','int32','float32','int16','float16'] and target_length<=10: \n return dict({'type':'Classification'})\n else: \n return dict({'type':'Regression'})\n" ]
[ [ "numpy.unique" ] ]
OsmanMutlu/pytorch-pretrained-BERT
[ "837cde8fe82549dc5aeb34aa25b86c07c9448a46" ]
[ "examples/error_analysis.py" ]
[ "#!/usr/bin/env python\n\n\"\"\"Random baseline for the PAN19 hyperpartisan news detection task\"\"\"\n# Version: 2018-09-24\n\n# Parameters:\n# --inputDataset=<directory>\n# Directory that contains the articles XML file with the articles for which a prediction should be made.\n# --outputDir=<directory>\n# Directory to which the predictions will be written. Will be created if it does not exist.\n\nfrom __future__ import division\n\nimport os\nimport sys\nfrom lxml import etree\nimport codecs\nimport xml.etree.ElementTree as ET\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nimport glob\nimport argparse\nimport logging\nimport datetime\nimport random\nimport math\n\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom pytorch_pretrained_bert.tokenization import printable_text, BertTokenizer\nfrom pytorch_pretrained_bert.modeling import BertForSequenceClassification\nfrom pytorch_pretrained_bert.optimization import BertAdam\n\nlogging.basicConfig(filename = '{}_log.txt'.format(datetime.datetime.now()),\n format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt = '%m/%d/%Y %H:%M:%S',\n level = logging.INFO)\nlogger = logging.getLogger(__name__)\n\nPYTORCH_PRETRAINED_BERT_CACHE = Path(os.getenv('PYTORCH_PRETRAINED_BERT_CACHE',\n Path.home() / '.pytorch_pretrained_bert'))\n\nrunOutputFileName = \"prediction.txt\"\n\nclass InputExample(object):\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\n\n def __init__(self, guid, text_a, text_b=None, label=None):\n \"\"\"Constructs a InputExample.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self, input_ids, input_mask, segment_ids, label_id):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.label_id = label_id\n\nclass DataProcessor(object):\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\n\n def get_test_examples(self, inputFile):\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\n raise NotImplementedError()\n\n def get_labels(self):\n \"\"\"Gets the list of labels for this data set.\"\"\"\n raise NotImplementedError()\n\n @classmethod\n def _read_tsv(cls, input_file, quotechar=None):\n \"\"\"Reads a comma separated value file.\"\"\"\n lines = pd.read_csv(input_file)\n return lines\n\nclass HyperProcessor(DataProcessor):\n \"\"\"Processor for the Hyperpartisan data set.\"\"\"\n\n def get_test_examples(self, inputFile):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(inputFile), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in lines.iterrows():\n guid = i\n text_a = str(line.text)\n label = str(int(line.hyperpartisan))\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n\n return examples\n\nclass EmwProcessor(DataProcessor):\n \"\"\"Processor for the Emw data set.\"\"\"\n\n def get_test_examples(self, inputFile):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(inputFile), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in lines.iterrows():\n # guid = i\n guid = i\n text_a = str(line.text)\n label = str(int(line.label))\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n\n return examples\n\nclass EmwProcessor2(DataProcessor):\n \"\"\"Processor for the Emw data set.\"\"\"\n\n def get_test_examples(self, inputFile):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(inputFile), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\", \"2\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in lines.iterrows():\n # guid = i\n guid = i\n text_a = str(line.text)\n label = str(int(line.label))\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n\n return examples\n\n\ndef convert_examples_to_features(example, label_list, max_seq_length, tokenizer):\n \"\"\"Loads a data file into a list of `InputBatch`s.\"\"\"\n\n label_map = {}\n for (i, label) in enumerate(label_list):\n label_map[label] = i\n\n tokens_a = tokenizer.tokenize(example.text_a)\n\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n\n if tokens_b:\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[0:(max_seq_length - 2)]\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambigiously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = []\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in tokens_a:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n if tokens_b:\n for token in tokens_b:\n tokens.append(token)\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n label_id = label_map[example.label]\n return InputFeatures(input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id)\n\n\ndef _truncate_seq_pair(tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\nclass HyperpartisanData(Dataset):\n \"\"\"\"\"\"\n def __init__(self, examples, label_list, max_seq_length, tokenizer):\n self.examples = examples\n self.label_list = label_list\n self.max_seq_length = max_seq_length\n self.tokenizer = tokenizer\n\n def __len__(self):\n return len(self.examples)\n\n def __getitem__(self, idx):\n ex = self.examples[idx]\n feats = convert_examples_to_features(ex, self.label_list, self.max_seq_length, self.tokenizer)\n\n input_ids = torch.tensor(feats.input_ids, dtype=torch.long)\n input_mask = torch.tensor(feats.input_mask, dtype=torch.long)\n segment_ids = torch.tensor(feats.segment_ids, dtype=torch.long)\n label_id = torch.tensor(feats.label_id, dtype=torch.long)\n\n return input_ids, input_mask, segment_ids, label_id, ex.guid\n\ndef main():\n \"\"\"Main method of this module.\"\"\"\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-c\", \"--inputFile\",\n default=None,\n type=str,\n required=True,\n help=\"The input data dir\")\n parser.add_argument(\"-o\", \"--outputFile\", default=None, type=str,\n help=\"Output file for predictions\")\n parser.add_argument(\"--bert_model\", default=\"bert-base-uncased\", type=str,\n help=\"Bert pre-trained model selected in the list: bert-base-uncased, \"\n \"bert-large-uncased, bert-base-cased, bert-base-multilingual, bert-base-chinese.\")\n parser.add_argument(\"--task_name\",\n default=\"emw\",\n type=str,\n help=\"The name of the task to train.\")\n parser.add_argument(\"--model_load\",\n default=\"\",\n type=str,\n required=True,\n help=\"The path of model state.\")\n parser.add_argument(\"--max_seq_length\",\n default=256,\n type=int,\n help=\"The maximum total input sequence length after WordPiece tokenization. \\n\"\n \"Sequences longer than this will be truncated, and sequences shorter \\n\"\n \"than this will be padded.\")\n parser.add_argument(\"--batch_size\",\n default=16,\n type=int,\n help=\"Batch size.\")\n\n args = parser.parse_args()\n\n processors = {\n \"hyperpartisan\": HyperProcessor,\n \"emw\": EmwProcessor,\n \"emw2\": EmwProcessor2,\n }\n\n bert_model = args.bert_model\n max_seq_length = args.max_seq_length\n model_path = args.model_load\n batch_size = args.batch_size\n task_name = args.task_name.lower()\n processor = processors[task_name]()\n label_list = processor.get_labels()\n\n inputFile = args.inputFile\n outputFile = args.outputFile\n num_labels = len(label_list)\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n tokenizer = BertTokenizer.from_pretrained(bert_model)\n model = BertForSequenceClassification.from_pretrained(bert_model, PYTORCH_PRETRAINED_BERT_CACHE, num_labels=num_labels)\n try:\n model.load_state_dict(torch.load(model_path)) # , map_location='cpu' for only cpu\n except: #When model is parallel\n model = torch.nn.DataParallel(model)\n model.load_state_dict(torch.load(model_path)) # , map_location='cpu' for only cpu\n\n logger.info(\"Model state has been loaded.\")\n\n model.to(device)\n\n test_examples = processor.get_test_examples(inputFile)\n random.shuffle(test_examples)\n\n test_dataloader = DataLoader(dataset=HyperpartisanData(test_examples, label_list, max_seq_length, tokenizer), batch_size=batch_size)\n\n df = pd.read_csv(inputFile)\n df[\"prediction\"] = 0\n\n model.eval()\n for input_ids, input_mask, segment_ids, label_ids, doc_ids in test_dataloader:\n\n input_ids = input_ids.to(device)\n input_mask = input_mask.to(device)\n segment_ids = segment_ids.to(device)\n with torch.no_grad():\n logits = model(input_ids, segment_ids, input_mask)\n logits = logits.detach().cpu().numpy()\n labels = np.argmax(logits, axis=1)\n\n for i in range(len(labels)):\n df.iloc[int(doc_ids[i].item()), df.columns.get_loc(\"prediction\")] = int(labels[i])\n\n df.to_csv(outputFile, index=False)\n logger.info(\"The predictions have been written to the output folder.\")\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "pandas.read_csv", "torch.load", "torch.tensor", "numpy.argmax", "torch.no_grad", "torch.cuda.is_available", "torch.nn.DataParallel" ] ]
xiaomingzhid/SSKD
[ "806d6db5c5dea4e018e49ee30d7bfc7b95977ffe" ]
[ "fastreid/evaluation/reid_evaluation.py" ]
[ "# encoding: utf-8\n\"\"\"\n@author: liaoxingyu\n@contact: [email protected]\n\"\"\"\nimport copy\nimport logging\nfrom collections import OrderedDict\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom sklearn import metrics\nimport pdb\nfrom fastreid.utils import comm\nfrom fastreid.utils.compute_dist import build_dist\nfrom .evaluator import DatasetEvaluator\nfrom .query_expansion import aqe\nfrom .rank import evaluate_rank\nfrom .roc import evaluate_roc\n\nlogger = logging.getLogger(__name__)\n\n\nclass ReidEvaluator(DatasetEvaluator):\n def __init__(self, cfg, num_query, output_dir=None):\n self.cfg = cfg\n self._num_query = num_query\n self._output_dir = output_dir\n\n self.features = []\n self.pids = []\n self.camids = []\n\n def reset(self):\n self.features = []\n self.pids = []\n self.camids = []\n\n def process(self, inputs, outputs):\n self.pids.extend(inputs[\"targets\"])\n self.camids.extend(inputs[\"camids\"])\n self.features.append(outputs.cpu())\n\n def evaluate(self):\n if comm.get_world_size() > 1:\n comm.synchronize()\n features = comm.gather(self.features)\n features = sum(features, [])\n\n pids = comm.gather(self.pids)\n pids = sum(pids, [])\n\n camids = comm.gather(self.camids)\n camids = sum(camids, [])\n\n # fmt: off\n if not comm.is_main_process(): return {}\n # fmt: on\n else:\n features = self.features\n pids = self.pids\n camids = self.camids\n\n features = torch.cat(features, dim=0)\n # query feature, person ids and camera ids\n query_features = features[:self._num_query]\n query_pids = np.asarray(pids[:self._num_query])\n query_camids = np.asarray(camids[:self._num_query])\n\n # gallery features, person ids and camera ids\n gallery_features = features[self._num_query:]\n gallery_pids = np.asarray(pids[self._num_query:])\n gallery_camids = np.asarray(camids[self._num_query:])\n\n self._results = OrderedDict()\n\n if self.cfg.TEST.AQE.ENABLED:\n logger.info(\"Test with AQE setting\")\n qe_time = self.cfg.TEST.AQE.QE_TIME\n qe_k = self.cfg.TEST.AQE.QE_K\n alpha = self.cfg.TEST.AQE.ALPHA\n query_features, gallery_features = aqe(query_features, gallery_features, qe_time, qe_k, alpha)\n\n dist = build_dist(query_features, gallery_features, self.cfg.TEST.METRIC)\n \n if self.cfg.TEST.RERANK.ENABLED:\n logger.info(\"Test with rerank setting\")\n k1 = self.cfg.TEST.RERANK.K1\n k2 = self.cfg.TEST.RERANK.K2\n lambda_value = self.cfg.TEST.RERANK.LAMBDA\n\n if self.cfg.TEST.METRIC == \"cosine\":\n query_features = F.normalize(query_features, dim=1)\n gallery_features = F.normalize(gallery_features, dim=1)\n\n rerank_dist = build_dist(query_features, gallery_features, metric=\"jaccard\", k1=k1, k2=k2)\n dist = rerank_dist * (1 - lambda_value) + dist * lambda_value\n\n cmc, all_AP, all_INP = evaluate_rank(dist, query_pids, gallery_pids, query_camids, gallery_camids)\n\n mAP = np.mean(all_AP)\n mINP = np.mean(all_INP)\n for r in [1, 5, 10]:\n self._results['Rank-{}'.format(r)] = cmc[r - 1] * 100\n self._results['mAP'] = mAP * 100\n self._results['mINP'] = mINP * 100\n self._results[\"metric\"] = (mAP + cmc[0]) / 2 * 100\n\n if self.cfg.TEST.ROC_ENABLED:\n scores, labels = evaluate_roc(dist, query_pids, gallery_pids, query_camids, gallery_camids)\n fprs, tprs, thres = metrics.roc_curve(labels, scores)\n\n for fpr in [1e-4, 1e-3, 1e-2]:\n ind = np.argmin(np.abs(fprs - fpr))\n self._results[\"TPR@FPR={:.0e}\".format(fpr)] = tprs[ind]\n\n return copy.deepcopy(self._results)\n" ]
[ [ "torch.nn.functional.normalize", "numpy.abs", "torch.cat", "numpy.asarray", "sklearn.metrics.roc_curve", "numpy.mean" ] ]
detrout/woldlab-rna-seq
[ "02099219ff783503e8b6acce94d96b2b374b72da" ]
[ "woldrnaseq/transcript_types.py" ]
[ "#!/usr/bin/python3\n\"\"\"Read annotation bam and count reads per gene_type\n\"\"\"\nfrom argparse import ArgumentParser\nfrom collections import Counter\nimport logging\nfrom pathlib import Path\nimport pandas\nimport pysam\nimport time\n\nfrom .common import (\n add_debug_arguments,\n add_metadata_arguments,\n add_separator_argument,\n add_version_argument,\n configure_logging,\n get_seperator,\n)\n\nfrom .models import (\n load_library_tables,\n load_experiments,\n find_library_bam_file,\n)\n\nlogger = logging.getLogger(__name__)\n\n\ndef main(cmdline=None):\n parser = make_parser()\n args = parser.parse_args(cmdline)\n\n configure_logging(args)\n\n transcript_type_map = make_transcript_type_map(args.gtf_cache)\n\n if len(args.filenames) > 0:\n if args.output is None:\n parser.perror(\"Output filename is required when listing bam files directly\")\n\n scores = make_transcript_type_scores(args.filenames, transcript_type_map)\n scores.to_csv(args.output, sep=\"\\t\")\n\n if not (args.libraries is None or args.experiments is None):\n sep = get_seperator(args.sep)\n libraries = load_library_tables(args.libraries, sep=sep)\n experiments = load_experiments(args.experiments, sep=sep)\n\n for i, experiment in experiments.iterrows():\n logging.info(\"Processing: %s\", experiment.name)\n scores = make_experiment_transcript_type_scores(\n experiment, libraries, transcript_type_map\n )\n name = \"{}_gene_type.tsv\".format(experiment.name)\n scores.to_csv(name, sep=\"\\t\")\n elif args.libraries is None and args.experiments is None:\n # Neither provided\n pass\n else:\n # only one provided\n parser.perror(\n \"You need to provide both a libraries and experiment table to use this mode\")\n\n\ndef make_parser():\n parser = ArgumentParser()\n parser.add_argument(\n \"filenames\", nargs=\"*\", help=\"Names of transcriptome bam files to score\"\n )\n parser.add_argument(\n \"-o\", \"--output\", help=\"Name of output score table for directly read bam files\"\n )\n add_metadata_arguments(parser)\n parser.add_argument(\n \"--gtf-cache\", required=True, help=\"name of gtf-cache file to read\"\n )\n add_separator_argument(parser)\n add_version_argument(parser)\n add_debug_arguments(parser)\n return parser\n\n\ndef make_transcript_type_map(cache_filename):\n tstart = time.monotonic()\n logger.info(\"Loading GTF Cache\")\n type_name = \"gene_type\"\n store = pandas.HDFStore(cache_filename)\n trna = store.select(\n \"gtf\", columns=[\"transcript_id\", type_name], where=[\"type==tRNA\"]\n )\n transcripts = store.select(\n \"gtf\", columns=[\"transcript_id\", type_name], where=[\"type==transcript\"]\n )\n spikes = store.select(\"gtf\", columns=[\"transcript_id\"], where=[\"source==spikein\"])\n store.close()\n\n transcript_type_map = {k: \"spikein\" for k in spikes[\"transcript_id\"]}\n transcript_series = transcripts.set_index(\"transcript_id\")[type_name]\n transcript_type_map.update(transcript_series.to_dict())\n trna_series = trna.set_index(\"transcript_id\")[type_name]\n transcript_type_map.update(trna_series.to_dict())\n assert len(transcript_type_map) == (transcripts.shape[0] + spikes.shape[0] + trna.shape[0])\n logging.debug(\"Loading finished {:.3} sec\".format(time.monotonic() - tstart))\n return transcript_type_map\n\n\ndef make_experiment_transcript_type_scores(experiment, libraries, transcript_type_map):\n scores = {}\n for library_id in experiment.replicates:\n library = libraries.loc[library_id]\n anno = find_library_bam_file(library, \"transcriptome\")\n scores[library_id] = score_bam_transcript_type(anno, transcript_type_map)\n\n return pandas.DataFrame(scores)\n\n\ndef make_transcript_type_scores(urls, transcript_type_map):\n scores = {}\n for url in urls:\n basename = Path(url).name\n scores[basename] = score_bam_transcript_type(url, transcript_type_map)\n\n return pandas.DataFrame(scores)\n\n\ndef score_bam_transcript_type(alignment_filename, transcript_type_map):\n tstart = time.monotonic()\n logger.info(\"Counting {}\".format(alignment_filename))\n counts = Counter()\n with pysam.AlignmentFile(alignment_filename, \"r\") as aligned:\n for read in aligned.fetch(until_eof=True):\n if not (read.is_secondary or read.is_unmapped or read.is_qcfail or read.is_duplicate):\n transcript_type = transcript_type_map.get(read.reference_name, \"no id\")\n counts[transcript_type] += 1\n\n logging.debug(\n \"Finished counting {} {:.3f}\".format(\n alignment_filename, time.monotonic() - tstart\n )\n )\n return counts\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "pandas.HDFStore", "pandas.DataFrame" ] ]
gdaguilarc/intelligent-systems
[ "af8c7374a3225ad5944e63956a666ff1ccb6532d" ]
[ "main.py" ]
[ "# Proyecto Final\n# Clustering with kmeans a group of numbers from an image, crop and then predict the label with a NN\n\n# Location:\n# Tecnologico de Monterrey Campus Ciudad de México\n\n# Contributors:\n# Andrea Beatriz Becerra Bolaños - A01337434\n# Guillermo David Aguilar Castilleja - A01337242\n\n# Dependencies:\n# tensorflow == 2.3.0\n\nfrom datetime import date\nimport random\nfrom pathlib import Path\nfrom PIL import Image, ImageOps\nfrom sklearn.cluster import KMeans\nimport numpy as np\n\nimport tensorflow as tf\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout, Conv2D, BatchNormalization\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.models import load_model\n\nfrom matplotlib import pyplot as plt\n\n# IMAGES\nIMAGE_ONE = Image.open(\"img/digits-handmade.jpg\")\nIMAGE_TWO = Image.open(\"img/prueba1.png\")\nIMAGE_THREE = Image.open(\"img/prueba2.png\")\nIMAGE_FOUR = Image.open(\"img/prueba3.jpeg\")\n\n\n# NET CONSTANTS\nNUMBER_LAYERS = 3\nEPOCHS = 15\nOPTIMIZER = \"Adam\"\nDATE = date.today().strftime(\"%d-%m-%Y\")\nFILENAME = \"DigitNN-Layers{}-{}-{}epochs-{}.h5\".format(\n NUMBER_LAYERS, OPTIMIZER, EPOCHS, DATE)\n\nBEST_NET = \"DigitNN-3-adam-20-29-07-2020.h5\"\n\n\n# DATA\n(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()\n\n# NORMALIZING DATA\nx_train = x_train / 255\nx_test = x_test / 255\n\n\n# MODEL\ndef train(x_train, y_train, epochs=20, optimizer=\"adam\", net=FILENAME):\n\n if net != FILENAME:\n my_file = Path(\"models/\" + net)\n else:\n my_file = Path(\"models/\" + FILENAME)\n\n if my_file.is_file():\n if net != FILENAME:\n model = load_model(\"models/\" + net)\n else:\n model = load_model(\"models/\" + FILENAME)\n\n return model\n\n model = Sequential()\n model.add(Flatten())\n model.add(Dense(392, activation=\"relu\"))\n model.add(Dropout(0.4))\n model.add(Dense(128, activation=\"relu\"))\n model.add(Dropout(0.2))\n model.add(Dense(10, activation=\"softmax\"))\n model.compile(optimizer=optimizer,\n loss='sparse_categorical_crossentropy', metrics=[\"accuracy\"])\n history = model.fit(x_train, y_train, epochs=epochs,\n shuffle=True, validation_split=0.25)\n model.summary()\n model.save(\"models/\"+FILENAME)\n print_history(history)\n model.evaluate(x_test, y_test)\n return model\n\n\ndef print_history(history):\n plt.figure(figsize=(10, 6))\n plt.subplot(2, 2, 1)\n plt.plot(\n range(len(history.history['accuracy'])), history.history['accuracy'])\n plt.ylabel('accuracy')\n plt.xlabel('epochs')\n plt.subplot(2, 2, 2)\n plt.plot(range(len(history.history['loss'])), history.history['loss'])\n plt.ylabel('loss')\n plt.xlabel('epochs')\n plt.show()\n\n\ndef image_preprocessing(img, k, inverted=True):\n img = ImageOps.grayscale(img)\n if inverted:\n img = ImageOps.invert(img)\n img = np.asarray(img)\n pairs = pair_points(img)\n\n cluster_labels = cluster(pairs, k)\n\n images = []\n for i in range(k):\n images.append(cutted_digit(cluster_labels, img, pairs, i))\n\n return images\n\n\ndef cutted_digit(cluster, img, pairs, index, inverted=True):\n positions = np.where(cluster == index)\n img_boundaries = pairs[positions][:]\n\n # Get Square\n y_max = img_boundaries[:, 0].max()\n x_max = img_boundaries[:, 1].max()\n y_min = img_boundaries[:, 0].min()\n x_min = img_boundaries[:, 1].min()\n area = (x_min, y_min, x_max, y_max)\n\n cutted = Image.fromarray(img)\n cutted = cutted.crop(area)\n\n resized = cutted.resize((20, 20))\n # resized.show() # Borrar\n\n resized = np.array(resized)\n\n resized = Image.fromarray(resized)\n resized = ImageOps.invert(resized)\n resized = np.asarray(resized)\n return Image.fromarray(np.pad(resized, ((4, 4), (4, 4)), \"constant\", constant_values=0))\n\n\ndef pair_points(data):\n points = []\n max_x = len(data)\n max_y = len(data[0])\n for i in range(max_x):\n for j in range(max_y):\n if data[i][j] < 125:\n points.append((i, j))\n\n return np.array(points)\n\n\ndef cluster(pairs, k):\n dbscan = KMeans(n_clusters=k)\n cluster = dbscan.fit_predict(pairs)\n plt.scatter(pairs[:, 1], pairs[:, 0], c=cluster, cmap='plasma')\n plt.show()\n return cluster\n\n\ndef predict_images(images):\n\n _, axs = plt.subplots(1, len(images))\n\n for i in range(len(images)):\n image = np.asarray(images[i])\n pred = model.predict(image.reshape(1, 28, 28, 1))\n axs[i].set_title(str(pred.argmax()))\n axs[i].imshow(image, cmap=\"gray\")\n axs[i].axis('off')\n\n plt.show()\n\n\n\n\n\n# TRAINING OR IMPORTING THE MODEL\nmodel = train(x_train, y_train, EPOCHS, OPTIMIZER, net=FILENAME)\n\n# BEST TRY\n# DigitNN-3-adam-20-29-07-2020\n# IMAGE_ONE 12/16 16 False 75%\n# IMAGE_TWO 7/10 10 True 70% \n# IMAGE_THREE 8/10 10 True 80%\n\n# BEST TRY\n# DigitNN-Layers3-Adam-20epochs-30-07-2020\n# IMAGE_ONE 12/16 16 False 75%\n# IMAGE_TWO 7/10 10 True 70% \n# IMAGE_THREE 5/10 10 True 50%\n\n# BEST TRY\n# DigitNN-Layers3-Adam-15epochs-30-07-2020\n# IMAGE_ONE 12/16 16 False 62%\n# IMAGE_TWO 7/10 10 True 70% \n# IMAGE_THREE 7/10 10 True 70%\n\n# # SECOND BEST\n# DigitNN-3-Nadam-20epochs-30-07-2020\n# IMAGE_ONE 12/16 16 False 75%\n# IMAGE_TWO 8/10 10 True 80% \n# IMAGE_THREE 6/10 10 True 60% \n\n\n# THIRD BEST\n# DigitNN-3-Adam-15epochs-30-07-2020\n# IMAGE_ONE 11/16 16 False 68.75%\n# IMAGE_TWO 7/10 10 True 70% \n# IMAGE_THREE 7/10 10 True 70% \n \n# IMAGE CLUSTERING AND SEGMENTATION\n# CLUSTERING: KMEANS\nimages = image_preprocessing(IMAGE_ONE, 16, False)\n\n# RESULTS\npredict_images(images)\n" ]
[ [ "tensorflow.keras.layers.Dropout", "tensorflow.keras.models.load_model", "numpy.pad", "sklearn.cluster.KMeans", "matplotlib.pyplot.scatter", "numpy.asarray", "matplotlib.pyplot.figure", "tensorflow.keras.layers.Dense", "tensorflow.keras.datasets.mnist.load_data", "matplotlib.pyplot.subplot", "matplotlib.pyplot.xlabel", "numpy.array", "matplotlib.pyplot.show", "tensorflow.keras.models.Sequential", "numpy.where", "tensorflow.keras.layers.Flatten", "matplotlib.pyplot.ylabel" ] ]