diff --git a/benchmark/IOAI/IOAI-2025/Individual-Contest/Radar/Solution/Radar_Solution.ipynb b/benchmark/IOAI/IOAI-2025/Individual-Contest/Radar/Solution/Radar_Solution.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..294bd15ac3f335e6c1549e6e9a369a397dd148fc --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/Individual-Contest/Radar/Solution/Radar_Solution.ipynb @@ -0,0 +1,768 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "ab23242e-3c5e-4ba6-9cb9-dfc4d8c22321", + "metadata": {}, + "source": [ + "\"IOAI\n", + "\n", + "[IOAI 2025 (Beijing, China), Individual Contest](https://ioai-official.org/china-2025)\n", + "\n", + "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/IOAI-official/IOAI-2025/blob/main/Individual-Contest/Radar/Solution/Radar_Solution.ipynb)" + ] + }, + { + "cell_type": "markdown", + "id": "f2ea67c2-ec81-4ced-b8a4-a19b591376bb", + "metadata": {}, + "source": [ + "# Radar: Reference Solution" + ] + }, + { + "cell_type": "markdown", + "id": "97ae6685", + "metadata": {}, + "source": [ + "## Configs" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4243ca5d", + "metadata": { + "jupyter": { + "source_hidden": false + } + }, + "outputs": [], + "source": [ + "radar_configs = {\n", + " 'c': 3e8, \n", + " 'startFreq': 77e9, \n", + " 'Tr': 60e-6, # Sweeping frequency time\n", + " 'Idle_time': 100e-6, # free time\n", + " 'Fs': 10e6, # Sampling frequency\n", + " 'Slope': 29.982e12, # chirp slope\n", + " 'Bandwidth': 60e-6 * 29.982e12, # Transmission signal bandwidth\n", + " 'BandwidthValid': 0.767539200e9,# Effective bandwidth of the transmitted signal\n", + " 'range_size': 256, # range size\n", + " 'azimuth_size': 181, # azimuth size\n", + " 'elevation_size': 181, # elevation size\n", + " 'crop_num': 3, # crop some indices in range domain\n", + " 'n_chirps': 128, # number of chirps in one frame\n", + " 'min_azimuth': -90, # min radar azimuth\n", + " 'max_azimuth': 90, # max radar azimuth\n", + " 'min_elevation': -90, # min radar elevation\n", + " 'max_elevation': 90, # max radar elevation \n", + " 'min_range': 1.0, # min radar range\n", + " 'max_range': 25.0, # max radar range\n", + " 'range_res': 3e8/(2*0.767539200e9), \n", + " 'angle_res': 1\n", + "}\n", + "\n", + "dimssnet_configs = {\n", + " 'n_epoch': 10,\n", + " 'batch_size': 2,\n", + " 'learning_rate': 1e-5,\n", + " 'range_size': 50,\n", + " 'azimuth_size': 181,\n", + " 'elevation_size': 181,\n", + " 'doppler_size': 181, \n", + " 'min_azimuth': -90, # min radar azimuth\n", + " 'max_azimuth': 90, # max radar azimuth\n", + " 'min_elevation': -90, # min radar elevation\n", + " 'max_elevation': 90, # max radar elevation \n", + " 'min_range': 1.0, # min radar range\n", + " 'max_range': 25.0, # max radar range\n", + "}\n", + "\n", + "n_class = 5\n", + "class_table = {\n", + " -1: 'background', \n", + " 0: 'suicase', \n", + " 1: 'chair', \n", + " 2: 'person',\n", + " 3: 'wall'\n", + "}" + ] + }, + { + "cell_type": "markdown", + "id": "c39a54f5", + "metadata": {}, + "source": [ + "## Models" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "10817ce8", + "metadata": { + "jupyter": { + "source_hidden": false + } + }, + "outputs": [], + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "\n", + "class BaseEncoder(nn.Module):\n", + " def __init__(self):\n", + " super(BaseEncoder, self).__init__()\n", + " self.conv1a = nn.Conv2d(in_channels=1, out_channels=64, \n", + " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n", + " self.conv1b = nn.Conv2d(in_channels=64, out_channels=64, \n", + " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n", + " self.conv2a = nn.Conv2d(in_channels=64, out_channels=128, \n", + " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n", + " self.conv2b = nn.Conv2d(in_channels=128, out_channels=128, \n", + " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n", + " self.conv3a = nn.Conv2d(in_channels=128, out_channels=256, \n", + " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n", + " self.conv3b = nn.Conv2d(in_channels=256, out_channels=256, \n", + " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n", + "\n", + " self.bn1a = nn.BatchNorm2d(num_features=64)\n", + " self.bn1b = nn.BatchNorm2d(num_features=64)\n", + " self.bn2a = nn.BatchNorm2d(num_features=128)\n", + " self.bn2b = nn.BatchNorm2d(num_features=128)\n", + " self.bn3a = nn.BatchNorm2d(num_features=256)\n", + " self.bn3b = nn.BatchNorm2d(num_features=256)\n", + "\n", + " self.relu = nn.ReLU()\n", + " \n", + " def forward(self, x):\n", + " x = self.relu(self.bn1a(self.conv1a(x)))\n", + " x = self.relu(self.bn1b(self.conv1b(x)))\n", + " x = self.relu(self.bn2a(self.conv2a(x)))\n", + " x = self.relu(self.bn2b(self.conv2b(x)))\n", + " x = self.relu(self.bn3a(self.conv3a(x)))\n", + " x = self.relu(self.bn3b(self.conv3b(x)))\n", + " \n", + " return x\n", + "\n", + "\n", + "class BaseDecoder(nn.Module):\n", + " def __init__(self):\n", + " super(BaseDecoder, self).__init__()\n", + " self.convt1 = nn.ConvTranspose2d(in_channels=256, out_channels=128,\n", + " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n", + " self.convt2 = nn.ConvTranspose2d(in_channels=128, out_channels=64,\n", + " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n", + " self.convt3 = nn.ConvTranspose2d(in_channels=64, out_channels=32,\n", + " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n", + " self.prelu = nn.PReLU()\n", + "\n", + " def forward(self, x):\n", + " x = self.prelu(self.convt1(x))\n", + " x = self.prelu(self.convt2(x))\n", + " x = self.prelu(self.convt3(x))\n", + "\n", + " return x" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ddb913e6", + "metadata": { + "jupyter": { + "source_hidden": false + } + }, + "outputs": [], + "source": [ + "range_size=radar_configs['range_size']\n", + "azimuth_size=radar_configs['azimuth_size']\n", + "elevation_size=radar_configs['elevation_size']\n", + "\n", + "class Fuse_fea(nn.Module):\n", + " def __init__(self):\n", + " super(Fuse_fea, self).__init__()\n", + " self.convt1 = nn.Conv2d(in_channels=192, out_channels=96,\n", + " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n", + " self.convt2 = nn.Conv2d(in_channels=96, out_channels=48,\n", + " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n", + " self.convt3 = nn.Conv2d(in_channels=48, out_channels=24,\n", + " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n", + " self.convt4 = nn.Conv2d(in_channels=24, out_channels=n_class,\n", + " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) \n", + " self.relu = nn.ReLU()\n", + " self.sigmoid = nn.Sigmoid()\n", + "\n", + " def forward(self, feas_sra, feas_dra, feas_sre, feas_dre, feas_srd, feas_drd):\n", + " feas_sre = torch.sum(feas_sre, 3, keepdim=True) # (B, 32, 50, 181) -> (B, 32, 50, 1)\n", + " feas_sre = feas_sre.expand(-1, -1, -1, azimuth_size)\n", + " \n", + " feas_dre = torch.sum(feas_dre, 3, keepdim=True) # (B, 32, 50, 181) -> (B, 32, 50, 1)\n", + " feas_dre = feas_dre.expand(-1, -1, -1, azimuth_size)\n", + "\n", + " feas_srd = torch.sum(feas_srd, 3, keepdim=True) # (B, 32, 50, 181) -> (B, 32, 50, 1)\n", + " feas_srd = feas_srd.expand(-1, -1, -1, azimuth_size)\n", + "\n", + " feas_drd = torch.sum(feas_drd, 3, keepdim=True) # (B, 32, 50, 181) -> (B, 32, 50, 1)\n", + " feas_drd = feas_drd.expand(-1, -1, -1, azimuth_size)\n", + "\n", + " # Resize using bilinear interpolation\n", + " feas_sra = F.interpolate(feas_sra, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n", + " feas_dra = F.interpolate(feas_dra, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n", + " feas_sre = F.interpolate(feas_sre, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n", + " feas_dre = F.interpolate(feas_dre, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n", + " feas_srd = F.interpolate(feas_srd, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n", + " feas_drd = F.interpolate(feas_drd, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n", + " \n", + " feas_ra = torch.cat((feas_sra, feas_dra, feas_sre, feas_dre, feas_srd, feas_drd), 1) # 6*(B, 32, 50, 181) -> (B, 192, 50, 181)\n", + "\n", + " x = self.relu(self.convt1(feas_ra)) # (B, 192, 50, 181) -> (B, 96, 50, 181)\n", + " x = self.relu(self.convt2(x)) # (B, 96, 50, 181) -> (B, 48, 50, 181)\n", + " x = self.relu(self.convt3(x)) # (B, 48, 50, 181) -> (B, 24, 50, 181) \n", + " x = self.sigmoid(self.convt4(x)) # (B, 24, 50, 181) -> (B, 5, 50, 181)\n", + " \n", + " return x\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "483a5ba6", + "metadata": { + "jupyter": { + "source_hidden": false + } + }, + "outputs": [], + "source": [ + "class DIMSSNet(nn.Module):\n", + " def __init__(self):\n", + " super(DIMSSNet, self).__init__()\n", + " self.encode_sra, self.decode_sra = BaseEncoder(), BaseDecoder()\n", + " self.encode_dra, self.decode_dra = BaseEncoder(), BaseDecoder()\n", + " self.encode_sre, self.decode_sre = BaseEncoder(), BaseDecoder()\n", + " self.encode_dre, self.decode_dre = BaseEncoder(), BaseDecoder()\n", + " self.encode_srd, self.decode_srd = BaseEncoder(), BaseDecoder()\n", + " self.encode_drd, self.decode_drd = BaseEncoder(), BaseDecoder()\n", + " \n", + " self.fuse_fea = Fuse_fea()\n", + " \n", + " def forward(self, x_sra, x_dra, x_sre, x_dre, x_srd, x_drd):\n", + " x_sra = self.encode_sra(x_sra)\n", + " feas_sra = self.decode_sra(x_sra) # (B, 32, 50, 181)\n", + " \n", + " x_dra = self.encode_dra(x_dra)\n", + " feas_dra = self.decode_dra(x_dra) # (B, 32, 50, 181)\n", + " \n", + " x_sre = self.encode_sre(x_sre)\n", + " feas_sre = self.decode_sre(x_sre) # (B, 32, 50, 181)\n", + " \n", + " x_dre = self.encode_dre(x_dre)\n", + " feas_dre = self.decode_dre(x_dre) # (B, 32, 50, 181)\n", + "\n", + " x_srd = self.encode_sre(x_srd)\n", + " feas_srd = self.decode_sre(x_srd) # (B, 32, 50, 181)\n", + " \n", + " x_drd = self.encode_dre(x_drd)\n", + " feas_drd = self.decode_dre(x_drd) # (B, 32, 50, 181) \n", + " \n", + " feas = self.fuse_fea(feas_sra, feas_dra, feas_sre, feas_dre, feas_srd, feas_drd) # (B, 32, 50, 181)\n", + "\n", + " return feas" + ] + }, + { + "cell_type": "markdown", + "id": "b8d86ece", + "metadata": {}, + "source": [ + "## Utils" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "49705a8f", + "metadata": { + "jupyter": { + "source_hidden": false + } + }, + "outputs": [], + "source": [ + "import scipy.io\n", + "import numpy as np\n", + "\n", + "# Define the target size\n", + "TARGET_HEIGHT = 50\n", + "TARGET_WIDTH = 181\n", + "\n", + "def load_raw_data(file_path):\n", + " data = scipy.io.loadmat(file_path)\n", + "\n", + " # Range-Azimuth Static\n", + " range_az_static = data['range_az_static']\n", + " range_az_static_prob = data['range_az_music_average_static_probability']\n", + " range_az_static_class2_prob = range_az_static_prob[:, :, 1]\n", + "\n", + " # Range-Elevation Static\n", + " range_ele_static = data['range_ele_static_all']\n", + "\n", + " # Range-Azimuth Dynamic\n", + " range_az_dynamic = data['range_az_dynamic']\n", + " range_az_dynamic_prob = data['range_az_music_average_dynamic_probability']\n", + " range_az_dynamic_class1_prob = range_az_dynamic_prob[:, :, 0]\n", + "\n", + " # Range-Elevation Dynamic\n", + " range_ele_dynamic = data['range_ele_dynamic_all'] \n", + "\n", + " return [range_az_static, range_az_dynamic, range_ele_static,\n", + " range_ele_dynamic, range_az_dynamic_class1_prob, range_az_static_class2_prob]\n", + "\n", + "def generate_parameter():\n", + " parameter = {\n", + " 'c': 3e8, # the speed of light\n", + " 'start_freq': 77e9, # starting frequency\n", + " 'tr': 60e-6, # Sweeping time, that is, the cycle\n", + " 'samples': 256, # sampling point\n", + " 'fs': 10e6, # Sampling rate\n", + " 'tframe_set': 80e-3, # Frame period\n", + " 'range_bin': 256, # range bin\n", + " 'chirps': 128, # chirp number\n", + " 'doppler_bin': 128, # doppler bin\n", + " 'slope': 29.982e12, # chirp slope\n", + " 'bandwidth': 29.982e12 * 60e-6, # Effective bandwidth of the transmitted signal\n", + " 'bandwidth_valid': 256 / 10e6 * 29.982e12, # Transmission signal bandwidth\n", + " 'center_freq': 77e9 + (29.982e12 * 60e-6) / 2, # center frequency\n", + " 'lambda': 3e8 / (77e9 + (29.982e12 * 60e-6) / 2), # wavelength\n", + " 'tx_antenna': [1, 1, 1], # The number of transmitting antennas\n", + " 'rx_antenna': [1, 1, 1, 1], # Number of receiving antennas\n", + " 'tx_num': 3, # The number of transmitting antennas\n", + " 'rx_num': 4, # The number of receiving antennas\n", + " 'virtual_antenna': 12, # Number of virtual antennas\n", + " 'dz': (3e8 / (77e9 + (29.982e12 * 60e-6) / 2)) / 2, # Pitch spacing of the receiving antenna\n", + " 'dx': (3e8 / (77e9 + (29.982e12 * 60e-6) / 2)) / 2, # Horizontal spacing of receiving antennas\n", + " 'num_cpi': 50, # frames\n", + " }\n", + " return parameter\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "id": "c266f24b", + "metadata": {}, + "source": [ + "## Dataloaders" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "892cfb3a", + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "from torch.utils.data import Dataset, DataLoader\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "class CustomDataset(Dataset):\n", + " def __init__(self, file_paths, transform=None):\n", + " self.file_paths = file_paths\n", + " self.transform = transform\n", + " self.file_names = [os.path.basename(path) for path in file_paths]\n", + "\n", + " def __len__(self):\n", + " return len(self.file_paths)\n", + "\n", + " def __getitem__(self, idx):\n", + " data = torch.load(self.file_paths[idx], weights_only=True)\n", + " \n", + " images = data[:6] #first 6 channels are the heatmaps\n", + " labels = data[6] #last channel is the label\n", + " \n", + " images = images.float() \n", + " labels = labels.long() \n", + " labels = labels + 1 #labels are -1 to 3, add 1 to make them 0 to 4\n", + "\n", + " if self.transform:\n", + " images = self.transform(images)\n", + " labels = self.transform(labels)\n", + " \n", + " return images, labels, self.file_names[idx]\n", + "\n", + "class CustomDataset_test(Dataset):\n", + " def __init__(self, file_paths, transform=None):\n", + " self.file_paths = file_paths\n", + " self.transform = transform\n", + " self.file_names = [os.path.basename(path) for path in file_paths]\n", + "\n", + " def __len__(self):\n", + " return len(self.file_paths)\n", + "\n", + " def __getitem__(self, idx):\n", + " data = torch.load(self.file_paths[idx], weights_only=True)\n", + " \n", + " images = data[:6] #only load first 6 channels, labels are not in val_set and test_set\n", + " \n", + " images = images.float() \n", + "\n", + " if self.transform:\n", + " images = self.transform(images)\n", + " \n", + " return images, self.file_names[idx]\n", + "\n", + "# extend base_path to file_path\n", + "def generate_file_paths(base_path):\n", + " file_paths = []\n", + " for frame in os.listdir(base_path):\n", + " frame_path = os.path.join(base_path, frame)\n", + " if frame_path.endswith('.mat.pt'):\n", + " file_paths.append(frame_path)\n", + " return [path for path in file_paths if os.path.exists(path)]\n", + "\n", + "def load_data(base_path, batch_size=4, num_workers=2, test_size=0.2):\n", + " file_paths = generate_file_paths(base_path)\n", + " \n", + " train_paths, test_paths = train_test_split(file_paths, test_size=test_size, random_state=42)\n", + " \n", + " train_dataset = CustomDataset(file_paths=train_paths)\n", + " test_dataset = CustomDataset(file_paths=test_paths)\n", + " \n", + " train_loader = DataLoader(\n", + " train_dataset, \n", + " batch_size=batch_size, \n", + " shuffle=True, \n", + " num_workers=num_workers, \n", + " drop_last=True\n", + " )\n", + " \n", + " test_loader = DataLoader(\n", + " test_dataset, \n", + " batch_size=batch_size, \n", + " shuffle=False, \n", + " num_workers=num_workers, \n", + " drop_last=True\n", + " )\n", + " \n", + " return train_loader, test_loader\n" + ] + }, + { + "cell_type": "markdown", + "id": "67cd6c15", + "metadata": {}, + "source": [ + "## Loss Function" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4c573803", + "metadata": {}, + "outputs": [], + "source": [ + "#Used to handle the problem of class imbalance\n", + "\n", + "def to_one_hot(tensor, nClasses):\n", + " n, h, w = tensor.size()\n", + " one_hot = torch.zeros(n, nClasses, h, w, device=tensor.device)\n", + " index_tensor = tensor.long().view(n, 1, h, w)\n", + " one_hot = one_hot.scatter_(1, index_tensor, 1)\n", + " return one_hot\n", + "\n", + "def _neg_loss(pred, gt):\n", + " pred = torch.clamp(pred, 1e-5, 1-1e-5)\n", + "\n", + " pos_inds = gt.eq(1).float()\n", + " neg_inds = gt.eq(0).float()\n", + "\n", + " balance_cof = 1.0\n", + " pos_loss = torch.log(pred) * torch.pow(1 - pred, 2) * pos_inds * balance_cof\n", + " neg_loss = torch.log(1 - pred) * torch.pow(pred, 2) * neg_inds\n", + " num_pos = pos_inds.float().sum()\n", + " pos_loss_sum = pos_loss.sum()\n", + " neg_loss_sum = neg_loss.sum()\n", + " if num_pos == 0:\n", + " loss = -neg_loss_sum\n", + " else:\n", + " loss = -(pos_loss_sum + neg_loss_sum) / num_pos\n", + " return loss\n", + "\n", + "class FocalLoss(nn.Module):\n", + " def __init__(self):\n", + " super(FocalLoss, self).__init__()\n", + " self.neg_loss = _neg_loss\n", + "\n", + " def forward(self, out, target):\n", + " return self.neg_loss(out, target)" + ] + }, + { + "cell_type": "markdown", + "id": "dec2b582", + "metadata": {}, + "source": [ + "## Train" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7c2f0301", + "metadata": {}, + "outputs": [], + "source": [ + "import torch.optim as optim\n", + "import matplotlib.pyplot as plt\n", + "import time\n", + "\n", + "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "num_epochs = 20\n", + "\n", + "base_path = '../training_set'\n", + "train_loader, test_loader = load_data(\n", + " base_path=base_path,\n", + " batch_size=4,\n", + " num_workers=2,\n", + " test_size=0.2\n", + ")\n", + "\n", + "dimssnet = DIMSSNet().to(device)\n", + "criterion = FocalLoss()\n", + "optimizer = optim.Adam(dimssnet.parameters(), lr=0.001)\n", + "start_time = time.time()\n", + "test_loss_record = []\n", + "train_loss_record = []\n", + "\n", + "for epoch in range(num_epochs):\n", + " dimssnet.train()\n", + " running_loss = 0.0\n", + " for images, labels, _ in train_loader:\n", + " images = images.to(device)\n", + " labels = labels.to(device)\n", + " \n", + " images = [image.unsqueeze(1) for image in images]\n", + " images = torch.stack(images, dim=0)\n", + " images = images.float()\n", + " \n", + " outputs = dimssnet(images[:, 0, :, :], images[:, 1, :, :], images[:, 2, :, :],\n", + " images[:, 3, :, :], images[:, 4, :, :], images[:, 5, :, :])\n", + "\n", + " outputs_resized = F.interpolate(outputs, size=(TARGET_HEIGHT, TARGET_WIDTH), mode='bilinear', align_corners=False)\n", + " labels = to_one_hot(labels, n_class)\n", + " \n", + " loss = criterion(outputs_resized, labels.long())\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + " \n", + " running_loss += loss.item()\n", + "\n", + " test_loss = 0.0\n", + " dimssnet.eval()\n", + " with torch.no_grad():\n", + " for images, labels, _ in test_loader:\n", + " images = images.to(device)\n", + " labels = labels.to(device)\n", + " \n", + " images = [image.unsqueeze(1) for image in images]\n", + " images = torch.stack(images, dim=0)\n", + " images = images.float()\n", + " \n", + " outputs = dimssnet(images[:, 0, :, :], images[:, 1, :, :], images[:, 2, :, :],\n", + " images[:, 3, :, :], images[:, 4, :, :], images[:, 5, :, :])\n", + " \n", + " outputs_resized = F.interpolate(outputs, size=(TARGET_HEIGHT, TARGET_WIDTH), mode='bilinear', align_corners=False)\n", + " labels = to_one_hot(labels, n_class)\n", + " \n", + " loss = criterion(outputs_resized, labels.long())\n", + " test_loss += loss.item()\n", + " \n", + " test_loss_record.append(test_loss/len(test_loader))\n", + " train_loss_record.append(running_loss/len(train_loader))\n", + " print(f\"Epoch {epoch+1}/{num_epochs}, Training Loss: {running_loss/len(train_loader):.4f}, Test Loss: {test_loss/len(test_loader):.4f}\")\n", + "\n", + "# Create a new state_dict and add the \"model\" prefix, in order to match the loading method in metrics\n", + "new_state_dict = {}\n", + "for k, v in dimssnet.state_dict().items():\n", + " new_key = f\"model.{k}\" \n", + " new_state_dict[new_key] = v\n", + "\n", + "print(\"dimssnet successfully saved!\") \n", + "print(\"Training finished.\")\n", + "end_time = time.time()\n", + "total_time = end_time - start_time\n", + "print(f\"Training completed in {total_time} seconds\")" + ] + }, + { + "cell_type": "markdown", + "id": "f001aee8", + "metadata": {}, + "source": [ + "## Inference" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8b330819", + "metadata": {}, + "outputs": [], + "source": [ + "# Run inference on validation set and testing set\n", + "import pandas as pd\n", + "\n", + "def run_inference(model, data_loader):\n", + " model.eval()\n", + " predictions = []\n", + " filenames = []\n", + " \n", + " with torch.no_grad():\n", + " for images, file_names in data_loader:\n", + " images = images.cuda() if torch.cuda.is_available() else images\n", + " \n", + " x = [image.unsqueeze(1) for image in images]\n", + " x = torch.stack(x, dim=0)\n", + " x = x.float()\n", + " \n", + " # Forward propagation\n", + " outputs = model(x[:, 0, :, :], x[:, 1, :, :], x[:, 2, :, :],\n", + " x[:, 3, :, :], x[:, 4, :, :], x[:, 5, :, :])\n", + " \n", + " # Adjust the output size\n", + " outputs = F.interpolate(outputs, size=(50, 181), mode='bilinear', align_corners=False)\n", + "\n", + " preds = torch.argmax(outputs, dim=1)\n", + " \n", + " preds = preds - 1\n", + " \n", + " for i, pred in enumerate(preds):\n", + " predictions.append(pred.cpu().numpy().flatten())\n", + " filenames.append(file_names[i])\n", + " \n", + " return predictions, filenames\n", + "\n", + "# Load validation set\n", + "if os.environ.get('DATA_PATH'):\n", + " DATA_PATH = os.environ.get(\"DATA_PATH\") + \"/\" \n", + "else:\n", + " DATA_PATH = \"\" # Fallback for local testing\n", + "# Load validation set\n", + "val_paths = generate_file_paths(DATA_PATH + 'validation_set')\n", + "val_dataset = CustomDataset_test(file_paths=val_paths)\n", + "val_loader = DataLoader(\n", + " val_dataset,\n", + " batch_size=1,\n", + " shuffle=False,\n", + " num_workers=0\n", + ")\n", + "\n", + "# Load testing set\n", + "if os.environ.get('DATA_PATH'):\n", + " DATA_PATH = os.environ.get(\"DATA_PATH\") + \"/\" \n", + "else:\n", + " DATA_PATH = \"\" # Fallback for local testing\n", + "# Load testing set\n", + "test_paths = generate_file_paths(DATA_PATH + 'testing_set')\n", + "test_dataset = CustomDataset_test(file_paths=test_paths)\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=1,\n", + " shuffle=False,\n", + " num_workers=0\n", + ")\n", + "\n", + "# Run inference on validation set\n", + "print(\"Running inference on validation set...\")\n", + "val_predictions, val_filenames = run_inference(dimssnet, val_loader)\n", + "\n", + "# Save validation results to CSV\n", + "val_results = []\n", + "for filename, pred in zip(val_filenames, val_predictions):\n", + " # Create a row with filename and flattened predictions\n", + " row = {'filename': filename}\n", + " for i, p in enumerate(pred):\n", + " row[f'pixel_{i}'] = p\n", + " val_results.append(row)\n", + "\n", + "val_df = pd.DataFrame(val_results)\n", + "val_df.to_csv('submission_val.csv', index=False)\n", + "print(f\"Validation results saved to output_validation.csv with shape: {val_df.shape}\")\n", + "\n", + "# Run inference on testing set\n", + "print(\"Running inference on testing set...\")\n", + "test_predictions, test_filenames = run_inference(dimssnet, test_loader)\n", + "\n", + "# Save testing results to CSV\n", + "test_results = []\n", + "for filename, pred in zip(test_filenames, test_predictions):\n", + " # Create a row with filename and flattened predictions\n", + " row = {'filename': filename}\n", + " for i, p in enumerate(pred):\n", + " row[f'pixel_{i}'] = p\n", + " test_results.append(row)\n", + "\n", + "test_df = pd.DataFrame(test_results)\n", + "test_df.to_csv('submission_test.csv', index=False)\n", + "print(f\"Testing results saved to output_testing.csv with shape: {test_df.shape}\")\n", + "\n", + "print(\"\\nInference completed! Results saved to:\")\n", + "print(\"- submission_val_ref.csv (for validation set leaderboard)\")\n", + "print(\"- submission_test_ref.csv (for testing set leaderboard)\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "72fde72d", + "metadata": {}, + "outputs": [], + "source": [ + "import zipfile\n", + "import os\n", + "\n", + "# Define the files to zip and the zip file name.\n", + "files_to_zip = ['submission_val.csv', 'submission_test.csv']\n", + "zip_filename = 'submission.zip'\n", + "\n", + "# Create a zip file\n", + "with zipfile.ZipFile(zip_filename, 'w') as zipf:\n", + " for file in files_to_zip:\n", + " # Add the file to the zip fil\n", + " zipf.write(file, os.path.basename(file))\n", + "\n", + "print(f'{zip_filename} Created successfully!')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "ioai", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.11" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/intelccompiler.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/intelccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..3386775ee56ab03fe476c08653d99a19d532e47a --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/intelccompiler.py @@ -0,0 +1,113 @@ +from __future__ import division, absolute_import, print_function + +import platform + +from distutils.unixccompiler import UnixCCompiler +from numpy.distutils.exec_command import find_executable +from numpy.distutils.ccompiler import simple_version_match +if platform.system() == 'Windows': + from numpy.distutils.msvc9compiler import MSVCCompiler + + +class IntelCCompiler(UnixCCompiler): + """A modified Intel compiler compatible with a GCC-built Python.""" + compiler_type = 'intel' + cc_exe = 'icc' + cc_args = 'fPIC' + + def __init__(self, verbose=0, dry_run=0, force=0): + UnixCCompiler.__init__(self, verbose, dry_run, force) + + v = self.get_version() + mpopt = 'openmp' if v and v < '15' else 'qopenmp' + self.cc_exe = ('icc -fPIC -fp-model strict -O3 ' + '-fomit-frame-pointer -{}').format(mpopt) + compiler = self.cc_exe + + if platform.system() == 'Darwin': + shared_flag = '-Wl,-undefined,dynamic_lookup' + else: + shared_flag = '-shared' + self.set_executables(compiler=compiler, + compiler_so=compiler, + compiler_cxx=compiler, + archiver='xiar' + ' cru', + linker_exe=compiler + ' -shared-intel', + linker_so=compiler + ' ' + shared_flag + + ' -shared-intel') + + +class IntelItaniumCCompiler(IntelCCompiler): + compiler_type = 'intele' + + # On Itanium, the Intel Compiler used to be called ecc, let's search for + # it (now it's also icc, so ecc is last in the search). + for cc_exe in map(find_executable, ['icc', 'ecc']): + if cc_exe: + break + + +class IntelEM64TCCompiler(UnixCCompiler): + """ + A modified Intel x86_64 compiler compatible with a 64bit GCC-built Python. + """ + compiler_type = 'intelem' + cc_exe = 'icc -m64' + cc_args = '-fPIC' + + def __init__(self, verbose=0, dry_run=0, force=0): + UnixCCompiler.__init__(self, verbose, dry_run, force) + + v = self.get_version() + mpopt = 'openmp' if v and v < '15' else 'qopenmp' + self.cc_exe = ('icc -m64 -fPIC -fp-model strict -O3 ' + '-fomit-frame-pointer -{}').format(mpopt) + compiler = self.cc_exe + + if platform.system() == 'Darwin': + shared_flag = '-Wl,-undefined,dynamic_lookup' + else: + shared_flag = '-shared' + self.set_executables(compiler=compiler, + compiler_so=compiler, + compiler_cxx=compiler, + archiver='xiar' + ' cru', + linker_exe=compiler + ' -shared-intel', + linker_so=compiler + ' ' + shared_flag + + ' -shared-intel') + + +if platform.system() == 'Windows': + class IntelCCompilerW(MSVCCompiler): + """ + A modified Intel compiler compatible with an MSVC-built Python. + """ + compiler_type = 'intelw' + compiler_cxx = 'icl' + + def __init__(self, verbose=0, dry_run=0, force=0): + MSVCCompiler.__init__(self, verbose, dry_run, force) + version_match = simple_version_match(start=r'Intel\(R\).*?32,') + self.__version = version_match + + def initialize(self, plat_name=None): + MSVCCompiler.initialize(self, plat_name) + self.cc = self.find_exe('icl.exe') + self.lib = self.find_exe('xilib') + self.linker = self.find_exe('xilink') + self.compile_options = ['/nologo', '/O3', '/MD', '/W3', + '/Qstd=c99'] + self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', + '/Qstd=c99', '/Z7', '/D_DEBUG'] + + class IntelEM64TCCompilerW(IntelCCompilerW): + """ + A modified Intel x86_64 compiler compatible with + a 64bit MSVC-built Python. + """ + compiler_type = 'intelemw' + + def __init__(self, verbose=0, dry_run=0, force=0): + MSVCCompiler.__init__(self, verbose, dry_run, force) + version_match = simple_version_match(start=r'Intel\(R\).*?64,') + self.__version = version_match diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/lib2def.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/lib2def.py new file mode 100644 index 0000000000000000000000000000000000000000..2d013a1e3d411d5949af9c91599617cd3f0e902c --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/lib2def.py @@ -0,0 +1,115 @@ +from __future__ import division, absolute_import, print_function + +import re +import sys +import subprocess + +__doc__ = """This module generates a DEF file from the symbols in +an MSVC-compiled DLL import library. It correctly discriminates between +data and functions. The data is collected from the output of the program +nm(1). + +Usage: + python lib2def.py [libname.lib] [output.def] +or + python lib2def.py [libname.lib] > output.def + +libname.lib defaults to python.lib and output.def defaults to stdout + +Author: Robert Kern +Last Update: April 30, 1999 +""" + +__version__ = '0.1a' + +py_ver = "%d%d" % tuple(sys.version_info[:2]) + +DEFAULT_NM = 'nm -Cs' + +DEF_HEADER = """LIBRARY python%s.dll +;CODE PRELOAD MOVEABLE DISCARDABLE +;DATA PRELOAD SINGLE + +EXPORTS +""" % py_ver +# the header of the DEF file + +FUNC_RE = re.compile(r"^(.*) in python%s\.dll" % py_ver, re.MULTILINE) +DATA_RE = re.compile(r"^_imp__(.*) in python%s\.dll" % py_ver, re.MULTILINE) + +def parse_cmd(): + """Parses the command-line arguments. + +libfile, deffile = parse_cmd()""" + if len(sys.argv) == 3: + if sys.argv[1][-4:] == '.lib' and sys.argv[2][-4:] == '.def': + libfile, deffile = sys.argv[1:] + elif sys.argv[1][-4:] == '.def' and sys.argv[2][-4:] == '.lib': + deffile, libfile = sys.argv[1:] + else: + print("I'm assuming that your first argument is the library") + print("and the second is the DEF file.") + elif len(sys.argv) == 2: + if sys.argv[1][-4:] == '.def': + deffile = sys.argv[1] + libfile = 'python%s.lib' % py_ver + elif sys.argv[1][-4:] == '.lib': + deffile = None + libfile = sys.argv[1] + else: + libfile = 'python%s.lib' % py_ver + deffile = None + return libfile, deffile + +def getnm(nm_cmd = ['nm', '-Cs', 'python%s.lib' % py_ver]): + """Returns the output of nm_cmd via a pipe. + +nm_output = getnam(nm_cmd = 'nm -Cs py_lib')""" + f = subprocess.Popen(nm_cmd, shell=True, stdout=subprocess.PIPE, universal_newlines=True) + nm_output = f.stdout.read() + f.stdout.close() + return nm_output + +def parse_nm(nm_output): + """Returns a tuple of lists: dlist for the list of data +symbols and flist for the list of function symbols. + +dlist, flist = parse_nm(nm_output)""" + data = DATA_RE.findall(nm_output) + func = FUNC_RE.findall(nm_output) + + flist = [] + for sym in data: + if sym in func and (sym[:2] == 'Py' or sym[:3] == '_Py' or sym[:4] == 'init'): + flist.append(sym) + + dlist = [] + for sym in data: + if sym not in flist and (sym[:2] == 'Py' or sym[:3] == '_Py'): + dlist.append(sym) + + dlist.sort() + flist.sort() + return dlist, flist + +def output_def(dlist, flist, header, file = sys.stdout): + """Outputs the final DEF file to a file defaulting to stdout. + +output_def(dlist, flist, header, file = sys.stdout)""" + for data_sym in dlist: + header = header + '\t%s DATA\n' % data_sym + header = header + '\n' # blank line + for func_sym in flist: + header = header + '\t%s\n' % func_sym + file.write(header) + +if __name__ == '__main__': + libfile, deffile = parse_cmd() + if deffile is None: + deffile = sys.stdout + else: + deffile = open(deffile, 'w') + nm_cmd = [str(DEFAULT_NM), str(libfile)] + nm_output = getnm(nm_cmd) + dlist, flist = parse_nm(nm_output) + output_def(dlist, flist, DEF_HEADER, deffile) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/line_endings.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/line_endings.py new file mode 100644 index 0000000000000000000000000000000000000000..5ecb104ffdf5181c5d7773885aa2f3a69e57f0a3 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/line_endings.py @@ -0,0 +1,76 @@ +""" Functions for converting from DOS to UNIX line endings + +""" +from __future__ import division, absolute_import, print_function + +import sys, re, os + +def dos2unix(file): + "Replace CRLF with LF in argument files. Print names of changed files." + if os.path.isdir(file): + print(file, "Directory!") + return + + data = open(file, "rb").read() + if '\0' in data: + print(file, "Binary!") + return + + newdata = re.sub("\r\n", "\n", data) + if newdata != data: + print('dos2unix:', file) + f = open(file, "wb") + f.write(newdata) + f.close() + return file + else: + print(file, 'ok') + +def dos2unix_one_dir(modified_files, dir_name, file_names): + for file in file_names: + full_path = os.path.join(dir_name, file) + file = dos2unix(full_path) + if file is not None: + modified_files.append(file) + +def dos2unix_dir(dir_name): + modified_files = [] + os.path.walk(dir_name, dos2unix_one_dir, modified_files) + return modified_files +#---------------------------------- + +def unix2dos(file): + "Replace LF with CRLF in argument files. Print names of changed files." + if os.path.isdir(file): + print(file, "Directory!") + return + + data = open(file, "rb").read() + if '\0' in data: + print(file, "Binary!") + return + newdata = re.sub("\r\n", "\n", data) + newdata = re.sub("\n", "\r\n", newdata) + if newdata != data: + print('unix2dos:', file) + f = open(file, "wb") + f.write(newdata) + f.close() + return file + else: + print(file, 'ok') + +def unix2dos_one_dir(modified_files, dir_name, file_names): + for file in file_names: + full_path = os.path.join(dir_name, file) + unix2dos(full_path) + if file is not None: + modified_files.append(file) + +def unix2dos_dir(dir_name): + modified_files = [] + os.path.walk(dir_name, unix2dos_one_dir, modified_files) + return modified_files + +if __name__ == "__main__": + dos2unix_dir(sys.argv[1]) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/log.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/log.py new file mode 100644 index 0000000000000000000000000000000000000000..37f9fe5dd0ef6c2f76185b2465a4d07fe8f44656 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/log.py @@ -0,0 +1,93 @@ +# Colored log, requires Python 2.3 or up. +from __future__ import division, absolute_import, print_function + +import sys +from distutils.log import * +from distutils.log import Log as old_Log +from distutils.log import _global_log + +if sys.version_info[0] < 3: + from .misc_util import (red_text, default_text, cyan_text, green_text, + is_sequence, is_string) +else: + from numpy.distutils.misc_util import (red_text, default_text, cyan_text, + green_text, is_sequence, is_string) + + +def _fix_args(args,flag=1): + if is_string(args): + return args.replace('%', '%%') + if flag and is_sequence(args): + return tuple([_fix_args(a, flag=0) for a in args]) + return args + + +class Log(old_Log): + def _log(self, level, msg, args): + if level >= self.threshold: + if args: + msg = msg % _fix_args(args) + if 0: + if msg.startswith('copying ') and msg.find(' -> ') != -1: + return + if msg.startswith('byte-compiling '): + return + print(_global_color_map[level](msg)) + sys.stdout.flush() + + def good(self, msg, *args): + """ + If we log WARN messages, log this message as a 'nice' anti-warn + message. + + """ + if WARN >= self.threshold: + if args: + print(green_text(msg % _fix_args(args))) + else: + print(green_text(msg)) + sys.stdout.flush() + + +_global_log.__class__ = Log + +good = _global_log.good + +def set_threshold(level, force=False): + prev_level = _global_log.threshold + if prev_level > DEBUG or force: + # If we're running at DEBUG, don't change the threshold, as there's + # likely a good reason why we're running at this level. + _global_log.threshold = level + if level <= DEBUG: + info('set_threshold: setting threshold to DEBUG level,' + ' it can be changed only with force argument') + else: + info('set_threshold: not changing threshold from DEBUG level' + ' %s to %s' % (prev_level, level)) + return prev_level + + +def set_verbosity(v, force=False): + prev_level = _global_log.threshold + if v < 0: + set_threshold(ERROR, force) + elif v == 0: + set_threshold(WARN, force) + elif v == 1: + set_threshold(INFO, force) + elif v >= 2: + set_threshold(DEBUG, force) + return {FATAL:-2,ERROR:-1,WARN:0,INFO:1,DEBUG:2}.get(prev_level, 1) + + +_global_color_map = { + DEBUG:cyan_text, + INFO:default_text, + WARN:red_text, + ERROR:red_text, + FATAL:red_text +} + +# don't use INFO,.. flags in set_verbosity, these flags are for set_threshold. +set_verbosity(0, force=True) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/mingw32ccompiler.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/mingw32ccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..e6bbe1996a7c0a4f448521a9866f3864c06ce55a --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/mingw32ccompiler.py @@ -0,0 +1,656 @@ +""" +Support code for building Python extensions on Windows. + + # NT stuff + # 1. Make sure libpython.a exists for gcc. If not, build it. + # 2. Force windows to use gcc (we're struggling with MSVC and g77 support) + # 3. Force windows to use g77 + +""" +from __future__ import division, absolute_import, print_function + +import os +import sys +import subprocess +import re + +# Overwrite certain distutils.ccompiler functions: +import numpy.distutils.ccompiler + +if sys.version_info[0] < 3: + from . import log +else: + from numpy.distutils import log +# NT stuff +# 1. Make sure libpython.a exists for gcc. If not, build it. +# 2. Force windows to use gcc (we're struggling with MSVC and g77 support) +# --> this is done in numpy/distutils/ccompiler.py +# 3. Force windows to use g77 + +import distutils.cygwinccompiler +from distutils.version import StrictVersion +from numpy.distutils.ccompiler import gen_preprocess_options, gen_lib_options +from distutils.unixccompiler import UnixCCompiler +from distutils.msvccompiler import get_build_version as get_build_msvc_version +from distutils.errors import (DistutilsExecError, CompileError, + UnknownFileError) +from numpy.distutils.misc_util import (msvc_runtime_library, + msvc_runtime_version, + msvc_runtime_major, + get_build_architecture) + +def get_msvcr_replacement(): + """Replacement for outdated version of get_msvcr from cygwinccompiler""" + msvcr = msvc_runtime_library() + return [] if msvcr is None else [msvcr] + +# monkey-patch cygwinccompiler with our updated version from misc_util +# to avoid getting an exception raised on Python 3.5 +distutils.cygwinccompiler.get_msvcr = get_msvcr_replacement + +# Useful to generate table of symbols from a dll +_START = re.compile(r'\[Ordinal/Name Pointer\] Table') +_TABLE = re.compile(r'^\s+\[([\s*[0-9]*)\] ([a-zA-Z0-9_]*)') + +# the same as cygwin plus some additional parameters +class Mingw32CCompiler(distutils.cygwinccompiler.CygwinCCompiler): + """ A modified MingW32 compiler compatible with an MSVC built Python. + + """ + + compiler_type = 'mingw32' + + def __init__ (self, + verbose=0, + dry_run=0, + force=0): + + distutils.cygwinccompiler.CygwinCCompiler.__init__ (self, verbose, + dry_run, force) + + # we need to support 3.2 which doesn't match the standard + # get_versions methods regex + if self.gcc_version is None: + p = subprocess.Popen(['gcc', '-dumpversion'], shell=True, + stdout=subprocess.PIPE) + out_string = p.stdout.read() + p.stdout.close() + result = re.search(r'(\d+\.\d+)', out_string) + if result: + self.gcc_version = StrictVersion(result.group(1)) + + # A real mingw32 doesn't need to specify a different entry point, + # but cygwin 2.91.57 in no-cygwin-mode needs it. + if self.gcc_version <= "2.91.57": + entry_point = '--entry _DllMain@12' + else: + entry_point = '' + + if self.linker_dll == 'dllwrap': + # Commented out '--driver-name g++' part that fixes weird + # g++.exe: g++: No such file or directory + # error (mingw 1.0 in Enthon24 tree, gcc-3.4.5). + # If the --driver-name part is required for some environment + # then make the inclusion of this part specific to that + # environment. + self.linker = 'dllwrap' # --driver-name g++' + elif self.linker_dll == 'gcc': + self.linker = 'g++' + + # **changes: eric jones 4/11/01 + # 1. Check for import library on Windows. Build if it doesn't exist. + + build_import_library() + + # Check for custom msvc runtime library on Windows. Build if it doesn't exist. + msvcr_success = build_msvcr_library() + msvcr_dbg_success = build_msvcr_library(debug=True) + if msvcr_success or msvcr_dbg_success: + # add preprocessor statement for using customized msvcr lib + self.define_macro('NPY_MINGW_USE_CUSTOM_MSVCR') + + # Define the MSVC version as hint for MinGW + msvcr_version = msvc_runtime_version() + if msvcr_version: + self.define_macro('__MSVCRT_VERSION__', '0x%04i' % msvcr_version) + + # MS_WIN64 should be defined when building for amd64 on windows, + # but python headers define it only for MS compilers, which has all + # kind of bad consequences, like using Py_ModuleInit4 instead of + # Py_ModuleInit4_64, etc... So we add it here + if get_build_architecture() == 'AMD64': + if self.gcc_version < "4.0": + self.set_executables( + compiler='gcc -g -DDEBUG -DMS_WIN64 -mno-cygwin -O0 -Wall', + compiler_so='gcc -g -DDEBUG -DMS_WIN64 -mno-cygwin -O0' + ' -Wall -Wstrict-prototypes', + linker_exe='gcc -g -mno-cygwin', + linker_so='gcc -g -mno-cygwin -shared') + else: + # gcc-4 series releases do not support -mno-cygwin option + self.set_executables( + compiler='gcc -g -DDEBUG -DMS_WIN64 -O0 -Wall', + compiler_so='gcc -g -DDEBUG -DMS_WIN64 -O0 -Wall -Wstrict-prototypes', + linker_exe='gcc -g', + linker_so='gcc -g -shared') + else: + if self.gcc_version <= "3.0.0": + self.set_executables( + compiler='gcc -mno-cygwin -O2 -w', + compiler_so='gcc -mno-cygwin -mdll -O2 -w' + ' -Wstrict-prototypes', + linker_exe='g++ -mno-cygwin', + linker_so='%s -mno-cygwin -mdll -static %s' % + (self.linker, entry_point)) + elif self.gcc_version < "4.0": + self.set_executables( + compiler='gcc -mno-cygwin -O2 -Wall', + compiler_so='gcc -mno-cygwin -O2 -Wall' + ' -Wstrict-prototypes', + linker_exe='g++ -mno-cygwin', + linker_so='g++ -mno-cygwin -shared') + else: + # gcc-4 series releases do not support -mno-cygwin option + self.set_executables(compiler='gcc -O2 -Wall', + compiler_so='gcc -O2 -Wall -Wstrict-prototypes', + linker_exe='g++ ', + linker_so='g++ -shared') + # added for python2.3 support + # we can't pass it through set_executables because pre 2.2 would fail + self.compiler_cxx = ['g++'] + + # Maybe we should also append -mthreads, but then the finished dlls + # need another dll (mingwm10.dll see Mingw32 docs) (-mthreads: Support + # thread-safe exception handling on `Mingw32') + + # no additional libraries needed + #self.dll_libraries=[] + return + + # __init__ () + + def link(self, + target_desc, + objects, + output_filename, + output_dir, + libraries, + library_dirs, + runtime_library_dirs, + export_symbols = None, + debug=0, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None): + # Include the appropriate MSVC runtime library if Python was built + # with MSVC >= 7.0 (MinGW standard is msvcrt) + runtime_library = msvc_runtime_library() + if runtime_library: + if not libraries: + libraries = [] + libraries.append(runtime_library) + args = (self, + target_desc, + objects, + output_filename, + output_dir, + libraries, + library_dirs, + runtime_library_dirs, + None, #export_symbols, we do this in our def-file + debug, + extra_preargs, + extra_postargs, + build_temp, + target_lang) + if self.gcc_version < "3.0.0": + func = distutils.cygwinccompiler.CygwinCCompiler.link + else: + func = UnixCCompiler.link + func(*args[:func.__code__.co_argcount]) + return + + def object_filenames (self, + source_filenames, + strip_dir=0, + output_dir=''): + if output_dir is None: output_dir = '' + obj_names = [] + for src_name in source_filenames: + # use normcase to make sure '.rc' is really '.rc' and not '.RC' + (base, ext) = os.path.splitext (os.path.normcase(src_name)) + + # added these lines to strip off windows drive letters + # without it, .o files are placed next to .c files + # instead of the build directory + drv, base = os.path.splitdrive(base) + if drv: + base = base[1:] + + if ext not in (self.src_extensions + ['.rc', '.res']): + raise UnknownFileError( + "unknown file type '%s' (from '%s')" % \ + (ext, src_name)) + if strip_dir: + base = os.path.basename (base) + if ext == '.res' or ext == '.rc': + # these need to be compiled to object files + obj_names.append (os.path.join (output_dir, + base + ext + self.obj_extension)) + else: + obj_names.append (os.path.join (output_dir, + base + self.obj_extension)) + return obj_names + + # object_filenames () + + +def find_python_dll(): + # We can't do much here: + # - find it in the virtualenv (sys.prefix) + # - find it in python main dir (sys.base_prefix, if in a virtualenv) + # - sys.real_prefix is main dir for virtualenvs in Python 2.7 + # - in system32, + # - ortherwise (Sxs), I don't know how to get it. + stems = [sys.prefix] + if hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix: + stems.append(sys.base_prefix) + elif hasattr(sys, 'real_prefix') and sys.real_prefix != sys.prefix: + stems.append(sys.real_prefix) + + sub_dirs = ['', 'lib', 'bin'] + # generate possible combinations of directory trees and sub-directories + lib_dirs = [] + for stem in stems: + for folder in sub_dirs: + lib_dirs.append(os.path.join(stem, folder)) + + # add system directory as well + if 'SYSTEMROOT' in os.environ: + lib_dirs.append(os.path.join(os.environ['SYSTEMROOT'], 'System32')) + + # search in the file system for possible candidates + major_version, minor_version = tuple(sys.version_info[:2]) + patterns = ['python%d%d.dll'] + + for pat in patterns: + dllname = pat % (major_version, minor_version) + print("Looking for %s" % dllname) + for folder in lib_dirs: + dll = os.path.join(folder, dllname) + if os.path.exists(dll): + return dll + + raise ValueError("%s not found in %s" % (dllname, lib_dirs)) + +def dump_table(dll): + st = subprocess.Popen(["objdump.exe", "-p", dll], stdout=subprocess.PIPE) + return st.stdout.readlines() + +def generate_def(dll, dfile): + """Given a dll file location, get all its exported symbols and dump them + into the given def file. + + The .def file will be overwritten""" + dump = dump_table(dll) + for i in range(len(dump)): + if _START.match(dump[i].decode()): + break + else: + raise ValueError("Symbol table not found") + + syms = [] + for j in range(i+1, len(dump)): + m = _TABLE.match(dump[j].decode()) + if m: + syms.append((int(m.group(1).strip()), m.group(2))) + else: + break + + if len(syms) == 0: + log.warn('No symbols found in %s' % dll) + + d = open(dfile, 'w') + d.write('LIBRARY %s\n' % os.path.basename(dll)) + d.write(';CODE PRELOAD MOVEABLE DISCARDABLE\n') + d.write(';DATA PRELOAD SINGLE\n') + d.write('\nEXPORTS\n') + for s in syms: + #d.write('@%d %s\n' % (s[0], s[1])) + d.write('%s\n' % s[1]) + d.close() + +def find_dll(dll_name): + + arch = {'AMD64' : 'amd64', + 'Intel' : 'x86'}[get_build_architecture()] + + def _find_dll_in_winsxs(dll_name): + # Walk through the WinSxS directory to find the dll. + winsxs_path = os.path.join(os.environ.get('WINDIR', r'C:\WINDOWS'), + 'winsxs') + if not os.path.exists(winsxs_path): + return None + for root, dirs, files in os.walk(winsxs_path): + if dll_name in files and arch in root: + return os.path.join(root, dll_name) + return None + + def _find_dll_in_path(dll_name): + # First, look in the Python directory, then scan PATH for + # the given dll name. + for path in [sys.prefix] + os.environ['PATH'].split(';'): + filepath = os.path.join(path, dll_name) + if os.path.exists(filepath): + return os.path.abspath(filepath) + + return _find_dll_in_winsxs(dll_name) or _find_dll_in_path(dll_name) + +def build_msvcr_library(debug=False): + if os.name != 'nt': + return False + + # If the version number is None, then we couldn't find the MSVC runtime at + # all, because we are running on a Python distribution which is customed + # compiled; trust that the compiler is the same as the one available to us + # now, and that it is capable of linking with the correct runtime without + # any extra options. + msvcr_ver = msvc_runtime_major() + if msvcr_ver is None: + log.debug('Skip building import library: ' + 'Runtime is not compiled with MSVC') + return False + + # Skip using a custom library for versions < MSVC 8.0 + if msvcr_ver < 80: + log.debug('Skip building msvcr library:' + ' custom functionality not present') + return False + + msvcr_name = msvc_runtime_library() + if debug: + msvcr_name += 'd' + + # Skip if custom library already exists + out_name = "lib%s.a" % msvcr_name + out_file = os.path.join(sys.prefix, 'libs', out_name) + if os.path.isfile(out_file): + log.debug('Skip building msvcr library: "%s" exists' % + (out_file,)) + return True + + # Find the msvcr dll + msvcr_dll_name = msvcr_name + '.dll' + dll_file = find_dll(msvcr_dll_name) + if not dll_file: + log.warn('Cannot build msvcr library: "%s" not found' % + msvcr_dll_name) + return False + + def_name = "lib%s.def" % msvcr_name + def_file = os.path.join(sys.prefix, 'libs', def_name) + + log.info('Building msvcr library: "%s" (from %s)' \ + % (out_file, dll_file)) + + # Generate a symbol definition file from the msvcr dll + generate_def(dll_file, def_file) + + # Create a custom mingw library for the given symbol definitions + cmd = ['dlltool', '-d', def_file, '-l', out_file] + retcode = subprocess.call(cmd) + + # Clean up symbol definitions + os.remove(def_file) + + return (not retcode) + +def build_import_library(): + if os.name != 'nt': + return + + arch = get_build_architecture() + if arch == 'AMD64': + return _build_import_library_amd64() + elif arch == 'Intel': + return _build_import_library_x86() + else: + raise ValueError("Unhandled arch %s" % arch) + +def _check_for_import_lib(): + """Check if an import library for the Python runtime already exists.""" + major_version, minor_version = tuple(sys.version_info[:2]) + + # patterns for the file name of the library itself + patterns = ['libpython%d%d.a', + 'libpython%d%d.dll.a', + 'libpython%d.%d.dll.a'] + + # directory trees that may contain the library + stems = [sys.prefix] + if hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix: + stems.append(sys.base_prefix) + elif hasattr(sys, 'real_prefix') and sys.real_prefix != sys.prefix: + stems.append(sys.real_prefix) + + # possible subdirectories within those trees where it is placed + sub_dirs = ['libs', 'lib'] + + # generate a list of candidate locations + candidates = [] + for pat in patterns: + filename = pat % (major_version, minor_version) + for stem_dir in stems: + for folder in sub_dirs: + candidates.append(os.path.join(stem_dir, folder, filename)) + + # test the filesystem to see if we can find any of these + for fullname in candidates: + if os.path.isfile(fullname): + # already exists, in location given + return (True, fullname) + + # needs to be built, preferred location given first + return (False, candidates[0]) + +def _build_import_library_amd64(): + out_exists, out_file = _check_for_import_lib() + if out_exists: + log.debug('Skip building import library: "%s" exists', out_file) + return + + # get the runtime dll for which we are building import library + dll_file = find_python_dll() + log.info('Building import library (arch=AMD64): "%s" (from %s)' % + (out_file, dll_file)) + + # generate symbol list from this library + def_name = "python%d%d.def" % tuple(sys.version_info[:2]) + def_file = os.path.join(sys.prefix, 'libs', def_name) + generate_def(dll_file, def_file) + + # generate import library from this symbol list + cmd = ['dlltool', '-d', def_file, '-l', out_file] + subprocess.Popen(cmd) + +def _build_import_library_x86(): + """ Build the import libraries for Mingw32-gcc on Windows + """ + out_exists, out_file = _check_for_import_lib() + if out_exists: + log.debug('Skip building import library: "%s" exists', out_file) + return + + lib_name = "python%d%d.lib" % tuple(sys.version_info[:2]) + lib_file = os.path.join(sys.prefix, 'libs', lib_name) + if not os.path.isfile(lib_file): + # didn't find library file in virtualenv, try base distribution, too, + # and use that instead if found there. for Python 2.7 venvs, the base + # directory is in attribute real_prefix instead of base_prefix. + if hasattr(sys, 'base_prefix'): + base_lib = os.path.join(sys.base_prefix, 'libs', lib_name) + elif hasattr(sys, 'real_prefix'): + base_lib = os.path.join(sys.real_prefix, 'libs', lib_name) + else: + base_lib = '' # os.path.isfile('') == False + + if os.path.isfile(base_lib): + lib_file = base_lib + else: + log.warn('Cannot build import library: "%s" not found', lib_file) + return + log.info('Building import library (ARCH=x86): "%s"', out_file) + + from numpy.distutils import lib2def + + def_name = "python%d%d.def" % tuple(sys.version_info[:2]) + def_file = os.path.join(sys.prefix, 'libs', def_name) + nm_cmd = '%s %s' % (lib2def.DEFAULT_NM, lib_file) + nm_output = lib2def.getnm(nm_cmd) + dlist, flist = lib2def.parse_nm(nm_output) + lib2def.output_def(dlist, flist, lib2def.DEF_HEADER, open(def_file, 'w')) + + dll_name = find_python_dll () + args = (dll_name, def_file, out_file) + cmd = 'dlltool --dllname "%s" --def "%s" --output-lib "%s"' % args + status = os.system(cmd) + # for now, fail silently + if status: + log.warn('Failed to build import library for gcc. Linking will fail.') + return + +#===================================== +# Dealing with Visual Studio MANIFESTS +#===================================== + +# Functions to deal with visual studio manifests. Manifest are a mechanism to +# enforce strong DLL versioning on windows, and has nothing to do with +# distutils MANIFEST. manifests are XML files with version info, and used by +# the OS loader; they are necessary when linking against a DLL not in the +# system path; in particular, official python 2.6 binary is built against the +# MS runtime 9 (the one from VS 2008), which is not available on most windows +# systems; python 2.6 installer does install it in the Win SxS (Side by side) +# directory, but this requires the manifest for this to work. This is a big +# mess, thanks MS for a wonderful system. + +# XXX: ideally, we should use exactly the same version as used by python. I +# submitted a patch to get this version, but it was only included for python +# 2.6.1 and above. So for versions below, we use a "best guess". +_MSVCRVER_TO_FULLVER = {} +if sys.platform == 'win32': + try: + import msvcrt + # I took one version in my SxS directory: no idea if it is the good + # one, and we can't retrieve it from python + _MSVCRVER_TO_FULLVER['80'] = "8.0.50727.42" + _MSVCRVER_TO_FULLVER['90'] = "9.0.21022.8" + # Value from msvcrt.CRT_ASSEMBLY_VERSION under Python 3.3.0 + # on Windows XP: + _MSVCRVER_TO_FULLVER['100'] = "10.0.30319.460" + if hasattr(msvcrt, "CRT_ASSEMBLY_VERSION"): + major, minor, rest = msvcrt.CRT_ASSEMBLY_VERSION.split(".", 2) + _MSVCRVER_TO_FULLVER[major + minor] = msvcrt.CRT_ASSEMBLY_VERSION + del major, minor, rest + except ImportError: + # If we are here, means python was not built with MSVC. Not sure what + # to do in that case: manifest building will fail, but it should not be + # used in that case anyway + log.warn('Cannot import msvcrt: using manifest will not be possible') + +def msvc_manifest_xml(maj, min): + """Given a major and minor version of the MSVCR, returns the + corresponding XML file.""" + try: + fullver = _MSVCRVER_TO_FULLVER[str(maj * 10 + min)] + except KeyError: + raise ValueError("Version %d,%d of MSVCRT not supported yet" % + (maj, min)) + # Don't be fooled, it looks like an XML, but it is not. In particular, it + # should not have any space before starting, and its size should be + # divisible by 4, most likely for alignment constraints when the xml is + # embedded in the binary... + # This template was copied directly from the python 2.6 binary (using + # strings.exe from mingw on python.exe). + template = """\ + + + + + + + + + + + + + +""" + + return template % {'fullver': fullver, 'maj': maj, 'min': min} + +def manifest_rc(name, type='dll'): + """Return the rc file used to generate the res file which will be embedded + as manifest for given manifest file name, of given type ('dll' or + 'exe'). + + Parameters + ---------- + name : str + name of the manifest file to embed + type : str {'dll', 'exe'} + type of the binary which will embed the manifest + + """ + if type == 'dll': + rctype = 2 + elif type == 'exe': + rctype = 1 + else: + raise ValueError("Type %s not supported" % type) + + return """\ +#include "winuser.h" +%d RT_MANIFEST %s""" % (rctype, name) + +def check_embedded_msvcr_match_linked(msver): + """msver is the ms runtime version used for the MANIFEST.""" + # check msvcr major version are the same for linking and + # embedding + maj = msvc_runtime_major() + if maj: + if not maj == int(msver): + raise ValueError( + "Discrepancy between linked msvcr " \ + "(%d) and the one about to be embedded " \ + "(%d)" % (int(msver), maj)) + +def configtest_name(config): + base = os.path.basename(config._gen_temp_sourcefile("yo", [], "c")) + return os.path.splitext(base)[0] + +def manifest_name(config): + # Get configest name (including suffix) + root = configtest_name(config) + exext = config.compiler.exe_extension + return root + exext + ".manifest" + +def rc_name(config): + # Get configtest name (including suffix) + root = configtest_name(config) + return root + ".rc" + +def generate_manifest(config): + msver = get_build_msvc_version() + if msver is not None: + if msver >= 8: + check_embedded_msvcr_match_linked(msver) + ma = int(msver) + mi = int((msver - ma) * 10) + # Write the manifest file + manxml = msvc_manifest_xml(ma, mi) + man = open(manifest_name(config), "w") + config.temp_files.append(manifest_name(config)) + man.write(manxml) + man.close() diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/misc_util.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/misc_util.py new file mode 100644 index 0000000000000000000000000000000000000000..42374ac4f5410b99742ede579e684ee97c493faf --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/misc_util.py @@ -0,0 +1,2330 @@ +from __future__ import division, absolute_import, print_function + +import os +import re +import sys +import copy +import glob +import atexit +import tempfile +import subprocess +import shutil +import multiprocessing + +import distutils +from distutils.errors import DistutilsError +try: + from threading import local as tlocal +except ImportError: + from dummy_threading import local as tlocal + +# stores temporary directory of each thread to only create one per thread +_tdata = tlocal() + +# store all created temporary directories so they can be deleted on exit +_tmpdirs = [] +def clean_up_temporary_directory(): + if _tmpdirs is not None: + for d in _tmpdirs: + try: + shutil.rmtree(d) + except OSError: + pass + +atexit.register(clean_up_temporary_directory) + +from numpy.distutils.compat import get_exception +from numpy.compat import basestring +from numpy.compat import npy_load_module + +__all__ = ['Configuration', 'get_numpy_include_dirs', 'default_config_dict', + 'dict_append', 'appendpath', 'generate_config_py', + 'get_cmd', 'allpath', 'get_mathlibs', + 'terminal_has_colors', 'red_text', 'green_text', 'yellow_text', + 'blue_text', 'cyan_text', 'cyg2win32', 'mingw32', 'all_strings', + 'has_f_sources', 'has_cxx_sources', 'filter_sources', + 'get_dependencies', 'is_local_src_dir', 'get_ext_source_files', + 'get_script_files', 'get_lib_source_files', 'get_data_files', + 'dot_join', 'get_frame', 'minrelpath', 'njoin', + 'is_sequence', 'is_string', 'as_list', 'gpaths', 'get_language', + 'quote_args', 'get_build_architecture', 'get_info', 'get_pkg_info', + 'get_num_build_jobs'] + +class InstallableLib(object): + """ + Container to hold information on an installable library. + + Parameters + ---------- + name : str + Name of the installed library. + build_info : dict + Dictionary holding build information. + target_dir : str + Absolute path specifying where to install the library. + + See Also + -------- + Configuration.add_installed_library + + Notes + ----- + The three parameters are stored as attributes with the same names. + + """ + def __init__(self, name, build_info, target_dir): + self.name = name + self.build_info = build_info + self.target_dir = target_dir + + +def get_num_build_jobs(): + """ + Get number of parallel build jobs set by the --parallel command line + argument of setup.py + If the command did not receive a setting the environment variable + NPY_NUM_BUILD_JOBS is checked. If that is unset, return the number of + processors on the system, with a maximum of 8 (to prevent + overloading the system if there a lot of CPUs). + + Returns + ------- + out : int + number of parallel jobs that can be run + + """ + from numpy.distutils.core import get_distribution + try: + cpu_count = len(os.sched_getaffinity(0)) + except AttributeError: + cpu_count = multiprocessing.cpu_count() + cpu_count = min(cpu_count, 8) + envjobs = int(os.environ.get("NPY_NUM_BUILD_JOBS", cpu_count)) + dist = get_distribution() + # may be None during configuration + if dist is None: + return envjobs + + # any of these three may have the job set, take the largest + cmdattr = (getattr(dist.get_command_obj('build'), 'parallel', None), + getattr(dist.get_command_obj('build_ext'), 'parallel', None), + getattr(dist.get_command_obj('build_clib'), 'parallel', None)) + if all(x is None for x in cmdattr): + return envjobs + else: + return max(x for x in cmdattr if x is not None) + +def quote_args(args): + # don't used _nt_quote_args as it does not check if + # args items already have quotes or not. + args = list(args) + for i in range(len(args)): + a = args[i] + if ' ' in a and a[0] not in '"\'': + args[i] = '"%s"' % (a) + return args + +def allpath(name): + "Convert a /-separated pathname to one using the OS's path separator." + splitted = name.split('/') + return os.path.join(*splitted) + +def rel_path(path, parent_path): + """Return path relative to parent_path.""" + # Use realpath to avoid issues with symlinked dirs (see gh-7707) + pd = os.path.realpath(os.path.abspath(parent_path)) + apath = os.path.realpath(os.path.abspath(path)) + if len(apath) < len(pd): + return path + if apath == pd: + return '' + if pd == apath[:len(pd)]: + assert apath[len(pd)] in [os.sep], repr((path, apath[len(pd)])) + path = apath[len(pd)+1:] + return path + +def get_path_from_frame(frame, parent_path=None): + """Return path of the module given a frame object from the call stack. + + Returned path is relative to parent_path when given, + otherwise it is absolute path. + """ + + # First, try to find if the file name is in the frame. + try: + caller_file = eval('__file__', frame.f_globals, frame.f_locals) + d = os.path.dirname(os.path.abspath(caller_file)) + except NameError: + # __file__ is not defined, so let's try __name__. We try this second + # because setuptools spoofs __name__ to be '__main__' even though + # sys.modules['__main__'] might be something else, like easy_install(1). + caller_name = eval('__name__', frame.f_globals, frame.f_locals) + __import__(caller_name) + mod = sys.modules[caller_name] + if hasattr(mod, '__file__'): + d = os.path.dirname(os.path.abspath(mod.__file__)) + else: + # we're probably running setup.py as execfile("setup.py") + # (likely we're building an egg) + d = os.path.abspath('.') + # hmm, should we use sys.argv[0] like in __builtin__ case? + + if parent_path is not None: + d = rel_path(d, parent_path) + + return d or '.' + +def njoin(*path): + """Join two or more pathname components + + - convert a /-separated pathname to one using the OS's path separator. + - resolve `..` and `.` from path. + + Either passing n arguments as in njoin('a','b'), or a sequence + of n names as in njoin(['a','b']) is handled, or a mixture of such arguments. + """ + paths = [] + for p in path: + if is_sequence(p): + # njoin(['a', 'b'], 'c') + paths.append(njoin(*p)) + else: + assert is_string(p) + paths.append(p) + path = paths + if not path: + # njoin() + joined = '' + else: + # njoin('a', 'b') + joined = os.path.join(*path) + if os.path.sep != '/': + joined = joined.replace('/', os.path.sep) + return minrelpath(joined) + +def get_mathlibs(path=None): + """Return the MATHLIB line from numpyconfig.h + """ + if path is not None: + config_file = os.path.join(path, '_numpyconfig.h') + else: + # Look for the file in each of the numpy include directories. + dirs = get_numpy_include_dirs() + for path in dirs: + fn = os.path.join(path, '_numpyconfig.h') + if os.path.exists(fn): + config_file = fn + break + else: + raise DistutilsError('_numpyconfig.h not found in numpy include ' + 'dirs %r' % (dirs,)) + + fid = open(config_file) + mathlibs = [] + s = '#define MATHLIB' + for line in fid: + if line.startswith(s): + value = line[len(s):].strip() + if value: + mathlibs.extend(value.split(',')) + fid.close() + return mathlibs + +def minrelpath(path): + """Resolve `..` and '.' from path. + """ + if not is_string(path): + return path + if '.' not in path: + return path + l = path.split(os.sep) + while l: + try: + i = l.index('.', 1) + except ValueError: + break + del l[i] + j = 1 + while l: + try: + i = l.index('..', j) + except ValueError: + break + if l[i-1]=='..': + j += 1 + else: + del l[i], l[i-1] + j = 1 + if not l: + return '' + return os.sep.join(l) + +def sorted_glob(fileglob): + """sorts output of python glob for https://bugs.python.org/issue30461 + to allow extensions to have reproducible build results""" + return sorted(glob.glob(fileglob)) + +def _fix_paths(paths, local_path, include_non_existing): + assert is_sequence(paths), repr(type(paths)) + new_paths = [] + assert not is_string(paths), repr(paths) + for n in paths: + if is_string(n): + if '*' in n or '?' in n: + p = sorted_glob(n) + p2 = sorted_glob(njoin(local_path, n)) + if p2: + new_paths.extend(p2) + elif p: + new_paths.extend(p) + else: + if include_non_existing: + new_paths.append(n) + print('could not resolve pattern in %r: %r' % + (local_path, n)) + else: + n2 = njoin(local_path, n) + if os.path.exists(n2): + new_paths.append(n2) + else: + if os.path.exists(n): + new_paths.append(n) + elif include_non_existing: + new_paths.append(n) + if not os.path.exists(n): + print('non-existing path in %r: %r' % + (local_path, n)) + + elif is_sequence(n): + new_paths.extend(_fix_paths(n, local_path, include_non_existing)) + else: + new_paths.append(n) + return [minrelpath(p) for p in new_paths] + +def gpaths(paths, local_path='', include_non_existing=True): + """Apply glob to paths and prepend local_path if needed. + """ + if is_string(paths): + paths = (paths,) + return _fix_paths(paths, local_path, include_non_existing) + +def make_temp_file(suffix='', prefix='', text=True): + if not hasattr(_tdata, 'tempdir'): + _tdata.tempdir = tempfile.mkdtemp() + _tmpdirs.append(_tdata.tempdir) + fid, name = tempfile.mkstemp(suffix=suffix, + prefix=prefix, + dir=_tdata.tempdir, + text=text) + fo = os.fdopen(fid, 'w') + return fo, name + +# Hooks for colored terminal output. +# See also https://web.archive.org/web/20100314204946/http://www.livinglogic.de/Python/ansistyle +def terminal_has_colors(): + if sys.platform=='cygwin' and 'USE_COLOR' not in os.environ: + # Avoid importing curses that causes illegal operation + # with a message: + # PYTHON2 caused an invalid page fault in + # module CYGNURSES7.DLL as 015f:18bbfc28 + # Details: Python 2.3.3 [GCC 3.3.1 (cygming special)] + # ssh to Win32 machine from debian + # curses.version is 2.2 + # CYGWIN_98-4.10, release 1.5.7(0.109/3/2)) + return 0 + if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty(): + try: + import curses + curses.setupterm() + if (curses.tigetnum("colors") >= 0 + and curses.tigetnum("pairs") >= 0 + and ((curses.tigetstr("setf") is not None + and curses.tigetstr("setb") is not None) + or (curses.tigetstr("setaf") is not None + and curses.tigetstr("setab") is not None) + or curses.tigetstr("scp") is not None)): + return 1 + except Exception: + pass + return 0 + +if terminal_has_colors(): + _colour_codes = dict(black=0, red=1, green=2, yellow=3, + blue=4, magenta=5, cyan=6, white=7, default=9) + def colour_text(s, fg=None, bg=None, bold=False): + seq = [] + if bold: + seq.append('1') + if fg: + fgcode = 30 + _colour_codes.get(fg.lower(), 0) + seq.append(str(fgcode)) + if bg: + bgcode = 40 + _colour_codes.get(fg.lower(), 7) + seq.append(str(bgcode)) + if seq: + return '\x1b[%sm%s\x1b[0m' % (';'.join(seq), s) + else: + return s +else: + def colour_text(s, fg=None, bg=None): + return s + +def default_text(s): + return colour_text(s, 'default') +def red_text(s): + return colour_text(s, 'red') +def green_text(s): + return colour_text(s, 'green') +def yellow_text(s): + return colour_text(s, 'yellow') +def cyan_text(s): + return colour_text(s, 'cyan') +def blue_text(s): + return colour_text(s, 'blue') + +######################### + +def cyg2win32(path): + if sys.platform=='cygwin' and path.startswith('/cygdrive'): + path = path[10] + ':' + os.path.normcase(path[11:]) + return path + +def mingw32(): + """Return true when using mingw32 environment. + """ + if sys.platform=='win32': + if os.environ.get('OSTYPE', '')=='msys': + return True + if os.environ.get('MSYSTEM', '')=='MINGW32': + return True + return False + +def msvc_runtime_version(): + "Return version of MSVC runtime library, as defined by __MSC_VER__ macro" + msc_pos = sys.version.find('MSC v.') + if msc_pos != -1: + msc_ver = int(sys.version[msc_pos+6:msc_pos+10]) + else: + msc_ver = None + return msc_ver + +def msvc_runtime_library(): + "Return name of MSVC runtime library if Python was built with MSVC >= 7" + ver = msvc_runtime_major () + if ver: + if ver < 140: + return "msvcr%i" % ver + else: + return "vcruntime%i" % ver + else: + return None + +def msvc_runtime_major(): + "Return major version of MSVC runtime coded like get_build_msvc_version" + major = {1300: 70, # MSVC 7.0 + 1310: 71, # MSVC 7.1 + 1400: 80, # MSVC 8 + 1500: 90, # MSVC 9 (aka 2008) + 1600: 100, # MSVC 10 (aka 2010) + 1900: 140, # MSVC 14 (aka 2015) + }.get(msvc_runtime_version(), None) + return major + +######################### + +#XXX need support for .C that is also C++ +cxx_ext_match = re.compile(r'.*[.](cpp|cxx|cc)\Z', re.I).match +fortran_ext_match = re.compile(r'.*[.](f90|f95|f77|for|ftn|f)\Z', re.I).match +f90_ext_match = re.compile(r'.*[.](f90|f95)\Z', re.I).match +f90_module_name_match = re.compile(r'\s*module\s*(?P[\w_]+)', re.I).match +def _get_f90_modules(source): + """Return a list of Fortran f90 module names that + given source file defines. + """ + if not f90_ext_match(source): + return [] + modules = [] + f = open(source, 'r') + for line in f: + m = f90_module_name_match(line) + if m: + name = m.group('name') + modules.append(name) + # break # XXX can we assume that there is one module per file? + f.close() + return modules + +def is_string(s): + return isinstance(s, basestring) + +def all_strings(lst): + """Return True if all items in lst are string objects. """ + for item in lst: + if not is_string(item): + return False + return True + +def is_sequence(seq): + if is_string(seq): + return False + try: + len(seq) + except Exception: + return False + return True + +def is_glob_pattern(s): + return is_string(s) and ('*' in s or '?' is s) + +def as_list(seq): + if is_sequence(seq): + return list(seq) + else: + return [seq] + +def get_language(sources): + # not used in numpy/scipy packages, use build_ext.detect_language instead + """Determine language value (c,f77,f90) from sources """ + language = None + for source in sources: + if isinstance(source, str): + if f90_ext_match(source): + language = 'f90' + break + elif fortran_ext_match(source): + language = 'f77' + return language + +def has_f_sources(sources): + """Return True if sources contains Fortran files """ + for source in sources: + if fortran_ext_match(source): + return True + return False + +def has_cxx_sources(sources): + """Return True if sources contains C++ files """ + for source in sources: + if cxx_ext_match(source): + return True + return False + +def filter_sources(sources): + """Return four lists of filenames containing + C, C++, Fortran, and Fortran 90 module sources, + respectively. + """ + c_sources = [] + cxx_sources = [] + f_sources = [] + fmodule_sources = [] + for source in sources: + if fortran_ext_match(source): + modules = _get_f90_modules(source) + if modules: + fmodule_sources.append(source) + else: + f_sources.append(source) + elif cxx_ext_match(source): + cxx_sources.append(source) + else: + c_sources.append(source) + return c_sources, cxx_sources, f_sources, fmodule_sources + + +def _get_headers(directory_list): + # get *.h files from list of directories + headers = [] + for d in directory_list: + head = sorted_glob(os.path.join(d, "*.h")) #XXX: *.hpp files?? + headers.extend(head) + return headers + +def _get_directories(list_of_sources): + # get unique directories from list of sources. + direcs = [] + for f in list_of_sources: + d = os.path.split(f) + if d[0] != '' and not d[0] in direcs: + direcs.append(d[0]) + return direcs + +def _commandline_dep_string(cc_args, extra_postargs, pp_opts): + """ + Return commandline representation used to determine if a file needs + to be recompiled + """ + cmdline = 'commandline: ' + cmdline += ' '.join(cc_args) + cmdline += ' '.join(extra_postargs) + cmdline += ' '.join(pp_opts) + '\n' + return cmdline + + +def get_dependencies(sources): + #XXX scan sources for include statements + return _get_headers(_get_directories(sources)) + +def is_local_src_dir(directory): + """Return true if directory is local directory. + """ + if not is_string(directory): + return False + abs_dir = os.path.abspath(directory) + c = os.path.commonprefix([os.getcwd(), abs_dir]) + new_dir = abs_dir[len(c):].split(os.sep) + if new_dir and not new_dir[0]: + new_dir = new_dir[1:] + if new_dir and new_dir[0]=='build': + return False + new_dir = os.sep.join(new_dir) + return os.path.isdir(new_dir) + +def general_source_files(top_path): + pruned_directories = {'CVS':1, '.svn':1, 'build':1} + prune_file_pat = re.compile(r'(?:[~#]|\.py[co]|\.o)$') + for dirpath, dirnames, filenames in os.walk(top_path, topdown=True): + pruned = [ d for d in dirnames if d not in pruned_directories ] + dirnames[:] = pruned + for f in filenames: + if not prune_file_pat.search(f): + yield os.path.join(dirpath, f) + +def general_source_directories_files(top_path): + """Return a directory name relative to top_path and + files contained. + """ + pruned_directories = ['CVS', '.svn', 'build'] + prune_file_pat = re.compile(r'(?:[~#]|\.py[co]|\.o)$') + for dirpath, dirnames, filenames in os.walk(top_path, topdown=True): + pruned = [ d for d in dirnames if d not in pruned_directories ] + dirnames[:] = pruned + for d in dirnames: + dpath = os.path.join(dirpath, d) + rpath = rel_path(dpath, top_path) + files = [] + for f in os.listdir(dpath): + fn = os.path.join(dpath, f) + if os.path.isfile(fn) and not prune_file_pat.search(fn): + files.append(fn) + yield rpath, files + dpath = top_path + rpath = rel_path(dpath, top_path) + filenames = [os.path.join(dpath, f) for f in os.listdir(dpath) \ + if not prune_file_pat.search(f)] + files = [f for f in filenames if os.path.isfile(f)] + yield rpath, files + + +def get_ext_source_files(ext): + # Get sources and any include files in the same directory. + filenames = [] + sources = [_m for _m in ext.sources if is_string(_m)] + filenames.extend(sources) + filenames.extend(get_dependencies(sources)) + for d in ext.depends: + if is_local_src_dir(d): + filenames.extend(list(general_source_files(d))) + elif os.path.isfile(d): + filenames.append(d) + return filenames + +def get_script_files(scripts): + scripts = [_m for _m in scripts if is_string(_m)] + return scripts + +def get_lib_source_files(lib): + filenames = [] + sources = lib[1].get('sources', []) + sources = [_m for _m in sources if is_string(_m)] + filenames.extend(sources) + filenames.extend(get_dependencies(sources)) + depends = lib[1].get('depends', []) + for d in depends: + if is_local_src_dir(d): + filenames.extend(list(general_source_files(d))) + elif os.path.isfile(d): + filenames.append(d) + return filenames + +def get_shared_lib_extension(is_python_ext=False): + """Return the correct file extension for shared libraries. + + Parameters + ---------- + is_python_ext : bool, optional + Whether the shared library is a Python extension. Default is False. + + Returns + ------- + so_ext : str + The shared library extension. + + Notes + ----- + For Python shared libs, `so_ext` will typically be '.so' on Linux and OS X, + and '.pyd' on Windows. For Python >= 3.2 `so_ext` has a tag prepended on + POSIX systems according to PEP 3149. For Python 3.2 this is implemented on + Linux, but not on OS X. + + """ + confvars = distutils.sysconfig.get_config_vars() + # SO is deprecated in 3.3.1, use EXT_SUFFIX instead + so_ext = confvars.get('EXT_SUFFIX', None) + if so_ext is None: + so_ext = confvars.get('SO', '') + + if not is_python_ext: + # hardcode known values, config vars (including SHLIB_SUFFIX) are + # unreliable (see #3182) + # darwin, windows and debug linux are wrong in 3.3.1 and older + if (sys.platform.startswith('linux') or + sys.platform.startswith('gnukfreebsd')): + so_ext = '.so' + elif sys.platform.startswith('darwin'): + so_ext = '.dylib' + elif sys.platform.startswith('win'): + so_ext = '.dll' + else: + # fall back to config vars for unknown platforms + # fix long extension for Python >=3.2, see PEP 3149. + if 'SOABI' in confvars: + # Does nothing unless SOABI config var exists + so_ext = so_ext.replace('.' + confvars.get('SOABI'), '', 1) + + return so_ext + +def get_data_files(data): + if is_string(data): + return [data] + sources = data[1] + filenames = [] + for s in sources: + if hasattr(s, '__call__'): + continue + if is_local_src_dir(s): + filenames.extend(list(general_source_files(s))) + elif is_string(s): + if os.path.isfile(s): + filenames.append(s) + else: + print('Not existing data file:', s) + else: + raise TypeError(repr(s)) + return filenames + +def dot_join(*args): + return '.'.join([a for a in args if a]) + +def get_frame(level=0): + """Return frame object from call stack with given level. + """ + try: + return sys._getframe(level+1) + except AttributeError: + frame = sys.exc_info()[2].tb_frame + for _ in range(level+1): + frame = frame.f_back + return frame + + +###################### + +class Configuration(object): + + _list_keys = ['packages', 'ext_modules', 'data_files', 'include_dirs', + 'libraries', 'headers', 'scripts', 'py_modules', + 'installed_libraries', 'define_macros'] + _dict_keys = ['package_dir', 'installed_pkg_config'] + _extra_keys = ['name', 'version'] + + numpy_include_dirs = [] + + def __init__(self, + package_name=None, + parent_name=None, + top_path=None, + package_path=None, + caller_level=1, + setup_name='setup.py', + **attrs): + """Construct configuration instance of a package. + + package_name -- name of the package + Ex.: 'distutils' + parent_name -- name of the parent package + Ex.: 'numpy' + top_path -- directory of the toplevel package + Ex.: the directory where the numpy package source sits + package_path -- directory of package. Will be computed by magic from the + directory of the caller module if not specified + Ex.: the directory where numpy.distutils is + caller_level -- frame level to caller namespace, internal parameter. + """ + self.name = dot_join(parent_name, package_name) + self.version = None + + caller_frame = get_frame(caller_level) + self.local_path = get_path_from_frame(caller_frame, top_path) + # local_path -- directory of a file (usually setup.py) that + # defines a configuration() function. + # local_path -- directory of a file (usually setup.py) that + # defines a configuration() function. + if top_path is None: + top_path = self.local_path + self.local_path = '' + if package_path is None: + package_path = self.local_path + elif os.path.isdir(njoin(self.local_path, package_path)): + package_path = njoin(self.local_path, package_path) + if not os.path.isdir(package_path or '.'): + raise ValueError("%r is not a directory" % (package_path,)) + self.top_path = top_path + self.package_path = package_path + # this is the relative path in the installed package + self.path_in_package = os.path.join(*self.name.split('.')) + + self.list_keys = self._list_keys[:] + self.dict_keys = self._dict_keys[:] + + for n in self.list_keys: + v = copy.copy(attrs.get(n, [])) + setattr(self, n, as_list(v)) + + for n in self.dict_keys: + v = copy.copy(attrs.get(n, {})) + setattr(self, n, v) + + known_keys = self.list_keys + self.dict_keys + self.extra_keys = self._extra_keys[:] + for n in attrs.keys(): + if n in known_keys: + continue + a = attrs[n] + setattr(self, n, a) + if isinstance(a, list): + self.list_keys.append(n) + elif isinstance(a, dict): + self.dict_keys.append(n) + else: + self.extra_keys.append(n) + + if os.path.exists(njoin(package_path, '__init__.py')): + self.packages.append(self.name) + self.package_dir[self.name] = package_path + + self.options = dict( + ignore_setup_xxx_py = False, + assume_default_configuration = False, + delegate_options_to_subpackages = False, + quiet = False, + ) + + caller_instance = None + for i in range(1, 3): + try: + f = get_frame(i) + except ValueError: + break + try: + caller_instance = eval('self', f.f_globals, f.f_locals) + break + except NameError: + pass + if isinstance(caller_instance, self.__class__): + if caller_instance.options['delegate_options_to_subpackages']: + self.set_options(**caller_instance.options) + + self.setup_name = setup_name + + def todict(self): + """ + Return a dictionary compatible with the keyword arguments of distutils + setup function. + + Examples + -------- + >>> setup(**config.todict()) #doctest: +SKIP + """ + + self._optimize_data_files() + d = {} + known_keys = self.list_keys + self.dict_keys + self.extra_keys + for n in known_keys: + a = getattr(self, n) + if a: + d[n] = a + return d + + def info(self, message): + if not self.options['quiet']: + print(message) + + def warn(self, message): + sys.stderr.write('Warning: %s' % (message,)) + + def set_options(self, **options): + """ + Configure Configuration instance. + + The following options are available: + - ignore_setup_xxx_py + - assume_default_configuration + - delegate_options_to_subpackages + - quiet + + """ + for key, value in options.items(): + if key in self.options: + self.options[key] = value + else: + raise ValueError('Unknown option: '+key) + + def get_distribution(self): + """Return the distutils distribution object for self.""" + from numpy.distutils.core import get_distribution + return get_distribution() + + def _wildcard_get_subpackage(self, subpackage_name, + parent_name, + caller_level = 1): + l = subpackage_name.split('.') + subpackage_path = njoin([self.local_path]+l) + dirs = [_m for _m in sorted_glob(subpackage_path) if os.path.isdir(_m)] + config_list = [] + for d in dirs: + if not os.path.isfile(njoin(d, '__init__.py')): + continue + if 'build' in d.split(os.sep): + continue + n = '.'.join(d.split(os.sep)[-len(l):]) + c = self.get_subpackage(n, + parent_name = parent_name, + caller_level = caller_level+1) + config_list.extend(c) + return config_list + + def _get_configuration_from_setup_py(self, setup_py, + subpackage_name, + subpackage_path, + parent_name, + caller_level = 1): + # In case setup_py imports local modules: + sys.path.insert(0, os.path.dirname(setup_py)) + try: + setup_name = os.path.splitext(os.path.basename(setup_py))[0] + n = dot_join(self.name, subpackage_name, setup_name) + setup_module = npy_load_module('_'.join(n.split('.')), + setup_py, + ('.py', 'U', 1)) + if not hasattr(setup_module, 'configuration'): + if not self.options['assume_default_configuration']: + self.warn('Assuming default configuration '\ + '(%s does not define configuration())'\ + % (setup_module)) + config = Configuration(subpackage_name, parent_name, + self.top_path, subpackage_path, + caller_level = caller_level + 1) + else: + pn = dot_join(*([parent_name] + subpackage_name.split('.')[:-1])) + args = (pn,) + def fix_args_py2(args): + if setup_module.configuration.__code__.co_argcount > 1: + args = args + (self.top_path,) + return args + def fix_args_py3(args): + if setup_module.configuration.__code__.co_argcount > 1: + args = args + (self.top_path,) + return args + if sys.version_info[0] < 3: + args = fix_args_py2(args) + else: + args = fix_args_py3(args) + config = setup_module.configuration(*args) + if config.name!=dot_join(parent_name, subpackage_name): + self.warn('Subpackage %r configuration returned as %r' % \ + (dot_join(parent_name, subpackage_name), config.name)) + finally: + del sys.path[0] + return config + + def get_subpackage(self,subpackage_name, + subpackage_path=None, + parent_name=None, + caller_level = 1): + """Return list of subpackage configurations. + + Parameters + ---------- + subpackage_name : str or None + Name of the subpackage to get the configuration. '*' in + subpackage_name is handled as a wildcard. + subpackage_path : str + If None, then the path is assumed to be the local path plus the + subpackage_name. If a setup.py file is not found in the + subpackage_path, then a default configuration is used. + parent_name : str + Parent name. + """ + if subpackage_name is None: + if subpackage_path is None: + raise ValueError( + "either subpackage_name or subpackage_path must be specified") + subpackage_name = os.path.basename(subpackage_path) + + # handle wildcards + l = subpackage_name.split('.') + if subpackage_path is None and '*' in subpackage_name: + return self._wildcard_get_subpackage(subpackage_name, + parent_name, + caller_level = caller_level+1) + assert '*' not in subpackage_name, repr((subpackage_name, subpackage_path, parent_name)) + if subpackage_path is None: + subpackage_path = njoin([self.local_path] + l) + else: + subpackage_path = njoin([subpackage_path] + l[:-1]) + subpackage_path = self.paths([subpackage_path])[0] + setup_py = njoin(subpackage_path, self.setup_name) + if not self.options['ignore_setup_xxx_py']: + if not os.path.isfile(setup_py): + setup_py = njoin(subpackage_path, + 'setup_%s.py' % (subpackage_name)) + if not os.path.isfile(setup_py): + if not self.options['assume_default_configuration']: + self.warn('Assuming default configuration '\ + '(%s/{setup_%s,setup}.py was not found)' \ + % (os.path.dirname(setup_py), subpackage_name)) + config = Configuration(subpackage_name, parent_name, + self.top_path, subpackage_path, + caller_level = caller_level+1) + else: + config = self._get_configuration_from_setup_py( + setup_py, + subpackage_name, + subpackage_path, + parent_name, + caller_level = caller_level + 1) + if config: + return [config] + else: + return [] + + def add_subpackage(self,subpackage_name, + subpackage_path=None, + standalone = False): + """Add a sub-package to the current Configuration instance. + + This is useful in a setup.py script for adding sub-packages to a + package. + + Parameters + ---------- + subpackage_name : str + name of the subpackage + subpackage_path : str + if given, the subpackage path such as the subpackage is in + subpackage_path / subpackage_name. If None,the subpackage is + assumed to be located in the local path / subpackage_name. + standalone : bool + """ + + if standalone: + parent_name = None + else: + parent_name = self.name + config_list = self.get_subpackage(subpackage_name, subpackage_path, + parent_name = parent_name, + caller_level = 2) + if not config_list: + self.warn('No configuration returned, assuming unavailable.') + for config in config_list: + d = config + if isinstance(config, Configuration): + d = config.todict() + assert isinstance(d, dict), repr(type(d)) + + self.info('Appending %s configuration to %s' \ + % (d.get('name'), self.name)) + self.dict_append(**d) + + dist = self.get_distribution() + if dist is not None: + self.warn('distutils distribution has been initialized,'\ + ' it may be too late to add a subpackage '+ subpackage_name) + + def add_data_dir(self, data_path): + """Recursively add files under data_path to data_files list. + + Recursively add files under data_path to the list of data_files to be + installed (and distributed). The data_path can be either a relative + path-name, or an absolute path-name, or a 2-tuple where the first + argument shows where in the install directory the data directory + should be installed to. + + Parameters + ---------- + data_path : seq or str + Argument can be either + + * 2-sequence (, ) + * path to data directory where python datadir suffix defaults + to package dir. + + Notes + ----- + Rules for installation paths:: + + foo/bar -> (foo/bar, foo/bar) -> parent/foo/bar + (gun, foo/bar) -> parent/gun + foo/* -> (foo/a, foo/a), (foo/b, foo/b) -> parent/foo/a, parent/foo/b + (gun, foo/*) -> (gun, foo/a), (gun, foo/b) -> gun + (gun/*, foo/*) -> parent/gun/a, parent/gun/b + /foo/bar -> (bar, /foo/bar) -> parent/bar + (gun, /foo/bar) -> parent/gun + (fun/*/gun/*, sun/foo/bar) -> parent/fun/foo/gun/bar + + Examples + -------- + For example suppose the source directory contains fun/foo.dat and + fun/bar/car.dat: + + >>> self.add_data_dir('fun') #doctest: +SKIP + >>> self.add_data_dir(('sun', 'fun')) #doctest: +SKIP + >>> self.add_data_dir(('gun', '/full/path/to/fun'))#doctest: +SKIP + + Will install data-files to the locations:: + + / + fun/ + foo.dat + bar/ + car.dat + sun/ + foo.dat + bar/ + car.dat + gun/ + foo.dat + car.dat + + """ + if is_sequence(data_path): + d, data_path = data_path + else: + d = None + if is_sequence(data_path): + [self.add_data_dir((d, p)) for p in data_path] + return + if not is_string(data_path): + raise TypeError("not a string: %r" % (data_path,)) + if d is None: + if os.path.isabs(data_path): + return self.add_data_dir((os.path.basename(data_path), data_path)) + return self.add_data_dir((data_path, data_path)) + paths = self.paths(data_path, include_non_existing=False) + if is_glob_pattern(data_path): + if is_glob_pattern(d): + pattern_list = allpath(d).split(os.sep) + pattern_list.reverse() + # /a/*//b/ -> /a/*/b + rl = list(range(len(pattern_list)-1)); rl.reverse() + for i in rl: + if not pattern_list[i]: + del pattern_list[i] + # + for path in paths: + if not os.path.isdir(path): + print('Not a directory, skipping', path) + continue + rpath = rel_path(path, self.local_path) + path_list = rpath.split(os.sep) + path_list.reverse() + target_list = [] + i = 0 + for s in pattern_list: + if is_glob_pattern(s): + if i>=len(path_list): + raise ValueError('cannot fill pattern %r with %r' \ + % (d, path)) + target_list.append(path_list[i]) + else: + assert s==path_list[i], repr((s, path_list[i], data_path, d, path, rpath)) + target_list.append(s) + i += 1 + if path_list[i:]: + self.warn('mismatch of pattern_list=%s and path_list=%s'\ + % (pattern_list, path_list)) + target_list.reverse() + self.add_data_dir((os.sep.join(target_list), path)) + else: + for path in paths: + self.add_data_dir((d, path)) + return + assert not is_glob_pattern(d), repr(d) + + dist = self.get_distribution() + if dist is not None and dist.data_files is not None: + data_files = dist.data_files + else: + data_files = self.data_files + + for path in paths: + for d1, f in list(general_source_directories_files(path)): + target_path = os.path.join(self.path_in_package, d, d1) + data_files.append((target_path, f)) + + def _optimize_data_files(self): + data_dict = {} + for p, files in self.data_files: + if p not in data_dict: + data_dict[p] = set() + for f in files: + data_dict[p].add(f) + self.data_files[:] = [(p, list(files)) for p, files in data_dict.items()] + + def add_data_files(self,*files): + """Add data files to configuration data_files. + + Parameters + ---------- + files : sequence + Argument(s) can be either + + * 2-sequence (,) + * paths to data files where python datadir prefix defaults + to package dir. + + Notes + ----- + The form of each element of the files sequence is very flexible + allowing many combinations of where to get the files from the package + and where they should ultimately be installed on the system. The most + basic usage is for an element of the files argument sequence to be a + simple filename. This will cause that file from the local path to be + installed to the installation path of the self.name package (package + path). The file argument can also be a relative path in which case the + entire relative path will be installed into the package directory. + Finally, the file can be an absolute path name in which case the file + will be found at the absolute path name but installed to the package + path. + + This basic behavior can be augmented by passing a 2-tuple in as the + file argument. The first element of the tuple should specify the + relative path (under the package install directory) where the + remaining sequence of files should be installed to (it has nothing to + do with the file-names in the source distribution). The second element + of the tuple is the sequence of files that should be installed. The + files in this sequence can be filenames, relative paths, or absolute + paths. For absolute paths the file will be installed in the top-level + package installation directory (regardless of the first argument). + Filenames and relative path names will be installed in the package + install directory under the path name given as the first element of + the tuple. + + Rules for installation paths: + + #. file.txt -> (., file.txt)-> parent/file.txt + #. foo/file.txt -> (foo, foo/file.txt) -> parent/foo/file.txt + #. /foo/bar/file.txt -> (., /foo/bar/file.txt) -> parent/file.txt + #. ``*``.txt -> parent/a.txt, parent/b.txt + #. foo/``*``.txt`` -> parent/foo/a.txt, parent/foo/b.txt + #. ``*/*.txt`` -> (``*``, ``*``/``*``.txt) -> parent/c/a.txt, parent/d/b.txt + #. (sun, file.txt) -> parent/sun/file.txt + #. (sun, bar/file.txt) -> parent/sun/file.txt + #. (sun, /foo/bar/file.txt) -> parent/sun/file.txt + #. (sun, ``*``.txt) -> parent/sun/a.txt, parent/sun/b.txt + #. (sun, bar/``*``.txt) -> parent/sun/a.txt, parent/sun/b.txt + #. (sun/``*``, ``*``/``*``.txt) -> parent/sun/c/a.txt, parent/d/b.txt + + An additional feature is that the path to a data-file can actually be + a function that takes no arguments and returns the actual path(s) to + the data-files. This is useful when the data files are generated while + building the package. + + Examples + -------- + Add files to the list of data_files to be included with the package. + + >>> self.add_data_files('foo.dat', + ... ('fun', ['gun.dat', 'nun/pun.dat', '/tmp/sun.dat']), + ... 'bar/cat.dat', + ... '/full/path/to/can.dat') #doctest: +SKIP + + will install these data files to:: + + / + foo.dat + fun/ + gun.dat + nun/ + pun.dat + sun.dat + bar/ + car.dat + can.dat + + where is the package (or sub-package) + directory such as '/usr/lib/python2.4/site-packages/mypackage' ('C: + \\Python2.4 \\Lib \\site-packages \\mypackage') or + '/usr/lib/python2.4/site- packages/mypackage/mysubpackage' ('C: + \\Python2.4 \\Lib \\site-packages \\mypackage \\mysubpackage'). + """ + + if len(files)>1: + for f in files: + self.add_data_files(f) + return + assert len(files)==1 + if is_sequence(files[0]): + d, files = files[0] + else: + d = None + if is_string(files): + filepat = files + elif is_sequence(files): + if len(files)==1: + filepat = files[0] + else: + for f in files: + self.add_data_files((d, f)) + return + else: + raise TypeError(repr(type(files))) + + if d is None: + if hasattr(filepat, '__call__'): + d = '' + elif os.path.isabs(filepat): + d = '' + else: + d = os.path.dirname(filepat) + self.add_data_files((d, files)) + return + + paths = self.paths(filepat, include_non_existing=False) + if is_glob_pattern(filepat): + if is_glob_pattern(d): + pattern_list = d.split(os.sep) + pattern_list.reverse() + for path in paths: + path_list = path.split(os.sep) + path_list.reverse() + path_list.pop() # filename + target_list = [] + i = 0 + for s in pattern_list: + if is_glob_pattern(s): + target_list.append(path_list[i]) + i += 1 + else: + target_list.append(s) + target_list.reverse() + self.add_data_files((os.sep.join(target_list), path)) + else: + self.add_data_files((d, paths)) + return + assert not is_glob_pattern(d), repr((d, filepat)) + + dist = self.get_distribution() + if dist is not None and dist.data_files is not None: + data_files = dist.data_files + else: + data_files = self.data_files + + data_files.append((os.path.join(self.path_in_package, d), paths)) + + ### XXX Implement add_py_modules + + def add_define_macros(self, macros): + """Add define macros to configuration + + Add the given sequence of macro name and value duples to the beginning + of the define_macros list This list will be visible to all extension + modules of the current package. + """ + dist = self.get_distribution() + if dist is not None: + if not hasattr(dist, 'define_macros'): + dist.define_macros = [] + dist.define_macros.extend(macros) + else: + self.define_macros.extend(macros) + + + def add_include_dirs(self,*paths): + """Add paths to configuration include directories. + + Add the given sequence of paths to the beginning of the include_dirs + list. This list will be visible to all extension modules of the + current package. + """ + include_dirs = self.paths(paths) + dist = self.get_distribution() + if dist is not None: + if dist.include_dirs is None: + dist.include_dirs = [] + dist.include_dirs.extend(include_dirs) + else: + self.include_dirs.extend(include_dirs) + + def add_headers(self,*files): + """Add installable headers to configuration. + + Add the given sequence of files to the beginning of the headers list. + By default, headers will be installed under // directory. If an item of files + is a tuple, then its first argument specifies the actual installation + location relative to the path. + + Parameters + ---------- + files : str or seq + Argument(s) can be either: + + * 2-sequence (,) + * path(s) to header file(s) where python includedir suffix will + default to package name. + """ + headers = [] + for path in files: + if is_string(path): + [headers.append((self.name, p)) for p in self.paths(path)] + else: + if not isinstance(path, (tuple, list)) or len(path) != 2: + raise TypeError(repr(path)) + [headers.append((path[0], p)) for p in self.paths(path[1])] + dist = self.get_distribution() + if dist is not None: + if dist.headers is None: + dist.headers = [] + dist.headers.extend(headers) + else: + self.headers.extend(headers) + + def paths(self,*paths,**kws): + """Apply glob to paths and prepend local_path if needed. + + Applies glob.glob(...) to each path in the sequence (if needed) and + pre-pends the local_path if needed. Because this is called on all + source lists, this allows wildcard characters to be specified in lists + of sources for extension modules and libraries and scripts and allows + path-names be relative to the source directory. + + """ + include_non_existing = kws.get('include_non_existing', True) + return gpaths(paths, + local_path = self.local_path, + include_non_existing=include_non_existing) + + def _fix_paths_dict(self, kw): + for k in kw.keys(): + v = kw[k] + if k in ['sources', 'depends', 'include_dirs', 'library_dirs', + 'module_dirs', 'extra_objects']: + new_v = self.paths(v) + kw[k] = new_v + + def add_extension(self,name,sources,**kw): + """Add extension to configuration. + + Create and add an Extension instance to the ext_modules list. This + method also takes the following optional keyword arguments that are + passed on to the Extension constructor. + + Parameters + ---------- + name : str + name of the extension + sources : seq + list of the sources. The list of sources may contain functions + (called source generators) which must take an extension instance + and a build directory as inputs and return a source file or list of + source files or None. If None is returned then no sources are + generated. If the Extension instance has no sources after + processing all source generators, then no extension module is + built. + include_dirs : + define_macros : + undef_macros : + library_dirs : + libraries : + runtime_library_dirs : + extra_objects : + extra_compile_args : + extra_link_args : + extra_f77_compile_args : + extra_f90_compile_args : + export_symbols : + swig_opts : + depends : + The depends list contains paths to files or directories that the + sources of the extension module depend on. If any path in the + depends list is newer than the extension module, then the module + will be rebuilt. + language : + f2py_options : + module_dirs : + extra_info : dict or list + dict or list of dict of keywords to be appended to keywords. + + Notes + ----- + The self.paths(...) method is applied to all lists that may contain + paths. + """ + ext_args = copy.copy(kw) + ext_args['name'] = dot_join(self.name, name) + ext_args['sources'] = sources + + if 'extra_info' in ext_args: + extra_info = ext_args['extra_info'] + del ext_args['extra_info'] + if isinstance(extra_info, dict): + extra_info = [extra_info] + for info in extra_info: + assert isinstance(info, dict), repr(info) + dict_append(ext_args,**info) + + self._fix_paths_dict(ext_args) + + # Resolve out-of-tree dependencies + libraries = ext_args.get('libraries', []) + libnames = [] + ext_args['libraries'] = [] + for libname in libraries: + if isinstance(libname, tuple): + self._fix_paths_dict(libname[1]) + + # Handle library names of the form libname@relative/path/to/library + if '@' in libname: + lname, lpath = libname.split('@', 1) + lpath = os.path.abspath(njoin(self.local_path, lpath)) + if os.path.isdir(lpath): + c = self.get_subpackage(None, lpath, + caller_level = 2) + if isinstance(c, Configuration): + c = c.todict() + for l in [l[0] for l in c.get('libraries', [])]: + llname = l.split('__OF__', 1)[0] + if llname == lname: + c.pop('name', None) + dict_append(ext_args,**c) + break + continue + libnames.append(libname) + + ext_args['libraries'] = libnames + ext_args['libraries'] + ext_args['define_macros'] = \ + self.define_macros + ext_args.get('define_macros', []) + + from numpy.distutils.core import Extension + ext = Extension(**ext_args) + self.ext_modules.append(ext) + + dist = self.get_distribution() + if dist is not None: + self.warn('distutils distribution has been initialized,'\ + ' it may be too late to add an extension '+name) + return ext + + def add_library(self,name,sources,**build_info): + """ + Add library to configuration. + + Parameters + ---------- + name : str + Name of the extension. + sources : sequence + List of the sources. The list of sources may contain functions + (called source generators) which must take an extension instance + and a build directory as inputs and return a source file or list of + source files or None. If None is returned then no sources are + generated. If the Extension instance has no sources after + processing all source generators, then no extension module is + built. + build_info : dict, optional + The following keys are allowed: + + * depends + * macros + * include_dirs + * extra_compiler_args + * extra_f77_compile_args + * extra_f90_compile_args + * f2py_options + * language + + """ + self._add_library(name, sources, None, build_info) + + dist = self.get_distribution() + if dist is not None: + self.warn('distutils distribution has been initialized,'\ + ' it may be too late to add a library '+ name) + + def _add_library(self, name, sources, install_dir, build_info): + """Common implementation for add_library and add_installed_library. Do + not use directly""" + build_info = copy.copy(build_info) + build_info['sources'] = sources + + # Sometimes, depends is not set up to an empty list by default, and if + # depends is not given to add_library, distutils barfs (#1134) + if not 'depends' in build_info: + build_info['depends'] = [] + + self._fix_paths_dict(build_info) + + # Add to libraries list so that it is build with build_clib + self.libraries.append((name, build_info)) + + def add_installed_library(self, name, sources, install_dir, build_info=None): + """ + Similar to add_library, but the specified library is installed. + + Most C libraries used with `distutils` are only used to build python + extensions, but libraries built through this method will be installed + so that they can be reused by third-party packages. + + Parameters + ---------- + name : str + Name of the installed library. + sources : sequence + List of the library's source files. See `add_library` for details. + install_dir : str + Path to install the library, relative to the current sub-package. + build_info : dict, optional + The following keys are allowed: + + * depends + * macros + * include_dirs + * extra_compiler_args + * extra_f77_compile_args + * extra_f90_compile_args + * f2py_options + * language + + Returns + ------- + None + + See Also + -------- + add_library, add_npy_pkg_config, get_info + + Notes + ----- + The best way to encode the options required to link against the specified + C libraries is to use a "libname.ini" file, and use `get_info` to + retrieve the required options (see `add_npy_pkg_config` for more + information). + + """ + if not build_info: + build_info = {} + + install_dir = os.path.join(self.package_path, install_dir) + self._add_library(name, sources, install_dir, build_info) + self.installed_libraries.append(InstallableLib(name, build_info, install_dir)) + + def add_npy_pkg_config(self, template, install_dir, subst_dict=None): + """ + Generate and install a npy-pkg config file from a template. + + The config file generated from `template` is installed in the + given install directory, using `subst_dict` for variable substitution. + + Parameters + ---------- + template : str + The path of the template, relatively to the current package path. + install_dir : str + Where to install the npy-pkg config file, relatively to the current + package path. + subst_dict : dict, optional + If given, any string of the form ``@key@`` will be replaced by + ``subst_dict[key]`` in the template file when installed. The install + prefix is always available through the variable ``@prefix@``, since the + install prefix is not easy to get reliably from setup.py. + + See also + -------- + add_installed_library, get_info + + Notes + ----- + This works for both standard installs and in-place builds, i.e. the + ``@prefix@`` refer to the source directory for in-place builds. + + Examples + -------- + :: + + config.add_npy_pkg_config('foo.ini.in', 'lib', {'foo': bar}) + + Assuming the foo.ini.in file has the following content:: + + [meta] + Name=@foo@ + Version=1.0 + Description=dummy description + + [default] + Cflags=-I@prefix@/include + Libs= + + The generated file will have the following content:: + + [meta] + Name=bar + Version=1.0 + Description=dummy description + + [default] + Cflags=-Iprefix_dir/include + Libs= + + and will be installed as foo.ini in the 'lib' subpath. + + """ + if subst_dict is None: + subst_dict = {} + template = os.path.join(self.package_path, template) + + if self.name in self.installed_pkg_config: + self.installed_pkg_config[self.name].append((template, install_dir, + subst_dict)) + else: + self.installed_pkg_config[self.name] = [(template, install_dir, + subst_dict)] + + + def add_scripts(self,*files): + """Add scripts to configuration. + + Add the sequence of files to the beginning of the scripts list. + Scripts will be installed under the /bin/ directory. + + """ + scripts = self.paths(files) + dist = self.get_distribution() + if dist is not None: + if dist.scripts is None: + dist.scripts = [] + dist.scripts.extend(scripts) + else: + self.scripts.extend(scripts) + + def dict_append(self,**dict): + for key in self.list_keys: + a = getattr(self, key) + a.extend(dict.get(key, [])) + for key in self.dict_keys: + a = getattr(self, key) + a.update(dict.get(key, {})) + known_keys = self.list_keys + self.dict_keys + self.extra_keys + for key in dict.keys(): + if key not in known_keys: + a = getattr(self, key, None) + if a and a==dict[key]: continue + self.warn('Inheriting attribute %r=%r from %r' \ + % (key, dict[key], dict.get('name', '?'))) + setattr(self, key, dict[key]) + self.extra_keys.append(key) + elif key in self.extra_keys: + self.info('Ignoring attempt to set %r (from %r to %r)' \ + % (key, getattr(self, key), dict[key])) + elif key in known_keys: + # key is already processed above + pass + else: + raise ValueError("Don't know about key=%r" % (key)) + + def __str__(self): + from pprint import pformat + known_keys = self.list_keys + self.dict_keys + self.extra_keys + s = '<'+5*'-' + '\n' + s += 'Configuration of '+self.name+':\n' + known_keys.sort() + for k in known_keys: + a = getattr(self, k, None) + if a: + s += '%s = %s\n' % (k, pformat(a)) + s += 5*'-' + '>' + return s + + def get_config_cmd(self): + """ + Returns the numpy.distutils config command instance. + """ + cmd = get_cmd('config') + cmd.ensure_finalized() + cmd.dump_source = 0 + cmd.noisy = 0 + old_path = os.environ.get('PATH') + if old_path: + path = os.pathsep.join(['.', old_path]) + os.environ['PATH'] = path + return cmd + + def get_build_temp_dir(self): + """ + Return a path to a temporary directory where temporary files should be + placed. + """ + cmd = get_cmd('build') + cmd.ensure_finalized() + return cmd.build_temp + + def have_f77c(self): + """Check for availability of Fortran 77 compiler. + + Use it inside source generating function to ensure that + setup distribution instance has been initialized. + + Notes + ----- + True if a Fortran 77 compiler is available (because a simple Fortran 77 + code was able to be compiled successfully). + """ + simple_fortran_subroutine = ''' + subroutine simple + end + ''' + config_cmd = self.get_config_cmd() + flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f77') + return flag + + def have_f90c(self): + """Check for availability of Fortran 90 compiler. + + Use it inside source generating function to ensure that + setup distribution instance has been initialized. + + Notes + ----- + True if a Fortran 90 compiler is available (because a simple Fortran + 90 code was able to be compiled successfully) + """ + simple_fortran_subroutine = ''' + subroutine simple + end + ''' + config_cmd = self.get_config_cmd() + flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f90') + return flag + + def append_to(self, extlib): + """Append libraries, include_dirs to extension or library item. + """ + if is_sequence(extlib): + lib_name, build_info = extlib + dict_append(build_info, + libraries=self.libraries, + include_dirs=self.include_dirs) + else: + from numpy.distutils.core import Extension + assert isinstance(extlib, Extension), repr(extlib) + extlib.libraries.extend(self.libraries) + extlib.include_dirs.extend(self.include_dirs) + + def _get_svn_revision(self, path): + """Return path's SVN revision number. + """ + try: + output = subprocess.check_output( + ['svnversion'], shell=True, cwd=path) + except (subprocess.CalledProcessError, OSError): + pass + else: + m = re.match(br'(?P\d+)', output) + if m: + return int(m.group('revision')) + + if sys.platform=='win32' and os.environ.get('SVN_ASP_DOT_NET_HACK', None): + entries = njoin(path, '_svn', 'entries') + else: + entries = njoin(path, '.svn', 'entries') + if os.path.isfile(entries): + f = open(entries) + fstr = f.read() + f.close() + if fstr[:5] == '\d+)"', fstr) + if m: + return int(m.group('revision')) + else: # non-xml entries file --- check to be sure that + m = re.search(r'dir[\n\r]+(?P\d+)', fstr) + if m: + return int(m.group('revision')) + return None + + def _get_hg_revision(self, path): + """Return path's Mercurial revision number. + """ + try: + output = subprocess.check_output( + ['hg identify --num'], shell=True, cwd=path) + except (subprocess.CalledProcessError, OSError): + pass + else: + m = re.match(br'(?P\d+)', output) + if m: + return int(m.group('revision')) + + branch_fn = njoin(path, '.hg', 'branch') + branch_cache_fn = njoin(path, '.hg', 'branch.cache') + + if os.path.isfile(branch_fn): + branch0 = None + f = open(branch_fn) + revision0 = f.read().strip() + f.close() + + branch_map = {} + for line in file(branch_cache_fn, 'r'): + branch1, revision1 = line.split()[:2] + if revision1==revision0: + branch0 = branch1 + try: + revision1 = int(revision1) + except ValueError: + continue + branch_map[branch1] = revision1 + + return branch_map.get(branch0) + + return None + + + def get_version(self, version_file=None, version_variable=None): + """Try to get version string of a package. + + Return a version string of the current package or None if the version + information could not be detected. + + Notes + ----- + This method scans files named + __version__.py, _version.py, version.py, and + __svn_version__.py for string variables version, __version__, and + _version, until a version number is found. + """ + version = getattr(self, 'version', None) + if version is not None: + return version + + # Get version from version file. + if version_file is None: + files = ['__version__.py', + self.name.split('.')[-1]+'_version.py', + 'version.py', + '__svn_version__.py', + '__hg_version__.py'] + else: + files = [version_file] + if version_variable is None: + version_vars = ['version', + '__version__', + self.name.split('.')[-1]+'_version'] + else: + version_vars = [version_variable] + for f in files: + fn = njoin(self.local_path, f) + if os.path.isfile(fn): + info = ('.py', 'U', 1) + name = os.path.splitext(os.path.basename(fn))[0] + n = dot_join(self.name, name) + try: + version_module = npy_load_module('_'.join(n.split('.')), + fn, info) + except ImportError: + msg = get_exception() + self.warn(str(msg)) + version_module = None + if version_module is None: + continue + + for a in version_vars: + version = getattr(version_module, a, None) + if version is not None: + break + if version is not None: + break + + if version is not None: + self.version = version + return version + + # Get version as SVN or Mercurial revision number + revision = self._get_svn_revision(self.local_path) + if revision is None: + revision = self._get_hg_revision(self.local_path) + + if revision is not None: + version = str(revision) + self.version = version + + return version + + def make_svn_version_py(self, delete=True): + """Appends a data function to the data_files list that will generate + __svn_version__.py file to the current package directory. + + Generate package __svn_version__.py file from SVN revision number, + it will be removed after python exits but will be available + when sdist, etc commands are executed. + + Notes + ----- + If __svn_version__.py existed before, nothing is done. + + This is + intended for working with source directories that are in an SVN + repository. + """ + target = njoin(self.local_path, '__svn_version__.py') + revision = self._get_svn_revision(self.local_path) + if os.path.isfile(target) or revision is None: + return + else: + def generate_svn_version_py(): + if not os.path.isfile(target): + version = str(revision) + self.info('Creating %s (version=%r)' % (target, version)) + f = open(target, 'w') + f.write('version = %r\n' % (version)) + f.close() + + def rm_file(f=target,p=self.info): + if delete: + try: os.remove(f); p('removed '+f) + except OSError: pass + try: os.remove(f+'c'); p('removed '+f+'c') + except OSError: pass + + atexit.register(rm_file) + + return target + + self.add_data_files(('', generate_svn_version_py())) + + def make_hg_version_py(self, delete=True): + """Appends a data function to the data_files list that will generate + __hg_version__.py file to the current package directory. + + Generate package __hg_version__.py file from Mercurial revision, + it will be removed after python exits but will be available + when sdist, etc commands are executed. + + Notes + ----- + If __hg_version__.py existed before, nothing is done. + + This is intended for working with source directories that are + in an Mercurial repository. + """ + target = njoin(self.local_path, '__hg_version__.py') + revision = self._get_hg_revision(self.local_path) + if os.path.isfile(target) or revision is None: + return + else: + def generate_hg_version_py(): + if not os.path.isfile(target): + version = str(revision) + self.info('Creating %s (version=%r)' % (target, version)) + f = open(target, 'w') + f.write('version = %r\n' % (version)) + f.close() + + def rm_file(f=target,p=self.info): + if delete: + try: os.remove(f); p('removed '+f) + except OSError: pass + try: os.remove(f+'c'); p('removed '+f+'c') + except OSError: pass + + atexit.register(rm_file) + + return target + + self.add_data_files(('', generate_hg_version_py())) + + def make_config_py(self,name='__config__'): + """Generate package __config__.py file containing system_info + information used during building the package. + + This file is installed to the + package installation directory. + + """ + self.py_modules.append((self.name, name, generate_config_py)) + + def get_info(self,*names): + """Get resources information. + + Return information (from system_info.get_info) for all of the names in + the argument list in a single dictionary. + """ + from .system_info import get_info, dict_append + info_dict = {} + for a in names: + dict_append(info_dict,**get_info(a)) + return info_dict + + +def get_cmd(cmdname, _cache={}): + if cmdname not in _cache: + import distutils.core + dist = distutils.core._setup_distribution + if dist is None: + from distutils.errors import DistutilsInternalError + raise DistutilsInternalError( + 'setup distribution instance not initialized') + cmd = dist.get_command_obj(cmdname) + _cache[cmdname] = cmd + return _cache[cmdname] + +def get_numpy_include_dirs(): + # numpy_include_dirs are set by numpy/core/setup.py, otherwise [] + include_dirs = Configuration.numpy_include_dirs[:] + if not include_dirs: + import numpy + include_dirs = [ numpy.get_include() ] + # else running numpy/core/setup.py + return include_dirs + +def get_npy_pkg_dir(): + """Return the path where to find the npy-pkg-config directory.""" + # XXX: import here for bootstrapping reasons + import numpy + d = os.path.join(os.path.dirname(numpy.__file__), + 'core', 'lib', 'npy-pkg-config') + return d + +def get_pkg_info(pkgname, dirs=None): + """ + Return library info for the given package. + + Parameters + ---------- + pkgname : str + Name of the package (should match the name of the .ini file, without + the extension, e.g. foo for the file foo.ini). + dirs : sequence, optional + If given, should be a sequence of additional directories where to look + for npy-pkg-config files. Those directories are searched prior to the + NumPy directory. + + Returns + ------- + pkginfo : class instance + The `LibraryInfo` instance containing the build information. + + Raises + ------ + PkgNotFound + If the package is not found. + + See Also + -------- + Configuration.add_npy_pkg_config, Configuration.add_installed_library, + get_info + + """ + from numpy.distutils.npy_pkg_config import read_config + + if dirs: + dirs.append(get_npy_pkg_dir()) + else: + dirs = [get_npy_pkg_dir()] + return read_config(pkgname, dirs) + +def get_info(pkgname, dirs=None): + """ + Return an info dict for a given C library. + + The info dict contains the necessary options to use the C library. + + Parameters + ---------- + pkgname : str + Name of the package (should match the name of the .ini file, without + the extension, e.g. foo for the file foo.ini). + dirs : sequence, optional + If given, should be a sequence of additional directories where to look + for npy-pkg-config files. Those directories are searched prior to the + NumPy directory. + + Returns + ------- + info : dict + The dictionary with build information. + + Raises + ------ + PkgNotFound + If the package is not found. + + See Also + -------- + Configuration.add_npy_pkg_config, Configuration.add_installed_library, + get_pkg_info + + Examples + -------- + To get the necessary information for the npymath library from NumPy: + + >>> npymath_info = np.distutils.misc_util.get_info('npymath') + >>> npymath_info #doctest: +SKIP + {'define_macros': [], 'libraries': ['npymath'], 'library_dirs': + ['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']} + + This info dict can then be used as input to a `Configuration` instance:: + + config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info) + + """ + from numpy.distutils.npy_pkg_config import parse_flags + pkg_info = get_pkg_info(pkgname, dirs) + + # Translate LibraryInfo instance into a build_info dict + info = parse_flags(pkg_info.cflags()) + for k, v in parse_flags(pkg_info.libs()).items(): + info[k].extend(v) + + # add_extension extra_info argument is ANAL + info['define_macros'] = info['macros'] + del info['macros'] + del info['ignored'] + + return info + +def is_bootstrapping(): + if sys.version_info[0] >= 3: + import builtins + else: + import __builtin__ as builtins + + try: + builtins.__NUMPY_SETUP__ + return True + except AttributeError: + return False + + +######################### + +def default_config_dict(name = None, parent_name = None, local_path=None): + """Return a configuration dictionary for usage in + configuration() function defined in file setup_.py. + """ + import warnings + warnings.warn('Use Configuration(%r,%r,top_path=%r) instead of '\ + 'deprecated default_config_dict(%r,%r,%r)' + % (name, parent_name, local_path, + name, parent_name, local_path, + ), stacklevel=2) + c = Configuration(name, parent_name, local_path) + return c.todict() + + +def dict_append(d, **kws): + for k, v in kws.items(): + if k in d: + ov = d[k] + if isinstance(ov, str): + d[k] = v + else: + d[k].extend(v) + else: + d[k] = v + +def appendpath(prefix, path): + if os.path.sep != '/': + prefix = prefix.replace('/', os.path.sep) + path = path.replace('/', os.path.sep) + drive = '' + if os.path.isabs(path): + drive = os.path.splitdrive(prefix)[0] + absprefix = os.path.splitdrive(os.path.abspath(prefix))[1] + pathdrive, path = os.path.splitdrive(path) + d = os.path.commonprefix([absprefix, path]) + if os.path.join(absprefix[:len(d)], absprefix[len(d):]) != absprefix \ + or os.path.join(path[:len(d)], path[len(d):]) != path: + # Handle invalid paths + d = os.path.dirname(d) + subpath = path[len(d):] + if os.path.isabs(subpath): + subpath = subpath[1:] + else: + subpath = path + return os.path.normpath(njoin(drive + prefix, subpath)) + +def generate_config_py(target): + """Generate config.py file containing system_info information + used during building the package. + + Usage: + config['py_modules'].append((packagename, '__config__',generate_config_py)) + """ + from numpy.distutils.system_info import system_info + from distutils.dir_util import mkpath + mkpath(os.path.dirname(target)) + f = open(target, 'w') + f.write('# This file is generated by numpy\'s %s\n' % (os.path.basename(sys.argv[0]))) + f.write('# It contains system_info results at the time of building this package.\n') + f.write('__all__ = ["get_info","show"]\n\n') + + # For gfortran+msvc combination, extra shared libraries may exist + f.write(""" + +import os +import sys + +extra_dll_dir = os.path.join(os.path.dirname(__file__), '.libs') + +if sys.platform == 'win32' and os.path.isdir(extra_dll_dir): + os.environ.setdefault('PATH', '') + os.environ['PATH'] += os.pathsep + extra_dll_dir + +""") + + for k, i in system_info.saved_results.items(): + f.write('%s=%r\n' % (k, i)) + f.write(r''' +def get_info(name): + g = globals() + return g.get(name, g.get(name + "_info", {})) + +def show(): + for name,info_dict in globals().items(): + if name[0] == "_" or type(info_dict) is not type({}): continue + print(name + ":") + if not info_dict: + print(" NOT AVAILABLE") + for k,v in info_dict.items(): + v = str(v) + if k == "sources" and len(v) > 200: + v = v[:60] + " ...\n... " + v[-60:] + print(" %s = %s" % (k,v)) + ''') + + f.close() + return target + +def msvc_version(compiler): + """Return version major and minor of compiler instance if it is + MSVC, raise an exception otherwise.""" + if not compiler.compiler_type == "msvc": + raise ValueError("Compiler instance is not msvc (%s)"\ + % compiler.compiler_type) + return compiler._MSVCCompiler__version + +def get_build_architecture(): + # Importing distutils.msvccompiler triggers a warning on non-Windows + # systems, so delay the import to here. + from distutils.msvccompiler import get_build_architecture + return get_build_architecture() diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/msvc9compiler.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/msvc9compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..e9cc334a5ec468360275384e18ba682596938b0d --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/msvc9compiler.py @@ -0,0 +1,65 @@ +from __future__ import division, absolute_import, print_function + +import os +from distutils.msvc9compiler import MSVCCompiler as _MSVCCompiler + +from .system_info import platform_bits + + +def _merge(old, new): + """Concatenate two environment paths avoiding repeats. + + Here `old` is the environment string before the base class initialize + function is called and `new` is the string after the call. The new string + will be a fixed string if it is not obtained from the current environment, + or the same as the old string if obtained from the same environment. The aim + here is not to append the new string if it is already contained in the old + string so as to limit the growth of the environment string. + + Parameters + ---------- + old : string + Previous environment string. + new : string + New environment string. + + Returns + ------- + ret : string + Updated environment string. + + """ + if not old: + return new + if new in old: + return old + + # Neither new nor old is empty. Give old priority. + return ';'.join([old, new]) + + +class MSVCCompiler(_MSVCCompiler): + def __init__(self, verbose=0, dry_run=0, force=0): + _MSVCCompiler.__init__(self, verbose, dry_run, force) + + def initialize(self, plat_name=None): + # The 'lib' and 'include' variables may be overwritten + # by MSVCCompiler.initialize, so save them for later merge. + environ_lib = os.getenv('lib') + environ_include = os.getenv('include') + _MSVCCompiler.initialize(self, plat_name) + + # Merge current and previous values of 'lib' and 'include' + os.environ['lib'] = _merge(environ_lib, os.environ['lib']) + os.environ['include'] = _merge(environ_include, os.environ['include']) + + # msvc9 building for 32 bits requires SSE2 to work around a + # compiler bug. + if platform_bits == 32: + self.compile_options += ['/arch:SSE2'] + self.compile_options_debug += ['/arch:SSE2'] + + def manifest_setup_ldargs(self, output_filename, build_temp, ld_args): + ld_args.append('/MANIFEST') + _MSVCCompiler.manifest_setup_ldargs(self, output_filename, + build_temp, ld_args) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/msvccompiler.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/msvccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..0cb4bf9794bea861b62c870272d4927a07a94f4f --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/msvccompiler.py @@ -0,0 +1,60 @@ +from __future__ import division, absolute_import, print_function + +import os +from distutils.msvccompiler import MSVCCompiler as _MSVCCompiler + +from .system_info import platform_bits + + +def _merge(old, new): + """Concatenate two environment paths avoiding repeats. + + Here `old` is the environment string before the base class initialize + function is called and `new` is the string after the call. The new string + will be a fixed string if it is not obtained from the current environment, + or the same as the old string if obtained from the same environment. The aim + here is not to append the new string if it is already contained in the old + string so as to limit the growth of the environment string. + + Parameters + ---------- + old : string + Previous environment string. + new : string + New environment string. + + Returns + ------- + ret : string + Updated environment string. + + """ + if new in old: + return old + if not old: + return new + + # Neither new nor old is empty. Give old priority. + return ';'.join([old, new]) + + +class MSVCCompiler(_MSVCCompiler): + def __init__(self, verbose=0, dry_run=0, force=0): + _MSVCCompiler.__init__(self, verbose, dry_run, force) + + def initialize(self): + # The 'lib' and 'include' variables may be overwritten + # by MSVCCompiler.initialize, so save them for later merge. + environ_lib = os.getenv('lib', '') + environ_include = os.getenv('include', '') + _MSVCCompiler.initialize(self) + + # Merge current and previous values of 'lib' and 'include' + os.environ['lib'] = _merge(environ_lib, os.environ['lib']) + os.environ['include'] = _merge(environ_include, os.environ['include']) + + # msvc9 building for 32 bits requires SSE2 to work around a + # compiler bug. + if platform_bits == 32: + self.compile_options += ['/arch:SSE2'] + self.compile_options_debug += ['/arch:SSE2'] diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/npy_pkg_config.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/npy_pkg_config.py new file mode 100644 index 0000000000000000000000000000000000000000..bfe8b9f77acb9ed706aab324d46414765f93a865 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/distutils/npy_pkg_config.py @@ -0,0 +1,443 @@ +from __future__ import division, absolute_import, print_function + +import sys +import re +import os + +if sys.version_info[0] < 3: + from ConfigParser import RawConfigParser +else: + from configparser import RawConfigParser + +__all__ = ['FormatError', 'PkgNotFound', 'LibraryInfo', 'VariableSet', + 'read_config', 'parse_flags'] + +_VAR = re.compile(r'\$\{([a-zA-Z0-9_-]+)\}') + +class FormatError(IOError): + """ + Exception thrown when there is a problem parsing a configuration file. + + """ + def __init__(self, msg): + self.msg = msg + + def __str__(self): + return self.msg + +class PkgNotFound(IOError): + """Exception raised when a package can not be located.""" + def __init__(self, msg): + self.msg = msg + + def __str__(self): + return self.msg + +def parse_flags(line): + """ + Parse a line from a config file containing compile flags. + + Parameters + ---------- + line : str + A single line containing one or more compile flags. + + Returns + ------- + d : dict + Dictionary of parsed flags, split into relevant categories. + These categories are the keys of `d`: + + * 'include_dirs' + * 'library_dirs' + * 'libraries' + * 'macros' + * 'ignored' + + """ + d = {'include_dirs': [], 'library_dirs': [], 'libraries': [], + 'macros': [], 'ignored': []} + + flags = (' ' + line).split(' -') + for flag in flags: + flag = '-' + flag + if len(flag) > 0: + if flag.startswith('-I'): + d['include_dirs'].append(flag[2:].strip()) + elif flag.startswith('-L'): + d['library_dirs'].append(flag[2:].strip()) + elif flag.startswith('-l'): + d['libraries'].append(flag[2:].strip()) + elif flag.startswith('-D'): + d['macros'].append(flag[2:].strip()) + else: + d['ignored'].append(flag) + + return d + +def _escape_backslash(val): + return val.replace('\\', '\\\\') + +class LibraryInfo(object): + """ + Object containing build information about a library. + + Parameters + ---------- + name : str + The library name. + description : str + Description of the library. + version : str + Version string. + sections : dict + The sections of the configuration file for the library. The keys are + the section headers, the values the text under each header. + vars : class instance + A `VariableSet` instance, which contains ``(name, value)`` pairs for + variables defined in the configuration file for the library. + requires : sequence, optional + The required libraries for the library to be installed. + + Notes + ----- + All input parameters (except "sections" which is a method) are available as + attributes of the same name. + + """ + def __init__(self, name, description, version, sections, vars, requires=None): + self.name = name + self.description = description + if requires: + self.requires = requires + else: + self.requires = [] + self.version = version + self._sections = sections + self.vars = vars + + def sections(self): + """ + Return the section headers of the config file. + + Parameters + ---------- + None + + Returns + ------- + keys : list of str + The list of section headers. + + """ + return list(self._sections.keys()) + + def cflags(self, section="default"): + val = self.vars.interpolate(self._sections[section]['cflags']) + return _escape_backslash(val) + + def libs(self, section="default"): + val = self.vars.interpolate(self._sections[section]['libs']) + return _escape_backslash(val) + + def __str__(self): + m = ['Name: %s' % self.name, 'Description: %s' % self.description] + if self.requires: + m.append('Requires:') + else: + m.append('Requires: %s' % ",".join(self.requires)) + m.append('Version: %s' % self.version) + + return "\n".join(m) + +class VariableSet(object): + """ + Container object for the variables defined in a config file. + + `VariableSet` can be used as a plain dictionary, with the variable names + as keys. + + Parameters + ---------- + d : dict + Dict of items in the "variables" section of the configuration file. + + """ + def __init__(self, d): + self._raw_data = dict([(k, v) for k, v in d.items()]) + + self._re = {} + self._re_sub = {} + + self._init_parse() + + def _init_parse(self): + for k, v in self._raw_data.items(): + self._init_parse_var(k, v) + + def _init_parse_var(self, name, value): + self._re[name] = re.compile(r'\$\{%s\}' % name) + self._re_sub[name] = value + + def interpolate(self, value): + # Brute force: we keep interpolating until there is no '${var}' anymore + # or until interpolated string is equal to input string + def _interpolate(value): + for k in self._re.keys(): + value = self._re[k].sub(self._re_sub[k], value) + return value + while _VAR.search(value): + nvalue = _interpolate(value) + if nvalue == value: + break + value = nvalue + + return value + + def variables(self): + """ + Return the list of variable names. + + Parameters + ---------- + None + + Returns + ------- + names : list of str + The names of all variables in the `VariableSet` instance. + + """ + return list(self._raw_data.keys()) + + # Emulate a dict to set/get variables values + def __getitem__(self, name): + return self._raw_data[name] + + def __setitem__(self, name, value): + self._raw_data[name] = value + self._init_parse_var(name, value) + +def parse_meta(config): + if not config.has_section('meta'): + raise FormatError("No meta section found !") + + d = dict(config.items('meta')) + + for k in ['name', 'description', 'version']: + if not k in d: + raise FormatError("Option %s (section [meta]) is mandatory, " + "but not found" % k) + + if not 'requires' in d: + d['requires'] = [] + + return d + +def parse_variables(config): + if not config.has_section('variables'): + raise FormatError("No variables section found !") + + d = {} + + for name, value in config.items("variables"): + d[name] = value + + return VariableSet(d) + +def parse_sections(config): + return meta_d, r + +def pkg_to_filename(pkg_name): + return "%s.ini" % pkg_name + +def parse_config(filename, dirs=None): + if dirs: + filenames = [os.path.join(d, filename) for d in dirs] + else: + filenames = [filename] + + config = RawConfigParser() + + n = config.read(filenames) + if not len(n) >= 1: + raise PkgNotFound("Could not find file(s) %s" % str(filenames)) + + # Parse meta and variables sections + meta = parse_meta(config) + + vars = {} + if config.has_section('variables'): + for name, value in config.items("variables"): + vars[name] = _escape_backslash(value) + + # Parse "normal" sections + secs = [s for s in config.sections() if not s in ['meta', 'variables']] + sections = {} + + requires = {} + for s in secs: + d = {} + if config.has_option(s, "requires"): + requires[s] = config.get(s, 'requires') + + for name, value in config.items(s): + d[name] = value + sections[s] = d + + return meta, vars, sections, requires + +def _read_config_imp(filenames, dirs=None): + def _read_config(f): + meta, vars, sections, reqs = parse_config(f, dirs) + # recursively add sections and variables of required libraries + for rname, rvalue in reqs.items(): + nmeta, nvars, nsections, nreqs = _read_config(pkg_to_filename(rvalue)) + + # Update var dict for variables not in 'top' config file + for k, v in nvars.items(): + if not k in vars: + vars[k] = v + + # Update sec dict + for oname, ovalue in nsections[rname].items(): + if ovalue: + sections[rname][oname] += ' %s' % ovalue + + return meta, vars, sections, reqs + + meta, vars, sections, reqs = _read_config(filenames) + + # FIXME: document this. If pkgname is defined in the variables section, and + # there is no pkgdir variable defined, pkgdir is automatically defined to + # the path of pkgname. This requires the package to be imported to work + if not 'pkgdir' in vars and "pkgname" in vars: + pkgname = vars["pkgname"] + if not pkgname in sys.modules: + raise ValueError("You should import %s to get information on %s" % + (pkgname, meta["name"])) + + mod = sys.modules[pkgname] + vars["pkgdir"] = _escape_backslash(os.path.dirname(mod.__file__)) + + return LibraryInfo(name=meta["name"], description=meta["description"], + version=meta["version"], sections=sections, vars=VariableSet(vars)) + +# Trivial cache to cache LibraryInfo instances creation. To be really +# efficient, the cache should be handled in read_config, since a same file can +# be parsed many time outside LibraryInfo creation, but I doubt this will be a +# problem in practice +_CACHE = {} +def read_config(pkgname, dirs=None): + """ + Return library info for a package from its configuration file. + + Parameters + ---------- + pkgname : str + Name of the package (should match the name of the .ini file, without + the extension, e.g. foo for the file foo.ini). + dirs : sequence, optional + If given, should be a sequence of directories - usually including + the NumPy base directory - where to look for npy-pkg-config files. + + Returns + ------- + pkginfo : class instance + The `LibraryInfo` instance containing the build information. + + Raises + ------ + PkgNotFound + If the package is not found. + + See Also + -------- + misc_util.get_info, misc_util.get_pkg_info + + Examples + -------- + >>> npymath_info = np.distutils.npy_pkg_config.read_config('npymath') + >>> type(npymath_info) + + >>> print(npymath_info) + Name: npymath + Description: Portable, core math library implementing C99 standard + Requires: + Version: 0.1 #random + + """ + try: + return _CACHE[pkgname] + except KeyError: + v = _read_config_imp(pkg_to_filename(pkgname), dirs) + _CACHE[pkgname] = v + return v + +# TODO: +# - implements version comparison (modversion + atleast) + +# pkg-config simple emulator - useful for debugging, and maybe later to query +# the system +if __name__ == '__main__': + import sys + from optparse import OptionParser + import glob + + parser = OptionParser() + parser.add_option("--cflags", dest="cflags", action="store_true", + help="output all preprocessor and compiler flags") + parser.add_option("--libs", dest="libs", action="store_true", + help="output all linker flags") + parser.add_option("--use-section", dest="section", + help="use this section instead of default for options") + parser.add_option("--version", dest="version", action="store_true", + help="output version") + parser.add_option("--atleast-version", dest="min_version", + help="Minimal version") + parser.add_option("--list-all", dest="list_all", action="store_true", + help="Minimal version") + parser.add_option("--define-variable", dest="define_variable", + help="Replace variable with the given value") + + (options, args) = parser.parse_args(sys.argv) + + if len(args) < 2: + raise ValueError("Expect package name on the command line:") + + if options.list_all: + files = glob.glob("*.ini") + for f in files: + info = read_config(f) + print("%s\t%s - %s" % (info.name, info.name, info.description)) + + pkg_name = args[1] + d = os.environ.get('NPY_PKG_CONFIG_PATH') + if d: + info = read_config(pkg_name, ['numpy/core/lib/npy-pkg-config', '.', d]) + else: + info = read_config(pkg_name, ['numpy/core/lib/npy-pkg-config', '.']) + + if options.section: + section = options.section + else: + section = "default" + + if options.define_variable: + m = re.search(r'([\S]+)=([\S]+)', options.define_variable) + if not m: + raise ValueError("--define-variable option should be of " \ + "the form --define-variable=foo=bar") + else: + name = m.group(1) + value = m.group(2) + info.vars[name] = value + + if options.cflags: + print(info.cflags(section)) + if options.libs: + print(info.libs(section)) + if options.version: + print(info.version) + if options.min_version: + print(info.version >= options.min_version) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/api/types/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/api/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..438e4afa3f5807de59f4fe7aa637d73ddfeec755 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/api/types/__init__.py @@ -0,0 +1,9 @@ +""" public toolkit API """ + +from pandas.core.dtypes.api import * # noqa +from pandas.core.dtypes.dtypes import (CategoricalDtype, # noqa + DatetimeTZDtype, + PeriodDtype, + IntervalDtype) +from pandas.core.dtypes.concat import union_categoricals # noqa +from pandas._libs.lib import infer_dtype # noqa diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/expr.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/expr.py new file mode 100644 index 0000000000000000000000000000000000000000..d840bf6ae71a2ed61d1be23ba1a3154048ad903c --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/expr.py @@ -0,0 +1,776 @@ +""":func:`~pandas.eval` parsers +""" + +import ast +from functools import partial +import tokenize + +import numpy as np + +from pandas.compat import StringIO, lmap, reduce, string_types, zip + +import pandas as pd +from pandas import compat +from pandas.core import common as com +from pandas.core.base import StringMixin +from pandas.core.computation.ops import ( + _LOCAL_TAG, BinOp, Constant, Div, FuncNode, Op, Term, UnaryOp, + UndefinedVariableError, _arith_ops_syms, _bool_ops_syms, _cmp_ops_syms, + _mathops, _reductions, _unary_ops_syms, is_term) +from pandas.core.computation.scope import Scope + +import pandas.io.formats.printing as printing + + +def tokenize_string(source): + """Tokenize a Python source code string. + + Parameters + ---------- + source : str + A Python source code string + """ + line_reader = StringIO(source).readline + for toknum, tokval, _, _, _ in tokenize.generate_tokens(line_reader): + yield toknum, tokval + + +def _rewrite_assign(tok): + """Rewrite the assignment operator for PyTables expressions that use ``=`` + as a substitute for ``==``. + + Parameters + ---------- + tok : tuple of int, str + ints correspond to the all caps constants in the tokenize module + + Returns + ------- + t : tuple of int, str + Either the input or token or the replacement values + """ + toknum, tokval = tok + return toknum, '==' if tokval == '=' else tokval + + +def _replace_booleans(tok): + """Replace ``&`` with ``and`` and ``|`` with ``or`` so that bitwise + precedence is changed to boolean precedence. + + Parameters + ---------- + tok : tuple of int, str + ints correspond to the all caps constants in the tokenize module + + Returns + ------- + t : tuple of int, str + Either the input or token or the replacement values + """ + toknum, tokval = tok + if toknum == tokenize.OP: + if tokval == '&': + return tokenize.NAME, 'and' + elif tokval == '|': + return tokenize.NAME, 'or' + return toknum, tokval + return toknum, tokval + + +def _replace_locals(tok): + """Replace local variables with a syntactically valid name. + + Parameters + ---------- + tok : tuple of int, str + ints correspond to the all caps constants in the tokenize module + + Returns + ------- + t : tuple of int, str + Either the input or token or the replacement values + + Notes + ----- + This is somewhat of a hack in that we rewrite a string such as ``'@a'`` as + ``'__pd_eval_local_a'`` by telling the tokenizer that ``__pd_eval_local_`` + is a ``tokenize.OP`` and to replace the ``'@'`` symbol with it. + """ + toknum, tokval = tok + if toknum == tokenize.OP and tokval == '@': + return tokenize.OP, _LOCAL_TAG + return toknum, tokval + + +def _compose2(f, g): + """Compose 2 callables""" + return lambda *args, **kwargs: f(g(*args, **kwargs)) + + +def _compose(*funcs): + """Compose 2 or more callables""" + assert len(funcs) > 1, 'At least 2 callables must be passed to compose' + return reduce(_compose2, funcs) + + +def _preparse(source, f=_compose(_replace_locals, _replace_booleans, + _rewrite_assign)): + """Compose a collection of tokenization functions + + Parameters + ---------- + source : str + A Python source code string + f : callable + This takes a tuple of (toknum, tokval) as its argument and returns a + tuple with the same structure but possibly different elements. Defaults + to the composition of ``_rewrite_assign``, ``_replace_booleans``, and + ``_replace_locals``. + + Returns + ------- + s : str + Valid Python source code + + Notes + ----- + The `f` parameter can be any callable that takes *and* returns input of the + form ``(toknum, tokval)``, where ``toknum`` is one of the constants from + the ``tokenize`` module and ``tokval`` is a string. + """ + assert callable(f), 'f must be callable' + return tokenize.untokenize(lmap(f, tokenize_string(source))) + + +def _is_type(t): + """Factory for a type checking function of type ``t`` or tuple of types.""" + return lambda x: isinstance(x.value, t) + + +_is_list = _is_type(list) +_is_str = _is_type(string_types) + + +# partition all AST nodes +_all_nodes = frozenset(filter(lambda x: isinstance(x, type) and + issubclass(x, ast.AST), + (getattr(ast, node) for node in dir(ast)))) + + +def _filter_nodes(superclass, all_nodes=_all_nodes): + """Filter out AST nodes that are subclasses of ``superclass``.""" + node_names = (node.__name__ for node in all_nodes + if issubclass(node, superclass)) + return frozenset(node_names) + + +_all_node_names = frozenset(map(lambda x: x.__name__, _all_nodes)) +_mod_nodes = _filter_nodes(ast.mod) +_stmt_nodes = _filter_nodes(ast.stmt) +_expr_nodes = _filter_nodes(ast.expr) +_expr_context_nodes = _filter_nodes(ast.expr_context) +_slice_nodes = _filter_nodes(ast.slice) +_boolop_nodes = _filter_nodes(ast.boolop) +_operator_nodes = _filter_nodes(ast.operator) +_unary_op_nodes = _filter_nodes(ast.unaryop) +_cmp_op_nodes = _filter_nodes(ast.cmpop) +_comprehension_nodes = _filter_nodes(ast.comprehension) +_handler_nodes = _filter_nodes(ast.excepthandler) +_arguments_nodes = _filter_nodes(ast.arguments) +_keyword_nodes = _filter_nodes(ast.keyword) +_alias_nodes = _filter_nodes(ast.alias) + + +# nodes that we don't support directly but are needed for parsing +_hacked_nodes = frozenset(['Assign', 'Module', 'Expr']) + + +_unsupported_expr_nodes = frozenset(['Yield', 'GeneratorExp', 'IfExp', + 'DictComp', 'SetComp', 'Repr', 'Lambda', + 'Set', 'AST', 'Is', 'IsNot']) + +# these nodes are low priority or won't ever be supported (e.g., AST) +_unsupported_nodes = ((_stmt_nodes | _mod_nodes | _handler_nodes | + _arguments_nodes | _keyword_nodes | _alias_nodes | + _expr_context_nodes | _unsupported_expr_nodes) - + _hacked_nodes) + +# we're adding a different assignment in some cases to be equality comparison +# and we don't want `stmt` and friends in their so get only the class whose +# names are capitalized +_base_supported_nodes = (_all_node_names - _unsupported_nodes) | _hacked_nodes +_msg = 'cannot both support and not support {intersection}'.format( + intersection=_unsupported_nodes & _base_supported_nodes) +assert not _unsupported_nodes & _base_supported_nodes, _msg + + +def _node_not_implemented(node_name, cls): + """Return a function that raises a NotImplementedError with a passed node + name. + """ + + def f(self, *args, **kwargs): + raise NotImplementedError("{name!r} nodes are not " + "implemented".format(name=node_name)) + return f + + +def disallow(nodes): + """Decorator to disallow certain nodes from parsing. Raises a + NotImplementedError instead. + + Returns + ------- + disallowed : callable + """ + def disallowed(cls): + cls.unsupported_nodes = () + for node in nodes: + new_method = _node_not_implemented(node, cls) + name = 'visit_{node}'.format(node=node) + cls.unsupported_nodes += (name,) + setattr(cls, name, new_method) + return cls + return disallowed + + +def _op_maker(op_class, op_symbol): + """Return a function to create an op class with its symbol already passed. + + Returns + ------- + f : callable + """ + + def f(self, node, *args, **kwargs): + """Return a partial function with an Op subclass with an operator + already passed. + + Returns + ------- + f : callable + """ + return partial(op_class, op_symbol, *args, **kwargs) + return f + + +_op_classes = {'binary': BinOp, 'unary': UnaryOp} + + +def add_ops(op_classes): + """Decorator to add default implementation of ops.""" + def f(cls): + for op_attr_name, op_class in compat.iteritems(op_classes): + ops = getattr(cls, '{name}_ops'.format(name=op_attr_name)) + ops_map = getattr(cls, '{name}_op_nodes_map'.format( + name=op_attr_name)) + for op in ops: + op_node = ops_map[op] + if op_node is not None: + made_op = _op_maker(op_class, op) + setattr(cls, 'visit_{node}'.format(node=op_node), made_op) + return cls + return f + + +@disallow(_unsupported_nodes) +@add_ops(_op_classes) +class BaseExprVisitor(ast.NodeVisitor): + + """Custom ast walker. Parsers of other engines should subclass this class + if necessary. + + Parameters + ---------- + env : Scope + engine : str + parser : str + preparser : callable + """ + const_type = Constant + term_type = Term + + binary_ops = _cmp_ops_syms + _bool_ops_syms + _arith_ops_syms + binary_op_nodes = ('Gt', 'Lt', 'GtE', 'LtE', 'Eq', 'NotEq', 'In', 'NotIn', + 'BitAnd', 'BitOr', 'And', 'Or', 'Add', 'Sub', 'Mult', + None, 'Pow', 'FloorDiv', 'Mod') + binary_op_nodes_map = dict(zip(binary_ops, binary_op_nodes)) + + unary_ops = _unary_ops_syms + unary_op_nodes = 'UAdd', 'USub', 'Invert', 'Not' + unary_op_nodes_map = dict(zip(unary_ops, unary_op_nodes)) + + rewrite_map = { + ast.Eq: ast.In, + ast.NotEq: ast.NotIn, + ast.In: ast.In, + ast.NotIn: ast.NotIn + } + + def __init__(self, env, engine, parser, preparser=_preparse): + self.env = env + self.engine = engine + self.parser = parser + self.preparser = preparser + self.assigner = None + + def visit(self, node, **kwargs): + if isinstance(node, string_types): + clean = self.preparser(node) + try: + node = ast.fix_missing_locations(ast.parse(clean)) + except SyntaxError as e: + from keyword import iskeyword + if any(iskeyword(x) for x in clean.split()): + e.msg = ("Python keyword not valid identifier" + " in numexpr query") + raise e + + method = 'visit_' + node.__class__.__name__ + visitor = getattr(self, method) + return visitor(node, **kwargs) + + def visit_Module(self, node, **kwargs): + if len(node.body) != 1: + raise SyntaxError('only a single expression is allowed') + expr = node.body[0] + return self.visit(expr, **kwargs) + + def visit_Expr(self, node, **kwargs): + return self.visit(node.value, **kwargs) + + def _rewrite_membership_op(self, node, left, right): + # the kind of the operator (is actually an instance) + op_instance = node.op + op_type = type(op_instance) + + # must be two terms and the comparison operator must be ==/!=/in/not in + if is_term(left) and is_term(right) and op_type in self.rewrite_map: + + left_list, right_list = map(_is_list, (left, right)) + left_str, right_str = map(_is_str, (left, right)) + + # if there are any strings or lists in the expression + if left_list or right_list or left_str or right_str: + op_instance = self.rewrite_map[op_type]() + + # pop the string variable out of locals and replace it with a list + # of one string, kind of a hack + if right_str: + name = self.env.add_tmp([right.value]) + right = self.term_type(name, self.env) + + if left_str: + name = self.env.add_tmp([left.value]) + left = self.term_type(name, self.env) + + op = self.visit(op_instance) + return op, op_instance, left, right + + def _maybe_transform_eq_ne(self, node, left=None, right=None): + if left is None: + left = self.visit(node.left, side='left') + if right is None: + right = self.visit(node.right, side='right') + op, op_class, left, right = self._rewrite_membership_op(node, left, + right) + return op, op_class, left, right + + def _maybe_downcast_constants(self, left, right): + f32 = np.dtype(np.float32) + if left.is_scalar and not right.is_scalar and right.return_type == f32: + # right is a float32 array, left is a scalar + name = self.env.add_tmp(np.float32(left.value)) + left = self.term_type(name, self.env) + if right.is_scalar and not left.is_scalar and left.return_type == f32: + # left is a float32 array, right is a scalar + name = self.env.add_tmp(np.float32(right.value)) + right = self.term_type(name, self.env) + + return left, right + + def _maybe_eval(self, binop, eval_in_python): + # eval `in` and `not in` (for now) in "partial" python space + # things that can be evaluated in "eval" space will be turned into + # temporary variables. for example, + # [1,2] in a + 2 * b + # in that case a + 2 * b will be evaluated using numexpr, and the "in" + # call will be evaluated using isin (in python space) + return binop.evaluate(self.env, self.engine, self.parser, + self.term_type, eval_in_python) + + def _maybe_evaluate_binop(self, op, op_class, lhs, rhs, + eval_in_python=('in', 'not in'), + maybe_eval_in_python=('==', '!=', '<', '>', + '<=', '>=')): + res = op(lhs, rhs) + + if res.has_invalid_return_type: + raise TypeError("unsupported operand type(s) for {op}:" + " '{lhs}' and '{rhs}'".format(op=res.op, + lhs=lhs.type, + rhs=rhs.type)) + + if self.engine != 'pytables': + if (res.op in _cmp_ops_syms and + getattr(lhs, 'is_datetime', False) or + getattr(rhs, 'is_datetime', False)): + # all date ops must be done in python bc numexpr doesn't work + # well with NaT + return self._maybe_eval(res, self.binary_ops) + + if res.op in eval_in_python: + # "in"/"not in" ops are always evaluated in python + return self._maybe_eval(res, eval_in_python) + elif self.engine != 'pytables': + if (getattr(lhs, 'return_type', None) == object or + getattr(rhs, 'return_type', None) == object): + # evaluate "==" and "!=" in python if either of our operands + # has an object return type + return self._maybe_eval(res, eval_in_python + + maybe_eval_in_python) + return res + + def visit_BinOp(self, node, **kwargs): + op, op_class, left, right = self._maybe_transform_eq_ne(node) + left, right = self._maybe_downcast_constants(left, right) + return self._maybe_evaluate_binop(op, op_class, left, right) + + def visit_Div(self, node, **kwargs): + truediv = self.env.scope['truediv'] + return lambda lhs, rhs: Div(lhs, rhs, truediv) + + def visit_UnaryOp(self, node, **kwargs): + op = self.visit(node.op) + operand = self.visit(node.operand) + return op(operand) + + def visit_Name(self, node, **kwargs): + return self.term_type(node.id, self.env, **kwargs) + + def visit_NameConstant(self, node, **kwargs): + return self.const_type(node.value, self.env) + + def visit_Num(self, node, **kwargs): + return self.const_type(node.n, self.env) + + def visit_Str(self, node, **kwargs): + name = self.env.add_tmp(node.s) + return self.term_type(name, self.env) + + def visit_List(self, node, **kwargs): + name = self.env.add_tmp([self.visit(e)(self.env) for e in node.elts]) + return self.term_type(name, self.env) + + visit_Tuple = visit_List + + def visit_Index(self, node, **kwargs): + """ df.index[4] """ + return self.visit(node.value) + + def visit_Subscript(self, node, **kwargs): + value = self.visit(node.value) + slobj = self.visit(node.slice) + result = pd.eval(slobj, local_dict=self.env, engine=self.engine, + parser=self.parser) + try: + # a Term instance + v = value.value[result] + except AttributeError: + # an Op instance + lhs = pd.eval(value, local_dict=self.env, engine=self.engine, + parser=self.parser) + v = lhs[result] + name = self.env.add_tmp(v) + return self.term_type(name, env=self.env) + + def visit_Slice(self, node, **kwargs): + """ df.index[slice(4,6)] """ + lower = node.lower + if lower is not None: + lower = self.visit(lower).value + upper = node.upper + if upper is not None: + upper = self.visit(upper).value + step = node.step + if step is not None: + step = self.visit(step).value + + return slice(lower, upper, step) + + def visit_Assign(self, node, **kwargs): + """ + support a single assignment node, like + + c = a + b + + set the assigner at the top level, must be a Name node which + might or might not exist in the resolvers + + """ + + if len(node.targets) != 1: + raise SyntaxError('can only assign a single expression') + if not isinstance(node.targets[0], ast.Name): + raise SyntaxError('left hand side of an assignment must be a ' + 'single name') + if self.env.target is None: + raise ValueError('cannot assign without a target object') + + try: + assigner = self.visit(node.targets[0], **kwargs) + except UndefinedVariableError: + assigner = node.targets[0].id + + self.assigner = getattr(assigner, 'name', assigner) + if self.assigner is None: + raise SyntaxError('left hand side of an assignment must be a ' + 'single resolvable name') + + return self.visit(node.value, **kwargs) + + def visit_Attribute(self, node, **kwargs): + attr = node.attr + value = node.value + + ctx = node.ctx + if isinstance(ctx, ast.Load): + # resolve the value + resolved = self.visit(value).value + try: + v = getattr(resolved, attr) + name = self.env.add_tmp(v) + return self.term_type(name, self.env) + except AttributeError: + # something like datetime.datetime where scope is overridden + if isinstance(value, ast.Name) and value.id == attr: + return resolved + + raise ValueError("Invalid Attribute context {name}" + .format(name=ctx.__name__)) + + def visit_Call_35(self, node, side=None, **kwargs): + """ in 3.5 the starargs attribute was changed to be more flexible, + #11097 """ + + if isinstance(node.func, ast.Attribute): + res = self.visit_Attribute(node.func) + elif not isinstance(node.func, ast.Name): + raise TypeError("Only named functions are supported") + else: + try: + res = self.visit(node.func) + except UndefinedVariableError: + # Check if this is a supported function name + try: + res = FuncNode(node.func.id) + except ValueError: + # Raise original error + raise + + if res is None: + raise ValueError("Invalid function call {func}" + .format(func=node.func.id)) + if hasattr(res, 'value'): + res = res.value + + if isinstance(res, FuncNode): + + new_args = [self.visit(arg) for arg in node.args] + + if node.keywords: + raise TypeError("Function \"{name}\" does not support keyword " + "arguments".format(name=res.name)) + + return res(*new_args, **kwargs) + + else: + + new_args = [self.visit(arg).value for arg in node.args] + + for key in node.keywords: + if not isinstance(key, ast.keyword): + raise ValueError("keyword error in function call " + "'{func}'".format(func=node.func.id)) + + if key.arg: + # TODO: bug? + kwargs.append(ast.keyword( + keyword.arg, self.visit(keyword.value))) # noqa + + return self.const_type(res(*new_args, **kwargs), self.env) + + def visit_Call_legacy(self, node, side=None, **kwargs): + + # this can happen with: datetime.datetime + if isinstance(node.func, ast.Attribute): + res = self.visit_Attribute(node.func) + elif not isinstance(node.func, ast.Name): + raise TypeError("Only named functions are supported") + else: + try: + res = self.visit(node.func) + except UndefinedVariableError: + # Check if this is a supported function name + try: + res = FuncNode(node.func.id) + except ValueError: + # Raise original error + raise + + if res is None: + raise ValueError("Invalid function call {func}" + .format(func=node.func.id)) + if hasattr(res, 'value'): + res = res.value + + if isinstance(res, FuncNode): + args = [self.visit(targ) for targ in node.args] + + if node.starargs is not None: + args += self.visit(node.starargs) + + if node.keywords or node.kwargs: + raise TypeError("Function \"{name}\" does not support keyword " + "arguments".format(name=res.name)) + + return res(*args, **kwargs) + + else: + args = [self.visit(targ).value for targ in node.args] + if node.starargs is not None: + args += self.visit(node.starargs).value + + keywords = {} + for key in node.keywords: + if not isinstance(key, ast.keyword): + raise ValueError("keyword error in function call " + "'{func}'".format(func=node.func.id)) + keywords[key.arg] = self.visit(key.value).value + if node.kwargs is not None: + keywords.update(self.visit(node.kwargs).value) + + return self.const_type(res(*args, **keywords), self.env) + + def translate_In(self, op): + return op + + def visit_Compare(self, node, **kwargs): + ops = node.ops + comps = node.comparators + + # base case: we have something like a CMP b + if len(comps) == 1: + op = self.translate_In(ops[0]) + binop = ast.BinOp(op=op, left=node.left, right=comps[0]) + return self.visit(binop) + + # recursive case: we have a chained comparison, a CMP b CMP c, etc. + left = node.left + values = [] + for op, comp in zip(ops, comps): + new_node = self.visit(ast.Compare(comparators=[comp], left=left, + ops=[self.translate_In(op)])) + left = comp + values.append(new_node) + return self.visit(ast.BoolOp(op=ast.And(), values=values)) + + def _try_visit_binop(self, bop): + if isinstance(bop, (Op, Term)): + return bop + return self.visit(bop) + + def visit_BoolOp(self, node, **kwargs): + def visitor(x, y): + lhs = self._try_visit_binop(x) + rhs = self._try_visit_binop(y) + + op, op_class, lhs, rhs = self._maybe_transform_eq_ne( + node, lhs, rhs) + return self._maybe_evaluate_binop(op, node.op, lhs, rhs) + + operands = node.values + return reduce(visitor, operands) + + +# ast.Call signature changed on 3.5, +# conditionally change which methods is named +# visit_Call depending on Python version, #11097 +if compat.PY35: + BaseExprVisitor.visit_Call = BaseExprVisitor.visit_Call_35 +else: + BaseExprVisitor.visit_Call = BaseExprVisitor.visit_Call_legacy + +_python_not_supported = frozenset(['Dict', 'BoolOp', 'In', 'NotIn']) +_numexpr_supported_calls = frozenset(_reductions + _mathops) + + +@disallow((_unsupported_nodes | _python_not_supported) - + (_boolop_nodes | frozenset(['BoolOp', 'Attribute', 'In', 'NotIn', + 'Tuple']))) +class PandasExprVisitor(BaseExprVisitor): + + def __init__(self, env, engine, parser, + preparser=partial(_preparse, f=_compose(_replace_locals, + _replace_booleans))): + super(PandasExprVisitor, self).__init__(env, engine, parser, preparser) + + +@disallow(_unsupported_nodes | _python_not_supported | frozenset(['Not'])) +class PythonExprVisitor(BaseExprVisitor): + + def __init__(self, env, engine, parser, preparser=lambda x: x): + super(PythonExprVisitor, self).__init__(env, engine, parser, + preparser=preparser) + + +class Expr(StringMixin): + + """Object encapsulating an expression. + + Parameters + ---------- + expr : str + engine : str, optional, default 'numexpr' + parser : str, optional, default 'pandas' + env : Scope, optional, default None + truediv : bool, optional, default True + level : int, optional, default 2 + """ + + def __init__(self, expr, engine='numexpr', parser='pandas', env=None, + truediv=True, level=0): + self.expr = expr + self.env = env or Scope(level=level + 1) + self.engine = engine + self.parser = parser + self.env.scope['truediv'] = truediv + self._visitor = _parsers[parser](self.env, self.engine, self.parser) + self.terms = self.parse() + + @property + def assigner(self): + return getattr(self._visitor, 'assigner', None) + + def __call__(self): + return self.terms(self.env) + + def __unicode__(self): + return printing.pprint_thing(self.terms) + + def __len__(self): + return len(self.expr) + + def parse(self): + """Parse an expression""" + return self._visitor.visit(self.expr) + + @property + def names(self): + """Get the names in an expression""" + if is_term(self.terms): + return frozenset([self.terms.name]) + return frozenset(term.name for term in com.flatten(self.terms)) + + +_parsers = {'python': PythonExprVisitor, 'pandas': PandasExprVisitor} diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/expressions.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/expressions.py new file mode 100644 index 0000000000000000000000000000000000000000..a91ef7592a36d24839dfe5bbdcdbb9b39106257b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/expressions.py @@ -0,0 +1,251 @@ +""" +Expressions +----------- + +Offer fast expression evaluation through numexpr + +""" + +import warnings + +import numpy as np + +from pandas.core.dtypes.generic import ABCDataFrame + +import pandas.core.common as com +from pandas.core.computation.check import _NUMEXPR_INSTALLED +from pandas.core.config import get_option + +if _NUMEXPR_INSTALLED: + import numexpr as ne + +_TEST_MODE = None +_TEST_RESULT = None +_USE_NUMEXPR = _NUMEXPR_INSTALLED +_evaluate = None +_where = None + +# the set of dtypes that we will allow pass to numexpr +_ALLOWED_DTYPES = { + 'evaluate': {'int64', 'int32', 'float64', 'float32', 'bool'}, + 'where': {'int64', 'float64', 'bool'} +} + +# the minimum prod shape that we will use numexpr +_MIN_ELEMENTS = 10000 + + +def set_use_numexpr(v=True): + # set/unset to use numexpr + global _USE_NUMEXPR + if _NUMEXPR_INSTALLED: + _USE_NUMEXPR = v + + # choose what we are going to do + global _evaluate, _where + if not _USE_NUMEXPR: + _evaluate = _evaluate_standard + _where = _where_standard + else: + _evaluate = _evaluate_numexpr + _where = _where_numexpr + + +def set_numexpr_threads(n=None): + # if we are using numexpr, set the threads to n + # otherwise reset + if _NUMEXPR_INSTALLED and _USE_NUMEXPR: + if n is None: + n = ne.detect_number_of_cores() + ne.set_num_threads(n) + + +def _evaluate_standard(op, op_str, a, b, **eval_kwargs): + """ standard evaluation """ + if _TEST_MODE: + _store_test_result(False) + with np.errstate(all='ignore'): + return op(a, b) + + +def _can_use_numexpr(op, op_str, a, b, dtype_check): + """ return a boolean if we WILL be using numexpr """ + if op_str is not None: + + # required min elements (otherwise we are adding overhead) + if np.prod(a.shape) > _MIN_ELEMENTS: + + # check for dtype compatibility + dtypes = set() + for o in [a, b]: + if hasattr(o, 'get_dtype_counts'): + s = o.get_dtype_counts() + if len(s) > 1: + return False + dtypes |= set(s.index) + elif isinstance(o, np.ndarray): + dtypes |= {o.dtype.name} + + # allowed are a superset + if not len(dtypes) or _ALLOWED_DTYPES[dtype_check] >= dtypes: + return True + + return False + + +def _evaluate_numexpr(op, op_str, a, b, truediv=True, + reversed=False, **eval_kwargs): + result = None + + if _can_use_numexpr(op, op_str, a, b, 'evaluate'): + try: + + # we were originally called by a reversed op + # method + if reversed: + a, b = b, a + + a_value = getattr(a, "values", a) + b_value = getattr(b, "values", b) + result = ne.evaluate('a_value {op} b_value'.format(op=op_str), + local_dict={'a_value': a_value, + 'b_value': b_value}, + casting='safe', truediv=truediv, + **eval_kwargs) + except ValueError as detail: + if 'unknown type object' in str(detail): + pass + + if _TEST_MODE: + _store_test_result(result is not None) + + if result is None: + result = _evaluate_standard(op, op_str, a, b) + + return result + + +def _where_standard(cond, a, b): + return np.where(com.values_from_object(cond), com.values_from_object(a), + com.values_from_object(b)) + + +def _where_numexpr(cond, a, b): + result = None + + if _can_use_numexpr(None, 'where', a, b, 'where'): + + try: + cond_value = getattr(cond, 'values', cond) + a_value = getattr(a, 'values', a) + b_value = getattr(b, 'values', b) + result = ne.evaluate('where(cond_value, a_value, b_value)', + local_dict={'cond_value': cond_value, + 'a_value': a_value, + 'b_value': b_value}, + casting='safe') + except ValueError as detail: + if 'unknown type object' in str(detail): + pass + except Exception as detail: + raise TypeError(str(detail)) + + if result is None: + result = _where_standard(cond, a, b) + + return result + + +# turn myself on +set_use_numexpr(get_option('compute.use_numexpr')) + + +def _has_bool_dtype(x): + try: + if isinstance(x, ABCDataFrame): + return 'bool' in x.dtypes + else: + return x.dtype == bool + except AttributeError: + return isinstance(x, (bool, np.bool_)) + + +def _bool_arith_check(op_str, a, b, not_allowed=frozenset(('/', '//', '**')), + unsupported=None): + if unsupported is None: + unsupported = {'+': '|', '*': '&', '-': '^'} + + if _has_bool_dtype(a) and _has_bool_dtype(b): + if op_str in unsupported: + warnings.warn("evaluating in Python space because the {op!r} " + "operator is not supported by numexpr for " + "the bool dtype, use {alt_op!r} instead" + .format(op=op_str, alt_op=unsupported[op_str])) + return False + + if op_str in not_allowed: + raise NotImplementedError("operator {op!r} not implemented for " + "bool dtypes".format(op=op_str)) + return True + + +def evaluate(op, op_str, a, b, use_numexpr=True, + **eval_kwargs): + """ evaluate and return the expression of the op on a and b + + Parameters + ---------- + + op : the actual operand + op_str: the string version of the op + a : left operand + b : right operand + use_numexpr : whether to try to use numexpr (default True) + """ + + use_numexpr = use_numexpr and _bool_arith_check(op_str, a, b) + if use_numexpr: + return _evaluate(op, op_str, a, b, **eval_kwargs) + return _evaluate_standard(op, op_str, a, b) + + +def where(cond, a, b, use_numexpr=True): + """ evaluate the where condition cond on a and b + + Parameters + ---------- + + cond : a boolean array + a : return if cond is True + b : return if cond is False + use_numexpr : whether to try to use numexpr (default True) + """ + + if use_numexpr: + return _where(cond, a, b) + return _where_standard(cond, a, b) + + +def set_test_mode(v=True): + """ + Keeps track of whether numexpr was used. Stores an additional ``True`` + for every successful use of evaluate with numexpr since the last + ``get_test_result`` + """ + global _TEST_MODE, _TEST_RESULT + _TEST_MODE = v + _TEST_RESULT = [] + + +def _store_test_result(used_numexpr): + global _TEST_RESULT + if used_numexpr: + _TEST_RESULT.append(used_numexpr) + + +def get_test_result(): + """get test result and reset test_results""" + global _TEST_RESULT + res = _TEST_RESULT + _TEST_RESULT = [] + return res diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/ops.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..8c3218a976b6b69bc3e7bec43b4fe0a6e57c7ae2 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/ops.py @@ -0,0 +1,561 @@ +"""Operator classes for eval. +""" + +from datetime import datetime +from distutils.version import LooseVersion +from functools import partial +import operator as op + +import numpy as np + +from pandas.compat import PY3, string_types, text_type + +from pandas.core.dtypes.common import is_list_like, is_scalar + +import pandas as pd +from pandas.core.base import StringMixin +import pandas.core.common as com +from pandas.core.computation.common import _ensure_decoded, _result_type_many +from pandas.core.computation.scope import _DEFAULT_GLOBALS + +from pandas.io.formats.printing import pprint_thing, pprint_thing_encoded + +_reductions = 'sum', 'prod' + +_unary_math_ops = ('sin', 'cos', 'exp', 'log', 'expm1', 'log1p', + 'sqrt', 'sinh', 'cosh', 'tanh', 'arcsin', 'arccos', + 'arctan', 'arccosh', 'arcsinh', 'arctanh', 'abs', 'log10', + 'floor', 'ceil' + ) +_binary_math_ops = ('arctan2',) + +_mathops = _unary_math_ops + _binary_math_ops + + +_LOCAL_TAG = '__pd_eval_local_' + + +class UndefinedVariableError(NameError): + + """NameError subclass for local variables.""" + + def __init__(self, name, is_local): + if is_local: + msg = 'local variable {0!r} is not defined' + else: + msg = 'name {0!r} is not defined' + super(UndefinedVariableError, self).__init__(msg.format(name)) + + +class Term(StringMixin): + + def __new__(cls, name, env, side=None, encoding=None): + klass = Constant if not isinstance(name, string_types) else cls + supr_new = super(Term, klass).__new__ + return supr_new(klass) + + def __init__(self, name, env, side=None, encoding=None): + self._name = name + self.env = env + self.side = side + tname = text_type(name) + self.is_local = (tname.startswith(_LOCAL_TAG) or + tname in _DEFAULT_GLOBALS) + self._value = self._resolve_name() + self.encoding = encoding + + @property + def local_name(self): + return self.name.replace(_LOCAL_TAG, '') + + def __unicode__(self): + return pprint_thing(self.name) + + def __call__(self, *args, **kwargs): + return self.value + + def evaluate(self, *args, **kwargs): + return self + + def _resolve_name(self): + res = self.env.resolve(self.local_name, is_local=self.is_local) + self.update(res) + + if hasattr(res, 'ndim') and res.ndim > 2: + raise NotImplementedError("N-dimensional objects, where N > 2," + " are not supported with eval") + return res + + def update(self, value): + """ + search order for local (i.e., @variable) variables: + + scope, key_variable + [('locals', 'local_name'), + ('globals', 'local_name'), + ('locals', 'key'), + ('globals', 'key')] + """ + key = self.name + + # if it's a variable name (otherwise a constant) + if isinstance(key, string_types): + self.env.swapkey(self.local_name, key, new_value=value) + + self.value = value + + @property + def is_scalar(self): + return is_scalar(self._value) + + @property + def type(self): + try: + # potentially very slow for large, mixed dtype frames + return self._value.values.dtype + except AttributeError: + try: + # ndarray + return self._value.dtype + except AttributeError: + # scalar + return type(self._value) + + return_type = type + + @property + def raw(self): + return pprint_thing('{0}(name={1!r}, type={2})' + ''.format(self.__class__.__name__, self.name, + self.type)) + + @property + def is_datetime(self): + try: + t = self.type.type + except AttributeError: + t = self.type + + return issubclass(t, (datetime, np.datetime64)) + + @property + def value(self): + return self._value + + @value.setter + def value(self, new_value): + self._value = new_value + + @property + def name(self): + return self._name + + @name.setter + def name(self, new_name): + self._name = new_name + + @property + def ndim(self): + return self._value.ndim + + +class Constant(Term): + + def __init__(self, value, env, side=None, encoding=None): + super(Constant, self).__init__(value, env, side=side, + encoding=encoding) + + def _resolve_name(self): + return self._name + + @property + def name(self): + return self.value + + def __unicode__(self): + # in python 2 str() of float + # can truncate shorter than repr() + return repr(self.name) + + +_bool_op_map = {'not': '~', 'and': '&', 'or': '|'} + + +class Op(StringMixin): + + """Hold an operator of arbitrary arity + """ + + def __init__(self, op, operands, *args, **kwargs): + self.op = _bool_op_map.get(op, op) + self.operands = operands + self.encoding = kwargs.get('encoding', None) + + def __iter__(self): + return iter(self.operands) + + def __unicode__(self): + """Print a generic n-ary operator and its operands using infix + notation""" + # recurse over the operands + parened = ('({0})'.format(pprint_thing(opr)) + for opr in self.operands) + return pprint_thing(' {0} '.format(self.op).join(parened)) + + @property + def return_type(self): + # clobber types to bool if the op is a boolean operator + if self.op in (_cmp_ops_syms + _bool_ops_syms): + return np.bool_ + return _result_type_many(*(term.type for term in com.flatten(self))) + + @property + def has_invalid_return_type(self): + types = self.operand_types + obj_dtype_set = frozenset([np.dtype('object')]) + return self.return_type == object and types - obj_dtype_set + + @property + def operand_types(self): + return frozenset(term.type for term in com.flatten(self)) + + @property + def is_scalar(self): + return all(operand.is_scalar for operand in self.operands) + + @property + def is_datetime(self): + try: + t = self.return_type.type + except AttributeError: + t = self.return_type + + return issubclass(t, (datetime, np.datetime64)) + + +def _in(x, y): + """Compute the vectorized membership of ``x in y`` if possible, otherwise + use Python. + """ + try: + return x.isin(y) + except AttributeError: + if is_list_like(x): + try: + return y.isin(x) + except AttributeError: + pass + return x in y + + +def _not_in(x, y): + """Compute the vectorized membership of ``x not in y`` if possible, + otherwise use Python. + """ + try: + return ~x.isin(y) + except AttributeError: + if is_list_like(x): + try: + return ~y.isin(x) + except AttributeError: + pass + return x not in y + + +_cmp_ops_syms = '>', '<', '>=', '<=', '==', '!=', 'in', 'not in' +_cmp_ops_funcs = op.gt, op.lt, op.ge, op.le, op.eq, op.ne, _in, _not_in +_cmp_ops_dict = dict(zip(_cmp_ops_syms, _cmp_ops_funcs)) + +_bool_ops_syms = '&', '|', 'and', 'or' +_bool_ops_funcs = op.and_, op.or_, op.and_, op.or_ +_bool_ops_dict = dict(zip(_bool_ops_syms, _bool_ops_funcs)) + +_arith_ops_syms = '+', '-', '*', '/', '**', '//', '%' +_arith_ops_funcs = (op.add, op.sub, op.mul, op.truediv if PY3 else op.div, + op.pow, op.floordiv, op.mod) +_arith_ops_dict = dict(zip(_arith_ops_syms, _arith_ops_funcs)) + +_special_case_arith_ops_syms = '**', '//', '%' +_special_case_arith_ops_funcs = op.pow, op.floordiv, op.mod +_special_case_arith_ops_dict = dict(zip(_special_case_arith_ops_syms, + _special_case_arith_ops_funcs)) + +_binary_ops_dict = {} + +for d in (_cmp_ops_dict, _bool_ops_dict, _arith_ops_dict): + _binary_ops_dict.update(d) + + +def _cast_inplace(terms, acceptable_dtypes, dtype): + """Cast an expression inplace. + + Parameters + ---------- + terms : Op + The expression that should cast. + acceptable_dtypes : list of acceptable numpy.dtype + Will not cast if term's dtype in this list. + + .. versionadded:: 0.19.0 + + dtype : str or numpy.dtype + The dtype to cast to. + """ + dt = np.dtype(dtype) + for term in terms: + if term.type in acceptable_dtypes: + continue + + try: + new_value = term.value.astype(dt) + except AttributeError: + new_value = dt.type(term.value) + term.update(new_value) + + +def is_term(obj): + return isinstance(obj, Term) + + +class BinOp(Op): + + """Hold a binary operator and its operands + + Parameters + ---------- + op : str + left : Term or Op + right : Term or Op + """ + + def __init__(self, op, lhs, rhs, **kwargs): + super(BinOp, self).__init__(op, (lhs, rhs)) + self.lhs = lhs + self.rhs = rhs + + self._disallow_scalar_only_bool_ops() + + self.convert_values() + + try: + self.func = _binary_ops_dict[op] + except KeyError: + # has to be made a list for python3 + keys = list(_binary_ops_dict.keys()) + raise ValueError('Invalid binary operator {0!r}, valid' + ' operators are {1}'.format(op, keys)) + + def __call__(self, env): + """Recursively evaluate an expression in Python space. + + Parameters + ---------- + env : Scope + + Returns + ------- + object + The result of an evaluated expression. + """ + # handle truediv + if self.op == '/' and env.scope['truediv']: + self.func = op.truediv + + # recurse over the left/right nodes + left = self.lhs(env) + right = self.rhs(env) + + return self.func(left, right) + + def evaluate(self, env, engine, parser, term_type, eval_in_python): + """Evaluate a binary operation *before* being passed to the engine. + + Parameters + ---------- + env : Scope + engine : str + parser : str + term_type : type + eval_in_python : list + + Returns + ------- + term_type + The "pre-evaluated" expression as an instance of ``term_type`` + """ + if engine == 'python': + res = self(env) + else: + # recurse over the left/right nodes + left = self.lhs.evaluate(env, engine=engine, parser=parser, + term_type=term_type, + eval_in_python=eval_in_python) + right = self.rhs.evaluate(env, engine=engine, parser=parser, + term_type=term_type, + eval_in_python=eval_in_python) + + # base cases + if self.op in eval_in_python: + res = self.func(left.value, right.value) + else: + res = pd.eval(self, local_dict=env, engine=engine, + parser=parser) + + name = env.add_tmp(res) + return term_type(name, env=env) + + def convert_values(self): + """Convert datetimes to a comparable value in an expression. + """ + def stringify(value): + if self.encoding is not None: + encoder = partial(pprint_thing_encoded, + encoding=self.encoding) + else: + encoder = pprint_thing + return encoder(value) + + lhs, rhs = self.lhs, self.rhs + + if is_term(lhs) and lhs.is_datetime and is_term(rhs) and rhs.is_scalar: + v = rhs.value + if isinstance(v, (int, float)): + v = stringify(v) + v = pd.Timestamp(_ensure_decoded(v)) + if v.tz is not None: + v = v.tz_convert('UTC') + self.rhs.update(v) + + if is_term(rhs) and rhs.is_datetime and is_term(lhs) and lhs.is_scalar: + v = lhs.value + if isinstance(v, (int, float)): + v = stringify(v) + v = pd.Timestamp(_ensure_decoded(v)) + if v.tz is not None: + v = v.tz_convert('UTC') + self.lhs.update(v) + + def _disallow_scalar_only_bool_ops(self): + if ((self.lhs.is_scalar or self.rhs.is_scalar) and + self.op in _bool_ops_dict and + (not (issubclass(self.rhs.return_type, (bool, np.bool_)) and + issubclass(self.lhs.return_type, (bool, np.bool_))))): + raise NotImplementedError("cannot evaluate scalar only bool ops") + + +def isnumeric(dtype): + return issubclass(np.dtype(dtype).type, np.number) + + +class Div(BinOp): + + """Div operator to special case casting. + + Parameters + ---------- + lhs, rhs : Term or Op + The Terms or Ops in the ``/`` expression. + truediv : bool + Whether or not to use true division. With Python 3 this happens + regardless of the value of ``truediv``. + """ + + def __init__(self, lhs, rhs, truediv, *args, **kwargs): + super(Div, self).__init__('/', lhs, rhs, *args, **kwargs) + + if not isnumeric(lhs.return_type) or not isnumeric(rhs.return_type): + raise TypeError("unsupported operand type(s) for {0}:" + " '{1}' and '{2}'".format(self.op, + lhs.return_type, + rhs.return_type)) + + if truediv or PY3: + # do not upcast float32s to float64 un-necessarily + acceptable_dtypes = [np.float32, np.float_] + _cast_inplace(com.flatten(self), acceptable_dtypes, np.float_) + + +_unary_ops_syms = '+', '-', '~', 'not' +_unary_ops_funcs = op.pos, op.neg, op.invert, op.invert +_unary_ops_dict = dict(zip(_unary_ops_syms, _unary_ops_funcs)) + + +class UnaryOp(Op): + + """Hold a unary operator and its operands + + Parameters + ---------- + op : str + The token used to represent the operator. + operand : Term or Op + The Term or Op operand to the operator. + + Raises + ------ + ValueError + * If no function associated with the passed operator token is found. + """ + + def __init__(self, op, operand): + super(UnaryOp, self).__init__(op, (operand,)) + self.operand = operand + + try: + self.func = _unary_ops_dict[op] + except KeyError: + raise ValueError('Invalid unary operator {0!r}, valid operators ' + 'are {1}'.format(op, _unary_ops_syms)) + + def __call__(self, env): + operand = self.operand(env) + return self.func(operand) + + def __unicode__(self): + return pprint_thing('{0}({1})'.format(self.op, self.operand)) + + @property + def return_type(self): + operand = self.operand + if operand.return_type == np.dtype('bool'): + return np.dtype('bool') + if (isinstance(operand, Op) and + (operand.op in _cmp_ops_dict or operand.op in _bool_ops_dict)): + return np.dtype('bool') + return np.dtype('int') + + +class MathCall(Op): + + def __init__(self, func, args): + super(MathCall, self).__init__(func.name, args) + self.func = func + + def __call__(self, env): + operands = [op(env) for op in self.operands] + with np.errstate(all='ignore'): + return self.func.func(*operands) + + def __unicode__(self): + operands = map(str, self.operands) + return pprint_thing('{0}({1})'.format(self.op, ','.join(operands))) + + +class FuncNode(object): + def __init__(self, name): + from pandas.core.computation.check import (_NUMEXPR_INSTALLED, + _NUMEXPR_VERSION) + if name not in _mathops or ( + _NUMEXPR_INSTALLED and + _NUMEXPR_VERSION < LooseVersion('2.6.9') and + name in ('floor', 'ceil') + ): + raise ValueError( + "\"{0}\" is not a supported function".format(name)) + + self.name = name + self.func = getattr(np, name) + + def __call__(self, *args): + return MathCall(self, args) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/pytables.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/pytables.py new file mode 100644 index 0000000000000000000000000000000000000000..00de29b07c75d5a136b9f2f1260801d298122cca --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/pytables.py @@ -0,0 +1,604 @@ +""" manage PyTables query interface via Expressions """ + +import ast +from functools import partial + +import numpy as np + +from pandas.compat import DeepChainMap, string_types, u + +from pandas.core.dtypes.common import is_list_like + +import pandas as pd +from pandas.core.base import StringMixin +import pandas.core.common as com +from pandas.core.computation import expr, ops +from pandas.core.computation.common import _ensure_decoded +from pandas.core.computation.expr import BaseExprVisitor +from pandas.core.computation.ops import UndefinedVariableError, is_term + +from pandas.io.formats.printing import pprint_thing, pprint_thing_encoded + + +class Scope(expr.Scope): + __slots__ = 'queryables', + + def __init__(self, level, global_dict=None, local_dict=None, + queryables=None): + super(Scope, self).__init__(level + 1, global_dict=global_dict, + local_dict=local_dict) + self.queryables = queryables or dict() + + +class Term(ops.Term): + + def __new__(cls, name, env, side=None, encoding=None): + klass = Constant if not isinstance(name, string_types) else cls + supr_new = StringMixin.__new__ + return supr_new(klass) + + def __init__(self, name, env, side=None, encoding=None): + super(Term, self).__init__(name, env, side=side, encoding=encoding) + + def _resolve_name(self): + # must be a queryables + if self.side == 'left': + if self.name not in self.env.queryables: + raise NameError('name {name!r} is not defined' + .format(name=self.name)) + return self.name + + # resolve the rhs (and allow it to be None) + try: + return self.env.resolve(self.name, is_local=False) + except UndefinedVariableError: + return self.name + + @property + def value(self): + return self._value + + +class Constant(Term): + + def __init__(self, value, env, side=None, encoding=None): + super(Constant, self).__init__(value, env, side=side, + encoding=encoding) + + def _resolve_name(self): + return self._name + + +class BinOp(ops.BinOp): + + _max_selectors = 31 + + def __init__(self, op, lhs, rhs, queryables, encoding): + super(BinOp, self).__init__(op, lhs, rhs) + self.queryables = queryables + self.encoding = encoding + self.filter = None + self.condition = None + + def _disallow_scalar_only_bool_ops(self): + pass + + def prune(self, klass): + + def pr(left, right): + """ create and return a new specialized BinOp from myself """ + + if left is None: + return right + elif right is None: + return left + + k = klass + if isinstance(left, ConditionBinOp): + if (isinstance(left, ConditionBinOp) and + isinstance(right, ConditionBinOp)): + k = JointConditionBinOp + elif isinstance(left, k): + return left + elif isinstance(right, k): + return right + + elif isinstance(left, FilterBinOp): + if (isinstance(left, FilterBinOp) and + isinstance(right, FilterBinOp)): + k = JointFilterBinOp + elif isinstance(left, k): + return left + elif isinstance(right, k): + return right + + return k(self.op, left, right, queryables=self.queryables, + encoding=self.encoding).evaluate() + + left, right = self.lhs, self.rhs + + if is_term(left) and is_term(right): + res = pr(left.value, right.value) + elif not is_term(left) and is_term(right): + res = pr(left.prune(klass), right.value) + elif is_term(left) and not is_term(right): + res = pr(left.value, right.prune(klass)) + elif not (is_term(left) or is_term(right)): + res = pr(left.prune(klass), right.prune(klass)) + + return res + + def conform(self, rhs): + """ inplace conform rhs """ + if not is_list_like(rhs): + rhs = [rhs] + if isinstance(rhs, np.ndarray): + rhs = rhs.ravel() + return rhs + + @property + def is_valid(self): + """ return True if this is a valid field """ + return self.lhs in self.queryables + + @property + def is_in_table(self): + """ return True if this is a valid column name for generation (e.g. an + actual column in the table) """ + return self.queryables.get(self.lhs) is not None + + @property + def kind(self): + """ the kind of my field """ + return getattr(self.queryables.get(self.lhs), 'kind', None) + + @property + def meta(self): + """ the meta of my field """ + return getattr(self.queryables.get(self.lhs), 'meta', None) + + @property + def metadata(self): + """ the metadata of my field """ + return getattr(self.queryables.get(self.lhs), 'metadata', None) + + def generate(self, v): + """ create and return the op string for this TermValue """ + val = v.tostring(self.encoding) + return "({lhs} {op} {val})".format(lhs=self.lhs, op=self.op, val=val) + + def convert_value(self, v): + """ convert the expression that is in the term to something that is + accepted by pytables """ + + def stringify(value): + if self.encoding is not None: + encoder = partial(pprint_thing_encoded, + encoding=self.encoding) + else: + encoder = pprint_thing + return encoder(value) + + kind = _ensure_decoded(self.kind) + meta = _ensure_decoded(self.meta) + if kind == u('datetime64') or kind == u('datetime'): + if isinstance(v, (int, float)): + v = stringify(v) + v = _ensure_decoded(v) + v = pd.Timestamp(v) + if v.tz is not None: + v = v.tz_convert('UTC') + return TermValue(v, v.value, kind) + elif kind == u('timedelta64') or kind == u('timedelta'): + v = pd.Timedelta(v, unit='s').value + return TermValue(int(v), v, kind) + elif meta == u('category'): + metadata = com.values_from_object(self.metadata) + result = metadata.searchsorted(v, side='left') + + # result returns 0 if v is first element or if v is not in metadata + # check that metadata contains v + if not result and v not in metadata: + result = -1 + return TermValue(result, result, u('integer')) + elif kind == u('integer'): + v = int(float(v)) + return TermValue(v, v, kind) + elif kind == u('float'): + v = float(v) + return TermValue(v, v, kind) + elif kind == u('bool'): + if isinstance(v, string_types): + v = not v.strip().lower() in [u('false'), u('f'), u('no'), + u('n'), u('none'), u('0'), + u('[]'), u('{}'), u('')] + else: + v = bool(v) + return TermValue(v, v, kind) + elif isinstance(v, string_types): + # string quoting + return TermValue(v, stringify(v), u('string')) + else: + raise TypeError("Cannot compare {v} of type {typ} to {kind} column" + .format(v=v, typ=type(v), kind=kind)) + + def convert_values(self): + pass + + +class FilterBinOp(BinOp): + + def __unicode__(self): + return pprint_thing("[Filter : [{lhs}] -> [{op}]" + .format(lhs=self.filter[0], op=self.filter[1])) + + def invert(self): + """ invert the filter """ + if self.filter is not None: + f = list(self.filter) + f[1] = self.generate_filter_op(invert=True) + self.filter = tuple(f) + return self + + def format(self): + """ return the actual filter format """ + return [self.filter] + + def evaluate(self): + + if not self.is_valid: + raise ValueError("query term is not valid [{slf}]" + .format(slf=self)) + + rhs = self.conform(self.rhs) + values = [TermValue(v, v, self.kind) for v in rhs] + + if self.is_in_table: + + # if too many values to create the expression, use a filter instead + if self.op in ['==', '!='] and len(values) > self._max_selectors: + + filter_op = self.generate_filter_op() + self.filter = ( + self.lhs, + filter_op, + pd.Index([v.value for v in values])) + + return self + return None + + # equality conditions + if self.op in ['==', '!=']: + + filter_op = self.generate_filter_op() + self.filter = ( + self.lhs, + filter_op, + pd.Index([v.value for v in values])) + + else: + raise TypeError("passing a filterable condition to a non-table " + "indexer [{slf}]".format(slf=self)) + + return self + + def generate_filter_op(self, invert=False): + if (self.op == '!=' and not invert) or (self.op == '==' and invert): + return lambda axis, vals: ~axis.isin(vals) + else: + return lambda axis, vals: axis.isin(vals) + + +class JointFilterBinOp(FilterBinOp): + + def format(self): + raise NotImplementedError("unable to collapse Joint Filters") + + def evaluate(self): + return self + + +class ConditionBinOp(BinOp): + + def __unicode__(self): + return pprint_thing("[Condition : [{cond}]]" + .format(cond=self.condition)) + + def invert(self): + """ invert the condition """ + # if self.condition is not None: + # self.condition = "~(%s)" % self.condition + # return self + raise NotImplementedError("cannot use an invert condition when " + "passing to numexpr") + + def format(self): + """ return the actual ne format """ + return self.condition + + def evaluate(self): + + if not self.is_valid: + raise ValueError("query term is not valid [{slf}]" + .format(slf=self)) + + # convert values if we are in the table + if not self.is_in_table: + return None + + rhs = self.conform(self.rhs) + values = [self.convert_value(v) for v in rhs] + + # equality conditions + if self.op in ['==', '!=']: + + # too many values to create the expression? + if len(values) <= self._max_selectors: + vs = [self.generate(v) for v in values] + self.condition = "({cond})".format(cond=' | '.join(vs)) + + # use a filter after reading + else: + return None + else: + self.condition = self.generate(values[0]) + + return self + + +class JointConditionBinOp(ConditionBinOp): + + def evaluate(self): + self.condition = "({lhs} {op} {rhs})".format(lhs=self.lhs.condition, + op=self.op, + rhs=self.rhs.condition) + return self + + +class UnaryOp(ops.UnaryOp): + + def prune(self, klass): + + if self.op != '~': + raise NotImplementedError("UnaryOp only support invert type ops") + + operand = self.operand + operand = operand.prune(klass) + + if operand is not None: + if issubclass(klass, ConditionBinOp): + if operand.condition is not None: + return operand.invert() + elif issubclass(klass, FilterBinOp): + if operand.filter is not None: + return operand.invert() + + return None + + +_op_classes = {'unary': UnaryOp} + + +class ExprVisitor(BaseExprVisitor): + const_type = Constant + term_type = Term + + def __init__(self, env, engine, parser, **kwargs): + super(ExprVisitor, self).__init__(env, engine, parser) + for bin_op in self.binary_ops: + bin_node = self.binary_op_nodes_map[bin_op] + setattr(self, 'visit_{node}'.format(node=bin_node), + lambda node, bin_op=bin_op: partial(BinOp, bin_op, + **kwargs)) + + def visit_UnaryOp(self, node, **kwargs): + if isinstance(node.op, (ast.Not, ast.Invert)): + return UnaryOp('~', self.visit(node.operand)) + elif isinstance(node.op, ast.USub): + return self.const_type(-self.visit(node.operand).value, self.env) + elif isinstance(node.op, ast.UAdd): + raise NotImplementedError('Unary addition not supported') + + def visit_Index(self, node, **kwargs): + return self.visit(node.value).value + + def visit_Assign(self, node, **kwargs): + cmpr = ast.Compare(ops=[ast.Eq()], left=node.targets[0], + comparators=[node.value]) + return self.visit(cmpr) + + def visit_Subscript(self, node, **kwargs): + # only allow simple suscripts + + value = self.visit(node.value) + slobj = self.visit(node.slice) + try: + value = value.value + except AttributeError: + pass + + try: + return self.const_type(value[slobj], self.env) + except TypeError: + raise ValueError("cannot subscript {value!r} with " + "{slobj!r}".format(value=value, slobj=slobj)) + + def visit_Attribute(self, node, **kwargs): + attr = node.attr + value = node.value + + ctx = node.ctx.__class__ + if ctx == ast.Load: + # resolve the value + resolved = self.visit(value) + + # try to get the value to see if we are another expression + try: + resolved = resolved.value + except (AttributeError): + pass + + try: + return self.term_type(getattr(resolved, attr), self.env) + except AttributeError: + + # something like datetime.datetime where scope is overridden + if isinstance(value, ast.Name) and value.id == attr: + return resolved + + raise ValueError("Invalid Attribute context {name}" + .format(name=ctx.__name__)) + + def translate_In(self, op): + return ast.Eq() if isinstance(op, ast.In) else op + + def _rewrite_membership_op(self, node, left, right): + return self.visit(node.op), node.op, left, right + + +def _validate_where(w): + """ + Validate that the where statement is of the right type. + + The type may either be String, Expr, or list-like of Exprs. + + Parameters + ---------- + w : String term expression, Expr, or list-like of Exprs. + + Returns + ------- + where : The original where clause if the check was successful. + + Raises + ------ + TypeError : An invalid data type was passed in for w (e.g. dict). + """ + + if not (isinstance(w, (Expr, string_types)) or is_list_like(w)): + raise TypeError("where must be passed as a string, Expr, " + "or list-like of Exprs") + + return w + + +class Expr(expr.Expr): + + """ hold a pytables like expression, comprised of possibly multiple 'terms' + + Parameters + ---------- + where : string term expression, Expr, or list-like of Exprs + queryables : a "kinds" map (dict of column name -> kind), or None if column + is non-indexable + encoding : an encoding that will encode the query terms + + Returns + ------- + an Expr object + + Examples + -------- + + 'index>=date' + "columns=['A', 'D']" + 'columns=A' + 'columns==A' + "~(columns=['A','B'])" + 'index>df.index[3] & string="bar"' + '(index>df.index[3] & index<=df.index[6]) | string="bar"' + "ts>=Timestamp('2012-02-01')" + "major_axis>=20130101" + """ + + def __init__(self, where, queryables=None, encoding=None, scope_level=0): + + where = _validate_where(where) + + self.encoding = encoding + self.condition = None + self.filter = None + self.terms = None + self._visitor = None + + # capture the environment if needed + local_dict = DeepChainMap() + + if isinstance(where, Expr): + local_dict = where.env.scope + where = where.expr + + elif isinstance(where, (list, tuple)): + for idx, w in enumerate(where): + if isinstance(w, Expr): + local_dict = w.env.scope + else: + w = _validate_where(w) + where[idx] = w + where = ' & '.join(map('({})'.format, com.flatten(where))) # noqa + + self.expr = where + self.env = Scope(scope_level + 1, local_dict=local_dict) + + if queryables is not None and isinstance(self.expr, string_types): + self.env.queryables.update(queryables) + self._visitor = ExprVisitor(self.env, queryables=queryables, + parser='pytables', engine='pytables', + encoding=encoding) + self.terms = self.parse() + + def __unicode__(self): + if self.terms is not None: + return pprint_thing(self.terms) + return pprint_thing(self.expr) + + def evaluate(self): + """ create and return the numexpr condition and filter """ + + try: + self.condition = self.terms.prune(ConditionBinOp) + except AttributeError: + raise ValueError("cannot process expression [{expr}], [{slf}] " + "is not a valid condition".format(expr=self.expr, + slf=self)) + try: + self.filter = self.terms.prune(FilterBinOp) + except AttributeError: + raise ValueError("cannot process expression [{expr}], [{slf}] " + "is not a valid filter".format(expr=self.expr, + slf=self)) + + return self.condition, self.filter + + +class TermValue(object): + + """ hold a term value the we use to construct a condition/filter """ + + def __init__(self, value, converted, kind): + self.value = value + self.converted = converted + self.kind = kind + + def tostring(self, encoding): + """ quote the string if not encoded + else encode and return """ + if self.kind == u'string': + if encoding is not None: + return self.converted + return '"{converted}"'.format(converted=self.converted) + elif self.kind == u'float': + # python 2 str(float) is not always + # round-trippable so use repr() + return repr(self.converted) + return self.converted + + +def maybe_expression(s): + """ loose checking if s is a pytables-acceptable expression """ + if not isinstance(s, string_types): + return False + ops = ExprVisitor.binary_ops + ExprVisitor.unary_ops + ('=',) + + # make sure we have an op at least + return any(op in s for op in ops) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/scope.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/scope.py new file mode 100644 index 0000000000000000000000000000000000000000..33c5a1c2e0f0ade8dfbbc8b3cf1feadf92c9022a --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/scope.py @@ -0,0 +1,302 @@ +""" +Module for scope operations +""" + +import datetime +import inspect +import itertools +import pprint +import struct +import sys + +import numpy as np + +from pandas.compat import DeepChainMap, StringIO, map + +import pandas as pd # noqa +from pandas.core.base import StringMixin +import pandas.core.computation as compu + + +def _ensure_scope(level, global_dict=None, local_dict=None, resolvers=(), + target=None, **kwargs): + """Ensure that we are grabbing the correct scope.""" + return Scope(level + 1, global_dict=global_dict, local_dict=local_dict, + resolvers=resolvers, target=target) + + +def _replacer(x): + """Replace a number with its hexadecimal representation. Used to tag + temporary variables with their calling scope's id. + """ + # get the hex repr of the binary char and remove 0x and pad by pad_size + # zeros + try: + hexin = ord(x) + except TypeError: + # bytes literals masquerade as ints when iterating in py3 + hexin = x + + return hex(hexin) + + +def _raw_hex_id(obj): + """Return the padded hexadecimal id of ``obj``.""" + # interpret as a pointer since that's what really what id returns + packed = struct.pack('@P', id(obj)) + return ''.join(map(_replacer, packed)) + + +_DEFAULT_GLOBALS = { + 'Timestamp': pd._libs.tslib.Timestamp, + 'datetime': datetime.datetime, + 'True': True, + 'False': False, + 'list': list, + 'tuple': tuple, + 'inf': np.inf, + 'Inf': np.inf, +} + + +def _get_pretty_string(obj): + """Return a prettier version of obj + + Parameters + ---------- + obj : object + Object to pretty print + + Returns + ------- + s : str + Pretty print object repr + """ + sio = StringIO() + pprint.pprint(obj, stream=sio) + return sio.getvalue() + + +class Scope(StringMixin): + + """Object to hold scope, with a few bells to deal with some custom syntax + and contexts added by pandas. + + Parameters + ---------- + level : int + global_dict : dict or None, optional, default None + local_dict : dict or Scope or None, optional, default None + resolvers : list-like or None, optional, default None + target : object + + Attributes + ---------- + level : int + scope : DeepChainMap + target : object + temps : dict + """ + __slots__ = 'level', 'scope', 'target', 'temps' + + def __init__(self, level, global_dict=None, local_dict=None, resolvers=(), + target=None): + self.level = level + 1 + + # shallow copy because we don't want to keep filling this up with what + # was there before if there are multiple calls to Scope/_ensure_scope + self.scope = DeepChainMap(_DEFAULT_GLOBALS.copy()) + self.target = target + + if isinstance(local_dict, Scope): + self.scope.update(local_dict.scope) + if local_dict.target is not None: + self.target = local_dict.target + self.update(local_dict.level) + + frame = sys._getframe(self.level) + + try: + # shallow copy here because we don't want to replace what's in + # scope when we align terms (alignment accesses the underlying + # numpy array of pandas objects) + self.scope = self.scope.new_child((global_dict or + frame.f_globals).copy()) + if not isinstance(local_dict, Scope): + self.scope = self.scope.new_child((local_dict or + frame.f_locals).copy()) + finally: + del frame + + # assumes that resolvers are going from outermost scope to inner + if isinstance(local_dict, Scope): + resolvers += tuple(local_dict.resolvers.maps) + self.resolvers = DeepChainMap(*resolvers) + self.temps = {} + + def __unicode__(self): + scope_keys = _get_pretty_string(list(self.scope.keys())) + res_keys = _get_pretty_string(list(self.resolvers.keys())) + unicode_str = '{name}(scope={scope_keys}, resolvers={res_keys})' + return unicode_str.format(name=type(self).__name__, + scope_keys=scope_keys, + res_keys=res_keys) + + @property + def has_resolvers(self): + """Return whether we have any extra scope. + + For example, DataFrames pass Their columns as resolvers during calls to + ``DataFrame.eval()`` and ``DataFrame.query()``. + + Returns + ------- + hr : bool + """ + return bool(len(self.resolvers)) + + def resolve(self, key, is_local): + """Resolve a variable name in a possibly local context + + Parameters + ---------- + key : text_type + A variable name + is_local : bool + Flag indicating whether the variable is local or not (prefixed with + the '@' symbol) + + Returns + ------- + value : object + The value of a particular variable + """ + try: + # only look for locals in outer scope + if is_local: + return self.scope[key] + + # not a local variable so check in resolvers if we have them + if self.has_resolvers: + return self.resolvers[key] + + # if we're here that means that we have no locals and we also have + # no resolvers + assert not is_local and not self.has_resolvers + return self.scope[key] + except KeyError: + try: + # last ditch effort we look in temporaries + # these are created when parsing indexing expressions + # e.g., df[df > 0] + return self.temps[key] + except KeyError: + raise compu.ops.UndefinedVariableError(key, is_local) + + def swapkey(self, old_key, new_key, new_value=None): + """Replace a variable name, with a potentially new value. + + Parameters + ---------- + old_key : str + Current variable name to replace + new_key : str + New variable name to replace `old_key` with + new_value : object + Value to be replaced along with the possible renaming + """ + if self.has_resolvers: + maps = self.resolvers.maps + self.scope.maps + else: + maps = self.scope.maps + + maps.append(self.temps) + + for mapping in maps: + if old_key in mapping: + mapping[new_key] = new_value + return + + def _get_vars(self, stack, scopes): + """Get specifically scoped variables from a list of stack frames. + + Parameters + ---------- + stack : list + A list of stack frames as returned by ``inspect.stack()`` + scopes : sequence of strings + A sequence containing valid stack frame attribute names that + evaluate to a dictionary. For example, ('locals', 'globals') + """ + variables = itertools.product(scopes, stack) + for scope, (frame, _, _, _, _, _) in variables: + try: + d = getattr(frame, 'f_' + scope) + self.scope = self.scope.new_child(d) + finally: + # won't remove it, but DECREF it + # in Py3 this probably isn't necessary since frame won't be + # scope after the loop + del frame + + def update(self, level): + """Update the current scope by going back `level` levels. + + Parameters + ---------- + level : int or None, optional, default None + """ + sl = level + 1 + + # add sl frames to the scope starting with the + # most distant and overwriting with more current + # makes sure that we can capture variable scope + stack = inspect.stack() + + try: + self._get_vars(stack[:sl], scopes=['locals']) + finally: + del stack[:], stack + + def add_tmp(self, value): + """Add a temporary variable to the scope. + + Parameters + ---------- + value : object + An arbitrary object to be assigned to a temporary variable. + + Returns + ------- + name : basestring + The name of the temporary variable created. + """ + name = '{name}_{num}_{hex_id}'.format(name=type(value).__name__, + num=self.ntemps, + hex_id=_raw_hex_id(self)) + + # add to inner most scope + assert name not in self.temps + self.temps[name] = value + assert name in self.temps + + # only increment if the variable gets put in the scope + return name + + @property + def ntemps(self): + """The number of temporary variables in this scope""" + return len(self.temps) + + @property + def full_scope(self): + """Return the full scope for use with passing to engines transparently + as a mapping. + + Returns + ------- + vars : DeepChainMap + All variables in this scope. + """ + maps = [self.temps] + self.resolvers.maps + self.scope.maps + return DeepChainMap(*maps) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/api.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/api.py new file mode 100644 index 0000000000000000000000000000000000000000..e9d7b9c4281bdfb3befbc3d7e8247952b8cf2211 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/api.py @@ -0,0 +1,14 @@ +# flake8: noqa + +from .common import ( + is_array_like, is_bool, is_bool_dtype, is_categorical, + is_categorical_dtype, is_complex, is_complex_dtype, + is_datetime64_any_dtype, is_datetime64_dtype, is_datetime64_ns_dtype, + is_datetime64tz_dtype, is_datetimetz, is_dict_like, is_dtype_equal, + is_extension_array_dtype, is_extension_type, is_file_like, is_float, + is_float_dtype, is_hashable, is_int64_dtype, is_integer, is_integer_dtype, + is_interval, is_interval_dtype, is_iterator, is_list_like, is_named_tuple, + is_number, is_numeric_dtype, is_object_dtype, is_period, is_period_dtype, + is_re, is_re_compilable, is_scalar, is_signed_integer_dtype, is_sparse, + is_string_dtype, is_timedelta64_dtype, is_timedelta64_ns_dtype, + is_unsigned_integer_dtype, pandas_dtype) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/base.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ab1cb9cf2499affeb0c85ac419b86b360b300fc6 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/base.py @@ -0,0 +1,294 @@ +"""Extend pandas with custom array types""" +import numpy as np + +from pandas.errors import AbstractMethodError + +from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries + +from pandas import compat + + +class _DtypeOpsMixin(object): + # Not all of pandas' extension dtypes are compatibile with + # the new ExtensionArray interface. This means PandasExtensionDtype + # can't subclass ExtensionDtype yet, as is_extension_array_dtype would + # incorrectly say that these types are extension types. + # + # In the interim, we put methods that are shared between the two base + # classes ExtensionDtype and PandasExtensionDtype here. Both those base + # classes will inherit from this Mixin. Once everything is compatible, this + # class's methods can be moved to ExtensionDtype and removed. + + # na_value is the default NA value to use for this type. This is used in + # e.g. ExtensionArray.take. This should be the user-facing "boxed" version + # of the NA value, not the physical NA vaalue for storage. + # e.g. for JSONArray, this is an empty dictionary. + na_value = np.nan + _metadata = () + + def __eq__(self, other): + """Check whether 'other' is equal to self. + + By default, 'other' is considered equal if either + + * it's a string matching 'self.name'. + * it's an instance of this type and all of the + the attributes in ``self._metadata`` are equal between + `self` and `other`. + + Parameters + ---------- + other : Any + + Returns + ------- + bool + """ + if isinstance(other, compat.string_types): + try: + other = self.construct_from_string(other) + except TypeError: + return False + if isinstance(other, type(self)): + return all( + getattr(self, attr) == getattr(other, attr) + for attr in self._metadata + ) + return False + + def __hash__(self): + return hash(tuple(getattr(self, attr) for attr in self._metadata)) + + def __ne__(self, other): + return not self.__eq__(other) + + @property + def names(self): + # type: () -> Optional[List[str]] + """Ordered list of field names, or None if there are no fields. + + This is for compatibility with NumPy arrays, and may be removed in the + future. + """ + return None + + @classmethod + def is_dtype(cls, dtype): + """Check if we match 'dtype'. + + Parameters + ---------- + dtype : object + The object to check. + + Returns + ------- + is_dtype : bool + + Notes + ----- + The default implementation is True if + + 1. ``cls.construct_from_string(dtype)`` is an instance + of ``cls``. + 2. ``dtype`` is an object and is an instance of ``cls`` + 3. ``dtype`` has a ``dtype`` attribute, and any of the above + conditions is true for ``dtype.dtype``. + """ + dtype = getattr(dtype, 'dtype', dtype) + + if isinstance(dtype, (ABCSeries, ABCIndexClass, + ABCDataFrame, np.dtype)): + # https://github.com/pandas-dev/pandas/issues/22960 + # avoid passing data to `construct_from_string`. This could + # cause a FutureWarning from numpy about failing elementwise + # comparison from, e.g., comparing DataFrame == 'category'. + return False + elif dtype is None: + return False + elif isinstance(dtype, cls): + return True + try: + return cls.construct_from_string(dtype) is not None + except TypeError: + return False + + @property + def _is_numeric(self): + # type: () -> bool + """ + Whether columns with this dtype should be considered numeric. + + By default ExtensionDtypes are assumed to be non-numeric. + They'll be excluded from operations that exclude non-numeric + columns, like (groupby) reductions, plotting, etc. + """ + return False + + @property + def _is_boolean(self): + # type: () -> bool + """ + Whether this dtype should be considered boolean. + + By default, ExtensionDtypes are assumed to be non-numeric. + Setting this to True will affect the behavior of several places, + e.g. + + * is_bool + * boolean indexing + + Returns + ------- + bool + """ + return False + + +class ExtensionDtype(_DtypeOpsMixin): + """ + A custom data type, to be paired with an ExtensionArray. + + .. versionadded:: 0.23.0 + + See Also + -------- + pandas.api.extensions.register_extension_dtype + pandas.api.extensions.ExtensionArray + + Notes + ----- + The interface includes the following abstract methods that must + be implemented by subclasses: + + * type + * name + * construct_from_string + + The following attributes influence the behavior of the dtype in + pandas operations + + * _is_numeric + * _is_boolean + + Optionally one can override construct_array_type for construction + with the name of this dtype via the Registry. See + :meth:`pandas.api.extensions.register_extension_dtype`. + + * construct_array_type + + The `na_value` class attribute can be used to set the default NA value + for this type. :attr:`numpy.nan` is used by default. + + ExtensionDtypes are required to be hashable. The base class provides + a default implementation, which relies on the ``_metadata`` class + attribute. ``_metadata`` should be a tuple containing the strings + that define your data type. For example, with ``PeriodDtype`` that's + the ``freq`` attribute. + + **If you have a parametrized dtype you should set the ``_metadata`` + class property**. + + Ideally, the attributes in ``_metadata`` will match the + parameters to your ``ExtensionDtype.__init__`` (if any). If any of + the attributes in ``_metadata`` don't implement the standard + ``__eq__`` or ``__hash__``, the default implementations here will not + work. + + .. versionchanged:: 0.24.0 + + Added ``_metadata``, ``__hash__``, and changed the default definition + of ``__eq__``. + + This class does not inherit from 'abc.ABCMeta' for performance reasons. + Methods and properties required by the interface raise + ``pandas.errors.AbstractMethodError`` and no ``register`` method is + provided for registering virtual subclasses. + """ + + def __str__(self): + return self.name + + @property + def type(self): + # type: () -> type + """ + The scalar type for the array, e.g. ``int`` + + It's expected ``ExtensionArray[item]`` returns an instance + of ``ExtensionDtype.type`` for scalar ``item``, assuming + that value is valid (not NA). NA values do not need to be + instances of `type`. + """ + raise AbstractMethodError(self) + + @property + def kind(self): + # type () -> str + """ + A character code (one of 'biufcmMOSUV'), default 'O' + + This should match the NumPy dtype used when the array is + converted to an ndarray, which is probably 'O' for object if + the extension type cannot be represented as a built-in NumPy + type. + + See Also + -------- + numpy.dtype.kind + """ + return 'O' + + @property + def name(self): + # type: () -> str + """ + A string identifying the data type. + + Will be used for display in, e.g. ``Series.dtype`` + """ + raise AbstractMethodError(self) + + @classmethod + def construct_array_type(cls): + """ + Return the array type associated with this dtype + + Returns + ------- + type + """ + raise NotImplementedError + + @classmethod + def construct_from_string(cls, string): + """ + Attempt to construct this type from a string. + + Parameters + ---------- + string : str + + Returns + ------- + self : instance of 'cls' + + Raises + ------ + TypeError + If a class cannot be constructed from this 'string'. + + Examples + -------- + If the extension dtype can be constructed without any arguments, + the following may be an adequate implementation. + + >>> @classmethod + ... def construct_from_string(cls, string) + ... if string == cls.name: + ... return cls() + ... else: + ... raise TypeError("Cannot construct a '{}' from " + ... "'{}'".format(cls, string)) + """ + raise AbstractMethodError(cls) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/cast.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/cast.py new file mode 100644 index 0000000000000000000000000000000000000000..ad62146dda268af362e17893642d90907b0857dd --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/cast.py @@ -0,0 +1,1328 @@ +""" routings for casting """ + +from datetime import datetime, timedelta + +import numpy as np + +from pandas._libs import lib, tslib, tslibs +from pandas._libs.tslibs import NaT, OutOfBoundsDatetime, Period, iNaT +from pandas.compat import PY3, string_types, text_type, to_str + +from .common import ( + _INT64_DTYPE, _NS_DTYPE, _POSSIBLY_CAST_DTYPES, _TD_DTYPE, ensure_int8, + ensure_int16, ensure_int32, ensure_int64, ensure_object, is_bool, + is_bool_dtype, is_categorical_dtype, is_complex, is_complex_dtype, + is_datetime64_dtype, is_datetime64_ns_dtype, is_datetime64tz_dtype, + is_datetime_or_timedelta_dtype, is_datetimelike, is_dtype_equal, + is_extension_array_dtype, is_extension_type, is_float, is_float_dtype, + is_integer, is_integer_dtype, is_object_dtype, is_scalar, is_string_dtype, + is_timedelta64_dtype, is_timedelta64_ns_dtype, is_unsigned_integer_dtype, + pandas_dtype) +from .dtypes import ( + DatetimeTZDtype, ExtensionDtype, PandasExtensionDtype, PeriodDtype) +from .generic import ( + ABCDatetimeArray, ABCDatetimeIndex, ABCPeriodArray, ABCPeriodIndex, + ABCSeries) +from .inference import is_list_like +from .missing import isna, notna + +_int8_max = np.iinfo(np.int8).max +_int16_max = np.iinfo(np.int16).max +_int32_max = np.iinfo(np.int32).max +_int64_max = np.iinfo(np.int64).max + + +def maybe_convert_platform(values): + """ try to do platform conversion, allow ndarray or list here """ + + if isinstance(values, (list, tuple)): + values = construct_1d_object_array_from_listlike(list(values)) + if getattr(values, 'dtype', None) == np.object_: + if hasattr(values, '_values'): + values = values._values + values = lib.maybe_convert_objects(values) + + return values + + +def is_nested_object(obj): + """ + return a boolean if we have a nested object, e.g. a Series with 1 or + more Series elements + + This may not be necessarily be performant. + + """ + + if isinstance(obj, ABCSeries) and is_object_dtype(obj): + + if any(isinstance(v, ABCSeries) for v in obj.values): + return True + + return False + + +def maybe_downcast_to_dtype(result, dtype): + """ try to cast to the specified dtype (e.g. convert back to bool/int + or could be an astype of float64->float32 + """ + + if is_scalar(result): + return result + + def trans(x): + return x + + if isinstance(dtype, string_types): + if dtype == 'infer': + inferred_type = lib.infer_dtype(ensure_object(result.ravel()), + skipna=False) + if inferred_type == 'boolean': + dtype = 'bool' + elif inferred_type == 'integer': + dtype = 'int64' + elif inferred_type == 'datetime64': + dtype = 'datetime64[ns]' + elif inferred_type == 'timedelta64': + dtype = 'timedelta64[ns]' + + # try to upcast here + elif inferred_type == 'floating': + dtype = 'int64' + if issubclass(result.dtype.type, np.number): + + def trans(x): # noqa + return x.round() + else: + dtype = 'object' + + if isinstance(dtype, string_types): + dtype = np.dtype(dtype) + + try: + + # don't allow upcasts here (except if empty) + if dtype.kind == result.dtype.kind: + if (result.dtype.itemsize <= dtype.itemsize and + np.prod(result.shape)): + return result + + if is_bool_dtype(dtype) or is_integer_dtype(dtype): + + # if we don't have any elements, just astype it + if not np.prod(result.shape): + return trans(result).astype(dtype) + + # do a test on the first element, if it fails then we are done + r = result.ravel() + arr = np.array([r[0]]) + + # if we have any nulls, then we are done + if (isna(arr).any() or + not np.allclose(arr, trans(arr).astype(dtype), rtol=0)): + return result + + # a comparable, e.g. a Decimal may slip in here + elif not isinstance(r[0], (np.integer, np.floating, np.bool, int, + float, bool)): + return result + + if (issubclass(result.dtype.type, (np.object_, np.number)) and + notna(result).all()): + new_result = trans(result).astype(dtype) + try: + if np.allclose(new_result, result, rtol=0): + return new_result + except Exception: + + # comparison of an object dtype with a number type could + # hit here + if (new_result == result).all(): + return new_result + elif (issubclass(dtype.type, np.floating) and + not is_bool_dtype(result.dtype)): + return result.astype(dtype) + + # a datetimelike + # GH12821, iNaT is casted to float + elif dtype.kind in ['M', 'm'] and result.dtype.kind in ['i', 'f']: + try: + result = result.astype(dtype) + except Exception: + if dtype.tz: + # convert to datetime and change timezone + from pandas import to_datetime + result = to_datetime(result).tz_localize('utc') + result = result.tz_convert(dtype.tz) + + elif dtype.type == Period: + # TODO(DatetimeArray): merge with previous elif + from pandas.core.arrays import PeriodArray + + return PeriodArray(result, freq=dtype.freq) + + except Exception: + pass + + return result + + +def maybe_upcast_putmask(result, mask, other): + """ + A safe version of putmask that potentially upcasts the result + + Parameters + ---------- + result : ndarray + The destination array. This will be mutated in-place if no upcasting is + necessary. + mask : boolean ndarray + other : ndarray or scalar + The source array or value + + Returns + ------- + result : ndarray + changed : boolean + Set to true if the result array was upcasted + """ + + if mask.any(): + # Two conversions for date-like dtypes that can't be done automatically + # in np.place: + # NaN -> NaT + # integer or integer array -> date-like array + if is_datetimelike(result.dtype): + if is_scalar(other): + if isna(other): + other = result.dtype.type('nat') + elif is_integer(other): + other = np.array(other, dtype=result.dtype) + elif is_integer_dtype(other): + other = np.array(other, dtype=result.dtype) + + def changeit(): + + # try to directly set by expanding our array to full + # length of the boolean + try: + om = other[mask] + om_at = om.astype(result.dtype) + if (om == om_at).all(): + new_result = result.values.copy() + new_result[mask] = om_at + result[:] = new_result + return result, False + except Exception: + pass + + # we are forced to change the dtype of the result as the input + # isn't compatible + r, _ = maybe_upcast(result, fill_value=other, copy=True) + np.place(r, mask, other) + + return r, True + + # we want to decide whether place will work + # if we have nans in the False portion of our mask then we need to + # upcast (possibly), otherwise we DON't want to upcast (e.g. if we + # have values, say integers, in the success portion then it's ok to not + # upcast) + new_dtype, _ = maybe_promote(result.dtype, other) + if new_dtype != result.dtype: + + # we have a scalar or len 0 ndarray + # and its nan and we are changing some values + if (is_scalar(other) or + (isinstance(other, np.ndarray) and other.ndim < 1)): + if isna(other): + return changeit() + + # we have an ndarray and the masking has nans in it + else: + + if isna(other[mask]).any(): + return changeit() + + try: + np.place(result, mask, other) + except Exception: + return changeit() + + return result, False + + +def maybe_promote(dtype, fill_value=np.nan): + # if we passed an array here, determine the fill value by dtype + if isinstance(fill_value, np.ndarray): + if issubclass(fill_value.dtype.type, (np.datetime64, np.timedelta64)): + fill_value = iNaT + else: + + # we need to change to object type as our + # fill_value is of object type + if fill_value.dtype == np.object_: + dtype = np.dtype(np.object_) + fill_value = np.nan + + # returns tuple of (dtype, fill_value) + if issubclass(dtype.type, np.datetime64): + fill_value = tslibs.Timestamp(fill_value).value + elif issubclass(dtype.type, np.timedelta64): + fill_value = tslibs.Timedelta(fill_value).value + elif is_datetime64tz_dtype(dtype): + if isna(fill_value): + fill_value = NaT + elif is_extension_array_dtype(dtype) and isna(fill_value): + fill_value = dtype.na_value + elif is_float(fill_value): + if issubclass(dtype.type, np.bool_): + dtype = np.object_ + elif issubclass(dtype.type, np.integer): + dtype = np.float64 + elif is_bool(fill_value): + if not issubclass(dtype.type, np.bool_): + dtype = np.object_ + elif is_integer(fill_value): + if issubclass(dtype.type, np.bool_): + dtype = np.object_ + elif issubclass(dtype.type, np.integer): + # upcast to prevent overflow + arr = np.asarray(fill_value) + if arr != arr.astype(dtype): + dtype = arr.dtype + elif is_complex(fill_value): + if issubclass(dtype.type, np.bool_): + dtype = np.object_ + elif issubclass(dtype.type, (np.integer, np.floating)): + dtype = np.complex128 + elif fill_value is None: + if is_float_dtype(dtype) or is_complex_dtype(dtype): + fill_value = np.nan + elif is_integer_dtype(dtype): + dtype = np.float64 + fill_value = np.nan + elif is_datetime_or_timedelta_dtype(dtype): + fill_value = iNaT + else: + dtype = np.object_ + fill_value = np.nan + else: + dtype = np.object_ + + # in case we have a string that looked like a number + if is_extension_array_dtype(dtype): + pass + elif is_datetime64tz_dtype(dtype): + pass + elif issubclass(np.dtype(dtype).type, string_types): + dtype = np.object_ + + return dtype, fill_value + + +def infer_dtype_from(val, pandas_dtype=False): + """ + interpret the dtype from a scalar or array. This is a convenience + routines to infer dtype from a scalar or an array + + Parameters + ---------- + pandas_dtype : bool, default False + whether to infer dtype including pandas extension types. + If False, scalar/array belongs to pandas extension types is inferred as + object + """ + if is_scalar(val): + return infer_dtype_from_scalar(val, pandas_dtype=pandas_dtype) + return infer_dtype_from_array(val, pandas_dtype=pandas_dtype) + + +def infer_dtype_from_scalar(val, pandas_dtype=False): + """ + interpret the dtype from a scalar + + Parameters + ---------- + pandas_dtype : bool, default False + whether to infer dtype including pandas extension types. + If False, scalar belongs to pandas extension types is inferred as + object + """ + + dtype = np.object_ + + # a 1-element ndarray + if isinstance(val, np.ndarray): + msg = "invalid ndarray passed to infer_dtype_from_scalar" + if val.ndim != 0: + raise ValueError(msg) + + dtype = val.dtype + val = val.item() + + elif isinstance(val, string_types): + + # If we create an empty array using a string to infer + # the dtype, NumPy will only allocate one character per entry + # so this is kind of bad. Alternately we could use np.repeat + # instead of np.empty (but then you still don't want things + # coming out as np.str_! + + dtype = np.object_ + + elif isinstance(val, (np.datetime64, datetime)): + val = tslibs.Timestamp(val) + if val is tslibs.NaT or val.tz is None: + dtype = np.dtype('M8[ns]') + else: + if pandas_dtype: + dtype = DatetimeTZDtype(unit='ns', tz=val.tz) + else: + # return datetimetz as object + return np.object_, val + val = val.value + + elif isinstance(val, (np.timedelta64, timedelta)): + val = tslibs.Timedelta(val).value + dtype = np.dtype('m8[ns]') + + elif is_bool(val): + dtype = np.bool_ + + elif is_integer(val): + if isinstance(val, np.integer): + dtype = type(val) + else: + dtype = np.int64 + + elif is_float(val): + if isinstance(val, np.floating): + dtype = type(val) + else: + dtype = np.float64 + + elif is_complex(val): + dtype = np.complex_ + + elif pandas_dtype: + if lib.is_period(val): + dtype = PeriodDtype(freq=val.freq) + val = val.ordinal + + return dtype, val + + +def infer_dtype_from_array(arr, pandas_dtype=False): + """ + infer the dtype from a scalar or array + + Parameters + ---------- + arr : scalar or array + pandas_dtype : bool, default False + whether to infer dtype including pandas extension types. + If False, array belongs to pandas extension types + is inferred as object + + Returns + ------- + tuple (numpy-compat/pandas-compat dtype, array) + + Notes + ----- + if pandas_dtype=False. these infer to numpy dtypes + exactly with the exception that mixed / object dtypes + are not coerced by stringifying or conversion + + if pandas_dtype=True. datetime64tz-aware/categorical + types will retain there character. + + Examples + -------- + >>> np.asarray([1, '1']) + array(['1', '1'], dtype='>> infer_dtype_from_array([1, '1']) + (numpy.object_, [1, '1']) + + """ + + if isinstance(arr, np.ndarray): + return arr.dtype, arr + + if not is_list_like(arr): + arr = [arr] + + if pandas_dtype and is_extension_type(arr): + return arr.dtype, arr + + elif isinstance(arr, ABCSeries): + return arr.dtype, np.asarray(arr) + + # don't force numpy coerce with nan's + inferred = lib.infer_dtype(arr, skipna=False) + if inferred in ['string', 'bytes', 'unicode', + 'mixed', 'mixed-integer']: + return (np.object_, arr) + + arr = np.asarray(arr) + return arr.dtype, arr + + +def maybe_infer_dtype_type(element): + """Try to infer an object's dtype, for use in arithmetic ops + + Uses `element.dtype` if that's available. + Objects implementing the iterator protocol are cast to a NumPy array, + and from there the array's type is used. + + Parameters + ---------- + element : object + Possibly has a `.dtype` attribute, and possibly the iterator + protocol. + + Returns + ------- + tipo : type + + Examples + -------- + >>> from collections import namedtuple + >>> Foo = namedtuple("Foo", "dtype") + >>> maybe_infer_dtype_type(Foo(np.dtype("i8"))) + numpy.int64 + """ + tipo = None + if hasattr(element, 'dtype'): + tipo = element.dtype + elif is_list_like(element): + element = np.asarray(element) + tipo = element.dtype + return tipo + + +def maybe_upcast(values, fill_value=np.nan, dtype=None, copy=False): + """ provide explicit type promotion and coercion + + Parameters + ---------- + values : the ndarray that we want to maybe upcast + fill_value : what we want to fill with + dtype : if None, then use the dtype of the values, else coerce to this type + copy : if True always make a copy even if no upcast is required + """ + + if is_extension_type(values): + if copy: + values = values.copy() + else: + if dtype is None: + dtype = values.dtype + new_dtype, fill_value = maybe_promote(dtype, fill_value) + if new_dtype != values.dtype: + values = values.astype(new_dtype) + elif copy: + values = values.copy() + + return values, fill_value + + +def maybe_cast_item(obj, item, dtype): + chunk = obj[item] + + if chunk.values.dtype != dtype: + if dtype in (np.object_, np.bool_): + obj[item] = chunk.astype(np.object_) + elif not issubclass(dtype, (np.integer, np.bool_)): # pragma: no cover + raise ValueError("Unexpected dtype encountered: {dtype}" + .format(dtype=dtype)) + + +def invalidate_string_dtypes(dtype_set): + """Change string like dtypes to object for + ``DataFrame.select_dtypes()``. + """ + non_string_dtypes = dtype_set - {np.dtype('S').type, np.dtype(' 1 and coerce: + raise ValueError("Only one of 'datetime', 'numeric' or " + "'timedelta' can be True when when coerce=True.") + + if isinstance(values, (list, tuple)): + # List or scalar + values = np.array(values, dtype=np.object_) + elif not hasattr(values, 'dtype'): + values = np.array([values], dtype=np.object_) + elif not is_object_dtype(values.dtype): + # If not object, do not attempt conversion + values = values.copy() if copy else values + return values + + # If 1 flag is coerce, ensure 2 others are False + if coerce: + # Immediate return if coerce + if datetime: + from pandas import to_datetime + return to_datetime(values, errors='coerce', box=False) + elif timedelta: + from pandas import to_timedelta + return to_timedelta(values, errors='coerce', box=False) + elif numeric: + from pandas import to_numeric + return to_numeric(values, errors='coerce') + + # Soft conversions + if datetime: + # GH 20380, when datetime is beyond year 2262, hence outside + # bound of nanosecond-resolution 64-bit integers. + try: + values = lib.maybe_convert_objects(values, + convert_datetime=datetime) + except OutOfBoundsDatetime: + pass + + if timedelta and is_object_dtype(values.dtype): + # Object check to ensure only run if previous did not convert + values = lib.maybe_convert_objects(values, convert_timedelta=timedelta) + + if numeric and is_object_dtype(values.dtype): + try: + converted = lib.maybe_convert_numeric(values, set(), + coerce_numeric=True) + # If all NaNs, then do not-alter + values = converted if not isna(converted).all() else values + values = values.copy() if copy else values + except Exception: + pass + + return values + + +def maybe_castable(arr): + # return False to force a non-fastpath + + # check datetime64[ns]/timedelta64[ns] are valid + # otherwise try to coerce + kind = arr.dtype.kind + if kind == 'M': + return is_datetime64_ns_dtype(arr.dtype) + elif kind == 'm': + return is_timedelta64_ns_dtype(arr.dtype) + + return arr.dtype.name not in _POSSIBLY_CAST_DTYPES + + +def maybe_infer_to_datetimelike(value, convert_dates=False): + """ + we might have a array (or single object) that is datetime like, + and no dtype is passed don't change the value unless we find a + datetime/timedelta set + + this is pretty strict in that a datetime/timedelta is REQUIRED + in addition to possible nulls/string likes + + Parameters + ---------- + value : np.array / Series / Index / list-like + convert_dates : boolean, default False + if True try really hard to convert dates (such as datetime.date), other + leave inferred dtype 'date' alone + + """ + + # TODO: why not timedelta? + if isinstance(value, (ABCDatetimeIndex, ABCPeriodIndex, + ABCDatetimeArray, ABCPeriodArray)): + return value + elif isinstance(value, ABCSeries): + if isinstance(value._values, ABCDatetimeIndex): + return value._values + + v = value + + if not is_list_like(v): + v = [v] + v = np.array(v, copy=False) + + # we only care about object dtypes + if not is_object_dtype(v): + return value + + shape = v.shape + if not v.ndim == 1: + v = v.ravel() + + if not len(v): + return value + + def try_datetime(v): + # safe coerce to datetime64 + try: + # GH19671 + v = tslib.array_to_datetime(v, + require_iso8601=True, + errors='raise')[0] + except ValueError: + + # we might have a sequence of the same-datetimes with tz's + # if so coerce to a DatetimeIndex; if they are not the same, + # then these stay as object dtype, xref GH19671 + try: + from pandas._libs.tslibs import conversion + from pandas import DatetimeIndex + + values, tz = conversion.datetime_to_datetime64(v) + return DatetimeIndex(values).tz_localize( + 'UTC').tz_convert(tz=tz) + except (ValueError, TypeError): + pass + + except Exception: + pass + + return v.reshape(shape) + + def try_timedelta(v): + # safe coerce to timedelta64 + + # will try first with a string & object conversion + from pandas import to_timedelta + try: + return to_timedelta(v)._ndarray_values.reshape(shape) + except Exception: + return v.reshape(shape) + + inferred_type = lib.infer_datetimelike_array(ensure_object(v)) + + if inferred_type == 'date' and convert_dates: + value = try_datetime(v) + elif inferred_type == 'datetime': + value = try_datetime(v) + elif inferred_type == 'timedelta': + value = try_timedelta(v) + elif inferred_type == 'nat': + + # if all NaT, return as datetime + if isna(v).all(): + value = try_datetime(v) + else: + + # We have at least a NaT and a string + # try timedelta first to avoid spurious datetime conversions + # e.g. '00:00:01' is a timedelta but technically is also a datetime + value = try_timedelta(v) + if lib.infer_dtype(value, skipna=False) in ['mixed']: + # cannot skip missing values, as NaT implies that the string + # is actually a datetime + value = try_datetime(v) + + return value + + +def maybe_cast_to_datetime(value, dtype, errors='raise'): + """ try to cast the array/value to a datetimelike dtype, converting float + nan to iNaT + """ + from pandas.core.tools.timedeltas import to_timedelta + from pandas.core.tools.datetimes import to_datetime + + if dtype is not None: + if isinstance(dtype, string_types): + dtype = np.dtype(dtype) + + is_datetime64 = is_datetime64_dtype(dtype) + is_datetime64tz = is_datetime64tz_dtype(dtype) + is_timedelta64 = is_timedelta64_dtype(dtype) + + if is_datetime64 or is_datetime64tz or is_timedelta64: + + # Force the dtype if needed. + msg = ("The '{dtype}' dtype has no unit. " + "Please pass in '{dtype}[ns]' instead.") + + if is_datetime64 and not is_dtype_equal(dtype, _NS_DTYPE): + if dtype.name in ('datetime64', 'datetime64[ns]'): + if dtype.name == 'datetime64': + raise ValueError(msg.format(dtype=dtype.name)) + dtype = _NS_DTYPE + else: + raise TypeError("cannot convert datetimelike to " + "dtype [{dtype}]".format(dtype=dtype)) + elif is_datetime64tz: + + # our NaT doesn't support tz's + # this will coerce to DatetimeIndex with + # a matching dtype below + if is_scalar(value) and isna(value): + value = [value] + + elif is_timedelta64 and not is_dtype_equal(dtype, _TD_DTYPE): + if dtype.name in ('timedelta64', 'timedelta64[ns]'): + if dtype.name == 'timedelta64': + raise ValueError(msg.format(dtype=dtype.name)) + dtype = _TD_DTYPE + else: + raise TypeError("cannot convert timedeltalike to " + "dtype [{dtype}]".format(dtype=dtype)) + + if is_scalar(value): + if value == iNaT or isna(value): + value = iNaT + else: + value = np.array(value, copy=False) + + # have a scalar array-like (e.g. NaT) + if value.ndim == 0: + value = iNaT + + # we have an array of datetime or timedeltas & nulls + elif np.prod(value.shape) or not is_dtype_equal(value.dtype, + dtype): + try: + if is_datetime64: + value = to_datetime(value, errors=errors)._values + elif is_datetime64tz: + # The string check can be removed once issue #13712 + # is solved. String data that is passed with a + # datetime64tz is assumed to be naive which should + # be localized to the timezone. + is_dt_string = is_string_dtype(value) + value = to_datetime(value, errors=errors).array + if is_dt_string: + # Strings here are naive, so directly localize + value = value.tz_localize(dtype.tz) + else: + # Numeric values are UTC at this point, + # so localize and convert + value = (value.tz_localize('UTC') + .tz_convert(dtype.tz)) + elif is_timedelta64: + value = to_timedelta(value, errors=errors)._values + except (AttributeError, ValueError, TypeError): + pass + + # coerce datetimelike to object + elif is_datetime64_dtype(value) and not is_datetime64_dtype(dtype): + if is_object_dtype(dtype): + if value.dtype != _NS_DTYPE: + value = value.astype(_NS_DTYPE) + ints = np.asarray(value).view('i8') + return tslib.ints_to_pydatetime(ints) + + # we have a non-castable dtype that was passed + raise TypeError('Cannot cast datetime64 to {dtype}' + .format(dtype=dtype)) + + else: + + is_array = isinstance(value, np.ndarray) + + # catch a datetime/timedelta that is not of ns variety + # and no coercion specified + if is_array and value.dtype.kind in ['M', 'm']: + dtype = value.dtype + + if dtype.kind == 'M' and dtype != _NS_DTYPE: + value = value.astype(_NS_DTYPE) + + elif dtype.kind == 'm' and dtype != _TD_DTYPE: + value = to_timedelta(value) + + # only do this if we have an array and the dtype of the array is not + # setup already we are not an integer/object, so don't bother with this + # conversion + elif not (is_array and not (issubclass(value.dtype.type, np.integer) or + value.dtype == np.object_)): + value = maybe_infer_to_datetimelike(value) + + return value + + +def find_common_type(types): + """ + Find a common data type among the given dtypes. + + Parameters + ---------- + types : list of dtypes + + Returns + ------- + pandas extension or numpy dtype + + See Also + -------- + numpy.find_common_type + + """ + + if len(types) == 0: + raise ValueError('no types given') + + first = types[0] + + # workaround for find_common_type([np.dtype('datetime64[ns]')] * 2) + # => object + if all(is_dtype_equal(first, t) for t in types[1:]): + return first + + if any(isinstance(t, (PandasExtensionDtype, ExtensionDtype)) + for t in types): + return np.object + + # take lowest unit + if all(is_datetime64_dtype(t) for t in types): + return np.dtype('datetime64[ns]') + if all(is_timedelta64_dtype(t) for t in types): + return np.dtype('timedelta64[ns]') + + # don't mix bool / int or float or complex + # this is different from numpy, which casts bool with float/int as int + has_bools = any(is_bool_dtype(t) for t in types) + if has_bools: + has_ints = any(is_integer_dtype(t) for t in types) + has_floats = any(is_float_dtype(t) for t in types) + has_complex = any(is_complex_dtype(t) for t in types) + if has_ints or has_floats or has_complex: + return np.object + + return np.find_common_type(types, []) + + +def cast_scalar_to_array(shape, value, dtype=None): + """ + create np.ndarray of specified shape and dtype, filled with values + + Parameters + ---------- + shape : tuple + value : scalar value + dtype : np.dtype, optional + dtype to coerce + + Returns + ------- + ndarray of shape, filled with value, of specified / inferred dtype + + """ + + if dtype is None: + dtype, fill_value = infer_dtype_from_scalar(value) + else: + fill_value = value + + values = np.empty(shape, dtype=dtype) + values.fill(fill_value) + + return values + + +def construct_1d_arraylike_from_scalar(value, length, dtype): + """ + create a np.ndarray / pandas type of specified shape and dtype + filled with values + + Parameters + ---------- + value : scalar value + length : int + dtype : pandas_dtype / np.dtype + + Returns + ------- + np.ndarray / pandas type of length, filled with value + + """ + if is_datetime64tz_dtype(dtype): + from pandas import DatetimeIndex + subarr = DatetimeIndex([value] * length, dtype=dtype) + elif is_categorical_dtype(dtype): + from pandas import Categorical + subarr = Categorical([value] * length, dtype=dtype) + else: + if not isinstance(dtype, (np.dtype, type(np.dtype))): + dtype = dtype.dtype + + if length and is_integer_dtype(dtype) and isna(value): + # coerce if we have nan for an integer dtype + dtype = np.dtype('float64') + elif isinstance(dtype, np.dtype) and dtype.kind in ("U", "S"): + # we need to coerce to object dtype to avoid + # to allow numpy to take our string as a scalar value + dtype = object + if not isna(value): + value = to_str(value) + + subarr = np.empty(length, dtype=dtype) + subarr.fill(value) + + return subarr + + +def construct_1d_object_array_from_listlike(values): + """ + Transform any list-like object in a 1-dimensional numpy array of object + dtype. + + Parameters + ---------- + values : any iterable which has a len() + + Raises + ------ + TypeError + * If `values` does not have a len() + + Returns + ------- + 1-dimensional numpy array of dtype object + """ + # numpy will try to interpret nested lists as further dimensions, hence + # making a 1D array that contains list-likes is a bit tricky: + result = np.empty(len(values), dtype='object') + result[:] = values + return result + + +def construct_1d_ndarray_preserving_na(values, dtype=None, copy=False): + """ + Construct a new ndarray, coercing `values` to `dtype`, preserving NA. + + Parameters + ---------- + values : Sequence + dtype : numpy.dtype, optional + copy : bool, default False + Note that copies may still be made with ``copy=False`` if casting + is required. + + Returns + ------- + arr : ndarray[dtype] + + Examples + -------- + >>> np.array([1.0, 2.0, None], dtype='str') + array(['1.0', '2.0', 'None'], dtype='>> construct_1d_ndarray_preserving_na([1.0, 2.0, None], dtype='str') + + + """ + subarr = np.array(values, dtype=dtype, copy=copy) + + if dtype is not None and dtype.kind in ("U", "S"): + # GH-21083 + # We can't just return np.array(subarr, dtype='str') since + # NumPy will convert the non-string objects into strings + # Including NA values. Se we have to go + # string -> object -> update NA, which requires an + # additional pass over the data. + na_values = isna(values) + subarr2 = subarr.astype(object) + subarr2[na_values] = np.asarray(values, dtype=object)[na_values] + subarr = subarr2 + + return subarr + + +def maybe_cast_to_integer_array(arr, dtype, copy=False): + """ + Takes any dtype and returns the casted version, raising for when data is + incompatible with integer/unsigned integer dtypes. + + .. versionadded:: 0.24.0 + + Parameters + ---------- + arr : array-like + The array to cast. + dtype : str, np.dtype + The integer dtype to cast the array to. + copy: boolean, default False + Whether to make a copy of the array before returning. + + Returns + ------- + int_arr : ndarray + An array of integer or unsigned integer dtype + + Raises + ------ + OverflowError : the dtype is incompatible with the data + ValueError : loss of precision has occurred during casting + + Examples + -------- + If you try to coerce negative values to unsigned integers, it raises: + + >>> Series([-1], dtype="uint64") + Traceback (most recent call last): + ... + OverflowError: Trying to coerce negative values to unsigned integers + + Also, if you try to coerce float values to integers, it raises: + + >>> Series([1, 2, 3.5], dtype="int64") + Traceback (most recent call last): + ... + ValueError: Trying to coerce float values to integers + """ + + try: + if not hasattr(arr, "astype"): + casted = np.array(arr, dtype=dtype, copy=copy) + else: + casted = arr.astype(dtype, copy=copy) + except OverflowError: + raise OverflowError("The elements provided in the data cannot all be " + "casted to the dtype {dtype}".format(dtype=dtype)) + + if np.array_equal(arr, casted): + return casted + + # We do this casting to allow for proper + # data and dtype checking. + # + # We didn't do this earlier because NumPy + # doesn't handle `uint64` correctly. + arr = np.asarray(arr) + + if is_unsigned_integer_dtype(dtype) and (arr < 0).any(): + raise OverflowError("Trying to coerce negative values " + "to unsigned integers") + + if is_integer_dtype(dtype) and (is_float_dtype(arr) or + is_object_dtype(arr)): + raise ValueError("Trying to coerce float values to integers") diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/common.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/common.py new file mode 100644 index 0000000000000000000000000000000000000000..e9bf0f87088db06027207a4944bb6faec51554b9 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/common.py @@ -0,0 +1,2031 @@ +""" common type operations """ +import warnings + +import numpy as np + +from pandas._libs import algos, lib +from pandas._libs.tslibs import conversion +from pandas.compat import PY3, PY36, string_types + +from pandas.core.dtypes.dtypes import ( + CategoricalDtype, DatetimeTZDtype, ExtensionDtype, IntervalDtype, + PandasExtensionDtype, PeriodDtype, registry) +from pandas.core.dtypes.generic import ( + ABCCategorical, ABCDateOffset, ABCDatetimeIndex, ABCIndexClass, + ABCPeriodArray, ABCPeriodIndex, ABCSeries) +from pandas.core.dtypes.inference import ( # noqa:F401 + is_array_like, is_bool, is_complex, is_decimal, is_dict_like, is_file_like, + is_float, is_hashable, is_integer, is_interval, is_iterator, is_list_like, + is_named_tuple, is_nested_list_like, is_number, is_re, is_re_compilable, + is_scalar, is_sequence, is_string_like) + +_POSSIBLY_CAST_DTYPES = {np.dtype(t).name + for t in ['O', 'int8', 'uint8', 'int16', 'uint16', + 'int32', 'uint32', 'int64', 'uint64']} + +_NS_DTYPE = conversion.NS_DTYPE +_TD_DTYPE = conversion.TD_DTYPE +_INT64_DTYPE = np.dtype(np.int64) + +# oh the troubles to reduce import time +_is_scipy_sparse = None + +ensure_float64 = algos.ensure_float64 +ensure_float32 = algos.ensure_float32 + +_ensure_datetime64ns = conversion.ensure_datetime64ns +_ensure_timedelta64ns = conversion.ensure_timedelta64ns + + +def ensure_float(arr): + """ + Ensure that an array object has a float dtype if possible. + + Parameters + ---------- + arr : array-like + The array whose data type we want to enforce as float. + + Returns + ------- + float_arr : The original array cast to the float dtype if + possible. Otherwise, the original array is returned. + """ + + if issubclass(arr.dtype.type, (np.integer, np.bool_)): + arr = arr.astype(float) + return arr + + +ensure_uint64 = algos.ensure_uint64 +ensure_int64 = algos.ensure_int64 +ensure_int32 = algos.ensure_int32 +ensure_int16 = algos.ensure_int16 +ensure_int8 = algos.ensure_int8 +ensure_platform_int = algos.ensure_platform_int +ensure_object = algos.ensure_object + + +def ensure_categorical(arr): + """ + Ensure that an array-like object is a Categorical (if not already). + + Parameters + ---------- + arr : array-like + The array that we want to convert into a Categorical. + + Returns + ------- + cat_arr : The original array cast as a Categorical. If it already + is a Categorical, we return as is. + """ + + if not is_categorical(arr): + from pandas import Categorical + arr = Categorical(arr) + return arr + + +def ensure_int64_or_float64(arr, copy=False): + """ + Ensure that an dtype array of some integer dtype + has an int64 dtype if possible + If it's not possible, potentially because of overflow, + convert the array to float64 instead. + + Parameters + ---------- + arr : array-like + The array whose data type we want to enforce. + copy: boolean + Whether to copy the original array or reuse + it in place, if possible. + + Returns + ------- + out_arr : The input array cast as int64 if + possible without overflow. + Otherwise the input array cast to float64. + """ + try: + return arr.astype('int64', copy=copy, casting='safe') + except TypeError: + return arr.astype('float64', copy=copy) + + +def classes(*klasses): + """ evaluate if the tipo is a subclass of the klasses """ + return lambda tipo: issubclass(tipo, klasses) + + +def classes_and_not_datetimelike(*klasses): + """ + evaluate if the tipo is a subclass of the klasses + and not a datetimelike + """ + return lambda tipo: (issubclass(tipo, klasses) and + not issubclass(tipo, (np.datetime64, np.timedelta64))) + + +def is_object_dtype(arr_or_dtype): + """ + Check whether an array-like or dtype is of the object dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array-like or dtype to check. + + Returns + ------- + boolean : Whether or not the array-like or dtype is of the object dtype. + + Examples + -------- + >>> is_object_dtype(object) + True + >>> is_object_dtype(int) + False + >>> is_object_dtype(np.array([], dtype=object)) + True + >>> is_object_dtype(np.array([], dtype=int)) + False + >>> is_object_dtype([1, 2, 3]) + False + """ + return _is_dtype_type(arr_or_dtype, classes(np.object_)) + + +def is_sparse(arr): + """ + Check whether an array-like is a 1-D pandas sparse array. + + Check that the one-dimensional array-like is a pandas sparse array. + Returns True if it is a pandas sparse array, not another type of + sparse array. + + Parameters + ---------- + arr : array-like + Array-like to check. + + Returns + ------- + bool + Whether or not the array-like is a pandas sparse array. + + See Also + -------- + DataFrame.to_sparse : Convert DataFrame to a SparseDataFrame. + Series.to_sparse : Convert Series to SparseSeries. + Series.to_dense : Return dense representation of a Series. + + Examples + -------- + Returns `True` if the parameter is a 1-D pandas sparse array. + + >>> is_sparse(pd.SparseArray([0, 0, 1, 0])) + True + >>> is_sparse(pd.SparseSeries([0, 0, 1, 0])) + True + + Returns `False` if the parameter is not sparse. + + >>> is_sparse(np.array([0, 0, 1, 0])) + False + >>> is_sparse(pd.Series([0, 1, 0, 0])) + False + + Returns `False` if the parameter is not a pandas sparse array. + + >>> from scipy.sparse import bsr_matrix + >>> is_sparse(bsr_matrix([0, 1, 0, 0])) + False + + Returns `False` if the parameter has more than one dimension. + + >>> df = pd.SparseDataFrame([389., 24., 80.5, np.nan], + columns=['max_speed'], + index=['falcon', 'parrot', 'lion', 'monkey']) + >>> is_sparse(df) + False + >>> is_sparse(df.max_speed) + True + """ + from pandas.core.arrays.sparse import SparseDtype + + dtype = getattr(arr, 'dtype', arr) + return isinstance(dtype, SparseDtype) + + +def is_scipy_sparse(arr): + """ + Check whether an array-like is a scipy.sparse.spmatrix instance. + + Parameters + ---------- + arr : array-like + The array-like to check. + + Returns + ------- + boolean : Whether or not the array-like is a + scipy.sparse.spmatrix instance. + + Notes + ----- + If scipy is not installed, this function will always return False. + + Examples + -------- + >>> from scipy.sparse import bsr_matrix + >>> is_scipy_sparse(bsr_matrix([1, 2, 3])) + True + >>> is_scipy_sparse(pd.SparseArray([1, 2, 3])) + False + >>> is_scipy_sparse(pd.SparseSeries([1, 2, 3])) + False + """ + + global _is_scipy_sparse + + if _is_scipy_sparse is None: + try: + from scipy.sparse import issparse as _is_scipy_sparse + except ImportError: + _is_scipy_sparse = lambda _: False + + return _is_scipy_sparse(arr) + + +def is_categorical(arr): + """ + Check whether an array-like is a Categorical instance. + + Parameters + ---------- + arr : array-like + The array-like to check. + + Returns + ------- + boolean : Whether or not the array-like is of a Categorical instance. + + Examples + -------- + >>> is_categorical([1, 2, 3]) + False + + Categoricals, Series Categoricals, and CategoricalIndex will return True. + + >>> cat = pd.Categorical([1, 2, 3]) + >>> is_categorical(cat) + True + >>> is_categorical(pd.Series(cat)) + True + >>> is_categorical(pd.CategoricalIndex([1, 2, 3])) + True + """ + + return isinstance(arr, ABCCategorical) or is_categorical_dtype(arr) + + +def is_datetimetz(arr): + """ + Check whether an array-like is a datetime array-like with a timezone + component in its dtype. + + .. deprecated:: 0.24.0 + + Parameters + ---------- + arr : array-like + The array-like to check. + + Returns + ------- + boolean : Whether or not the array-like is a datetime array-like with + a timezone component in its dtype. + + Examples + -------- + >>> is_datetimetz([1, 2, 3]) + False + + Although the following examples are both DatetimeIndex objects, + the first one returns False because it has no timezone component + unlike the second one, which returns True. + + >>> is_datetimetz(pd.DatetimeIndex([1, 2, 3])) + False + >>> is_datetimetz(pd.DatetimeIndex([1, 2, 3], tz="US/Eastern")) + True + + The object need not be a DatetimeIndex object. It just needs to have + a dtype which has a timezone component. + + >>> dtype = DatetimeTZDtype("ns", tz="US/Eastern") + >>> s = pd.Series([], dtype=dtype) + >>> is_datetimetz(s) + True + """ + + warnings.warn("'is_datetimetz' is deprecated and will be removed in a " + "future version. Use 'is_datetime64tz_dtype' instead.", + FutureWarning, stacklevel=2) + return is_datetime64tz_dtype(arr) + + +def is_offsetlike(arr_or_obj): + """ + Check if obj or all elements of list-like is DateOffset + + Parameters + ---------- + arr_or_obj : object + + Returns + ------- + boolean : Whether the object is a DateOffset or listlike of DatetOffsets + + Examples + -------- + >>> is_offsetlike(pd.DateOffset(days=1)) + True + >>> is_offsetlike('offset') + False + >>> is_offsetlike([pd.offsets.Minute(4), pd.offsets.MonthEnd()]) + True + >>> is_offsetlike(np.array([pd.DateOffset(months=3), pd.Timestamp.now()])) + False + """ + if isinstance(arr_or_obj, ABCDateOffset): + return True + elif (is_list_like(arr_or_obj) and len(arr_or_obj) and + is_object_dtype(arr_or_obj)): + return all(isinstance(x, ABCDateOffset) for x in arr_or_obj) + return False + + +def is_period(arr): + """ + Check whether an array-like is a periodical index. + + .. deprecated:: 0.24.0 + + Parameters + ---------- + arr : array-like + The array-like to check. + + Returns + ------- + boolean : Whether or not the array-like is a periodical index. + + Examples + -------- + >>> is_period([1, 2, 3]) + False + >>> is_period(pd.Index([1, 2, 3])) + False + >>> is_period(pd.PeriodIndex(["2017-01-01"], freq="D")) + True + """ + + warnings.warn("'is_period' is deprecated and will be removed in a future " + "version. Use 'is_period_dtype' or is_period_arraylike' " + "instead.", FutureWarning, stacklevel=2) + + return isinstance(arr, ABCPeriodIndex) or is_period_arraylike(arr) + + +def is_datetime64_dtype(arr_or_dtype): + """ + Check whether an array-like or dtype is of the datetime64 dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array-like or dtype to check. + + Returns + ------- + boolean : Whether or not the array-like or dtype is of + the datetime64 dtype. + + Examples + -------- + >>> is_datetime64_dtype(object) + False + >>> is_datetime64_dtype(np.datetime64) + True + >>> is_datetime64_dtype(np.array([], dtype=int)) + False + >>> is_datetime64_dtype(np.array([], dtype=np.datetime64)) + True + >>> is_datetime64_dtype([1, 2, 3]) + False + """ + + return _is_dtype_type(arr_or_dtype, classes(np.datetime64)) + + +def is_datetime64tz_dtype(arr_or_dtype): + """ + Check whether an array-like or dtype is of a DatetimeTZDtype dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array-like or dtype to check. + + Returns + ------- + boolean : Whether or not the array-like or dtype is of + a DatetimeTZDtype dtype. + + Examples + -------- + >>> is_datetime64tz_dtype(object) + False + >>> is_datetime64tz_dtype([1, 2, 3]) + False + >>> is_datetime64tz_dtype(pd.DatetimeIndex([1, 2, 3])) # tz-naive + False + >>> is_datetime64tz_dtype(pd.DatetimeIndex([1, 2, 3], tz="US/Eastern")) + True + + >>> dtype = DatetimeTZDtype("ns", tz="US/Eastern") + >>> s = pd.Series([], dtype=dtype) + >>> is_datetime64tz_dtype(dtype) + True + >>> is_datetime64tz_dtype(s) + True + """ + + if arr_or_dtype is None: + return False + return DatetimeTZDtype.is_dtype(arr_or_dtype) + + +def is_timedelta64_dtype(arr_or_dtype): + """ + Check whether an array-like or dtype is of the timedelta64 dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array-like or dtype to check. + + Returns + ------- + boolean : Whether or not the array-like or dtype is + of the timedelta64 dtype. + + Examples + -------- + >>> is_timedelta64_dtype(object) + False + >>> is_timedelta64_dtype(np.timedelta64) + True + >>> is_timedelta64_dtype([1, 2, 3]) + False + >>> is_timedelta64_dtype(pd.Series([], dtype="timedelta64[ns]")) + True + >>> is_timedelta64_dtype('0 days') + False + """ + + return _is_dtype_type(arr_or_dtype, classes(np.timedelta64)) + + +def is_period_dtype(arr_or_dtype): + """ + Check whether an array-like or dtype is of the Period dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array-like or dtype to check. + + Returns + ------- + boolean : Whether or not the array-like or dtype is of the Period dtype. + + Examples + -------- + >>> is_period_dtype(object) + False + >>> is_period_dtype(PeriodDtype(freq="D")) + True + >>> is_period_dtype([1, 2, 3]) + False + >>> is_period_dtype(pd.Period("2017-01-01")) + False + >>> is_period_dtype(pd.PeriodIndex([], freq="A")) + True + """ + + # TODO: Consider making Period an instance of PeriodDtype + if arr_or_dtype is None: + return False + return PeriodDtype.is_dtype(arr_or_dtype) + + +def is_interval_dtype(arr_or_dtype): + """ + Check whether an array-like or dtype is of the Interval dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array-like or dtype to check. + + Returns + ------- + boolean : Whether or not the array-like or dtype is + of the Interval dtype. + + Examples + -------- + >>> is_interval_dtype(object) + False + >>> is_interval_dtype(IntervalDtype()) + True + >>> is_interval_dtype([1, 2, 3]) + False + >>> + >>> interval = pd.Interval(1, 2, closed="right") + >>> is_interval_dtype(interval) + False + >>> is_interval_dtype(pd.IntervalIndex([interval])) + True + """ + + # TODO: Consider making Interval an instance of IntervalDtype + if arr_or_dtype is None: + return False + return IntervalDtype.is_dtype(arr_or_dtype) + + +def is_categorical_dtype(arr_or_dtype): + """ + Check whether an array-like or dtype is of the Categorical dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array-like or dtype to check. + + Returns + ------- + boolean : Whether or not the array-like or dtype is + of the Categorical dtype. + + Examples + -------- + >>> is_categorical_dtype(object) + False + >>> is_categorical_dtype(CategoricalDtype()) + True + >>> is_categorical_dtype([1, 2, 3]) + False + >>> is_categorical_dtype(pd.Categorical([1, 2, 3])) + True + >>> is_categorical_dtype(pd.CategoricalIndex([1, 2, 3])) + True + """ + + if arr_or_dtype is None: + return False + return CategoricalDtype.is_dtype(arr_or_dtype) + + +def is_string_dtype(arr_or_dtype): + """ + Check whether the provided array or dtype is of the string dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype is of the string dtype. + + Examples + -------- + >>> is_string_dtype(str) + True + >>> is_string_dtype(object) + True + >>> is_string_dtype(int) + False + >>> + >>> is_string_dtype(np.array(['a', 'b'])) + True + >>> is_string_dtype(pd.Series([1, 2])) + False + """ + + # TODO: gh-15585: consider making the checks stricter. + def condition(dtype): + return dtype.kind in ('O', 'S', 'U') and not is_period_dtype(dtype) + return _is_dtype(arr_or_dtype, condition) + + +def is_period_arraylike(arr): + """ + Check whether an array-like is a periodical array-like or PeriodIndex. + + Parameters + ---------- + arr : array-like + The array-like to check. + + Returns + ------- + boolean : Whether or not the array-like is a periodical + array-like or PeriodIndex instance. + + Examples + -------- + >>> is_period_arraylike([1, 2, 3]) + False + >>> is_period_arraylike(pd.Index([1, 2, 3])) + False + >>> is_period_arraylike(pd.PeriodIndex(["2017-01-01"], freq="D")) + True + """ + + if isinstance(arr, (ABCPeriodIndex, ABCPeriodArray)): + return True + elif isinstance(arr, (np.ndarray, ABCSeries)): + return is_period_dtype(arr.dtype) + return getattr(arr, 'inferred_type', None) == 'period' + + +def is_datetime_arraylike(arr): + """ + Check whether an array-like is a datetime array-like or DatetimeIndex. + + Parameters + ---------- + arr : array-like + The array-like to check. + + Returns + ------- + boolean : Whether or not the array-like is a datetime + array-like or DatetimeIndex. + + Examples + -------- + >>> is_datetime_arraylike([1, 2, 3]) + False + >>> is_datetime_arraylike(pd.Index([1, 2, 3])) + False + >>> is_datetime_arraylike(pd.DatetimeIndex([1, 2, 3])) + True + """ + + if isinstance(arr, ABCDatetimeIndex): + return True + elif isinstance(arr, (np.ndarray, ABCSeries)): + return (is_object_dtype(arr.dtype) + and lib.infer_dtype(arr, skipna=False) == 'datetime') + return getattr(arr, 'inferred_type', None) == 'datetime' + + +def is_datetimelike(arr): + """ + Check whether an array-like is a datetime-like array-like. + + Acceptable datetime-like objects are (but not limited to) datetime + indices, periodic indices, and timedelta indices. + + Parameters + ---------- + arr : array-like + The array-like to check. + + Returns + ------- + boolean : Whether or not the array-like is a datetime-like array-like. + + Examples + -------- + >>> is_datetimelike([1, 2, 3]) + False + >>> is_datetimelike(pd.Index([1, 2, 3])) + False + >>> is_datetimelike(pd.DatetimeIndex([1, 2, 3])) + True + >>> is_datetimelike(pd.DatetimeIndex([1, 2, 3], tz="US/Eastern")) + True + >>> is_datetimelike(pd.PeriodIndex([], freq="A")) + True + >>> is_datetimelike(np.array([], dtype=np.datetime64)) + True + >>> is_datetimelike(pd.Series([], dtype="timedelta64[ns]")) + True + >>> + >>> dtype = DatetimeTZDtype("ns", tz="US/Eastern") + >>> s = pd.Series([], dtype=dtype) + >>> is_datetimelike(s) + True + """ + + return (is_datetime64_dtype(arr) or is_datetime64tz_dtype(arr) or + is_timedelta64_dtype(arr) or + isinstance(arr, ABCPeriodIndex)) + + +def is_dtype_equal(source, target): + """ + Check if two dtypes are equal. + + Parameters + ---------- + source : The first dtype to compare + target : The second dtype to compare + + Returns + ---------- + boolean : Whether or not the two dtypes are equal. + + Examples + -------- + >>> is_dtype_equal(int, float) + False + >>> is_dtype_equal("int", int) + True + >>> is_dtype_equal(object, "category") + False + >>> is_dtype_equal(CategoricalDtype(), "category") + True + >>> is_dtype_equal(DatetimeTZDtype(), "datetime64") + False + """ + + try: + source = _get_dtype(source) + target = _get_dtype(target) + return source == target + except (TypeError, AttributeError): + + # invalid comparison + # object == category will hit this + return False + + +def is_dtype_union_equal(source, target): + """ + Check whether two arrays have compatible dtypes to do a union. + numpy types are checked with ``is_dtype_equal``. Extension types are + checked separately. + + Parameters + ---------- + source : The first dtype to compare + target : The second dtype to compare + + Returns + ---------- + boolean : Whether or not the two dtypes are equal. + + >>> is_dtype_equal("int", int) + True + + >>> is_dtype_equal(CategoricalDtype(['a', 'b'], + ... CategoricalDtype(['b', 'c'])) + True + + >>> is_dtype_equal(CategoricalDtype(['a', 'b'], + ... CategoricalDtype(['b', 'c'], ordered=True)) + False + """ + source = _get_dtype(source) + target = _get_dtype(target) + if is_categorical_dtype(source) and is_categorical_dtype(target): + # ordered False for both + return source.ordered is target.ordered + return is_dtype_equal(source, target) + + +def is_any_int_dtype(arr_or_dtype): + """Check whether the provided array or dtype is of an integer dtype. + + In this function, timedelta64 instances are also considered "any-integer" + type objects and will return True. + + This function is internal and should not be exposed in the public API. + + .. versionchanged:: 0.24.0 + + The nullable Integer dtypes (e.g. pandas.Int64Dtype) are also considered + as integer by this function. + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype is of an integer dtype. + + Examples + -------- + >>> is_any_int_dtype(str) + False + >>> is_any_int_dtype(int) + True + >>> is_any_int_dtype(float) + False + >>> is_any_int_dtype(np.uint64) + True + >>> is_any_int_dtype(np.datetime64) + False + >>> is_any_int_dtype(np.timedelta64) + True + >>> is_any_int_dtype(np.array(['a', 'b'])) + False + >>> is_any_int_dtype(pd.Series([1, 2])) + True + >>> is_any_int_dtype(np.array([], dtype=np.timedelta64)) + True + >>> is_any_int_dtype(pd.Index([1, 2.])) # float + False + """ + + return _is_dtype_type( + arr_or_dtype, classes(np.integer, np.timedelta64)) + + +def is_integer_dtype(arr_or_dtype): + """ + Check whether the provided array or dtype is of an integer dtype. + + Unlike in `in_any_int_dtype`, timedelta64 instances will return False. + + .. versionchanged:: 0.24.0 + + The nullable Integer dtypes (e.g. pandas.Int64Dtype) are also considered + as integer by this function. + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype is of an integer dtype + and not an instance of timedelta64. + + Examples + -------- + >>> is_integer_dtype(str) + False + >>> is_integer_dtype(int) + True + >>> is_integer_dtype(float) + False + >>> is_integer_dtype(np.uint64) + True + >>> is_integer_dtype('int8') + True + >>> is_integer_dtype('Int8') + True + >>> is_integer_dtype(pd.Int8Dtype) + True + >>> is_integer_dtype(np.datetime64) + False + >>> is_integer_dtype(np.timedelta64) + False + >>> is_integer_dtype(np.array(['a', 'b'])) + False + >>> is_integer_dtype(pd.Series([1, 2])) + True + >>> is_integer_dtype(np.array([], dtype=np.timedelta64)) + False + >>> is_integer_dtype(pd.Index([1, 2.])) # float + False + """ + + return _is_dtype_type( + arr_or_dtype, classes_and_not_datetimelike(np.integer)) + + +def is_signed_integer_dtype(arr_or_dtype): + """ + Check whether the provided array or dtype is of a signed integer dtype. + + Unlike in `in_any_int_dtype`, timedelta64 instances will return False. + + .. versionchanged:: 0.24.0 + + The nullable Integer dtypes (e.g. pandas.Int64Dtype) are also considered + as integer by this function. + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype is of a signed integer dtype + and not an instance of timedelta64. + + Examples + -------- + >>> is_signed_integer_dtype(str) + False + >>> is_signed_integer_dtype(int) + True + >>> is_signed_integer_dtype(float) + False + >>> is_signed_integer_dtype(np.uint64) # unsigned + False + >>> is_signed_integer_dtype('int8') + True + >>> is_signed_integer_dtype('Int8') + True + >>> is_signed_dtype(pd.Int8Dtype) + True + >>> is_signed_integer_dtype(np.datetime64) + False + >>> is_signed_integer_dtype(np.timedelta64) + False + >>> is_signed_integer_dtype(np.array(['a', 'b'])) + False + >>> is_signed_integer_dtype(pd.Series([1, 2])) + True + >>> is_signed_integer_dtype(np.array([], dtype=np.timedelta64)) + False + >>> is_signed_integer_dtype(pd.Index([1, 2.])) # float + False + >>> is_signed_integer_dtype(np.array([1, 2], dtype=np.uint32)) # unsigned + False + """ + + return _is_dtype_type( + arr_or_dtype, classes_and_not_datetimelike(np.signedinteger)) + + +def is_unsigned_integer_dtype(arr_or_dtype): + """ + Check whether the provided array or dtype is of an unsigned integer dtype. + + .. versionchanged:: 0.24.0 + + The nullable Integer dtypes (e.g. pandas.UInt64Dtype) are also + considered as integer by this function. + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype is of an + unsigned integer dtype. + + Examples + -------- + >>> is_unsigned_integer_dtype(str) + False + >>> is_unsigned_integer_dtype(int) # signed + False + >>> is_unsigned_integer_dtype(float) + False + >>> is_unsigned_integer_dtype(np.uint64) + True + >>> is_unsigned_integer_dtype('uint8') + True + >>> is_unsigned_integer_dtype('UInt8') + True + >>> is_unsigned_integer_dtype(pd.UInt8Dtype) + True + >>> is_unsigned_integer_dtype(np.array(['a', 'b'])) + False + >>> is_unsigned_integer_dtype(pd.Series([1, 2])) # signed + False + >>> is_unsigned_integer_dtype(pd.Index([1, 2.])) # float + False + >>> is_unsigned_integer_dtype(np.array([1, 2], dtype=np.uint32)) + True + """ + return _is_dtype_type( + arr_or_dtype, classes_and_not_datetimelike(np.unsignedinteger)) + + +def is_int64_dtype(arr_or_dtype): + """ + Check whether the provided array or dtype is of the int64 dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype is of the int64 dtype. + + Notes + ----- + Depending on system architecture, the return value of `is_int64_dtype( + int)` will be True if the OS uses 64-bit integers and False if the OS + uses 32-bit integers. + + Examples + -------- + >>> is_int64_dtype(str) + False + >>> is_int64_dtype(np.int32) + False + >>> is_int64_dtype(np.int64) + True + >>> is_int64_dtype('int8') + False + >>> is_int64_dtype('Int8') + False + >>> is_int64_dtype(pd.Int64Dtype) + True + >>> is_int64_dtype(float) + False + >>> is_int64_dtype(np.uint64) # unsigned + False + >>> is_int64_dtype(np.array(['a', 'b'])) + False + >>> is_int64_dtype(np.array([1, 2], dtype=np.int64)) + True + >>> is_int64_dtype(pd.Index([1, 2.])) # float + False + >>> is_int64_dtype(np.array([1, 2], dtype=np.uint32)) # unsigned + False + """ + + return _is_dtype_type(arr_or_dtype, classes(np.int64)) + + +def is_datetime64_any_dtype(arr_or_dtype): + """ + Check whether the provided array or dtype is of the datetime64 dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype is of the datetime64 dtype. + + Examples + -------- + >>> is_datetime64_any_dtype(str) + False + >>> is_datetime64_any_dtype(int) + False + >>> is_datetime64_any_dtype(np.datetime64) # can be tz-naive + True + >>> is_datetime64_any_dtype(DatetimeTZDtype("ns", "US/Eastern")) + True + >>> is_datetime64_any_dtype(np.array(['a', 'b'])) + False + >>> is_datetime64_any_dtype(np.array([1, 2])) + False + >>> is_datetime64_any_dtype(np.array([], dtype=np.datetime64)) + True + >>> is_datetime64_any_dtype(pd.DatetimeIndex([1, 2, 3], + dtype=np.datetime64)) + True + """ + + if arr_or_dtype is None: + return False + return (is_datetime64_dtype(arr_or_dtype) or + is_datetime64tz_dtype(arr_or_dtype)) + + +def is_datetime64_ns_dtype(arr_or_dtype): + """ + Check whether the provided array or dtype is of the datetime64[ns] dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype is of the datetime64[ns] dtype. + + Examples + -------- + >>> is_datetime64_ns_dtype(str) + False + >>> is_datetime64_ns_dtype(int) + False + >>> is_datetime64_ns_dtype(np.datetime64) # no unit + False + >>> is_datetime64_ns_dtype(DatetimeTZDtype("ns", "US/Eastern")) + True + >>> is_datetime64_ns_dtype(np.array(['a', 'b'])) + False + >>> is_datetime64_ns_dtype(np.array([1, 2])) + False + >>> is_datetime64_ns_dtype(np.array([], dtype=np.datetime64)) # no unit + False + >>> is_datetime64_ns_dtype(np.array([], + dtype="datetime64[ps]")) # wrong unit + False + >>> is_datetime64_ns_dtype(pd.DatetimeIndex([1, 2, 3], + dtype=np.datetime64)) # has 'ns' unit + True + """ + + if arr_or_dtype is None: + return False + try: + tipo = _get_dtype(arr_or_dtype) + except TypeError: + if is_datetime64tz_dtype(arr_or_dtype): + tipo = _get_dtype(arr_or_dtype.dtype) + else: + return False + return tipo == _NS_DTYPE or getattr(tipo, 'base', None) == _NS_DTYPE + + +def is_timedelta64_ns_dtype(arr_or_dtype): + """ + Check whether the provided array or dtype is of the timedelta64[ns] dtype. + + This is a very specific dtype, so generic ones like `np.timedelta64` + will return False if passed into this function. + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype is of the + timedelta64[ns] dtype. + + Examples + -------- + >>> is_timedelta64_ns_dtype(np.dtype('m8[ns]')) + True + >>> is_timedelta64_ns_dtype(np.dtype('m8[ps]')) # Wrong frequency + False + >>> is_timedelta64_ns_dtype(np.array([1, 2], dtype='m8[ns]')) + True + >>> is_timedelta64_ns_dtype(np.array([1, 2], dtype=np.timedelta64)) + False + """ + return _is_dtype(arr_or_dtype, lambda dtype: dtype == _TD_DTYPE) + + +def is_datetime_or_timedelta_dtype(arr_or_dtype): + """ + Check whether the provided array or dtype is of + a timedelta64 or datetime64 dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype is of a + timedelta64, or datetime64 dtype. + + Examples + -------- + >>> is_datetime_or_timedelta_dtype(str) + False + >>> is_datetime_or_timedelta_dtype(int) + False + >>> is_datetime_or_timedelta_dtype(np.datetime64) + True + >>> is_datetime_or_timedelta_dtype(np.timedelta64) + True + >>> is_datetime_or_timedelta_dtype(np.array(['a', 'b'])) + False + >>> is_datetime_or_timedelta_dtype(pd.Series([1, 2])) + False + >>> is_datetime_or_timedelta_dtype(np.array([], dtype=np.timedelta64)) + True + >>> is_datetime_or_timedelta_dtype(np.array([], dtype=np.datetime64)) + True + """ + + return _is_dtype_type( + arr_or_dtype, classes(np.datetime64, np.timedelta64)) + + +def _is_unorderable_exception(e): + """ + Check if the exception raised is an unorderable exception. + + The error message differs for 3 <= PY <= 3.5 and PY >= 3.6, so + we need to condition based on Python version. + + Parameters + ---------- + e : Exception or sub-class + The exception object to check. + + Returns + ------- + boolean : Whether or not the exception raised is an unorderable exception. + """ + + if PY36: + return "'>' not supported between instances of" in str(e) + + elif PY3: + return 'unorderable' in str(e) + return False + + +def is_numeric_v_string_like(a, b): + """ + Check if we are comparing a string-like object to a numeric ndarray. + + NumPy doesn't like to compare such objects, especially numeric arrays + and scalar string-likes. + + Parameters + ---------- + a : array-like, scalar + The first object to check. + b : array-like, scalar + The second object to check. + + Returns + ------- + boolean : Whether we return a comparing a string-like + object to a numeric array. + + Examples + -------- + >>> is_numeric_v_string_like(1, 1) + False + >>> is_numeric_v_string_like("foo", "foo") + False + >>> is_numeric_v_string_like(1, "foo") # non-array numeric + False + >>> is_numeric_v_string_like(np.array([1]), "foo") + True + >>> is_numeric_v_string_like("foo", np.array([1])) # symmetric check + True + >>> is_numeric_v_string_like(np.array([1, 2]), np.array(["foo"])) + True + >>> is_numeric_v_string_like(np.array(["foo"]), np.array([1, 2])) + True + >>> is_numeric_v_string_like(np.array([1]), np.array([2])) + False + >>> is_numeric_v_string_like(np.array(["foo"]), np.array(["foo"])) + False + """ + + is_a_array = isinstance(a, np.ndarray) + is_b_array = isinstance(b, np.ndarray) + + is_a_numeric_array = is_a_array and is_numeric_dtype(a) + is_b_numeric_array = is_b_array and is_numeric_dtype(b) + is_a_string_array = is_a_array and is_string_like_dtype(a) + is_b_string_array = is_b_array and is_string_like_dtype(b) + + is_a_scalar_string_like = not is_a_array and is_string_like(a) + is_b_scalar_string_like = not is_b_array and is_string_like(b) + + return ((is_a_numeric_array and is_b_scalar_string_like) or + (is_b_numeric_array and is_a_scalar_string_like) or + (is_a_numeric_array and is_b_string_array) or + (is_b_numeric_array and is_a_string_array)) + + +def is_datetimelike_v_numeric(a, b): + """ + Check if we are comparing a datetime-like object to a numeric object. + + By "numeric," we mean an object that is either of an int or float dtype. + + Parameters + ---------- + a : array-like, scalar + The first object to check. + b : array-like, scalar + The second object to check. + + Returns + ------- + boolean : Whether we return a comparing a datetime-like + to a numeric object. + + Examples + -------- + >>> dt = np.datetime64(pd.datetime(2017, 1, 1)) + >>> + >>> is_datetimelike_v_numeric(1, 1) + False + >>> is_datetimelike_v_numeric(dt, dt) + False + >>> is_datetimelike_v_numeric(1, dt) + True + >>> is_datetimelike_v_numeric(dt, 1) # symmetric check + True + >>> is_datetimelike_v_numeric(np.array([dt]), 1) + True + >>> is_datetimelike_v_numeric(np.array([1]), dt) + True + >>> is_datetimelike_v_numeric(np.array([dt]), np.array([1])) + True + >>> is_datetimelike_v_numeric(np.array([1]), np.array([2])) + False + >>> is_datetimelike_v_numeric(np.array([dt]), np.array([dt])) + False + """ + + if not hasattr(a, 'dtype'): + a = np.asarray(a) + if not hasattr(b, 'dtype'): + b = np.asarray(b) + + def is_numeric(x): + """ + Check if an object has a numeric dtype (i.e. integer or float). + """ + return is_integer_dtype(x) or is_float_dtype(x) + + is_datetimelike = needs_i8_conversion + return ((is_datetimelike(a) and is_numeric(b)) or + (is_datetimelike(b) and is_numeric(a))) + + +def is_datetimelike_v_object(a, b): + """ + Check if we are comparing a datetime-like object to an object instance. + + Parameters + ---------- + a : array-like, scalar + The first object to check. + b : array-like, scalar + The second object to check. + + Returns + ------- + boolean : Whether we return a comparing a datetime-like + to an object instance. + + Examples + -------- + >>> obj = object() + >>> dt = np.datetime64(pd.datetime(2017, 1, 1)) + >>> + >>> is_datetimelike_v_object(obj, obj) + False + >>> is_datetimelike_v_object(dt, dt) + False + >>> is_datetimelike_v_object(obj, dt) + True + >>> is_datetimelike_v_object(dt, obj) # symmetric check + True + >>> is_datetimelike_v_object(np.array([dt]), obj) + True + >>> is_datetimelike_v_object(np.array([obj]), dt) + True + >>> is_datetimelike_v_object(np.array([dt]), np.array([obj])) + True + >>> is_datetimelike_v_object(np.array([obj]), np.array([obj])) + False + >>> is_datetimelike_v_object(np.array([dt]), np.array([1])) + False + >>> is_datetimelike_v_object(np.array([dt]), np.array([dt])) + False + """ + + if not hasattr(a, 'dtype'): + a = np.asarray(a) + if not hasattr(b, 'dtype'): + b = np.asarray(b) + + is_datetimelike = needs_i8_conversion + return ((is_datetimelike(a) and is_object_dtype(b)) or + (is_datetimelike(b) and is_object_dtype(a))) + + +def needs_i8_conversion(arr_or_dtype): + """ + Check whether the array or dtype should be converted to int64. + + An array-like or dtype "needs" such a conversion if the array-like + or dtype is of a datetime-like dtype + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype should be converted to int64. + + Examples + -------- + >>> needs_i8_conversion(str) + False + >>> needs_i8_conversion(np.int64) + False + >>> needs_i8_conversion(np.datetime64) + True + >>> needs_i8_conversion(np.array(['a', 'b'])) + False + >>> needs_i8_conversion(pd.Series([1, 2])) + False + >>> needs_i8_conversion(pd.Series([], dtype="timedelta64[ns]")) + True + >>> needs_i8_conversion(pd.DatetimeIndex([1, 2, 3], tz="US/Eastern")) + True + """ + + if arr_or_dtype is None: + return False + return (is_datetime_or_timedelta_dtype(arr_or_dtype) or + is_datetime64tz_dtype(arr_or_dtype) or + is_period_dtype(arr_or_dtype)) + + +def is_numeric_dtype(arr_or_dtype): + """ + Check whether the provided array or dtype is of a numeric dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype is of a numeric dtype. + + Examples + -------- + >>> is_numeric_dtype(str) + False + >>> is_numeric_dtype(int) + True + >>> is_numeric_dtype(float) + True + >>> is_numeric_dtype(np.uint64) + True + >>> is_numeric_dtype(np.datetime64) + False + >>> is_numeric_dtype(np.timedelta64) + False + >>> is_numeric_dtype(np.array(['a', 'b'])) + False + >>> is_numeric_dtype(pd.Series([1, 2])) + True + >>> is_numeric_dtype(pd.Index([1, 2.])) + True + >>> is_numeric_dtype(np.array([], dtype=np.timedelta64)) + False + """ + + return _is_dtype_type( + arr_or_dtype, classes_and_not_datetimelike(np.number, np.bool_)) + + +def is_string_like_dtype(arr_or_dtype): + """ + Check whether the provided array or dtype is of a string-like dtype. + + Unlike `is_string_dtype`, the object dtype is excluded because it + is a mixed dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype is of the string dtype. + + Examples + -------- + >>> is_string_like_dtype(str) + True + >>> is_string_like_dtype(object) + False + >>> is_string_like_dtype(np.array(['a', 'b'])) + True + >>> is_string_like_dtype(pd.Series([1, 2])) + False + """ + + return _is_dtype( + arr_or_dtype, lambda dtype: dtype.kind in ('S', 'U')) + + +def is_float_dtype(arr_or_dtype): + """ + Check whether the provided array or dtype is of a float dtype. + + This function is internal and should not be exposed in the public API. + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype is of a float dtype. + + Examples + -------- + >>> is_float_dtype(str) + False + >>> is_float_dtype(int) + False + >>> is_float_dtype(float) + True + >>> is_float_dtype(np.array(['a', 'b'])) + False + >>> is_float_dtype(pd.Series([1, 2])) + False + >>> is_float_dtype(pd.Index([1, 2.])) + True + """ + return _is_dtype_type(arr_or_dtype, classes(np.floating)) + + +def is_bool_dtype(arr_or_dtype): + """ + Check whether the provided array or dtype is of a boolean dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype is of a boolean dtype. + + Notes + ----- + An ExtensionArray is considered boolean when the ``_is_boolean`` + attribute is set to True. + + Examples + -------- + >>> is_bool_dtype(str) + False + >>> is_bool_dtype(int) + False + >>> is_bool_dtype(bool) + True + >>> is_bool_dtype(np.bool) + True + >>> is_bool_dtype(np.array(['a', 'b'])) + False + >>> is_bool_dtype(pd.Series([1, 2])) + False + >>> is_bool_dtype(np.array([True, False])) + True + >>> is_bool_dtype(pd.Categorical([True, False])) + True + >>> is_bool_dtype(pd.SparseArray([True, False])) + True + """ + if arr_or_dtype is None: + return False + try: + dtype = _get_dtype(arr_or_dtype) + except TypeError: + return False + + if isinstance(arr_or_dtype, CategoricalDtype): + arr_or_dtype = arr_or_dtype.categories + # now we use the special definition for Index + + if isinstance(arr_or_dtype, ABCIndexClass): + + # TODO(jreback) + # we don't have a boolean Index class + # so its object, we need to infer to + # guess this + return (arr_or_dtype.is_object and + arr_or_dtype.inferred_type == 'boolean') + elif is_extension_array_dtype(arr_or_dtype): + dtype = getattr(arr_or_dtype, 'dtype', arr_or_dtype) + return dtype._is_boolean + + return issubclass(dtype.type, np.bool_) + + +def is_extension_type(arr): + """ + Check whether an array-like is of a pandas extension class instance. + + Extension classes include categoricals, pandas sparse objects (i.e. + classes represented within the pandas library and not ones external + to it like scipy sparse matrices), and datetime-like arrays. + + Parameters + ---------- + arr : array-like + The array-like to check. + + Returns + ------- + boolean : Whether or not the array-like is of a pandas + extension class instance. + + Examples + -------- + >>> is_extension_type([1, 2, 3]) + False + >>> is_extension_type(np.array([1, 2, 3])) + False + >>> + >>> cat = pd.Categorical([1, 2, 3]) + >>> + >>> is_extension_type(cat) + True + >>> is_extension_type(pd.Series(cat)) + True + >>> is_extension_type(pd.SparseArray([1, 2, 3])) + True + >>> is_extension_type(pd.SparseSeries([1, 2, 3])) + True + >>> + >>> from scipy.sparse import bsr_matrix + >>> is_extension_type(bsr_matrix([1, 2, 3])) + False + >>> is_extension_type(pd.DatetimeIndex([1, 2, 3])) + False + >>> is_extension_type(pd.DatetimeIndex([1, 2, 3], tz="US/Eastern")) + True + >>> + >>> dtype = DatetimeTZDtype("ns", tz="US/Eastern") + >>> s = pd.Series([], dtype=dtype) + >>> is_extension_type(s) + True + """ + + if is_categorical(arr): + return True + elif is_sparse(arr): + return True + elif is_datetime64tz_dtype(arr): + return True + return False + + +def is_extension_array_dtype(arr_or_dtype): + """ + Check if an object is a pandas extension array type. + + See the :ref:`Use Guide ` for more. + + Parameters + ---------- + arr_or_dtype : object + For array-like input, the ``.dtype`` attribute will + be extracted. + + Returns + ------- + bool + Whether the `arr_or_dtype` is an extension array type. + + Notes + ----- + This checks whether an object implements the pandas extension + array interface. In pandas, this includes: + + * Categorical + * Sparse + * Interval + * Period + * DatetimeArray + * TimedeltaArray + + Third-party libraries may implement arrays or types satisfying + this interface as well. + + Examples + -------- + >>> from pandas.api.types import is_extension_array_dtype + >>> arr = pd.Categorical(['a', 'b']) + >>> is_extension_array_dtype(arr) + True + >>> is_extension_array_dtype(arr.dtype) + True + + >>> arr = np.array(['a', 'b']) + >>> is_extension_array_dtype(arr.dtype) + False + """ + dtype = getattr(arr_or_dtype, 'dtype', arr_or_dtype) + return (isinstance(dtype, ExtensionDtype) or + registry.find(dtype) is not None) + + +def is_complex_dtype(arr_or_dtype): + """ + Check whether the provided array or dtype is of a complex dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array or dtype to check. + + Returns + ------- + boolean : Whether or not the array or dtype is of a compex dtype. + + Examples + -------- + >>> is_complex_dtype(str) + False + >>> is_complex_dtype(int) + False + >>> is_complex_dtype(np.complex) + True + >>> is_complex_dtype(np.array(['a', 'b'])) + False + >>> is_complex_dtype(pd.Series([1, 2])) + False + >>> is_complex_dtype(np.array([1 + 1j, 5])) + True + """ + + return _is_dtype_type(arr_or_dtype, classes(np.complexfloating)) + + +def _is_dtype(arr_or_dtype, condition): + """ + Return a boolean if the condition is satisfied for the arr_or_dtype. + + Parameters + ---------- + arr_or_dtype : array-like, str, np.dtype, or ExtensionArrayType + The array-like or dtype object whose dtype we want to extract. + condition : callable[Union[np.dtype, ExtensionDtype]] + + Returns + ------- + bool + + """ + + if arr_or_dtype is None: + return False + try: + dtype = _get_dtype(arr_or_dtype) + except (TypeError, ValueError, UnicodeEncodeError): + return False + return condition(dtype) + + +def _get_dtype(arr_or_dtype): + """ + Get the dtype instance associated with an array + or dtype object. + + Parameters + ---------- + arr_or_dtype : array-like + The array-like or dtype object whose dtype we want to extract. + + Returns + ------- + obj_dtype : The extract dtype instance from the + passed in array or dtype object. + + Raises + ------ + TypeError : The passed in object is None. + """ + + if arr_or_dtype is None: + raise TypeError("Cannot deduce dtype from null object") + + # fastpath + elif isinstance(arr_or_dtype, np.dtype): + return arr_or_dtype + elif isinstance(arr_or_dtype, type): + return np.dtype(arr_or_dtype) + + # if we have an array-like + elif hasattr(arr_or_dtype, 'dtype'): + arr_or_dtype = arr_or_dtype.dtype + + return pandas_dtype(arr_or_dtype) + + +def _is_dtype_type(arr_or_dtype, condition): + """ + Return a boolean if the condition is satisfied for the arr_or_dtype. + + Parameters + ---------- + arr_or_dtype : array-like + The array-like or dtype object whose dtype we want to extract. + condition : callable[Union[np.dtype, ExtensionDtypeType]] + + Returns + ------- + bool : if the condition is satisifed for the arr_or_dtype + """ + + if arr_or_dtype is None: + return condition(type(None)) + + # fastpath + if isinstance(arr_or_dtype, np.dtype): + return condition(arr_or_dtype.type) + elif isinstance(arr_or_dtype, type): + if issubclass(arr_or_dtype, (PandasExtensionDtype, ExtensionDtype)): + arr_or_dtype = arr_or_dtype.type + return condition(np.dtype(arr_or_dtype).type) + elif arr_or_dtype is None: + return condition(type(None)) + + # if we have an array-like + if hasattr(arr_or_dtype, 'dtype'): + arr_or_dtype = arr_or_dtype.dtype + + # we are not possibly a dtype + elif is_list_like(arr_or_dtype): + return condition(type(None)) + + try: + tipo = pandas_dtype(arr_or_dtype).type + except (TypeError, ValueError, UnicodeEncodeError): + if is_scalar(arr_or_dtype): + return condition(type(None)) + + return False + + return condition(tipo) + + +def infer_dtype_from_object(dtype): + """ + Get a numpy dtype.type-style object for a dtype object. + + This methods also includes handling of the datetime64[ns] and + datetime64[ns, TZ] objects. + + If no dtype can be found, we return ``object``. + + Parameters + ---------- + dtype : dtype, type + The dtype object whose numpy dtype.type-style + object we want to extract. + + Returns + ------- + dtype_object : The extracted numpy dtype.type-style object. + """ + + if isinstance(dtype, type) and issubclass(dtype, np.generic): + # Type object from a dtype + return dtype + elif isinstance(dtype, (np.dtype, PandasExtensionDtype, ExtensionDtype)): + # dtype object + try: + _validate_date_like_dtype(dtype) + except TypeError: + # Should still pass if we don't have a date-like + pass + return dtype.type + + try: + dtype = pandas_dtype(dtype) + except TypeError: + pass + + if is_extension_array_dtype(dtype): + return dtype.type + elif isinstance(dtype, string_types): + + # TODO(jreback) + # should deprecate these + if dtype in ['datetimetz', 'datetime64tz']: + return DatetimeTZDtype.type + elif dtype in ['period']: + raise NotImplementedError + + if dtype == 'datetime' or dtype == 'timedelta': + dtype += '64' + try: + return infer_dtype_from_object(getattr(np, dtype)) + except (AttributeError, TypeError): + # Handles cases like _get_dtype(int) i.e., + # Python objects that are valid dtypes + # (unlike user-defined types, in general) + # + # TypeError handles the float16 type code of 'e' + # further handle internal types + pass + + return infer_dtype_from_object(np.dtype(dtype)) + + +def _validate_date_like_dtype(dtype): + """ + Check whether the dtype is a date-like dtype. Raises an error if invalid. + + Parameters + ---------- + dtype : dtype, type + The dtype to check. + + Raises + ------ + TypeError : The dtype could not be casted to a date-like dtype. + ValueError : The dtype is an illegal date-like dtype (e.g. the + the frequency provided is too specific) + """ + + try: + typ = np.datetime_data(dtype)[0] + except ValueError as e: + raise TypeError('{error}'.format(error=e)) + if typ != 'generic' and typ != 'ns': + msg = '{name!r} is too specific of a frequency, try passing {type!r}' + raise ValueError(msg.format(name=dtype.name, type=dtype.type.__name__)) + + +def pandas_dtype(dtype): + """ + Converts input into a pandas only dtype object or a numpy dtype object. + + Parameters + ---------- + dtype : object to be converted + + Returns + ------- + np.dtype or a pandas dtype + + Raises + ------ + TypeError if not a dtype + """ + # short-circuit + if isinstance(dtype, np.ndarray): + return dtype.dtype + elif isinstance(dtype, (np.dtype, PandasExtensionDtype, ExtensionDtype)): + return dtype + + # registered extension types + result = registry.find(dtype) + if result is not None: + return result + + # try a numpy dtype + # raise a consistent TypeError if failed + try: + npdtype = np.dtype(dtype) + except Exception: + # we don't want to force a repr of the non-string + if not isinstance(dtype, string_types): + raise TypeError("data type not understood") + raise TypeError("data type '{}' not understood".format( + dtype)) + + # Any invalid dtype (such as pd.Timestamp) should raise an error. + # np.dtype(invalid_type).kind = 0 for such objects. However, this will + # also catch some valid dtypes such as object, np.object_ and 'object' + # which we safeguard against by catching them earlier and returning + # np.dtype(valid_dtype) before this condition is evaluated. + if is_hashable(dtype) and dtype in [object, np.object_, 'object', 'O']: + # check hashability to avoid errors/DeprecationWarning when we get + # here and `dtype` is an array + return npdtype + elif npdtype.kind == 'O': + raise TypeError("dtype '{}' not understood".format(dtype)) + + return npdtype diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/concat.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/concat.py new file mode 100644 index 0000000000000000000000000000000000000000..aada777decaa70f9a7a4a57fbd9a2752e922bd17 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/concat.py @@ -0,0 +1,583 @@ +""" +Utility functions related to concat +""" + +import numpy as np + +from pandas._libs import tslib, tslibs + +from pandas.core.dtypes.common import ( + _NS_DTYPE, _TD_DTYPE, is_bool_dtype, is_categorical_dtype, + is_datetime64_dtype, is_datetime64tz_dtype, is_dtype_equal, + is_extension_array_dtype, is_object_dtype, is_sparse, is_timedelta64_dtype) +from pandas.core.dtypes.generic import ( + ABCDatetimeArray, ABCDatetimeIndex, ABCIndexClass, ABCPeriodIndex, + ABCRangeIndex, ABCSparseDataFrame, ABCTimedeltaIndex) + +from pandas import compat + + +def get_dtype_kinds(l): + """ + Parameters + ---------- + l : list of arrays + + Returns + ------- + a set of kinds that exist in this list of arrays + """ + + typs = set() + for arr in l: + + dtype = arr.dtype + if is_categorical_dtype(dtype): + typ = 'category' + elif is_sparse(arr): + typ = 'sparse' + elif isinstance(arr, ABCRangeIndex): + typ = 'range' + elif is_datetime64tz_dtype(arr): + # if to_concat contains different tz, + # the result must be object dtype + typ = str(arr.dtype) + elif is_datetime64_dtype(dtype): + typ = 'datetime' + elif is_timedelta64_dtype(dtype): + typ = 'timedelta' + elif is_object_dtype(dtype): + typ = 'object' + elif is_bool_dtype(dtype): + typ = 'bool' + elif is_extension_array_dtype(dtype): + typ = str(arr.dtype) + else: + typ = dtype.kind + typs.add(typ) + return typs + + +def _get_series_result_type(result, objs=None): + """ + return appropriate class of Series concat + input is either dict or array-like + """ + from pandas import SparseSeries, SparseDataFrame, DataFrame + + # concat Series with axis 1 + if isinstance(result, dict): + # concat Series with axis 1 + if all(isinstance(c, (SparseSeries, SparseDataFrame)) + for c in compat.itervalues(result)): + return SparseDataFrame + else: + return DataFrame + + # otherwise it is a SingleBlockManager (axis = 0) + if result._block.is_sparse: + return SparseSeries + else: + return objs[0]._constructor + + +def _get_frame_result_type(result, objs): + """ + return appropriate class of DataFrame-like concat + if all blocks are sparse, return SparseDataFrame + otherwise, return 1st obj + """ + + if (result.blocks and ( + all(is_sparse(b) for b in result.blocks) or + all(isinstance(obj, ABCSparseDataFrame) for obj in objs))): + from pandas.core.sparse.api import SparseDataFrame + return SparseDataFrame + else: + return next(obj for obj in objs if not isinstance(obj, + ABCSparseDataFrame)) + + +def _concat_compat(to_concat, axis=0): + """ + provide concatenation of an array of arrays each of which is a single + 'normalized' dtypes (in that for example, if it's object, then it is a + non-datetimelike and provide a combined dtype for the resulting array that + preserves the overall dtype if possible) + + Parameters + ---------- + to_concat : array of arrays + axis : axis to provide concatenation + + Returns + ------- + a single array, preserving the combined dtypes + """ + + # filter empty arrays + # 1-d dtypes always are included here + def is_nonempty(x): + try: + return x.shape[axis] > 0 + except Exception: + return True + + nonempty = [x for x in to_concat if is_nonempty(x)] + + # If all arrays are empty, there's nothing to convert, just short-cut to + # the concatenation, #3121. + # + # Creating an empty array directly is tempting, but the winnings would be + # marginal given that it would still require shape & dtype calculation and + # np.concatenate which has them both implemented is compiled. + + typs = get_dtype_kinds(to_concat) + _contains_datetime = any(typ.startswith('datetime') for typ in typs) + _contains_period = any(typ.startswith('period') for typ in typs) + + if 'category' in typs: + # this must be priort to _concat_datetime, + # to support Categorical + datetime-like + return _concat_categorical(to_concat, axis=axis) + + elif _contains_datetime or 'timedelta' in typs or _contains_period: + return _concat_datetime(to_concat, axis=axis, typs=typs) + + # these are mandated to handle empties as well + elif 'sparse' in typs: + return _concat_sparse(to_concat, axis=axis, typs=typs) + + extensions = [is_extension_array_dtype(x) for x in to_concat] + if any(extensions) and axis == 1: + to_concat = [np.atleast_2d(x.astype('object')) for x in to_concat] + + if not nonempty: + # we have all empties, but may need to coerce the result dtype to + # object if we have non-numeric type operands (numpy would otherwise + # cast this to float) + typs = get_dtype_kinds(to_concat) + if len(typs) != 1: + + if (not len(typs - {'i', 'u', 'f'}) or + not len(typs - {'bool', 'i', 'u'})): + # let numpy coerce + pass + else: + # coerce to object + to_concat = [x.astype('object') for x in to_concat] + + return np.concatenate(to_concat, axis=axis) + + +def _concat_categorical(to_concat, axis=0): + """Concatenate an object/categorical array of arrays, each of which is a + single dtype + + Parameters + ---------- + to_concat : array of arrays + axis : int + Axis to provide concatenation in the current implementation this is + always 0, e.g. we only have 1D categoricals + + Returns + ------- + Categorical + A single array, preserving the combined dtypes + """ + + # we could have object blocks and categoricals here + # if we only have a single categoricals then combine everything + # else its a non-compat categorical + categoricals = [x for x in to_concat if is_categorical_dtype(x.dtype)] + + # validate the categories + if len(categoricals) != len(to_concat): + pass + else: + # when all categories are identical + first = to_concat[0] + if all(first.is_dtype_equal(other) for other in to_concat[1:]): + return union_categoricals(categoricals) + + # extract the categoricals & coerce to object if needed + to_concat = [x.get_values() if is_categorical_dtype(x.dtype) + else np.asarray(x).ravel() if not is_datetime64tz_dtype(x) + else np.asarray(x.astype(object)) for x in to_concat] + result = _concat_compat(to_concat) + if axis == 1: + result = result.reshape(1, len(result)) + return result + + +def union_categoricals(to_union, sort_categories=False, ignore_order=False): + """ + Combine list-like of Categorical-like, unioning categories. All + categories must have the same dtype. + + .. versionadded:: 0.19.0 + + Parameters + ---------- + to_union : list-like of Categorical, CategoricalIndex, + or Series with dtype='category' + sort_categories : boolean, default False + If true, resulting categories will be lexsorted, otherwise + they will be ordered as they appear in the data. + ignore_order : boolean, default False + If true, the ordered attribute of the Categoricals will be ignored. + Results in an unordered categorical. + + .. versionadded:: 0.20.0 + + Returns + ------- + result : Categorical + + Raises + ------ + TypeError + - all inputs do not have the same dtype + - all inputs do not have the same ordered property + - all inputs are ordered and their categories are not identical + - sort_categories=True and Categoricals are ordered + ValueError + Empty list of categoricals passed + + Notes + ----- + + To learn more about categories, see `link + `__ + + Examples + -------- + + >>> from pandas.api.types import union_categoricals + + If you want to combine categoricals that do not necessarily have + the same categories, `union_categoricals` will combine a list-like + of categoricals. The new categories will be the union of the + categories being combined. + + >>> a = pd.Categorical(["b", "c"]) + >>> b = pd.Categorical(["a", "b"]) + >>> union_categoricals([a, b]) + [b, c, a, b] + Categories (3, object): [b, c, a] + + By default, the resulting categories will be ordered as they appear + in the `categories` of the data. If you want the categories to be + lexsorted, use `sort_categories=True` argument. + + >>> union_categoricals([a, b], sort_categories=True) + [b, c, a, b] + Categories (3, object): [a, b, c] + + `union_categoricals` also works with the case of combining two + categoricals of the same categories and order information (e.g. what + you could also `append` for). + + >>> a = pd.Categorical(["a", "b"], ordered=True) + >>> b = pd.Categorical(["a", "b", "a"], ordered=True) + >>> union_categoricals([a, b]) + [a, b, a, b, a] + Categories (2, object): [a < b] + + Raises `TypeError` because the categories are ordered and not identical. + + >>> a = pd.Categorical(["a", "b"], ordered=True) + >>> b = pd.Categorical(["a", "b", "c"], ordered=True) + >>> union_categoricals([a, b]) + TypeError: to union ordered Categoricals, all categories must be the same + + New in version 0.20.0 + + Ordered categoricals with different categories or orderings can be + combined by using the `ignore_ordered=True` argument. + + >>> a = pd.Categorical(["a", "b", "c"], ordered=True) + >>> b = pd.Categorical(["c", "b", "a"], ordered=True) + >>> union_categoricals([a, b], ignore_order=True) + [a, b, c, c, b, a] + Categories (3, object): [a, b, c] + + `union_categoricals` also works with a `CategoricalIndex`, or `Series` + containing categorical data, but note that the resulting array will + always be a plain `Categorical` + + >>> a = pd.Series(["b", "c"], dtype='category') + >>> b = pd.Series(["a", "b"], dtype='category') + >>> union_categoricals([a, b]) + [b, c, a, b] + Categories (3, object): [b, c, a] + """ + from pandas import Index, Categorical, CategoricalIndex, Series + from pandas.core.arrays.categorical import _recode_for_categories + + if len(to_union) == 0: + raise ValueError('No Categoricals to union') + + def _maybe_unwrap(x): + if isinstance(x, (CategoricalIndex, Series)): + return x.values + elif isinstance(x, Categorical): + return x + else: + raise TypeError("all components to combine must be Categorical") + + to_union = [_maybe_unwrap(x) for x in to_union] + first = to_union[0] + + if not all(is_dtype_equal(other.categories.dtype, first.categories.dtype) + for other in to_union[1:]): + raise TypeError("dtype of categories must be the same") + + ordered = False + if all(first.is_dtype_equal(other) for other in to_union[1:]): + # identical categories - fastpath + categories = first.categories + ordered = first.ordered + + if all(first.categories.equals(other.categories) + for other in to_union[1:]): + new_codes = np.concatenate([c.codes for c in to_union]) + else: + codes = [first.codes] + [_recode_for_categories(other.codes, + other.categories, + first.categories) + for other in to_union[1:]] + new_codes = np.concatenate(codes) + + if sort_categories and not ignore_order and ordered: + raise TypeError("Cannot use sort_categories=True with " + "ordered Categoricals") + + if sort_categories and not categories.is_monotonic_increasing: + categories = categories.sort_values() + indexer = categories.get_indexer(first.categories) + + from pandas.core.algorithms import take_1d + new_codes = take_1d(indexer, new_codes, fill_value=-1) + elif ignore_order or all(not c.ordered for c in to_union): + # different categories - union and recode + cats = first.categories.append([c.categories for c in to_union[1:]]) + categories = Index(cats.unique()) + if sort_categories: + categories = categories.sort_values() + + new_codes = [_recode_for_categories(c.codes, c.categories, categories) + for c in to_union] + new_codes = np.concatenate(new_codes) + else: + # ordered - to show a proper error message + if all(c.ordered for c in to_union): + msg = ("to union ordered Categoricals, " + "all categories must be the same") + raise TypeError(msg) + else: + raise TypeError('Categorical.ordered must be the same') + + if ignore_order: + ordered = False + + return Categorical(new_codes, categories=categories, ordered=ordered, + fastpath=True) + + +def _concatenate_2d(to_concat, axis): + # coerce to 2d if needed & concatenate + if axis == 1: + to_concat = [np.atleast_2d(x) for x in to_concat] + return np.concatenate(to_concat, axis=axis) + + +def _concat_datetime(to_concat, axis=0, typs=None): + """ + provide concatenation of an datetimelike array of arrays each of which is a + single M8[ns], datetimet64[ns, tz] or m8[ns] dtype + + Parameters + ---------- + to_concat : array of arrays + axis : axis to provide concatenation + typs : set of to_concat dtypes + + Returns + ------- + a single array, preserving the combined dtypes + """ + + if typs is None: + typs = get_dtype_kinds(to_concat) + + # multiple types, need to coerce to object + if len(typs) != 1: + return _concatenate_2d([_convert_datetimelike_to_object(x) + for x in to_concat], + axis=axis) + + # must be single dtype + if any(typ.startswith('datetime') for typ in typs): + + if 'datetime' in typs: + to_concat = [x.astype(np.int64, copy=False) for x in to_concat] + return _concatenate_2d(to_concat, axis=axis).view(_NS_DTYPE) + else: + # when to_concat has different tz, len(typs) > 1. + # thus no need to care + return _concat_datetimetz(to_concat) + + elif 'timedelta' in typs: + return _concatenate_2d([x.view(np.int64) for x in to_concat], + axis=axis).view(_TD_DTYPE) + + elif any(typ.startswith('period') for typ in typs): + assert len(typs) == 1 + cls = to_concat[0] + new_values = cls._concat_same_type(to_concat) + return new_values + + +def _convert_datetimelike_to_object(x): + # coerce datetimelike array to object dtype + + # if dtype is of datetimetz or timezone + if x.dtype.kind == _NS_DTYPE.kind: + if getattr(x, 'tz', None) is not None: + x = np.asarray(x.astype(object)) + else: + shape = x.shape + x = tslib.ints_to_pydatetime(x.view(np.int64).ravel(), + box="timestamp") + x = x.reshape(shape) + + elif x.dtype == _TD_DTYPE: + shape = x.shape + x = tslibs.ints_to_pytimedelta(x.view(np.int64).ravel(), box=True) + x = x.reshape(shape) + + return x + + +def _concat_datetimetz(to_concat, name=None): + """ + concat DatetimeIndex with the same tz + all inputs must be DatetimeIndex + it is used in DatetimeIndex.append also + """ + # Right now, internals will pass a List[DatetimeArray] here + # for reductions like quantile. I would like to disentangle + # all this before we get here. + sample = to_concat[0] + + if isinstance(sample, ABCIndexClass): + return sample._concat_same_dtype(to_concat, name=name) + elif isinstance(sample, ABCDatetimeArray): + return sample._concat_same_type(to_concat) + + +def _concat_index_same_dtype(indexes, klass=None): + klass = klass if klass is not None else indexes[0].__class__ + return klass(np.concatenate([x._values for x in indexes])) + + +def _concat_index_asobject(to_concat, name=None): + """ + concat all inputs as object. DatetimeIndex, TimedeltaIndex and + PeriodIndex are converted to object dtype before concatenation + """ + from pandas import Index + from pandas.core.arrays import ExtensionArray + + klasses = (ABCDatetimeIndex, ABCTimedeltaIndex, ABCPeriodIndex, + ExtensionArray) + to_concat = [x.astype(object) if isinstance(x, klasses) else x + for x in to_concat] + + self = to_concat[0] + attribs = self._get_attributes_dict() + attribs['name'] = name + + to_concat = [x._values if isinstance(x, Index) else x + for x in to_concat] + + return self._shallow_copy_with_infer(np.concatenate(to_concat), **attribs) + + +def _concat_sparse(to_concat, axis=0, typs=None): + """ + provide concatenation of an sparse/dense array of arrays each of which is a + single dtype + + Parameters + ---------- + to_concat : array of arrays + axis : axis to provide concatenation + typs : set of to_concat dtypes + + Returns + ------- + a single array, preserving the combined dtypes + """ + + from pandas.core.arrays import SparseArray + + fill_values = [x.fill_value for x in to_concat + if isinstance(x, SparseArray)] + fill_value = fill_values[0] + + # TODO: Fix join unit generation so we aren't passed this. + to_concat = [x if isinstance(x, SparseArray) + else SparseArray(x.squeeze(), fill_value=fill_value) + for x in to_concat] + + return SparseArray._concat_same_type(to_concat) + + +def _concat_rangeindex_same_dtype(indexes): + """ + Concatenates multiple RangeIndex instances. All members of "indexes" must + be of type RangeIndex; result will be RangeIndex if possible, Int64Index + otherwise. E.g.: + indexes = [RangeIndex(3), RangeIndex(3, 6)] -> RangeIndex(6) + indexes = [RangeIndex(3), RangeIndex(4, 6)] -> Int64Index([0,1,2,4,5]) + """ + from pandas import Int64Index, RangeIndex + + start = step = next = None + + # Filter the empty indexes + non_empty_indexes = [obj for obj in indexes if len(obj)] + + for obj in non_empty_indexes: + + if start is None: + # This is set by the first non-empty index + start = obj._start + if step is None and len(obj) > 1: + step = obj._step + elif step is None: + # First non-empty index had only one element + if obj._start == start: + return _concat_index_same_dtype(indexes, klass=Int64Index) + step = obj._start - start + + non_consecutive = ((step != obj._step and len(obj) > 1) or + (next is not None and obj._start != next)) + if non_consecutive: + return _concat_index_same_dtype(indexes, klass=Int64Index) + + if step is not None: + next = obj[-1] + step + + if non_empty_indexes: + # Get the stop value from "next" or alternatively + # from the last non-empty index + stop = non_empty_indexes[-1]._stop if next is None else next + return RangeIndex(start, stop, step) + + # Here all "indexes" had 0 length, i.e. were empty. + # In this case return an empty range index. + return RangeIndex(0, 0) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/dtypes.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..b73f55329e25b9b17796a6ab4e3e7e7f1bbc4065 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/dtypes.py @@ -0,0 +1,991 @@ +""" define extension dtypes """ +import re +import warnings + +import numpy as np +import pytz + +from pandas._libs.interval import Interval +from pandas._libs.tslibs import NaT, Period, Timestamp, timezones + +from pandas.core.dtypes.generic import ABCCategoricalIndex, ABCIndexClass + +from pandas import compat + +from .base import ExtensionDtype, _DtypeOpsMixin +from .inference import is_list_like + + +def register_extension_dtype(cls): + """Class decorator to register an ExtensionType with pandas. + + .. versionadded:: 0.24.0 + + This enables operations like ``.astype(name)`` for the name + of the ExtensionDtype. + + Examples + -------- + >>> from pandas.api.extensions import register_extension_dtype + >>> from pandas.api.extensions import ExtensionDtype + >>> @register_extension_dtype + ... class MyExtensionDtype(ExtensionDtype): + ... pass + """ + registry.register(cls) + return cls + + +class Registry(object): + """ + Registry for dtype inference + + The registry allows one to map a string repr of a extension + dtype to an extension dtype. The string alias can be used in several + places, including + + * Series and Index constructors + * :meth:`pandas.array` + * :meth:`pandas.Series.astype` + + Multiple extension types can be registered. + These are tried in order. + """ + def __init__(self): + self.dtypes = [] + + def register(self, dtype): + """ + Parameters + ---------- + dtype : ExtensionDtype + """ + if not issubclass(dtype, (PandasExtensionDtype, ExtensionDtype)): + raise ValueError("can only register pandas extension dtypes") + + self.dtypes.append(dtype) + + def find(self, dtype): + """ + Parameters + ---------- + dtype : PandasExtensionDtype or string + + Returns + ------- + return the first matching dtype, otherwise return None + """ + if not isinstance(dtype, compat.string_types): + dtype_type = dtype + if not isinstance(dtype, type): + dtype_type = type(dtype) + if issubclass(dtype_type, ExtensionDtype): + return dtype + + return None + + for dtype_type in self.dtypes: + try: + return dtype_type.construct_from_string(dtype) + except TypeError: + pass + + return None + + +registry = Registry() + + +class PandasExtensionDtype(_DtypeOpsMixin): + """ + A np.dtype duck-typed class, suitable for holding a custom dtype. + + THIS IS NOT A REAL NUMPY DTYPE + """ + type = None + subdtype = None + kind = None + str = None + num = 100 + shape = tuple() + itemsize = 8 + base = None + isbuiltin = 0 + isnative = 0 + _cache = {} + + def __unicode__(self): + return self.name + + def __str__(self): + """ + Return a string representation for a particular Object + + Invoked by str(df) in both py2/py3. + Yields Bytestring in Py2, Unicode String in py3. + """ + + if compat.PY3: + return self.__unicode__() + return self.__bytes__() + + def __bytes__(self): + """ + Return a string representation for a particular object. + + Invoked by bytes(obj) in py3 only. + Yields a bytestring in both py2/py3. + """ + from pandas.core.config import get_option + + encoding = get_option("display.encoding") + return self.__unicode__().encode(encoding, 'replace') + + def __repr__(self): + """ + Return a string representation for a particular object. + + Yields Bytestring in Py2, Unicode String in py3. + """ + return str(self) + + def __hash__(self): + raise NotImplementedError("sub-classes should implement an __hash__ " + "method") + + def __getstate__(self): + # pickle support; we don't want to pickle the cache + return {k: getattr(self, k, None) for k in self._metadata} + + @classmethod + def reset_cache(cls): + """ clear the cache """ + cls._cache = {} + + +class CategoricalDtypeType(type): + """ + the type of CategoricalDtype, this metaclass determines subclass ability + """ + pass + + +@register_extension_dtype +class CategoricalDtype(PandasExtensionDtype, ExtensionDtype): + """ + Type for categorical data with the categories and orderedness + + .. versionchanged:: 0.21.0 + + Parameters + ---------- + categories : sequence, optional + Must be unique, and must not contain any nulls. + ordered : bool, default False + + Attributes + ---------- + categories + ordered + + Methods + ------- + None + + See Also + -------- + pandas.Categorical + + Notes + ----- + This class is useful for specifying the type of a ``Categorical`` + independent of the values. See :ref:`categorical.categoricaldtype` + for more. + + Examples + -------- + >>> t = pd.CategoricalDtype(categories=['b', 'a'], ordered=True) + >>> pd.Series(['a', 'b', 'a', 'c'], dtype=t) + 0 a + 1 b + 2 a + 3 NaN + dtype: category + Categories (2, object): [b < a] + """ + # TODO: Document public vs. private API + name = 'category' + type = CategoricalDtypeType + kind = 'O' + str = '|O08' + base = np.dtype('O') + _metadata = ('categories', 'ordered') + _cache = {} + + def __init__(self, categories=None, ordered=None): + self._finalize(categories, ordered, fastpath=False) + + @classmethod + def _from_fastpath(cls, categories=None, ordered=None): + self = cls.__new__(cls) + self._finalize(categories, ordered, fastpath=True) + return self + + @classmethod + def _from_categorical_dtype(cls, dtype, categories=None, ordered=None): + if categories is ordered is None: + return dtype + if categories is None: + categories = dtype.categories + if ordered is None: + ordered = dtype.ordered + return cls(categories, ordered) + + @classmethod + def _from_values_or_dtype(cls, values=None, categories=None, ordered=None, + dtype=None): + """ + Construct dtype from the input parameters used in :class:`Categorical`. + + This constructor method specifically does not do the factorization + step, if that is needed to find the categories. This constructor may + therefore return ``CategoricalDtype(categories=None, ordered=None)``, + which may not be useful. Additional steps may therefore have to be + taken to create the final dtype. + + The return dtype is specified from the inputs in this prioritized + order: + 1. if dtype is a CategoricalDtype, return dtype + 2. if dtype is the string 'category', create a CategoricalDtype from + the supplied categories and ordered parameters, and return that. + 3. if values is a categorical, use value.dtype, but override it with + categories and ordered if either/both of those are not None. + 4. if dtype is None and values is not a categorical, construct the + dtype from categories and ordered, even if either of those is None. + + Parameters + ---------- + values : list-like, optional + The list-like must be 1-dimensional. + categories : list-like, optional + Categories for the CategoricalDtype. + ordered : bool, optional + Designating if the categories are ordered. + dtype : CategoricalDtype or the string "category", optional + If ``CategoricalDtype``, cannot be used together with + `categories` or `ordered`. + + Returns + ------- + CategoricalDtype + + Examples + -------- + >>> CategoricalDtype._from_values_or_dtype() + CategoricalDtype(categories=None, ordered=None) + >>> CategoricalDtype._from_values_or_dtype(categories=['a', 'b'], + ... ordered=True) + CategoricalDtype(categories=['a', 'b'], ordered=True) + >>> dtype1 = CategoricalDtype(['a', 'b'], ordered=True) + >>> dtype2 = CategoricalDtype(['x', 'y'], ordered=False) + >>> c = Categorical([0, 1], dtype=dtype1, fastpath=True) + >>> CategoricalDtype._from_values_or_dtype(c, ['x', 'y'], ordered=True, + ... dtype=dtype2) + ValueError: Cannot specify `categories` or `ordered` together with + `dtype`. + + The supplied dtype takes precedence over values' dtype: + + >>> CategoricalDtype._from_values_or_dtype(c, dtype=dtype2) + CategoricalDtype(['x', 'y'], ordered=False) + """ + from pandas.core.dtypes.common import is_categorical + + if dtype is not None: + # The dtype argument takes precedence over values.dtype (if any) + if isinstance(dtype, compat.string_types): + if dtype == 'category': + dtype = CategoricalDtype(categories, ordered) + else: + msg = "Unknown dtype {dtype!r}" + raise ValueError(msg.format(dtype=dtype)) + elif categories is not None or ordered is not None: + raise ValueError("Cannot specify `categories` or `ordered` " + "together with `dtype`.") + elif is_categorical(values): + # If no "dtype" was passed, use the one from "values", but honor + # the "ordered" and "categories" arguments + dtype = values.dtype._from_categorical_dtype(values.dtype, + categories, ordered) + else: + # If dtype=None and values is not categorical, create a new dtype. + # Note: This could potentially have categories=None and + # ordered=None. + dtype = CategoricalDtype(categories, ordered) + + return dtype + + def _finalize(self, categories, ordered, fastpath=False): + + if ordered is not None: + self.validate_ordered(ordered) + + if categories is not None: + categories = self.validate_categories(categories, + fastpath=fastpath) + + self._categories = categories + self._ordered = ordered + + def __setstate__(self, state): + self._categories = state.pop('categories', None) + self._ordered = state.pop('ordered', False) + + def __hash__(self): + # _hash_categories returns a uint64, so use the negative + # space for when we have unknown categories to avoid a conflict + if self.categories is None: + if self.ordered: + return -1 + else: + return -2 + # We *do* want to include the real self.ordered here + return int(self._hash_categories(self.categories, self.ordered)) + + def __eq__(self, other): + """ + Rules for CDT equality: + 1) Any CDT is equal to the string 'category' + 2) Any CDT is equal to itself + 3) Any CDT is equal to a CDT with categories=None regardless of ordered + 4) A CDT with ordered=True is only equal to another CDT with + ordered=True and identical categories in the same order + 5) A CDT with ordered={False, None} is only equal to another CDT with + ordered={False, None} and identical categories, but same order is + not required. There is no distinction between False/None. + 6) Any other comparison returns False + """ + if isinstance(other, compat.string_types): + return other == self.name + elif other is self: + return True + elif not (hasattr(other, 'ordered') and hasattr(other, 'categories')): + return False + elif self.categories is None or other.categories is None: + # We're forced into a suboptimal corner thanks to math and + # backwards compatibility. We require that `CDT(...) == 'category'` + # for all CDTs **including** `CDT(None, ...)`. Therefore, *all* + # CDT(., .) = CDT(None, False) and *all* + # CDT(., .) = CDT(None, True). + return True + elif self.ordered or other.ordered: + # At least one has ordered=True; equal if both have ordered=True + # and the same values for categories in the same order. + return ((self.ordered == other.ordered) and + self.categories.equals(other.categories)) + else: + # Neither has ordered=True; equal if both have the same categories, + # but same order is not necessary. There is no distinction between + # ordered=False and ordered=None: CDT(., False) and CDT(., None) + # will be equal if they have the same categories. + return hash(self) == hash(other) + + def __repr__(self): + tpl = u'CategoricalDtype(categories={}ordered={})' + if self.categories is None: + data = u"None, " + else: + data = self.categories._format_data(name=self.__class__.__name__) + return tpl.format(data, self.ordered) + + @staticmethod + def _hash_categories(categories, ordered=True): + from pandas.core.util.hashing import ( + hash_array, _combine_hash_arrays, hash_tuples + ) + from pandas.core.dtypes.common import is_datetime64tz_dtype, _NS_DTYPE + + if len(categories) and isinstance(categories[0], tuple): + # assumes if any individual category is a tuple, then all our. ATM + # I don't really want to support just some of the categories being + # tuples. + categories = list(categories) # breaks if a np.array of categories + cat_array = hash_tuples(categories) + else: + if categories.dtype == 'O': + types = [type(x) for x in categories] + if not len(set(types)) == 1: + # TODO: hash_array doesn't handle mixed types. It casts + # everything to a str first, which means we treat + # {'1', '2'} the same as {'1', 2} + # find a better solution + hashed = hash((tuple(categories), ordered)) + return hashed + + if is_datetime64tz_dtype(categories.dtype): + # Avoid future warning. + categories = categories.astype(_NS_DTYPE) + + cat_array = hash_array(np.asarray(categories), categorize=False) + if ordered: + cat_array = np.vstack([ + cat_array, np.arange(len(cat_array), dtype=cat_array.dtype) + ]) + else: + cat_array = [cat_array] + hashed = _combine_hash_arrays(iter(cat_array), + num_items=len(cat_array)) + return np.bitwise_xor.reduce(hashed) + + @classmethod + def construct_array_type(cls): + """ + Return the array type associated with this dtype + + Returns + ------- + type + """ + from pandas import Categorical + return Categorical + + @classmethod + def construct_from_string(cls, string): + """ + attempt to construct this type from a string, raise a TypeError if + it's not possible """ + try: + if string == 'category': + return cls() + else: + raise TypeError("cannot construct a CategoricalDtype") + except AttributeError: + pass + + @staticmethod + def validate_ordered(ordered): + """ + Validates that we have a valid ordered parameter. If + it is not a boolean, a TypeError will be raised. + + Parameters + ---------- + ordered : object + The parameter to be verified. + + Raises + ------ + TypeError + If 'ordered' is not a boolean. + """ + from pandas.core.dtypes.common import is_bool + if not is_bool(ordered): + raise TypeError("'ordered' must either be 'True' or 'False'") + + @staticmethod + def validate_categories(categories, fastpath=False): + """ + Validates that we have good categories + + Parameters + ---------- + categories : array-like + fastpath : bool + Whether to skip nan and uniqueness checks + + Returns + ------- + categories : Index + """ + from pandas import Index + + if not fastpath and not is_list_like(categories): + msg = "Parameter 'categories' must be list-like, was {!r}" + raise TypeError(msg.format(categories)) + elif not isinstance(categories, ABCIndexClass): + categories = Index(categories, tupleize_cols=False) + + if not fastpath: + + if categories.hasnans: + raise ValueError('Categorial categories cannot be null') + + if not categories.is_unique: + raise ValueError('Categorical categories must be unique') + + if isinstance(categories, ABCCategoricalIndex): + categories = categories.categories + + return categories + + def update_dtype(self, dtype): + """ + Returns a CategoricalDtype with categories and ordered taken from dtype + if specified, otherwise falling back to self if unspecified + + Parameters + ---------- + dtype : CategoricalDtype + + Returns + ------- + new_dtype : CategoricalDtype + """ + if isinstance(dtype, compat.string_types) and dtype == 'category': + # dtype='category' should not change anything + return self + elif not self.is_dtype(dtype): + msg = ('a CategoricalDtype must be passed to perform an update, ' + 'got {dtype!r}').format(dtype=dtype) + raise ValueError(msg) + elif dtype.categories is not None and dtype.ordered is self.ordered: + return dtype + + # dtype is CDT: keep current categories/ordered if None + new_categories = dtype.categories + if new_categories is None: + new_categories = self.categories + + new_ordered = dtype.ordered + if new_ordered is None: + new_ordered = self.ordered + + return CategoricalDtype(new_categories, new_ordered) + + @property + def categories(self): + """ + An ``Index`` containing the unique categories allowed. + """ + return self._categories + + @property + def ordered(self): + """ + Whether the categories have an ordered relationship. + """ + return self._ordered + + @property + def _is_boolean(self): + from pandas.core.dtypes.common import is_bool_dtype + + return is_bool_dtype(self.categories) + + +@register_extension_dtype +class DatetimeTZDtype(PandasExtensionDtype, ExtensionDtype): + + """ + A np.dtype duck-typed class, suitable for holding a custom datetime with tz + dtype. + + THIS IS NOT A REAL NUMPY DTYPE, but essentially a sub-class of + np.datetime64[ns] + """ + type = Timestamp + kind = 'M' + str = '|M8[ns]' + num = 101 + base = np.dtype('M8[ns]') + na_value = NaT + _metadata = ('unit', 'tz') + _match = re.compile(r"(datetime64|M8)\[(?P.+), (?P.+)\]") + _cache = {} + + def __init__(self, unit="ns", tz=None): + """ + An ExtensionDtype for timezone-aware datetime data. + + Parameters + ---------- + unit : str, default "ns" + The precision of the datetime data. Currently limited + to ``"ns"``. + tz : str, int, or datetime.tzinfo + The timezone. + + Raises + ------ + pytz.UnknownTimeZoneError + When the requested timezone cannot be found. + + Examples + -------- + >>> pd.core.dtypes.dtypes.DatetimeTZDtype(tz='UTC') + datetime64[ns, UTC] + + >>> pd.core.dtypes.dtypes.DatetimeTZDtype(tz='dateutil/US/Central') + datetime64[ns, tzfile('/usr/share/zoneinfo/US/Central')] + """ + if isinstance(unit, DatetimeTZDtype): + unit, tz = unit.unit, unit.tz + + if unit != 'ns': + if isinstance(unit, compat.string_types) and tz is None: + # maybe a string like datetime64[ns, tz], which we support for + # now. + result = type(self).construct_from_string(unit) + unit = result.unit + tz = result.tz + msg = ( + "Passing a dtype alias like 'datetime64[ns, {tz}]' " + "to DatetimeTZDtype is deprecated. Use " + "'DatetimeTZDtype.construct_from_string()' instead." + ) + warnings.warn(msg.format(tz=tz), FutureWarning, stacklevel=2) + else: + raise ValueError("DatetimeTZDtype only supports ns units") + + if tz: + tz = timezones.maybe_get_tz(tz) + elif tz is not None: + raise pytz.UnknownTimeZoneError(tz) + elif tz is None: + raise TypeError("A 'tz' is required.") + + self._unit = unit + self._tz = tz + + @property + def unit(self): + """The precision of the datetime data.""" + return self._unit + + @property + def tz(self): + """The timezone.""" + return self._tz + + @classmethod + def construct_array_type(cls): + """ + Return the array type associated with this dtype + + Returns + ------- + type + """ + from pandas.core.arrays import DatetimeArray + return DatetimeArray + + @classmethod + def construct_from_string(cls, string): + """ + Construct a DatetimeTZDtype from a string. + + Parameters + ---------- + string : str + The string alias for this DatetimeTZDtype. + Should be formatted like ``datetime64[ns, ]``, + where ```` is the timezone name. + + Examples + -------- + >>> DatetimeTZDtype.construct_from_string('datetime64[ns, UTC]') + datetime64[ns, UTC] + """ + if isinstance(string, compat.string_types): + msg = "Could not construct DatetimeTZDtype from '{}'" + try: + match = cls._match.match(string) + if match: + d = match.groupdict() + return cls(unit=d['unit'], tz=d['tz']) + except Exception: + # TODO(py3): Change this pass to `raise TypeError(msg) from e` + pass + raise TypeError(msg.format(string)) + + raise TypeError("Could not construct DatetimeTZDtype") + + def __unicode__(self): + return "datetime64[{unit}, {tz}]".format(unit=self.unit, tz=self.tz) + + @property + def name(self): + """A string representation of the dtype.""" + return str(self) + + def __hash__(self): + # make myself hashable + # TODO: update this. + return hash(str(self)) + + def __eq__(self, other): + if isinstance(other, compat.string_types): + return other == self.name + + return (isinstance(other, DatetimeTZDtype) and + self.unit == other.unit and + str(self.tz) == str(other.tz)) + + def __setstate__(self, state): + # for pickle compat. + self._tz = state['tz'] + self._unit = state['unit'] + + +@register_extension_dtype +class PeriodDtype(ExtensionDtype, PandasExtensionDtype): + """ + A Period duck-typed class, suitable for holding a period with freq dtype. + + THIS IS NOT A REAL NUMPY DTYPE, but essentially a sub-class of np.int64. + """ + type = Period + kind = 'O' + str = '|O08' + base = np.dtype('O') + num = 102 + _metadata = ('freq',) + _match = re.compile(r"(P|p)eriod\[(?P.+)\]") + _cache = {} + + def __new__(cls, freq=None): + """ + Parameters + ---------- + freq : frequency + """ + + if isinstance(freq, PeriodDtype): + return freq + + elif freq is None: + # empty constructor for pickle compat + return object.__new__(cls) + + from pandas.tseries.offsets import DateOffset + if not isinstance(freq, DateOffset): + freq = cls._parse_dtype_strict(freq) + + try: + return cls._cache[freq.freqstr] + except KeyError: + u = object.__new__(cls) + u.freq = freq + cls._cache[freq.freqstr] = u + return u + + @classmethod + def _parse_dtype_strict(cls, freq): + if isinstance(freq, compat.string_types): + if freq.startswith('period[') or freq.startswith('Period['): + m = cls._match.search(freq) + if m is not None: + freq = m.group('freq') + from pandas.tseries.frequencies import to_offset + freq = to_offset(freq) + if freq is not None: + return freq + + raise ValueError("could not construct PeriodDtype") + + @classmethod + def construct_from_string(cls, string): + """ + Strict construction from a string, raise a TypeError if not + possible + """ + from pandas.tseries.offsets import DateOffset + + if (isinstance(string, compat.string_types) and + (string.startswith('period[') or + string.startswith('Period[')) or + isinstance(string, DateOffset)): + # do not parse string like U as period[U] + # avoid tuple to be regarded as freq + try: + return cls(freq=string) + except ValueError: + pass + raise TypeError("could not construct PeriodDtype") + + def __unicode__(self): + return compat.text_type(self.name) + + @property + def name(self): + return str("period[{freq}]".format(freq=self.freq.freqstr)) + + @property + def na_value(self): + return NaT + + def __hash__(self): + # make myself hashable + return hash(str(self)) + + def __eq__(self, other): + if isinstance(other, compat.string_types): + return other == self.name or other == self.name.title() + + return isinstance(other, PeriodDtype) and self.freq == other.freq + + @classmethod + def is_dtype(cls, dtype): + """ + Return a boolean if we if the passed type is an actual dtype that we + can match (via string or type) + """ + + if isinstance(dtype, compat.string_types): + # PeriodDtype can be instantiated from freq string like "U", + # but doesn't regard freq str like "U" as dtype. + if dtype.startswith('period[') or dtype.startswith('Period['): + try: + if cls._parse_dtype_strict(dtype) is not None: + return True + else: + return False + except ValueError: + return False + else: + return False + return super(PeriodDtype, cls).is_dtype(dtype) + + @classmethod + def construct_array_type(cls): + from pandas.core.arrays import PeriodArray + + return PeriodArray + + +@register_extension_dtype +class IntervalDtype(PandasExtensionDtype, ExtensionDtype): + """ + A Interval duck-typed class, suitable for holding an interval + + THIS IS NOT A REAL NUMPY DTYPE + """ + name = 'interval' + kind = None + str = '|O08' + base = np.dtype('O') + num = 103 + _metadata = ('subtype',) + _match = re.compile(r"(I|i)nterval\[(?P.+)\]") + _cache = {} + + def __new__(cls, subtype=None): + """ + Parameters + ---------- + subtype : the dtype of the Interval + """ + from pandas.core.dtypes.common import ( + is_categorical_dtype, is_string_dtype, pandas_dtype) + + if isinstance(subtype, IntervalDtype): + return subtype + elif subtype is None: + # we are called as an empty constructor + # generally for pickle compat + u = object.__new__(cls) + u.subtype = None + return u + elif (isinstance(subtype, compat.string_types) and + subtype.lower() == 'interval'): + subtype = None + else: + if isinstance(subtype, compat.string_types): + m = cls._match.search(subtype) + if m is not None: + subtype = m.group('subtype') + + try: + subtype = pandas_dtype(subtype) + except TypeError: + raise TypeError("could not construct IntervalDtype") + + if is_categorical_dtype(subtype) or is_string_dtype(subtype): + # GH 19016 + msg = ('category, object, and string subtypes are not supported ' + 'for IntervalDtype') + raise TypeError(msg) + + try: + return cls._cache[str(subtype)] + except KeyError: + u = object.__new__(cls) + u.subtype = subtype + cls._cache[str(subtype)] = u + return u + + @classmethod + def construct_array_type(cls): + """ + Return the array type associated with this dtype + + Returns + ------- + type + """ + from pandas.core.arrays import IntervalArray + return IntervalArray + + @classmethod + def construct_from_string(cls, string): + """ + attempt to construct this type from a string, raise a TypeError + if its not possible + """ + if not isinstance(string, compat.string_types): + msg = "a string needs to be passed, got type {typ}" + raise TypeError(msg.format(typ=type(string))) + + if (string.lower() == 'interval' or + cls._match.search(string) is not None): + return cls(string) + + msg = ('Incorrectly formatted string passed to constructor. ' + 'Valid formats include Interval or Interval[dtype] ' + 'where dtype is numeric, datetime, or timedelta') + raise TypeError(msg) + + @property + def type(self): + return Interval + + def __unicode__(self): + if self.subtype is None: + return "interval" + return "interval[{subtype}]".format(subtype=self.subtype) + + def __hash__(self): + # make myself hashable + return hash(str(self)) + + def __eq__(self, other): + if isinstance(other, compat.string_types): + return other.lower() in (self.name.lower(), str(self).lower()) + elif not isinstance(other, IntervalDtype): + return False + elif self.subtype is None or other.subtype is None: + # None should match any subtype + return True + else: + from pandas.core.dtypes.common import is_dtype_equal + return is_dtype_equal(self.subtype, other.subtype) + + @classmethod + def is_dtype(cls, dtype): + """ + Return a boolean if we if the passed type is an actual dtype that we + can match (via string or type) + """ + + if isinstance(dtype, compat.string_types): + if dtype.lower().startswith('interval'): + try: + if cls.construct_from_string(dtype) is not None: + return True + else: + return False + except (ValueError, TypeError): + return False + else: + return False + return super(IntervalDtype, cls).is_dtype(dtype) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/generic.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/generic.py new file mode 100644 index 0000000000000000000000000000000000000000..134ec95729833e27042bbc8a5333c139446b631b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/generic.py @@ -0,0 +1,84 @@ +""" define generic base classes for pandas objects """ + + +# define abstract base classes to enable isinstance type checking on our +# objects +def create_pandas_abc_type(name, attr, comp): + @classmethod + def _check(cls, inst): + return getattr(inst, attr, '_typ') in comp + + dct = dict(__instancecheck__=_check, __subclasscheck__=_check) + meta = type("ABCBase", (type, ), dct) + return meta(name, tuple(), dct) + + +ABCIndex = create_pandas_abc_type("ABCIndex", "_typ", ("index", )) +ABCInt64Index = create_pandas_abc_type("ABCInt64Index", "_typ", + ("int64index", )) +ABCUInt64Index = create_pandas_abc_type("ABCUInt64Index", "_typ", + ("uint64index", )) +ABCRangeIndex = create_pandas_abc_type("ABCRangeIndex", "_typ", + ("rangeindex", )) +ABCFloat64Index = create_pandas_abc_type("ABCFloat64Index", "_typ", + ("float64index", )) +ABCMultiIndex = create_pandas_abc_type("ABCMultiIndex", "_typ", + ("multiindex", )) +ABCDatetimeIndex = create_pandas_abc_type("ABCDatetimeIndex", "_typ", + ("datetimeindex", )) +ABCTimedeltaIndex = create_pandas_abc_type("ABCTimedeltaIndex", "_typ", + ("timedeltaindex", )) +ABCPeriodIndex = create_pandas_abc_type("ABCPeriodIndex", "_typ", + ("periodindex", )) +ABCCategoricalIndex = create_pandas_abc_type("ABCCategoricalIndex", "_typ", + ("categoricalindex", )) +ABCIntervalIndex = create_pandas_abc_type("ABCIntervalIndex", "_typ", + ("intervalindex", )) +ABCIndexClass = create_pandas_abc_type("ABCIndexClass", "_typ", + ("index", "int64index", "rangeindex", + "float64index", "uint64index", + "multiindex", "datetimeindex", + "timedeltaindex", "periodindex", + "categoricalindex", "intervalindex")) + +ABCSeries = create_pandas_abc_type("ABCSeries", "_typ", ("series", )) +ABCDataFrame = create_pandas_abc_type("ABCDataFrame", "_typ", ("dataframe", )) +ABCSparseDataFrame = create_pandas_abc_type("ABCSparseDataFrame", "_subtyp", + ("sparse_frame", )) +ABCPanel = create_pandas_abc_type("ABCPanel", "_typ", ("panel",)) +ABCSparseSeries = create_pandas_abc_type("ABCSparseSeries", "_subtyp", + ('sparse_series', + 'sparse_time_series')) +ABCSparseArray = create_pandas_abc_type("ABCSparseArray", "_subtyp", + ('sparse_array', 'sparse_series')) +ABCCategorical = create_pandas_abc_type("ABCCategorical", "_typ", + ("categorical")) +ABCDatetimeArray = create_pandas_abc_type("ABCDatetimeArray", "_typ", + ("datetimearray")) +ABCTimedeltaArray = create_pandas_abc_type("ABCTimedeltaArray", "_typ", + ("timedeltaarray")) +ABCPeriodArray = create_pandas_abc_type("ABCPeriodArray", "_typ", + ("periodarray", )) +ABCPeriod = create_pandas_abc_type("ABCPeriod", "_typ", ("period", )) +ABCDateOffset = create_pandas_abc_type("ABCDateOffset", "_typ", + ("dateoffset",)) +ABCInterval = create_pandas_abc_type("ABCInterval", "_typ", ("interval", )) +ABCExtensionArray = create_pandas_abc_type("ABCExtensionArray", "_typ", + ("extension", + "categorical", + "periodarray", + "datetimearray", + "timedeltaarray", + )) +ABCPandasArray = create_pandas_abc_type("ABCPandasArray", + "_typ", + ("npy_extension",)) + + +class _ABCGeneric(type): + + def __instancecheck__(cls, inst): + return hasattr(inst, "_data") + + +ABCGeneric = _ABCGeneric("ABCGeneric", tuple(), {}) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/inference.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..dd05e2022f066666e40a6304b653b76faef676ae --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/dtypes/inference.py @@ -0,0 +1,499 @@ +""" basic inference routines """ + +from numbers import Number +import re + +import numpy as np + +from pandas._libs import lib +from pandas.compat import ( + PY2, Set, re_type, string_and_binary_types, string_types, text_type) + +from pandas import compat + +is_bool = lib.is_bool + +is_integer = lib.is_integer + +is_float = lib.is_float + +is_complex = lib.is_complex + +is_scalar = lib.is_scalar + +is_decimal = lib.is_decimal + +is_interval = lib.is_interval + + +def is_number(obj): + """ + Check if the object is a number. + + Returns True when the object is a number, and False if is not. + + Parameters + ---------- + obj : any type + The object to check if is a number. + + Returns + ------- + is_number : bool + Whether `obj` is a number or not. + + See Also + -------- + pandas.api.types.is_integer: Checks a subgroup of numbers. + + Examples + -------- + >>> pd.api.types.is_number(1) + True + >>> pd.api.types.is_number(7.15) + True + + Booleans are valid because they are int subclass. + + >>> pd.api.types.is_number(False) + True + + >>> pd.api.types.is_number("foo") + False + >>> pd.api.types.is_number("5") + False + """ + + return isinstance(obj, (Number, np.number)) + + +def is_string_like(obj): + """ + Check if the object is a string. + + Parameters + ---------- + obj : The object to check + + Examples + -------- + >>> is_string_like("foo") + True + >>> is_string_like(1) + False + + Returns + ------- + is_str_like : bool + Whether `obj` is a string or not. + """ + + return isinstance(obj, (text_type, string_types)) + + +def _iterable_not_string(obj): + """ + Check if the object is an iterable but not a string. + + Parameters + ---------- + obj : The object to check. + + Returns + ------- + is_iter_not_string : bool + Whether `obj` is a non-string iterable. + + Examples + -------- + >>> _iterable_not_string([1, 2, 3]) + True + >>> _iterable_not_string("foo") + False + >>> _iterable_not_string(1) + False + """ + + return (isinstance(obj, compat.Iterable) and + not isinstance(obj, string_types)) + + +def is_iterator(obj): + """ + Check if the object is an iterator. + + For example, lists are considered iterators + but not strings or datetime objects. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + is_iter : bool + Whether `obj` is an iterator. + + Examples + -------- + >>> is_iterator([1, 2, 3]) + True + >>> is_iterator(datetime(2017, 1, 1)) + False + >>> is_iterator("foo") + False + >>> is_iterator(1) + False + """ + + if not hasattr(obj, '__iter__'): + return False + + if PY2: + return hasattr(obj, 'next') + else: + # Python 3 generators have + # __next__ instead of next + return hasattr(obj, '__next__') + + +def is_file_like(obj): + """ + Check if the object is a file-like object. + + For objects to be considered file-like, they must + be an iterator AND have either a `read` and/or `write` + method as an attribute. + + Note: file-like objects must be iterable, but + iterable objects need not be file-like. + + .. versionadded:: 0.20.0 + + Parameters + ---------- + obj : The object to check + + Returns + ------- + is_file_like : bool + Whether `obj` has file-like properties. + + Examples + -------- + >>> buffer(StringIO("data")) + >>> is_file_like(buffer) + True + >>> is_file_like([1, 2, 3]) + False + """ + + if not (hasattr(obj, 'read') or hasattr(obj, 'write')): + return False + + if not hasattr(obj, "__iter__"): + return False + + return True + + +def is_re(obj): + """ + Check if the object is a regex pattern instance. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + is_regex : bool + Whether `obj` is a regex pattern. + + Examples + -------- + >>> is_re(re.compile(".*")) + True + >>> is_re("foo") + False + """ + + return isinstance(obj, re_type) + + +def is_re_compilable(obj): + """ + Check if the object can be compiled into a regex pattern instance. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + is_regex_compilable : bool + Whether `obj` can be compiled as a regex pattern. + + Examples + -------- + >>> is_re_compilable(".*") + True + >>> is_re_compilable(1) + False + """ + + try: + re.compile(obj) + except TypeError: + return False + else: + return True + + +def is_list_like(obj, allow_sets=True): + """ + Check if the object is list-like. + + Objects that are considered list-like are for example Python + lists, tuples, sets, NumPy arrays, and Pandas Series. + + Strings and datetime objects, however, are not considered list-like. + + Parameters + ---------- + obj : The object to check + allow_sets : boolean, default True + If this parameter is False, sets will not be considered list-like + + .. versionadded:: 0.24.0 + + Returns + ------- + is_list_like : bool + Whether `obj` has list-like properties. + + Examples + -------- + >>> is_list_like([1, 2, 3]) + True + >>> is_list_like({1, 2, 3}) + True + >>> is_list_like(datetime(2017, 1, 1)) + False + >>> is_list_like("foo") + False + >>> is_list_like(1) + False + >>> is_list_like(np.array([2])) + True + >>> is_list_like(np.array(2))) + False + """ + + return (isinstance(obj, compat.Iterable) + # we do not count strings/unicode/bytes as list-like + and not isinstance(obj, string_and_binary_types) + + # exclude zero-dimensional numpy arrays, effectively scalars + and not (isinstance(obj, np.ndarray) and obj.ndim == 0) + + # exclude sets if allow_sets is False + and not (allow_sets is False and isinstance(obj, Set))) + + +def is_array_like(obj): + """ + Check if the object is array-like. + + For an object to be considered array-like, it must be list-like and + have a `dtype` attribute. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + is_array_like : bool + Whether `obj` has array-like properties. + + Examples + -------- + >>> is_array_like(np.array([1, 2, 3])) + True + >>> is_array_like(pd.Series(["a", "b"])) + True + >>> is_array_like(pd.Index(["2016-01-01"])) + True + >>> is_array_like([1, 2, 3]) + False + >>> is_array_like(("a", "b")) + False + """ + + return is_list_like(obj) and hasattr(obj, "dtype") + + +def is_nested_list_like(obj): + """ + Check if the object is list-like, and that all of its elements + are also list-like. + + .. versionadded:: 0.20.0 + + Parameters + ---------- + obj : The object to check + + Returns + ------- + is_list_like : bool + Whether `obj` has list-like properties. + + Examples + -------- + >>> is_nested_list_like([[1, 2, 3]]) + True + >>> is_nested_list_like([{1, 2, 3}, {1, 2, 3}]) + True + >>> is_nested_list_like(["foo"]) + False + >>> is_nested_list_like([]) + False + >>> is_nested_list_like([[1, 2, 3], 1]) + False + + Notes + ----- + This won't reliably detect whether a consumable iterator (e. g. + a generator) is a nested-list-like without consuming the iterator. + To avoid consuming it, we always return False if the outer container + doesn't define `__len__`. + + See Also + -------- + is_list_like + """ + return (is_list_like(obj) and hasattr(obj, '__len__') and + len(obj) > 0 and all(is_list_like(item) for item in obj)) + + +def is_dict_like(obj): + """ + Check if the object is dict-like. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + is_dict_like : bool + Whether `obj` has dict-like properties. + + Examples + -------- + >>> is_dict_like({1: 2}) + True + >>> is_dict_like([1, 2, 3]) + False + >>> is_dict_like(dict) + False + >>> is_dict_like(dict()) + True + """ + dict_like_attrs = ("__getitem__", "keys", "__contains__") + return (all(hasattr(obj, attr) for attr in dict_like_attrs) + # [GH 25196] exclude classes + and not isinstance(obj, type)) + + +def is_named_tuple(obj): + """ + Check if the object is a named tuple. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + is_named_tuple : bool + Whether `obj` is a named tuple. + + Examples + -------- + >>> Point = namedtuple("Point", ["x", "y"]) + >>> p = Point(1, 2) + >>> + >>> is_named_tuple(p) + True + >>> is_named_tuple((1, 2)) + False + """ + + return isinstance(obj, tuple) and hasattr(obj, '_fields') + + +def is_hashable(obj): + """Return True if hash(obj) will succeed, False otherwise. + + Some types will pass a test against collections.Hashable but fail when they + are actually hashed with hash(). + + Distinguish between these and other types by trying the call to hash() and + seeing if they raise TypeError. + + Examples + -------- + >>> a = ([],) + >>> isinstance(a, collections.Hashable) + True + >>> is_hashable(a) + False + """ + # Unfortunately, we can't use isinstance(obj, collections.Hashable), which + # can be faster than calling hash. That is because numpy scalars on Python + # 3 fail this test. + + # Reconsider this decision once this numpy bug is fixed: + # https://github.com/numpy/numpy/issues/5562 + + try: + hash(obj) + except TypeError: + return False + else: + return True + + +def is_sequence(obj): + """ + Check if the object is a sequence of objects. + String types are not included as sequences here. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + is_sequence : bool + Whether `obj` is a sequence of objects. + + Examples + -------- + >>> l = [1, 2, 3] + >>> + >>> is_sequence(l) + True + >>> is_sequence(iter(l)) + False + """ + + try: + iter(obj) # Can iterate over it. + len(obj) # Has a length associated with it. + return not isinstance(obj, string_and_binary_types) + except (TypeError, AttributeError): + return False diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/multi.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/multi.py new file mode 100644 index 0000000000000000000000000000000000000000..14975dbbefa63261e0d03988a95081587eb9c0f2 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/multi.py @@ -0,0 +1,3166 @@ +# pylint: disable=E1101,E1103,W0232 +from collections import OrderedDict +import datetime +from sys import getsizeof +import warnings + +import numpy as np + +from pandas._libs import ( + Timestamp, algos as libalgos, index as libindex, lib, tslibs) +import pandas.compat as compat +from pandas.compat import lrange, lzip, map, range, zip +from pandas.compat.numpy import function as nv +from pandas.errors import PerformanceWarning, UnsortedIndexError +from pandas.util._decorators import Appender, cache_readonly, deprecate_kwarg + +from pandas.core.dtypes.common import ( + ensure_int64, ensure_platform_int, is_categorical_dtype, is_hashable, + is_integer, is_iterator, is_list_like, is_object_dtype, is_scalar, + pandas_dtype) +from pandas.core.dtypes.dtypes import ExtensionDtype, PandasExtensionDtype +from pandas.core.dtypes.generic import ABCDataFrame +from pandas.core.dtypes.missing import array_equivalent, isna + +import pandas.core.algorithms as algos +import pandas.core.common as com +from pandas.core.config import get_option +import pandas.core.indexes.base as ibase +from pandas.core.indexes.base import ( + Index, InvalidIndexError, _index_shared_docs, ensure_index) +from pandas.core.indexes.frozen import FrozenList, _ensure_frozen +import pandas.core.missing as missing + +from pandas.io.formats.printing import pprint_thing + +_index_doc_kwargs = dict(ibase._index_doc_kwargs) +_index_doc_kwargs.update( + dict(klass='MultiIndex', + target_klass='MultiIndex or list of tuples')) + + +class MultiIndexUIntEngine(libindex.BaseMultiIndexCodesEngine, + libindex.UInt64Engine): + """ + This class manages a MultiIndex by mapping label combinations to positive + integers. + """ + _base = libindex.UInt64Engine + + def _codes_to_ints(self, codes): + """ + Transform combination(s) of uint64 in one uint64 (each), in a strictly + monotonic way (i.e. respecting the lexicographic order of integer + combinations): see BaseMultiIndexCodesEngine documentation. + + Parameters + ---------- + codes : 1- or 2-dimensional array of dtype uint64 + Combinations of integers (one per row) + + Returns + ------ + int_keys : scalar or 1-dimensional array, of dtype uint64 + Integer(s) representing one combination (each) + """ + # Shift the representation of each level by the pre-calculated number + # of bits: + codes <<= self.offsets + + # Now sum and OR are in fact interchangeable. This is a simple + # composition of the (disjunct) significant bits of each level (i.e. + # each column in "codes") in a single positive integer: + if codes.ndim == 1: + # Single key + return np.bitwise_or.reduce(codes) + + # Multiple keys + return np.bitwise_or.reduce(codes, axis=1) + + +class MultiIndexPyIntEngine(libindex.BaseMultiIndexCodesEngine, + libindex.ObjectEngine): + """ + This class manages those (extreme) cases in which the number of possible + label combinations overflows the 64 bits integers, and uses an ObjectEngine + containing Python integers. + """ + _base = libindex.ObjectEngine + + def _codes_to_ints(self, codes): + """ + Transform combination(s) of uint64 in one Python integer (each), in a + strictly monotonic way (i.e. respecting the lexicographic order of + integer combinations): see BaseMultiIndexCodesEngine documentation. + + Parameters + ---------- + codes : 1- or 2-dimensional array of dtype uint64 + Combinations of integers (one per row) + + Returns + ------ + int_keys : int, or 1-dimensional array of dtype object + Integer(s) representing one combination (each) + """ + + # Shift the representation of each level by the pre-calculated number + # of bits. Since this can overflow uint64, first make sure we are + # working with Python integers: + codes = codes.astype('object') << self.offsets + + # Now sum and OR are in fact interchangeable. This is a simple + # composition of the (disjunct) significant bits of each level (i.e. + # each column in "codes") in a single positive integer (per row): + if codes.ndim == 1: + # Single key + return np.bitwise_or.reduce(codes) + + # Multiple keys + return np.bitwise_or.reduce(codes, axis=1) + + +class MultiIndex(Index): + """ + A multi-level, or hierarchical, index object for pandas objects. + + Parameters + ---------- + levels : sequence of arrays + The unique labels for each level. + codes : sequence of arrays + Integers for each level designating which label at each location. + + .. versionadded:: 0.24.0 + labels : sequence of arrays + Integers for each level designating which label at each location. + + .. deprecated:: 0.24.0 + Use ``codes`` instead + sortorder : optional int + Level of sortedness (must be lexicographically sorted by that + level). + names : optional sequence of objects + Names for each of the index levels. (name is accepted for compat). + copy : bool, default False + Copy the meta-data. + verify_integrity : bool, default True + Check that the levels/codes are consistent and valid. + + Attributes + ---------- + names + levels + codes + nlevels + levshape + + Methods + ------- + from_arrays + from_tuples + from_product + from_frame + set_levels + set_codes + to_frame + to_flat_index + is_lexsorted + sortlevel + droplevel + swaplevel + reorder_levels + remove_unused_levels + + See Also + -------- + MultiIndex.from_arrays : Convert list of arrays to MultiIndex. + MultiIndex.from_product : Create a MultiIndex from the cartesian product + of iterables. + MultiIndex.from_tuples : Convert list of tuples to a MultiIndex. + MultiIndex.from_frame : Make a MultiIndex from a DataFrame. + Index : The base pandas Index type. + + Examples + --------- + A new ``MultiIndex`` is typically constructed using one of the helper + methods :meth:`MultiIndex.from_arrays`, :meth:`MultiIndex.from_product` + and :meth:`MultiIndex.from_tuples`. For example (using ``.from_arrays``): + + >>> arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']] + >>> pd.MultiIndex.from_arrays(arrays, names=('number', 'color')) + MultiIndex(levels=[[1, 2], ['blue', 'red']], + codes=[[0, 0, 1, 1], [1, 0, 1, 0]], + names=['number', 'color']) + + See further examples for how to construct a MultiIndex in the doc strings + of the mentioned helper methods. + + Notes + ----- + See the `user guide + `_ for more. + """ + + # initialize to zero-length tuples to make everything work + _typ = 'multiindex' + _names = FrozenList() + _levels = FrozenList() + _codes = FrozenList() + _comparables = ['names'] + rename = Index.set_names + + # -------------------------------------------------------------------- + # Constructors + + @deprecate_kwarg(old_arg_name='labels', new_arg_name='codes') + def __new__(cls, levels=None, codes=None, sortorder=None, names=None, + dtype=None, copy=False, name=None, + verify_integrity=True, _set_identity=True): + + # compat with Index + if name is not None: + names = name + if levels is None or codes is None: + raise TypeError("Must pass both levels and codes") + if len(levels) != len(codes): + raise ValueError('Length of levels and codes must be the same.') + if len(levels) == 0: + raise ValueError('Must pass non-zero number of levels/codes') + + result = object.__new__(MultiIndex) + + # we've already validated levels and codes, so shortcut here + result._set_levels(levels, copy=copy, validate=False) + result._set_codes(codes, copy=copy, validate=False) + + if names is not None: + # handles name validation + result._set_names(names) + + if sortorder is not None: + result.sortorder = int(sortorder) + else: + result.sortorder = sortorder + + if verify_integrity: + result._verify_integrity() + if _set_identity: + result._reset_identity() + return result + + def _verify_integrity(self, codes=None, levels=None): + """ + + Parameters + ---------- + codes : optional list + Codes to check for validity. Defaults to current codes. + levels : optional list + Levels to check for validity. Defaults to current levels. + + Raises + ------ + ValueError + If length of levels and codes don't match, if the codes for any + level would exceed level bounds, or there are any duplicate levels. + """ + # NOTE: Currently does not check, among other things, that cached + # nlevels matches nor that sortorder matches actually sortorder. + codes = codes or self.codes + levels = levels or self.levels + + if len(levels) != len(codes): + raise ValueError("Length of levels and codes must match. NOTE:" + " this index is in an inconsistent state.") + codes_length = len(self.codes[0]) + for i, (level, level_codes) in enumerate(zip(levels, codes)): + if len(level_codes) != codes_length: + raise ValueError("Unequal code lengths: %s" % + ([len(code_) for code_ in codes])) + if len(level_codes) and level_codes.max() >= len(level): + raise ValueError("On level %d, code max (%d) >= length of" + " level (%d). NOTE: this index is in an" + " inconsistent state" % (i, level_codes.max(), + len(level))) + if not level.is_unique: + raise ValueError("Level values must be unique: {values} on " + "level {level}".format( + values=[value for value in level], + level=i)) + + @classmethod + def from_arrays(cls, arrays, sortorder=None, names=None): + """ + Convert arrays to MultiIndex. + + Parameters + ---------- + arrays : list / sequence of array-likes + Each array-like gives one level's value for each data point. + len(arrays) is the number of levels. + sortorder : int or None + Level of sortedness (must be lexicographically sorted by that + level). + names : list / sequence of str, optional + Names for the levels in the index. + + Returns + ------- + index : MultiIndex + + See Also + -------- + MultiIndex.from_tuples : Convert list of tuples to MultiIndex. + MultiIndex.from_product : Make a MultiIndex from cartesian product + of iterables. + MultiIndex.from_frame : Make a MultiIndex from a DataFrame. + + Examples + -------- + >>> arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']] + >>> pd.MultiIndex.from_arrays(arrays, names=('number', 'color')) + MultiIndex(levels=[[1, 2], ['blue', 'red']], + codes=[[0, 0, 1, 1], [1, 0, 1, 0]], + names=['number', 'color']) + """ + if not is_list_like(arrays): + raise TypeError("Input must be a list / sequence of array-likes.") + elif is_iterator(arrays): + arrays = list(arrays) + + # Check if lengths of all arrays are equal or not, + # raise ValueError, if not + for i in range(1, len(arrays)): + if len(arrays[i]) != len(arrays[i - 1]): + raise ValueError('all arrays must be same length') + + from pandas.core.arrays.categorical import _factorize_from_iterables + + codes, levels = _factorize_from_iterables(arrays) + if names is None: + names = [getattr(arr, "name", None) for arr in arrays] + + return MultiIndex(levels=levels, codes=codes, sortorder=sortorder, + names=names, verify_integrity=False) + + @classmethod + def from_tuples(cls, tuples, sortorder=None, names=None): + """ + Convert list of tuples to MultiIndex. + + Parameters + ---------- + tuples : list / sequence of tuple-likes + Each tuple is the index of one row/column. + sortorder : int or None + Level of sortedness (must be lexicographically sorted by that + level). + names : list / sequence of str, optional + Names for the levels in the index. + + Returns + ------- + index : MultiIndex + + See Also + -------- + MultiIndex.from_arrays : Convert list of arrays to MultiIndex. + MultiIndex.from_product : Make a MultiIndex from cartesian product + of iterables. + MultiIndex.from_frame : Make a MultiIndex from a DataFrame. + + Examples + -------- + >>> tuples = [(1, u'red'), (1, u'blue'), + ... (2, u'red'), (2, u'blue')] + >>> pd.MultiIndex.from_tuples(tuples, names=('number', 'color')) + MultiIndex(levels=[[1, 2], ['blue', 'red']], + codes=[[0, 0, 1, 1], [1, 0, 1, 0]], + names=['number', 'color']) + """ + if not is_list_like(tuples): + raise TypeError('Input must be a list / sequence of tuple-likes.') + elif is_iterator(tuples): + tuples = list(tuples) + + if len(tuples) == 0: + if names is None: + msg = 'Cannot infer number of levels from empty list' + raise TypeError(msg) + arrays = [[]] * len(names) + elif isinstance(tuples, (np.ndarray, Index)): + if isinstance(tuples, Index): + tuples = tuples._values + + arrays = list(lib.tuples_to_object_array(tuples).T) + elif isinstance(tuples, list): + arrays = list(lib.to_object_array_tuples(tuples).T) + else: + arrays = lzip(*tuples) + + return MultiIndex.from_arrays(arrays, sortorder=sortorder, names=names) + + @classmethod + def from_product(cls, iterables, sortorder=None, names=None): + """ + Make a MultiIndex from the cartesian product of multiple iterables. + + Parameters + ---------- + iterables : list / sequence of iterables + Each iterable has unique labels for each level of the index. + sortorder : int or None + Level of sortedness (must be lexicographically sorted by that + level). + names : list / sequence of str, optional + Names for the levels in the index. + + Returns + ------- + index : MultiIndex + + See Also + -------- + MultiIndex.from_arrays : Convert list of arrays to MultiIndex. + MultiIndex.from_tuples : Convert list of tuples to MultiIndex. + MultiIndex.from_frame : Make a MultiIndex from a DataFrame. + + Examples + -------- + >>> numbers = [0, 1, 2] + >>> colors = ['green', 'purple'] + >>> pd.MultiIndex.from_product([numbers, colors], + ... names=['number', 'color']) + MultiIndex(levels=[[0, 1, 2], ['green', 'purple']], + codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]], + names=['number', 'color']) + """ + from pandas.core.arrays.categorical import _factorize_from_iterables + from pandas.core.reshape.util import cartesian_product + + if not is_list_like(iterables): + raise TypeError("Input must be a list / sequence of iterables.") + elif is_iterator(iterables): + iterables = list(iterables) + + codes, levels = _factorize_from_iterables(iterables) + codes = cartesian_product(codes) + return MultiIndex(levels, codes, sortorder=sortorder, names=names) + + @classmethod + def from_frame(cls, df, sortorder=None, names=None): + """ + Make a MultiIndex from a DataFrame. + + .. versionadded:: 0.24.0 + + Parameters + ---------- + df : DataFrame + DataFrame to be converted to MultiIndex. + sortorder : int, optional + Level of sortedness (must be lexicographically sorted by that + level). + names : list-like, optional + If no names are provided, use the column names, or tuple of column + names if the columns is a MultiIndex. If a sequence, overwrite + names with the given sequence. + + Returns + ------- + MultiIndex + The MultiIndex representation of the given DataFrame. + + See Also + -------- + MultiIndex.from_arrays : Convert list of arrays to MultiIndex. + MultiIndex.from_tuples : Convert list of tuples to MultiIndex. + MultiIndex.from_product : Make a MultiIndex from cartesian product + of iterables. + + Examples + -------- + >>> df = pd.DataFrame([['HI', 'Temp'], ['HI', 'Precip'], + ... ['NJ', 'Temp'], ['NJ', 'Precip']], + ... columns=['a', 'b']) + >>> df + a b + 0 HI Temp + 1 HI Precip + 2 NJ Temp + 3 NJ Precip + + >>> pd.MultiIndex.from_frame(df) + MultiIndex(levels=[['HI', 'NJ'], ['Precip', 'Temp']], + codes=[[0, 0, 1, 1], [1, 0, 1, 0]], + names=['a', 'b']) + + Using explicit names, instead of the column names + + >>> pd.MultiIndex.from_frame(df, names=['state', 'observation']) + MultiIndex(levels=[['HI', 'NJ'], ['Precip', 'Temp']], + codes=[[0, 0, 1, 1], [1, 0, 1, 0]], + names=['state', 'observation']) + """ + if not isinstance(df, ABCDataFrame): + raise TypeError("Input must be a DataFrame") + + column_names, columns = lzip(*df.iteritems()) + names = column_names if names is None else names + return cls.from_arrays(columns, sortorder=sortorder, names=names) + + # -------------------------------------------------------------------- + + @property + def levels(self): + return self._levels + + @property + def _values(self): + # We override here, since our parent uses _data, which we dont' use. + return self.values + + @property + def array(self): + """ + Raises a ValueError for `MultiIndex` because there's no single + array backing a MultiIndex. + + Raises + ------ + ValueError + """ + msg = ("MultiIndex has no single backing array. Use " + "'MultiIndex.to_numpy()' to get a NumPy array of tuples.") + raise ValueError(msg) + + @property + def _is_homogeneous_type(self): + """Whether the levels of a MultiIndex all have the same dtype. + + This looks at the dtypes of the levels. + + See Also + -------- + Index._is_homogeneous_type + DataFrame._is_homogeneous_type + + Examples + -------- + >>> MultiIndex.from_tuples([ + ... ('a', 'b'), ('a', 'c')])._is_homogeneous_type + True + >>> MultiIndex.from_tuples([ + ... ('a', 1), ('a', 2)])._is_homogeneous_type + False + """ + return len({x.dtype for x in self.levels}) <= 1 + + def _set_levels(self, levels, level=None, copy=False, validate=True, + verify_integrity=False): + # This is NOT part of the levels property because it should be + # externally not allowed to set levels. User beware if you change + # _levels directly + if validate and len(levels) == 0: + raise ValueError('Must set non-zero number of levels.') + if validate and level is None and len(levels) != self.nlevels: + raise ValueError('Length of levels must match number of levels.') + if validate and level is not None and len(levels) != len(level): + raise ValueError('Length of levels must match length of level.') + + if level is None: + new_levels = FrozenList( + ensure_index(lev, copy=copy)._shallow_copy() + for lev in levels) + else: + level = [self._get_level_number(l) for l in level] + new_levels = list(self._levels) + for l, v in zip(level, levels): + new_levels[l] = ensure_index(v, copy=copy)._shallow_copy() + new_levels = FrozenList(new_levels) + + if verify_integrity: + self._verify_integrity(levels=new_levels) + + names = self.names + self._levels = new_levels + if any(names): + self._set_names(names) + + self._tuples = None + self._reset_cache() + + def set_levels(self, levels, level=None, inplace=False, + verify_integrity=True): + """ + Set new levels on MultiIndex. Defaults to returning + new index. + + Parameters + ---------- + levels : sequence or list of sequence + new level(s) to apply + level : int, level name, or sequence of int/level names (default None) + level(s) to set (None for all levels) + inplace : bool + if True, mutates in place + verify_integrity : bool (default True) + if True, checks that levels and codes are compatible + + Returns + ------- + new index (of same type and class...etc) + + Examples + -------- + >>> idx = pd.MultiIndex.from_tuples([(1, u'one'), (1, u'two'), + (2, u'one'), (2, u'two')], + names=['foo', 'bar']) + >>> idx.set_levels([['a','b'], [1,2]]) + MultiIndex(levels=[[u'a', u'b'], [1, 2]], + codes=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=[u'foo', u'bar']) + >>> idx.set_levels(['a','b'], level=0) + MultiIndex(levels=[[u'a', u'b'], [u'one', u'two']], + codes=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=[u'foo', u'bar']) + >>> idx.set_levels(['a','b'], level='bar') + MultiIndex(levels=[[1, 2], [u'a', u'b']], + codes=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=[u'foo', u'bar']) + >>> idx.set_levels([['a','b'], [1,2]], level=[0,1]) + MultiIndex(levels=[[u'a', u'b'], [1, 2]], + codes=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=[u'foo', u'bar']) + """ + if is_list_like(levels) and not isinstance(levels, Index): + levels = list(levels) + + if level is not None and not is_list_like(level): + if not is_list_like(levels): + raise TypeError("Levels must be list-like") + if is_list_like(levels[0]): + raise TypeError("Levels must be list-like") + level = [level] + levels = [levels] + elif level is None or is_list_like(level): + if not is_list_like(levels) or not is_list_like(levels[0]): + raise TypeError("Levels must be list of lists-like") + + if inplace: + idx = self + else: + idx = self._shallow_copy() + idx._reset_identity() + idx._set_levels(levels, level=level, validate=True, + verify_integrity=verify_integrity) + if not inplace: + return idx + + @property + def codes(self): + return self._codes + + @property + def labels(self): + warnings.warn((".labels was deprecated in version 0.24.0. " + "Use .codes instead."), + FutureWarning, stacklevel=2) + return self.codes + + def _set_codes(self, codes, level=None, copy=False, validate=True, + verify_integrity=False): + + if validate and level is None and len(codes) != self.nlevels: + raise ValueError("Length of codes must match number of levels") + if validate and level is not None and len(codes) != len(level): + raise ValueError('Length of codes must match length of levels.') + + if level is None: + new_codes = FrozenList( + _ensure_frozen(level_codes, lev, copy=copy)._shallow_copy() + for lev, level_codes in zip(self.levels, codes)) + else: + level = [self._get_level_number(l) for l in level] + new_codes = list(self._codes) + for lev_idx, level_codes in zip(level, codes): + lev = self.levels[lev_idx] + new_codes[lev_idx] = _ensure_frozen( + level_codes, lev, copy=copy)._shallow_copy() + new_codes = FrozenList(new_codes) + + if verify_integrity: + self._verify_integrity(codes=new_codes) + + self._codes = new_codes + self._tuples = None + self._reset_cache() + + def set_labels(self, labels, level=None, inplace=False, + verify_integrity=True): + warnings.warn((".set_labels was deprecated in version 0.24.0. " + "Use .set_codes instead."), + FutureWarning, stacklevel=2) + return self.set_codes(codes=labels, level=level, inplace=inplace, + verify_integrity=verify_integrity) + + @deprecate_kwarg(old_arg_name='labels', new_arg_name='codes') + def set_codes(self, codes, level=None, inplace=False, + verify_integrity=True): + """ + Set new codes on MultiIndex. Defaults to returning + new index. + + .. versionadded:: 0.24.0 + + New name for deprecated method `set_labels`. + + Parameters + ---------- + codes : sequence or list of sequence + new codes to apply + level : int, level name, or sequence of int/level names (default None) + level(s) to set (None for all levels) + inplace : bool + if True, mutates in place + verify_integrity : bool (default True) + if True, checks that levels and codes are compatible + + Returns + ------- + new index (of same type and class...etc) + + Examples + -------- + >>> idx = pd.MultiIndex.from_tuples([(1, u'one'), (1, u'two'), + (2, u'one'), (2, u'two')], + names=['foo', 'bar']) + >>> idx.set_codes([[1,0,1,0], [0,0,1,1]]) + MultiIndex(levels=[[1, 2], [u'one', u'two']], + codes=[[1, 0, 1, 0], [0, 0, 1, 1]], + names=[u'foo', u'bar']) + >>> idx.set_codes([1,0,1,0], level=0) + MultiIndex(levels=[[1, 2], [u'one', u'two']], + codes=[[1, 0, 1, 0], [0, 1, 0, 1]], + names=[u'foo', u'bar']) + >>> idx.set_codes([0,0,1,1], level='bar') + MultiIndex(levels=[[1, 2], [u'one', u'two']], + codes=[[0, 0, 1, 1], [0, 0, 1, 1]], + names=[u'foo', u'bar']) + >>> idx.set_codes([[1,0,1,0], [0,0,1,1]], level=[0,1]) + MultiIndex(levels=[[1, 2], [u'one', u'two']], + codes=[[1, 0, 1, 0], [0, 0, 1, 1]], + names=[u'foo', u'bar']) + """ + if level is not None and not is_list_like(level): + if not is_list_like(codes): + raise TypeError("Codes must be list-like") + if is_list_like(codes[0]): + raise TypeError("Codes must be list-like") + level = [level] + codes = [codes] + elif level is None or is_list_like(level): + if not is_list_like(codes) or not is_list_like(codes[0]): + raise TypeError("Codes must be list of lists-like") + + if inplace: + idx = self + else: + idx = self._shallow_copy() + idx._reset_identity() + idx._set_codes(codes, level=level, verify_integrity=verify_integrity) + if not inplace: + return idx + + @deprecate_kwarg(old_arg_name='labels', new_arg_name='codes') + def copy(self, names=None, dtype=None, levels=None, codes=None, + deep=False, _set_identity=False, **kwargs): + """ + Make a copy of this object. Names, dtype, levels and codes can be + passed and will be set on new copy. + + Parameters + ---------- + names : sequence, optional + dtype : numpy dtype or pandas type, optional + levels : sequence, optional + codes : sequence, optional + + Returns + ------- + copy : MultiIndex + + Notes + ----- + In most cases, there should be no functional difference from using + ``deep``, but if ``deep`` is passed it will attempt to deepcopy. + This could be potentially expensive on large MultiIndex objects. + """ + name = kwargs.get('name') + names = self._validate_names(name=name, names=names, deep=deep) + + if deep: + from copy import deepcopy + if levels is None: + levels = deepcopy(self.levels) + if codes is None: + codes = deepcopy(self.codes) + else: + if levels is None: + levels = self.levels + if codes is None: + codes = self.codes + return MultiIndex(levels=levels, codes=codes, names=names, + sortorder=self.sortorder, verify_integrity=False, + _set_identity=_set_identity) + + def __array__(self, dtype=None): + """ the array interface, return my values """ + return self.values + + def view(self, cls=None): + """ this is defined as a copy with the same identity """ + result = self.copy() + result._id = self._id + return result + + def _shallow_copy_with_infer(self, values, **kwargs): + # On equal MultiIndexes the difference is empty. + # Therefore, an empty MultiIndex is returned GH13490 + if len(values) == 0: + return MultiIndex(levels=[[] for _ in range(self.nlevels)], + codes=[[] for _ in range(self.nlevels)], + **kwargs) + return self._shallow_copy(values, **kwargs) + + @Appender(_index_shared_docs['contains'] % _index_doc_kwargs) + def __contains__(self, key): + hash(key) + try: + self.get_loc(key) + return True + except (LookupError, TypeError): + return False + + contains = __contains__ + + @Appender(_index_shared_docs['_shallow_copy']) + def _shallow_copy(self, values=None, **kwargs): + if values is not None: + names = kwargs.pop('names', kwargs.pop('name', self.names)) + # discards freq + kwargs.pop('freq', None) + return MultiIndex.from_tuples(values, names=names, **kwargs) + return self.view() + + @cache_readonly + def dtype(self): + return np.dtype('O') + + def _is_memory_usage_qualified(self): + """ return a boolean if we need a qualified .info display """ + def f(l): + return 'mixed' in l or 'string' in l or 'unicode' in l + return any(f(l) for l in self._inferred_type_levels) + + @Appender(Index.memory_usage.__doc__) + def memory_usage(self, deep=False): + # we are overwriting our base class to avoid + # computing .values here which could materialize + # a tuple representation uncessarily + return self._nbytes(deep) + + @cache_readonly + def nbytes(self): + """ return the number of bytes in the underlying data """ + return self._nbytes(False) + + def _nbytes(self, deep=False): + """ + return the number of bytes in the underlying data + deeply introspect the level data if deep=True + + include the engine hashtable + + *this is in internal routine* + + """ + + # for implementations with no useful getsizeof (PyPy) + objsize = 24 + + level_nbytes = sum(i.memory_usage(deep=deep) for i in self.levels) + label_nbytes = sum(i.nbytes for i in self.codes) + names_nbytes = sum(getsizeof(i, objsize) for i in self.names) + result = level_nbytes + label_nbytes + names_nbytes + + # include our engine hashtable + result += self._engine.sizeof(deep=deep) + return result + + # -------------------------------------------------------------------- + # Rendering Methods + + def _format_attrs(self): + """ + Return a list of tuples of the (attr,formatted_value) + """ + attrs = [ + ('levels', ibase.default_pprint(self._levels, + max_seq_items=False)), + ('codes', ibase.default_pprint(self._codes, + max_seq_items=False))] + if com._any_not_none(*self.names): + attrs.append(('names', ibase.default_pprint(self.names))) + if self.sortorder is not None: + attrs.append(('sortorder', ibase.default_pprint(self.sortorder))) + return attrs + + def _format_space(self): + return "\n%s" % (' ' * (len(self.__class__.__name__) + 1)) + + def _format_data(self, name=None): + # we are formatting thru the attributes + return None + + def _format_native_types(self, na_rep='nan', **kwargs): + new_levels = [] + new_codes = [] + + # go through the levels and format them + for level, level_codes in zip(self.levels, self.codes): + level = level._format_native_types(na_rep=na_rep, **kwargs) + # add nan values, if there are any + mask = (level_codes == -1) + if mask.any(): + nan_index = len(level) + level = np.append(level, na_rep) + level_codes = level_codes.values() + level_codes[mask] = nan_index + new_levels.append(level) + new_codes.append(level_codes) + + if len(new_levels) == 1: + return Index(new_levels[0])._format_native_types() + else: + # reconstruct the multi-index + mi = MultiIndex(levels=new_levels, codes=new_codes, + names=self.names, sortorder=self.sortorder, + verify_integrity=False) + return mi.values + + def format(self, space=2, sparsify=None, adjoin=True, names=False, + na_rep=None, formatter=None): + if len(self) == 0: + return [] + + stringified_levels = [] + for lev, level_codes in zip(self.levels, self.codes): + na = na_rep if na_rep is not None else _get_na_rep(lev.dtype.type) + + if len(lev) > 0: + + formatted = lev.take(level_codes).format(formatter=formatter) + + # we have some NA + mask = level_codes == -1 + if mask.any(): + formatted = np.array(formatted, dtype=object) + formatted[mask] = na + formatted = formatted.tolist() + + else: + # weird all NA case + formatted = [pprint_thing(na if isna(x) else x, + escape_chars=('\t', '\r', '\n')) + for x in algos.take_1d(lev._values, level_codes)] + stringified_levels.append(formatted) + + result_levels = [] + for lev, name in zip(stringified_levels, self.names): + level = [] + + if names: + level.append(pprint_thing(name, + escape_chars=('\t', '\r', '\n')) + if name is not None else '') + + level.extend(np.array(lev, dtype=object)) + result_levels.append(level) + + if sparsify is None: + sparsify = get_option("display.multi_sparse") + + if sparsify: + sentinel = '' + # GH3547 + # use value of sparsify as sentinel, unless it's an obvious + # "Truthey" value + if sparsify not in [True, 1]: + sentinel = sparsify + # little bit of a kludge job for #1217 + result_levels = _sparsify(result_levels, start=int(names), + sentinel=sentinel) + + if adjoin: + from pandas.io.formats.format import _get_adjustment + adj = _get_adjustment() + return adj.adjoin(space, *result_levels).split('\n') + else: + return result_levels + + # -------------------------------------------------------------------- + + def __len__(self): + return len(self.codes[0]) + + def _get_names(self): + return FrozenList(level.name for level in self.levels) + + def _set_names(self, names, level=None, validate=True): + """ + Set new names on index. Each name has to be a hashable type. + + Parameters + ---------- + values : str or sequence + name(s) to set + level : int, level name, or sequence of int/level names (default None) + If the index is a MultiIndex (hierarchical), level(s) to set (None + for all levels). Otherwise level must be None + validate : boolean, default True + validate that the names match level lengths + + Raises + ------ + TypeError if each name is not hashable. + + Notes + ----- + sets names on levels. WARNING: mutates! + + Note that you generally want to set this *after* changing levels, so + that it only acts on copies + """ + # GH 15110 + # Don't allow a single string for names in a MultiIndex + if names is not None and not is_list_like(names): + raise ValueError('Names should be list-like for a MultiIndex') + names = list(names) + + if validate and level is not None and len(names) != len(level): + raise ValueError('Length of names must match length of level.') + if validate and level is None and len(names) != self.nlevels: + raise ValueError('Length of names must match number of levels in ' + 'MultiIndex.') + + if level is None: + level = range(self.nlevels) + else: + level = [self._get_level_number(l) for l in level] + + # set the name + for l, name in zip(level, names): + if name is not None: + # GH 20527 + # All items in 'names' need to be hashable: + if not is_hashable(name): + raise TypeError('{}.name must be a hashable type' + .format(self.__class__.__name__)) + self.levels[l].rename(name, inplace=True) + + names = property(fset=_set_names, fget=_get_names, + doc="Names of levels in MultiIndex") + + @Appender(_index_shared_docs['_get_grouper_for_level']) + def _get_grouper_for_level(self, mapper, level): + indexer = self.codes[level] + level_index = self.levels[level] + + if mapper is not None: + # Handle group mapping function and return + level_values = self.levels[level].take(indexer) + grouper = level_values.map(mapper) + return grouper, None, None + + codes, uniques = algos.factorize(indexer, sort=True) + + if len(uniques) > 0 and uniques[0] == -1: + # Handle NAs + mask = indexer != -1 + ok_codes, uniques = algos.factorize(indexer[mask], sort=True) + + codes = np.empty(len(indexer), dtype=indexer.dtype) + codes[mask] = ok_codes + codes[~mask] = -1 + + if len(uniques) < len(level_index): + # Remove unobserved levels from level_index + level_index = level_index.take(uniques) + + grouper = level_index.take(codes) + + return grouper, codes, level_index + + @property + def _constructor(self): + return MultiIndex.from_tuples + + @cache_readonly + def inferred_type(self): + return 'mixed' + + def _get_level_number(self, level): + count = self.names.count(level) + if (count > 1) and not is_integer(level): + raise ValueError('The name %s occurs multiple times, use a ' + 'level number' % level) + try: + level = self.names.index(level) + except ValueError: + if not is_integer(level): + raise KeyError('Level %s not found' % str(level)) + elif level < 0: + level += self.nlevels + if level < 0: + orig_level = level - self.nlevels + raise IndexError('Too many levels: Index has only %d ' + 'levels, %d is not a valid level number' % + (self.nlevels, orig_level)) + # Note: levels are zero-based + elif level >= self.nlevels: + raise IndexError('Too many levels: Index has only %d levels, ' + 'not %d' % (self.nlevels, level + 1)) + return level + + _tuples = None + + @cache_readonly + def _engine(self): + # Calculate the number of bits needed to represent labels in each + # level, as log2 of their sizes (including -1 for NaN): + sizes = np.ceil(np.log2([len(l) + 1 for l in self.levels])) + + # Sum bit counts, starting from the _right_.... + lev_bits = np.cumsum(sizes[::-1])[::-1] + + # ... in order to obtain offsets such that sorting the combination of + # shifted codes (one for each level, resulting in a unique integer) is + # equivalent to sorting lexicographically the codes themselves. Notice + # that each level needs to be shifted by the number of bits needed to + # represent the _previous_ ones: + offsets = np.concatenate([lev_bits[1:], [0]]).astype('uint64') + + # Check the total number of bits needed for our representation: + if lev_bits[0] > 64: + # The levels would overflow a 64 bit uint - use Python integers: + return MultiIndexPyIntEngine(self.levels, self.codes, offsets) + return MultiIndexUIntEngine(self.levels, self.codes, offsets) + + @property + def values(self): + if self._tuples is not None: + return self._tuples + + values = [] + + for i in range(self.nlevels): + vals = self._get_level_values(i) + if is_categorical_dtype(vals): + vals = vals.get_values() + if (isinstance(vals.dtype, (PandasExtensionDtype, ExtensionDtype)) + or hasattr(vals, '_box_values')): + vals = vals.astype(object) + vals = np.array(vals, copy=False) + values.append(vals) + + self._tuples = lib.fast_zip(values) + return self._tuples + + @property + def _has_complex_internals(self): + # to disable groupby tricks + return True + + @cache_readonly + def is_monotonic_increasing(self): + """ + return if the index is monotonic increasing (only equal or + increasing) values. + """ + + # reversed() because lexsort() wants the most significant key last. + values = [self._get_level_values(i).values + for i in reversed(range(len(self.levels)))] + try: + sort_order = np.lexsort(values) + return Index(sort_order).is_monotonic + except TypeError: + + # we have mixed types and np.lexsort is not happy + return Index(self.values).is_monotonic + + @cache_readonly + def is_monotonic_decreasing(self): + """ + return if the index is monotonic decreasing (only equal or + decreasing) values. + """ + # monotonic decreasing if and only if reverse is monotonic increasing + return self[::-1].is_monotonic_increasing + + @cache_readonly + def _have_mixed_levels(self): + """ return a boolean list indicated if we have mixed levels """ + return ['mixed' in l for l in self._inferred_type_levels] + + @cache_readonly + def _inferred_type_levels(self): + """ return a list of the inferred types, one for each level """ + return [i.inferred_type for i in self.levels] + + @cache_readonly + def _hashed_values(self): + """ return a uint64 ndarray of my hashed values """ + from pandas.core.util.hashing import hash_tuples + return hash_tuples(self) + + def _hashed_indexing_key(self, key): + """ + validate and return the hash for the provided key + + *this is internal for use for the cython routines* + + Parameters + ---------- + key : string or tuple + + Returns + ------- + np.uint64 + + Notes + ----- + we need to stringify if we have mixed levels + + """ + from pandas.core.util.hashing import hash_tuples, hash_tuple + + if not isinstance(key, tuple): + return hash_tuples(key) + + if not len(key) == self.nlevels: + raise KeyError + + def f(k, stringify): + if stringify and not isinstance(k, compat.string_types): + k = str(k) + return k + key = tuple(f(k, stringify) + for k, stringify in zip(key, self._have_mixed_levels)) + return hash_tuple(key) + + @Appender(Index.duplicated.__doc__) + def duplicated(self, keep='first'): + from pandas.core.sorting import get_group_index + from pandas._libs.hashtable import duplicated_int64 + + shape = map(len, self.levels) + ids = get_group_index(self.codes, shape, sort=False, xnull=False) + + return duplicated_int64(ids, keep) + + def fillna(self, value=None, downcast=None): + """ + fillna is not implemented for MultiIndex + """ + raise NotImplementedError('isna is not defined for MultiIndex') + + @Appender(_index_shared_docs['dropna']) + def dropna(self, how='any'): + nans = [level_codes == -1 for level_codes in self.codes] + if how == 'any': + indexer = np.any(nans, axis=0) + elif how == 'all': + indexer = np.all(nans, axis=0) + else: + raise ValueError("invalid how option: {0}".format(how)) + + new_codes = [level_codes[~indexer] for level_codes in self.codes] + return self.copy(codes=new_codes, deep=True) + + def get_value(self, series, key): + # somewhat broken encapsulation + from pandas.core.indexing import maybe_droplevels + + # Label-based + s = com.values_from_object(series) + k = com.values_from_object(key) + + def _try_mi(k): + # TODO: what if a level contains tuples?? + loc = self.get_loc(k) + new_values = series._values[loc] + new_index = self[loc] + new_index = maybe_droplevels(new_index, k) + return series._constructor(new_values, index=new_index, + name=series.name).__finalize__(self) + + try: + return self._engine.get_value(s, k) + except KeyError as e1: + try: + return _try_mi(key) + except KeyError: + pass + + try: + return libindex.get_value_at(s, k) + except IndexError: + raise + except TypeError: + # generator/iterator-like + if is_iterator(key): + raise InvalidIndexError(key) + else: + raise e1 + except Exception: # pragma: no cover + raise e1 + except TypeError: + + # a Timestamp will raise a TypeError in a multi-index + # rather than a KeyError, try it here + # note that a string that 'looks' like a Timestamp will raise + # a KeyError! (GH5725) + if (isinstance(key, (datetime.datetime, np.datetime64)) or + (compat.PY3 and isinstance(key, compat.string_types))): + try: + return _try_mi(key) + except KeyError: + raise + except (IndexError, ValueError, TypeError): + pass + + try: + return _try_mi(Timestamp(key)) + except (KeyError, TypeError, + IndexError, ValueError, tslibs.OutOfBoundsDatetime): + pass + + raise InvalidIndexError(key) + + def _get_level_values(self, level, unique=False): + """ + Return vector of label values for requested level, + equal to the length of the index + + **this is an internal method** + + Parameters + ---------- + level : int level + unique : bool, default False + if True, drop duplicated values + + Returns + ------- + values : ndarray + """ + + values = self.levels[level] + level_codes = self.codes[level] + if unique: + level_codes = algos.unique(level_codes) + filled = algos.take_1d(values._values, level_codes, + fill_value=values._na_value) + values = values._shallow_copy(filled) + return values + + def get_level_values(self, level): + """ + Return vector of label values for requested level, + equal to the length of the index. + + Parameters + ---------- + level : int or str + ``level`` is either the integer position of the level in the + MultiIndex, or the name of the level. + + Returns + ------- + values : Index + ``values`` is a level of this MultiIndex converted to + a single :class:`Index` (or subclass thereof). + + Examples + --------- + + Create a MultiIndex: + + >>> mi = pd.MultiIndex.from_arrays((list('abc'), list('def'))) + >>> mi.names = ['level_1', 'level_2'] + + Get level values by supplying level as either integer or name: + + >>> mi.get_level_values(0) + Index(['a', 'b', 'c'], dtype='object', name='level_1') + >>> mi.get_level_values('level_2') + Index(['d', 'e', 'f'], dtype='object', name='level_2') + """ + level = self._get_level_number(level) + values = self._get_level_values(level) + return values + + @Appender(_index_shared_docs['index_unique'] % _index_doc_kwargs) + def unique(self, level=None): + + if level is None: + return super(MultiIndex, self).unique() + else: + level = self._get_level_number(level) + return self._get_level_values(level=level, unique=True) + + def _to_safe_for_reshape(self): + """ convert to object if we are a categorical """ + return self.set_levels([i._to_safe_for_reshape() for i in self.levels]) + + def to_frame(self, index=True, name=None): + """ + Create a DataFrame with the levels of the MultiIndex as columns. + + Column ordering is determined by the DataFrame constructor with data as + a dict. + + .. versionadded:: 0.24.0 + + Parameters + ---------- + index : boolean, default True + Set the index of the returned DataFrame as the original MultiIndex. + + name : list / sequence of strings, optional + The passed names should substitute index level names. + + Returns + ------- + DataFrame : a DataFrame containing the original MultiIndex data. + + See Also + -------- + DataFrame + """ + + from pandas import DataFrame + if name is not None: + if not is_list_like(name): + raise TypeError("'name' must be a list / sequence " + "of column names.") + + if len(name) != len(self.levels): + raise ValueError("'name' should have same length as " + "number of levels on index.") + idx_names = name + else: + idx_names = self.names + + # Guarantee resulting column order + result = DataFrame( + OrderedDict([ + ((level if lvlname is None else lvlname), + self._get_level_values(level)) + for lvlname, level in zip(idx_names, range(len(self.levels))) + ]), + copy=False + ) + + if index: + result.index = self + return result + + def to_hierarchical(self, n_repeat, n_shuffle=1): + """ + Return a MultiIndex reshaped to conform to the + shapes given by n_repeat and n_shuffle. + + .. deprecated:: 0.24.0 + + Useful to replicate and rearrange a MultiIndex for combination + with another Index with n_repeat items. + + Parameters + ---------- + n_repeat : int + Number of times to repeat the labels on self + n_shuffle : int + Controls the reordering of the labels. If the result is going + to be an inner level in a MultiIndex, n_shuffle will need to be + greater than one. The size of each label must divisible by + n_shuffle. + + Returns + ------- + MultiIndex + + Examples + -------- + >>> idx = pd.MultiIndex.from_tuples([(1, u'one'), (1, u'two'), + (2, u'one'), (2, u'two')]) + >>> idx.to_hierarchical(3) + MultiIndex(levels=[[1, 2], [u'one', u'two']], + codes=[[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], + [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1]]) + """ + levels = self.levels + codes = [np.repeat(level_codes, n_repeat) for + level_codes in self.codes] + # Assumes that each level_codes is divisible by n_shuffle + codes = [x.reshape(n_shuffle, -1).ravel(order='F') for x in codes] + names = self.names + warnings.warn("Method .to_hierarchical is deprecated and will " + "be removed in a future version", + FutureWarning, stacklevel=2) + return MultiIndex(levels=levels, codes=codes, names=names) + + def to_flat_index(self): + """ + Convert a MultiIndex to an Index of Tuples containing the level values. + + .. versionadded:: 0.24.0 + + Returns + ------- + pd.Index + Index with the MultiIndex data represented in Tuples. + + Notes + ----- + This method will simply return the caller if called by anything other + than a MultiIndex. + + Examples + -------- + >>> index = pd.MultiIndex.from_product( + ... [['foo', 'bar'], ['baz', 'qux']], + ... names=['a', 'b']) + >>> index.to_flat_index() + Index([('foo', 'baz'), ('foo', 'qux'), + ('bar', 'baz'), ('bar', 'qux')], + dtype='object') + """ + return Index(self.values, tupleize_cols=False) + + @property + def is_all_dates(self): + return False + + def is_lexsorted(self): + """ + Return True if the codes are lexicographically sorted + """ + return self.lexsort_depth == self.nlevels + + @cache_readonly + def lexsort_depth(self): + if self.sortorder is not None: + if self.sortorder == 0: + return self.nlevels + else: + return 0 + + int64_codes = [ensure_int64(level_codes) for level_codes in self.codes] + for k in range(self.nlevels, 0, -1): + if libalgos.is_lexsorted(int64_codes[:k]): + return k + + return 0 + + def _sort_levels_monotonic(self): + """ + .. versionadded:: 0.20.0 + + This is an *internal* function. + + Create a new MultiIndex from the current to monotonically sorted + items IN the levels. This does not actually make the entire MultiIndex + monotonic, JUST the levels. + + The resulting MultiIndex will have the same outward + appearance, meaning the same .values and ordering. It will also + be .equals() to the original. + + Returns + ------- + MultiIndex + + Examples + -------- + + >>> i = pd.MultiIndex(levels=[['a', 'b'], ['bb', 'aa']], + codes=[[0, 0, 1, 1], [0, 1, 0, 1]]) + >>> i + MultiIndex(levels=[['a', 'b'], ['bb', 'aa']], + codes=[[0, 0, 1, 1], [0, 1, 0, 1]]) + + >>> i.sort_monotonic() + MultiIndex(levels=[['a', 'b'], ['aa', 'bb']], + codes=[[0, 0, 1, 1], [1, 0, 1, 0]]) + + """ + + if self.is_lexsorted() and self.is_monotonic: + return self + + new_levels = [] + new_codes = [] + + for lev, level_codes in zip(self.levels, self.codes): + + if not lev.is_monotonic: + try: + # indexer to reorder the levels + indexer = lev.argsort() + except TypeError: + pass + else: + lev = lev.take(indexer) + + # indexer to reorder the level codes + indexer = ensure_int64(indexer) + ri = lib.get_reverse_indexer(indexer, len(indexer)) + level_codes = algos.take_1d(ri, level_codes) + + new_levels.append(lev) + new_codes.append(level_codes) + + return MultiIndex(new_levels, new_codes, + names=self.names, sortorder=self.sortorder, + verify_integrity=False) + + def remove_unused_levels(self): + """ + Create a new MultiIndex from the current that removes + unused levels, meaning that they are not expressed in the labels. + + The resulting MultiIndex will have the same outward + appearance, meaning the same .values and ordering. It will also + be .equals() to the original. + + .. versionadded:: 0.20.0 + + Returns + ------- + MultiIndex + + Examples + -------- + >>> i = pd.MultiIndex.from_product([range(2), list('ab')]) + MultiIndex(levels=[[0, 1], ['a', 'b']], + codes=[[0, 0, 1, 1], [0, 1, 0, 1]]) + + >>> i[2:] + MultiIndex(levels=[[0, 1], ['a', 'b']], + codes=[[1, 1], [0, 1]]) + + The 0 from the first level is not represented + and can be removed + + >>> i[2:].remove_unused_levels() + MultiIndex(levels=[[1], ['a', 'b']], + codes=[[0, 0], [0, 1]]) + """ + + new_levels = [] + new_codes = [] + + changed = False + for lev, level_codes in zip(self.levels, self.codes): + + # Since few levels are typically unused, bincount() is more + # efficient than unique() - however it only accepts positive values + # (and drops order): + uniques = np.where(np.bincount(level_codes + 1) > 0)[0] - 1 + has_na = int(len(uniques) and (uniques[0] == -1)) + + if len(uniques) != len(lev) + has_na: + # We have unused levels + changed = True + + # Recalculate uniques, now preserving order. + # Can easily be cythonized by exploiting the already existing + # "uniques" and stop parsing "level_codes" when all items + # are found: + uniques = algos.unique(level_codes) + if has_na: + na_idx = np.where(uniques == -1)[0] + # Just ensure that -1 is in first position: + uniques[[0, na_idx[0]]] = uniques[[na_idx[0], 0]] + + # codes get mapped from uniques to 0:len(uniques) + # -1 (if present) is mapped to last position + code_mapping = np.zeros(len(lev) + has_na) + # ... and reassigned value -1: + code_mapping[uniques] = np.arange(len(uniques)) - has_na + + level_codes = code_mapping[level_codes] + + # new levels are simple + lev = lev.take(uniques[has_na:]) + + new_levels.append(lev) + new_codes.append(level_codes) + + result = self._shallow_copy() + + if changed: + result._reset_identity() + result._set_levels(new_levels, validate=False) + result._set_codes(new_codes, validate=False) + + return result + + @property + def nlevels(self): + """Integer number of levels in this MultiIndex.""" + return len(self.levels) + + @property + def levshape(self): + """A tuple with the length of each level.""" + return tuple(len(x) for x in self.levels) + + def __reduce__(self): + """Necessary for making this object picklable""" + d = dict(levels=[lev for lev in self.levels], + codes=[level_codes for level_codes in self.codes], + sortorder=self.sortorder, names=list(self.names)) + return ibase._new_Index, (self.__class__, d), None + + def __setstate__(self, state): + """Necessary for making this object picklable""" + + if isinstance(state, dict): + levels = state.get('levels') + codes = state.get('codes') + sortorder = state.get('sortorder') + names = state.get('names') + + elif isinstance(state, tuple): + + nd_state, own_state = state + levels, codes, sortorder, names = own_state + + self._set_levels([Index(x) for x in levels], validate=False) + self._set_codes(codes) + self._set_names(names) + self.sortorder = sortorder + self._verify_integrity() + self._reset_identity() + + def __getitem__(self, key): + if is_scalar(key): + key = com.cast_scalar_indexer(key) + + retval = [] + for lev, level_codes in zip(self.levels, self.codes): + if level_codes[key] == -1: + retval.append(np.nan) + else: + retval.append(lev[level_codes[key]]) + + return tuple(retval) + else: + if com.is_bool_indexer(key): + key = np.asarray(key, dtype=bool) + sortorder = self.sortorder + else: + # cannot be sure whether the result will be sorted + sortorder = None + + if isinstance(key, Index): + key = np.asarray(key) + + new_codes = [level_codes[key] for level_codes in self.codes] + + return MultiIndex(levels=self.levels, codes=new_codes, + names=self.names, sortorder=sortorder, + verify_integrity=False) + + @Appender(_index_shared_docs['take'] % _index_doc_kwargs) + def take(self, indices, axis=0, allow_fill=True, + fill_value=None, **kwargs): + nv.validate_take(tuple(), kwargs) + indices = ensure_platform_int(indices) + taken = self._assert_take_fillable(self.codes, indices, + allow_fill=allow_fill, + fill_value=fill_value, + na_value=-1) + return MultiIndex(levels=self.levels, codes=taken, + names=self.names, verify_integrity=False) + + def _assert_take_fillable(self, values, indices, allow_fill=True, + fill_value=None, na_value=None): + """ Internal method to handle NA filling of take """ + # only fill if we are passing a non-None fill_value + if allow_fill and fill_value is not None: + if (indices < -1).any(): + msg = ('When allow_fill=True and fill_value is not None, ' + 'all indices must be >= -1') + raise ValueError(msg) + taken = [lab.take(indices) for lab in self.codes] + mask = indices == -1 + if mask.any(): + masked = [] + for new_label in taken: + label_values = new_label.values() + label_values[mask] = na_value + masked.append(np.asarray(label_values)) + taken = masked + else: + taken = [lab.take(indices) for lab in self.codes] + return taken + + def append(self, other): + """ + Append a collection of Index options together + + Parameters + ---------- + other : Index or list/tuple of indices + + Returns + ------- + appended : Index + """ + if not isinstance(other, (list, tuple)): + other = [other] + + if all((isinstance(o, MultiIndex) and o.nlevels >= self.nlevels) + for o in other): + arrays = [] + for i in range(self.nlevels): + label = self._get_level_values(i) + appended = [o._get_level_values(i) for o in other] + arrays.append(label.append(appended)) + return MultiIndex.from_arrays(arrays, names=self.names) + + to_concat = (self.values, ) + tuple(k._values for k in other) + new_tuples = np.concatenate(to_concat) + + # if all(isinstance(x, MultiIndex) for x in other): + try: + return MultiIndex.from_tuples(new_tuples, names=self.names) + except (TypeError, IndexError): + return Index(new_tuples) + + def argsort(self, *args, **kwargs): + return self.values.argsort(*args, **kwargs) + + @Appender(_index_shared_docs['repeat'] % _index_doc_kwargs) + def repeat(self, repeats, axis=None): + nv.validate_repeat(tuple(), dict(axis=axis)) + return MultiIndex(levels=self.levels, + codes=[level_codes.view(np.ndarray).repeat(repeats) + for level_codes in self.codes], + names=self.names, sortorder=self.sortorder, + verify_integrity=False) + + def where(self, cond, other=None): + raise NotImplementedError(".where is not supported for " + "MultiIndex operations") + + @deprecate_kwarg(old_arg_name='labels', new_arg_name='codes') + def drop(self, codes, level=None, errors='raise'): + """ + Make new MultiIndex with passed list of codes deleted + + Parameters + ---------- + codes : array-like + Must be a list of tuples + level : int or level name, default None + + Returns + ------- + dropped : MultiIndex + """ + if level is not None: + return self._drop_from_level(codes, level) + + try: + if not isinstance(codes, (np.ndarray, Index)): + codes = com.index_labels_to_array(codes) + indexer = self.get_indexer(codes) + mask = indexer == -1 + if mask.any(): + if errors != 'ignore': + raise ValueError('codes %s not contained in axis' % + codes[mask]) + except Exception: + pass + + inds = [] + for level_codes in codes: + try: + loc = self.get_loc(level_codes) + # get_loc returns either an integer, a slice, or a boolean + # mask + if isinstance(loc, int): + inds.append(loc) + elif isinstance(loc, slice): + inds.extend(lrange(loc.start, loc.stop)) + elif com.is_bool_indexer(loc): + if self.lexsort_depth == 0: + warnings.warn('dropping on a non-lexsorted multi-index' + ' without a level parameter may impact ' + 'performance.', + PerformanceWarning, + stacklevel=3) + loc = loc.nonzero()[0] + inds.extend(loc) + else: + msg = 'unsupported indexer of type {}'.format(type(loc)) + raise AssertionError(msg) + except KeyError: + if errors != 'ignore': + raise + + return self.delete(inds) + + def _drop_from_level(self, codes, level): + codes = com.index_labels_to_array(codes) + i = self._get_level_number(level) + index = self.levels[i] + values = index.get_indexer(codes) + + mask = ~algos.isin(self.codes[i], values) + + return self[mask] + + def swaplevel(self, i=-2, j=-1): + """ + Swap level i with level j. + + Calling this method does not change the ordering of the values. + + Parameters + ---------- + i : int, str, default -2 + First level of index to be swapped. Can pass level name as string. + Type of parameters can be mixed. + j : int, str, default -1 + Second level of index to be swapped. Can pass level name as string. + Type of parameters can be mixed. + + Returns + ------- + MultiIndex + A new MultiIndex + + .. versionchanged:: 0.18.1 + + The indexes ``i`` and ``j`` are now optional, and default to + the two innermost levels of the index. + + See Also + -------- + Series.swaplevel : Swap levels i and j in a MultiIndex. + Dataframe.swaplevel : Swap levels i and j in a MultiIndex on a + particular axis. + + Examples + -------- + >>> mi = pd.MultiIndex(levels=[['a', 'b'], ['bb', 'aa']], + ... codes=[[0, 0, 1, 1], [0, 1, 0, 1]]) + >>> mi + MultiIndex(levels=[['a', 'b'], ['bb', 'aa']], + codes=[[0, 0, 1, 1], [0, 1, 0, 1]]) + >>> mi.swaplevel(0, 1) + MultiIndex(levels=[['bb', 'aa'], ['a', 'b']], + codes=[[0, 1, 0, 1], [0, 0, 1, 1]]) + """ + new_levels = list(self.levels) + new_codes = list(self.codes) + new_names = list(self.names) + + i = self._get_level_number(i) + j = self._get_level_number(j) + + new_levels[i], new_levels[j] = new_levels[j], new_levels[i] + new_codes[i], new_codes[j] = new_codes[j], new_codes[i] + new_names[i], new_names[j] = new_names[j], new_names[i] + + return MultiIndex(levels=new_levels, codes=new_codes, + names=new_names, verify_integrity=False) + + def reorder_levels(self, order): + """ + Rearrange levels using input order. May not drop or duplicate levels + + Parameters + ---------- + """ + order = [self._get_level_number(i) for i in order] + if len(order) != self.nlevels: + raise AssertionError('Length of order must be same as ' + 'number of levels (%d), got %d' % + (self.nlevels, len(order))) + new_levels = [self.levels[i] for i in order] + new_codes = [self.codes[i] for i in order] + new_names = [self.names[i] for i in order] + + return MultiIndex(levels=new_levels, codes=new_codes, + names=new_names, verify_integrity=False) + + def __getslice__(self, i, j): + return self.__getitem__(slice(i, j)) + + def _get_codes_for_sorting(self): + """ + we categorizing our codes by using the + available categories (all, not just observed) + excluding any missing ones (-1); this is in preparation + for sorting, where we need to disambiguate that -1 is not + a valid valid + """ + from pandas.core.arrays import Categorical + + def cats(level_codes): + return np.arange(np.array(level_codes).max() + 1 if + len(level_codes) else 0, + dtype=level_codes.dtype) + + return [Categorical.from_codes(level_codes, cats(level_codes), + ordered=True) + for level_codes in self.codes] + + def sortlevel(self, level=0, ascending=True, sort_remaining=True): + """ + Sort MultiIndex at the requested level. The result will respect the + original ordering of the associated factor at that level. + + Parameters + ---------- + level : list-like, int or str, default 0 + If a string is given, must be a name of the level + If list-like must be names or ints of levels. + ascending : boolean, default True + False to sort in descending order + Can also be a list to specify a directed ordering + sort_remaining : sort by the remaining levels after level + + Returns + ------- + sorted_index : pd.MultiIndex + Resulting index + indexer : np.ndarray + Indices of output values in original index + """ + from pandas.core.sorting import indexer_from_factorized + + if isinstance(level, (compat.string_types, int)): + level = [level] + level = [self._get_level_number(lev) for lev in level] + sortorder = None + + # we have a directed ordering via ascending + if isinstance(ascending, list): + if not len(level) == len(ascending): + raise ValueError("level must have same length as ascending") + + from pandas.core.sorting import lexsort_indexer + indexer = lexsort_indexer([self.codes[lev] for lev in level], + orders=ascending) + + # level ordering + else: + + codes = list(self.codes) + shape = list(self.levshape) + + # partition codes and shape + primary = tuple(codes.pop(lev - i) for i, lev in enumerate(level)) + primshp = tuple(shape.pop(lev - i) for i, lev in enumerate(level)) + + if sort_remaining: + primary += primary + tuple(codes) + primshp += primshp + tuple(shape) + else: + sortorder = level[0] + + indexer = indexer_from_factorized(primary, primshp, + compress=False) + + if not ascending: + indexer = indexer[::-1] + + indexer = ensure_platform_int(indexer) + new_codes = [level_codes.take(indexer) for level_codes in self.codes] + + new_index = MultiIndex(codes=new_codes, levels=self.levels, + names=self.names, sortorder=sortorder, + verify_integrity=False) + + return new_index, indexer + + def _convert_listlike_indexer(self, keyarr, kind=None): + """ + Parameters + ---------- + keyarr : list-like + Indexer to convert. + + Returns + ------- + tuple (indexer, keyarr) + indexer is an ndarray or None if cannot convert + keyarr are tuple-safe keys + """ + indexer, keyarr = super(MultiIndex, self)._convert_listlike_indexer( + keyarr, kind=kind) + + # are we indexing a specific level + if indexer is None and len(keyarr) and not isinstance(keyarr[0], + tuple): + level = 0 + _, indexer = self.reindex(keyarr, level=level) + + # take all + if indexer is None: + indexer = np.arange(len(self)) + + check = self.levels[0].get_indexer(keyarr) + mask = check == -1 + if mask.any(): + raise KeyError('%s not in index' % keyarr[mask]) + + return indexer, keyarr + + @Appender(_index_shared_docs['get_indexer'] % _index_doc_kwargs) + def get_indexer(self, target, method=None, limit=None, tolerance=None): + method = missing.clean_reindex_fill_method(method) + target = ensure_index(target) + + # empty indexer + if is_list_like(target) and not len(target): + return ensure_platform_int(np.array([])) + + if not isinstance(target, MultiIndex): + try: + target = MultiIndex.from_tuples(target) + except (TypeError, ValueError): + + # let's instead try with a straight Index + if method is None: + return Index(self.values).get_indexer(target, + method=method, + limit=limit, + tolerance=tolerance) + + if not self.is_unique: + raise ValueError('Reindexing only valid with uniquely valued ' + 'Index objects') + + if method == 'pad' or method == 'backfill': + if tolerance is not None: + raise NotImplementedError("tolerance not implemented yet " + 'for MultiIndex') + indexer = self._engine.get_indexer(target, method, limit) + elif method == 'nearest': + raise NotImplementedError("method='nearest' not implemented yet " + 'for MultiIndex; see GitHub issue 9365') + else: + indexer = self._engine.get_indexer(target) + + return ensure_platform_int(indexer) + + @Appender(_index_shared_docs['get_indexer_non_unique'] % _index_doc_kwargs) + def get_indexer_non_unique(self, target): + return super(MultiIndex, self).get_indexer_non_unique(target) + + def reindex(self, target, method=None, level=None, limit=None, + tolerance=None): + """ + Create index with target's values (move/add/delete values as necessary) + + Returns + ------- + new_index : pd.MultiIndex + Resulting index + indexer : np.ndarray or None + Indices of output values in original index + + """ + # GH6552: preserve names when reindexing to non-named target + # (i.e. neither Index nor Series). + preserve_names = not hasattr(target, 'names') + + if level is not None: + if method is not None: + raise TypeError('Fill method not supported if level passed') + + # GH7774: preserve dtype/tz if target is empty and not an Index. + # target may be an iterator + target = ibase._ensure_has_len(target) + if len(target) == 0 and not isinstance(target, Index): + idx = self.levels[level] + attrs = idx._get_attributes_dict() + attrs.pop('freq', None) # don't preserve freq + target = type(idx)._simple_new(np.empty(0, dtype=idx.dtype), + **attrs) + else: + target = ensure_index(target) + target, indexer, _ = self._join_level(target, level, how='right', + return_indexers=True, + keep_order=False) + else: + target = ensure_index(target) + if self.equals(target): + indexer = None + else: + if self.is_unique: + indexer = self.get_indexer(target, method=method, + limit=limit, + tolerance=tolerance) + else: + raise ValueError("cannot handle a non-unique multi-index!") + + if not isinstance(target, MultiIndex): + if indexer is None: + target = self + elif (indexer >= 0).all(): + target = self.take(indexer) + else: + # hopefully? + target = MultiIndex.from_tuples(target) + + if (preserve_names and target.nlevels == self.nlevels and + target.names != self.names): + target = target.copy(deep=False) + target.names = self.names + + return target, indexer + + def get_slice_bound(self, label, side, kind): + + if not isinstance(label, tuple): + label = label, + return self._partial_tup_index(label, side=side) + + def slice_locs(self, start=None, end=None, step=None, kind=None): + """ + For an ordered MultiIndex, compute the slice locations for input + labels. + + The input labels can be tuples representing partial levels, e.g. for a + MultiIndex with 3 levels, you can pass a single value (corresponding to + the first level), or a 1-, 2-, or 3-tuple. + + Parameters + ---------- + start : label or tuple, default None + If None, defaults to the beginning + end : label or tuple + If None, defaults to the end + step : int or None + Slice step + kind : string, optional, defaults None + + Returns + ------- + (start, end) : (int, int) + + Notes + ----- + This method only works if the MultiIndex is properly lexsorted. So, + if only the first 2 levels of a 3-level MultiIndex are lexsorted, + you can only pass two levels to ``.slice_locs``. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([list('abbd'), list('deff')], + ... names=['A', 'B']) + + Get the slice locations from the beginning of 'b' in the first level + until the end of the multiindex: + + >>> mi.slice_locs(start='b') + (1, 4) + + Like above, but stop at the end of 'b' in the first level and 'f' in + the second level: + + >>> mi.slice_locs(start='b', end=('b', 'f')) + (1, 3) + + See Also + -------- + MultiIndex.get_loc : Get location for a label or a tuple of labels. + MultiIndex.get_locs : Get location for a label/slice/list/mask or a + sequence of such. + """ + # This function adds nothing to its parent implementation (the magic + # happens in get_slice_bound method), but it adds meaningful doc. + return super(MultiIndex, self).slice_locs(start, end, step, kind=kind) + + def _partial_tup_index(self, tup, side='left'): + if len(tup) > self.lexsort_depth: + raise UnsortedIndexError( + 'Key length (%d) was greater than MultiIndex' + ' lexsort depth (%d)' % + (len(tup), self.lexsort_depth)) + + n = len(tup) + start, end = 0, len(self) + zipped = zip(tup, self.levels, self.codes) + for k, (lab, lev, labs) in enumerate(zipped): + section = labs[start:end] + + if lab not in lev: + if not lev.is_type_compatible(lib.infer_dtype([lab], + skipna=False)): + raise TypeError('Level type mismatch: %s' % lab) + + # short circuit + loc = lev.searchsorted(lab, side=side) + if side == 'right' and loc >= 0: + loc -= 1 + return start + section.searchsorted(loc, side=side) + + idx = lev.get_loc(lab) + if k < n - 1: + end = start + section.searchsorted(idx, side='right') + start = start + section.searchsorted(idx, side='left') + else: + return start + section.searchsorted(idx, side=side) + + def get_loc(self, key, method=None): + """ + Get location for a label or a tuple of labels as an integer, slice or + boolean mask. + + Parameters + ---------- + key : label or tuple of labels (one for each level) + method : None + + Returns + ------- + loc : int, slice object or boolean mask + If the key is past the lexsort depth, the return may be a + boolean mask array, otherwise it is always a slice or int. + + Examples + --------- + >>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')]) + + >>> mi.get_loc('b') + slice(1, 3, None) + + >>> mi.get_loc(('b', 'e')) + 1 + + Notes + ------ + The key cannot be a slice, list of same-level labels, a boolean mask, + or a sequence of such. If you want to use those, use + :meth:`MultiIndex.get_locs` instead. + + See Also + -------- + Index.get_loc : The get_loc method for (single-level) index. + MultiIndex.slice_locs : Get slice location given start label(s) and + end label(s). + MultiIndex.get_locs : Get location for a label/slice/list/mask or a + sequence of such. + """ + if method is not None: + raise NotImplementedError('only the default get_loc method is ' + 'currently supported for MultiIndex') + + def _maybe_to_slice(loc): + """convert integer indexer to boolean mask or slice if possible""" + if not isinstance(loc, np.ndarray) or loc.dtype != 'int64': + return loc + + loc = lib.maybe_indices_to_slice(loc, len(self)) + if isinstance(loc, slice): + return loc + + mask = np.empty(len(self), dtype='bool') + mask.fill(False) + mask[loc] = True + return mask + + if not isinstance(key, tuple): + loc = self._get_level_indexer(key, level=0) + return _maybe_to_slice(loc) + + keylen = len(key) + if self.nlevels < keylen: + raise KeyError('Key length ({0}) exceeds index depth ({1})' + ''.format(keylen, self.nlevels)) + + if keylen == self.nlevels and self.is_unique: + return self._engine.get_loc(key) + + # -- partial selection or non-unique index + # break the key into 2 parts based on the lexsort_depth of the index; + # the first part returns a continuous slice of the index; the 2nd part + # needs linear search within the slice + i = self.lexsort_depth + lead_key, follow_key = key[:i], key[i:] + start, stop = (self.slice_locs(lead_key, lead_key) + if lead_key else (0, len(self))) + + if start == stop: + raise KeyError(key) + + if not follow_key: + return slice(start, stop) + + warnings.warn('indexing past lexsort depth may impact performance.', + PerformanceWarning, stacklevel=10) + + loc = np.arange(start, stop, dtype='int64') + + for i, k in enumerate(follow_key, len(lead_key)): + mask = self.codes[i][loc] == self.levels[i].get_loc(k) + if not mask.all(): + loc = loc[mask] + if not len(loc): + raise KeyError(key) + + return (_maybe_to_slice(loc) if len(loc) != stop - start else + slice(start, stop)) + + def get_loc_level(self, key, level=0, drop_level=True): + """ + Get both the location for the requested label(s) and the + resulting sliced index. + + Parameters + ---------- + key : label or sequence of labels + level : int/level name or list thereof, optional + drop_level : bool, default True + if ``False``, the resulting index will not drop any level. + + Returns + ------- + loc : A 2-tuple where the elements are: + Element 0: int, slice object or boolean array + Element 1: The resulting sliced multiindex/index. If the key + contains all levels, this will be ``None``. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')], + ... names=['A', 'B']) + + >>> mi.get_loc_level('b') + (slice(1, 3, None), Index(['e', 'f'], dtype='object', name='B')) + + >>> mi.get_loc_level('e', level='B') + (array([False, True, False], dtype=bool), + Index(['b'], dtype='object', name='A')) + + >>> mi.get_loc_level(['b', 'e']) + (1, None) + + See Also + --------- + MultiIndex.get_loc : Get location for a label or a tuple of labels. + MultiIndex.get_locs : Get location for a label/slice/list/mask or a + sequence of such. + """ + + def maybe_droplevels(indexer, levels, drop_level): + if not drop_level: + return self[indexer] + # kludgearound + orig_index = new_index = self[indexer] + levels = [self._get_level_number(i) for i in levels] + for i in sorted(levels, reverse=True): + try: + new_index = new_index.droplevel(i) + except ValueError: + + # no dropping here + return orig_index + return new_index + + if isinstance(level, (tuple, list)): + if len(key) != len(level): + raise AssertionError('Key for location must have same ' + 'length as number of levels') + result = None + for lev, k in zip(level, key): + loc, new_index = self.get_loc_level(k, level=lev) + if isinstance(loc, slice): + mask = np.zeros(len(self), dtype=bool) + mask[loc] = True + loc = mask + + result = loc if result is None else result & loc + + return result, maybe_droplevels(result, level, drop_level) + + level = self._get_level_number(level) + + # kludge for #1796 + if isinstance(key, list): + key = tuple(key) + + if isinstance(key, tuple) and level == 0: + + try: + if key in self.levels[0]: + indexer = self._get_level_indexer(key, level=level) + new_index = maybe_droplevels(indexer, [0], drop_level) + return indexer, new_index + except TypeError: + pass + + if not any(isinstance(k, slice) for k in key): + + # partial selection + # optionally get indexer to avoid re-calculation + def partial_selection(key, indexer=None): + if indexer is None: + indexer = self.get_loc(key) + ilevels = [i for i in range(len(key)) + if key[i] != slice(None, None)] + return indexer, maybe_droplevels(indexer, ilevels, + drop_level) + + if len(key) == self.nlevels and self.is_unique: + # Complete key in unique index -> standard get_loc + return (self._engine.get_loc(key), None) + else: + return partial_selection(key) + else: + indexer = None + for i, k in enumerate(key): + if not isinstance(k, slice): + k = self._get_level_indexer(k, level=i) + if isinstance(k, slice): + # everything + if k.start == 0 and k.stop == len(self): + k = slice(None, None) + else: + k_index = k + + if isinstance(k, slice): + if k == slice(None, None): + continue + else: + raise TypeError(key) + + if indexer is None: + indexer = k_index + else: # pragma: no cover + indexer &= k_index + if indexer is None: + indexer = slice(None, None) + ilevels = [i for i in range(len(key)) + if key[i] != slice(None, None)] + return indexer, maybe_droplevels(indexer, ilevels, drop_level) + else: + indexer = self._get_level_indexer(key, level=level) + return indexer, maybe_droplevels(indexer, [level], drop_level) + + def _get_level_indexer(self, key, level=0, indexer=None): + # return an indexer, boolean array or a slice showing where the key is + # in the totality of values + # if the indexer is provided, then use this + + level_index = self.levels[level] + level_codes = self.codes[level] + + def convert_indexer(start, stop, step, indexer=indexer, + codes=level_codes): + # given the inputs and the codes/indexer, compute an indexer set + # if we have a provided indexer, then this need not consider + # the entire labels set + + r = np.arange(start, stop, step) + if indexer is not None and len(indexer) != len(codes): + + # we have an indexer which maps the locations in the labels + # that we have already selected (and is not an indexer for the + # entire set) otherwise this is wasteful so we only need to + # examine locations that are in this set the only magic here is + # that the result are the mappings to the set that we have + # selected + from pandas import Series + mapper = Series(indexer) + indexer = codes.take(ensure_platform_int(indexer)) + result = Series(Index(indexer).isin(r).nonzero()[0]) + m = result.map(mapper)._ndarray_values + + else: + m = np.zeros(len(codes), dtype=bool) + m[np.in1d(codes, r, + assume_unique=Index(codes).is_unique)] = True + + return m + + if isinstance(key, slice): + # handle a slice, returnig a slice if we can + # otherwise a boolean indexer + + try: + if key.start is not None: + start = level_index.get_loc(key.start) + else: + start = 0 + if key.stop is not None: + stop = level_index.get_loc(key.stop) + else: + stop = len(level_index) - 1 + step = key.step + except KeyError: + + # we have a partial slice (like looking up a partial date + # string) + start = stop = level_index.slice_indexer(key.start, key.stop, + key.step, kind='loc') + step = start.step + + if isinstance(start, slice) or isinstance(stop, slice): + # we have a slice for start and/or stop + # a partial date slicer on a DatetimeIndex generates a slice + # note that the stop ALREADY includes the stopped point (if + # it was a string sliced) + return convert_indexer(start.start, stop.stop, step) + + elif level > 0 or self.lexsort_depth == 0 or step is not None: + # need to have like semantics here to right + # searching as when we are using a slice + # so include the stop+1 (so we include stop) + return convert_indexer(start, stop + 1, step) + else: + # sorted, so can return slice object -> view + i = level_codes.searchsorted(start, side='left') + j = level_codes.searchsorted(stop, side='right') + return slice(i, j, step) + + else: + + code = level_index.get_loc(key) + + if level > 0 or self.lexsort_depth == 0: + # Desired level is not sorted + locs = np.array(level_codes == code, dtype=bool, copy=False) + if not locs.any(): + # The label is present in self.levels[level] but unused: + raise KeyError(key) + return locs + + i = level_codes.searchsorted(code, side='left') + j = level_codes.searchsorted(code, side='right') + if i == j: + # The label is present in self.levels[level] but unused: + raise KeyError(key) + return slice(i, j) + + def get_locs(self, seq): + """ + Get location for a given label/slice/list/mask or a sequence of such as + an array of integers. + + Parameters + ---------- + seq : label/slice/list/mask or a sequence of such + You should use one of the above for each level. + If a level should not be used, set it to ``slice(None)``. + + Returns + ------- + locs : array of integers suitable for passing to iloc + + Examples + --------- + >>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')]) + + >>> mi.get_locs('b') + array([1, 2], dtype=int64) + + >>> mi.get_locs([slice(None), ['e', 'f']]) + array([1, 2], dtype=int64) + + >>> mi.get_locs([[True, False, True], slice('e', 'f')]) + array([2], dtype=int64) + + See Also + -------- + MultiIndex.get_loc : Get location for a label or a tuple of labels. + MultiIndex.slice_locs : Get slice location given start label(s) and + end label(s). + """ + from .numeric import Int64Index + + # must be lexsorted to at least as many levels + true_slices = [i for (i, s) in enumerate(com.is_true_slices(seq)) if s] + if true_slices and true_slices[-1] >= self.lexsort_depth: + raise UnsortedIndexError('MultiIndex slicing requires the index ' + 'to be lexsorted: slicing on levels {0}, ' + 'lexsort depth {1}' + .format(true_slices, self.lexsort_depth)) + # indexer + # this is the list of all values that we want to select + n = len(self) + indexer = None + + def _convert_to_indexer(r): + # return an indexer + if isinstance(r, slice): + m = np.zeros(n, dtype=bool) + m[r] = True + r = m.nonzero()[0] + elif com.is_bool_indexer(r): + if len(r) != n: + raise ValueError("cannot index with a boolean indexer " + "that is not the same length as the " + "index") + r = r.nonzero()[0] + return Int64Index(r) + + def _update_indexer(idxr, indexer=indexer): + if indexer is None: + indexer = Index(np.arange(n)) + if idxr is None: + return indexer + return indexer & idxr + + for i, k in enumerate(seq): + + if com.is_bool_indexer(k): + # a boolean indexer, must be the same length! + k = np.asarray(k) + indexer = _update_indexer(_convert_to_indexer(k), + indexer=indexer) + + elif is_list_like(k): + # a collection of labels to include from this level (these + # are or'd) + indexers = None + for x in k: + try: + idxrs = _convert_to_indexer( + self._get_level_indexer(x, level=i, + indexer=indexer)) + indexers = (idxrs if indexers is None + else indexers | idxrs) + except KeyError: + + # ignore not founds + continue + + if indexers is not None: + indexer = _update_indexer(indexers, indexer=indexer) + else: + # no matches we are done + return Int64Index([])._ndarray_values + + elif com.is_null_slice(k): + # empty slice + indexer = _update_indexer(None, indexer=indexer) + + elif isinstance(k, slice): + + # a slice, include BOTH of the labels + indexer = _update_indexer(_convert_to_indexer( + self._get_level_indexer(k, level=i, indexer=indexer)), + indexer=indexer) + else: + # a single label + indexer = _update_indexer(_convert_to_indexer( + self.get_loc_level(k, level=i, drop_level=False)[0]), + indexer=indexer) + + # empty indexer + if indexer is None: + return Int64Index([])._ndarray_values + return indexer._ndarray_values + + def truncate(self, before=None, after=None): + """ + Slice index between two labels / tuples, return new MultiIndex + + Parameters + ---------- + before : label or tuple, can be partial. Default None + None defaults to start + after : label or tuple, can be partial. Default None + None defaults to end + + Returns + ------- + truncated : MultiIndex + """ + if after and before and after < before: + raise ValueError('after < before') + + i, j = self.levels[0].slice_locs(before, after) + left, right = self.slice_locs(before, after) + + new_levels = list(self.levels) + new_levels[0] = new_levels[0][i:j] + + new_codes = [level_codes[left:right] for level_codes in self.codes] + new_codes[0] = new_codes[0] - i + + return MultiIndex(levels=new_levels, codes=new_codes, + verify_integrity=False) + + def equals(self, other): + """ + Determines if two MultiIndex objects have the same labeling information + (the levels themselves do not necessarily have to be the same) + + See Also + -------- + equal_levels + """ + if self.is_(other): + return True + + if not isinstance(other, Index): + return False + + if not isinstance(other, MultiIndex): + other_vals = com.values_from_object(ensure_index(other)) + return array_equivalent(self._ndarray_values, other_vals) + + if self.nlevels != other.nlevels: + return False + + if len(self) != len(other): + return False + + for i in range(self.nlevels): + self_codes = self.codes[i] + self_codes = self_codes[self_codes != -1] + self_values = algos.take_nd(np.asarray(self.levels[i]._values), + self_codes, allow_fill=False) + + other_codes = other.codes[i] + other_codes = other_codes[other_codes != -1] + other_values = algos.take_nd( + np.asarray(other.levels[i]._values), + other_codes, allow_fill=False) + + # since we use NaT both datetime64 and timedelta64 + # we can have a situation where a level is typed say + # timedelta64 in self (IOW it has other values than NaT) + # but types datetime64 in other (where its all NaT) + # but these are equivalent + if len(self_values) == 0 and len(other_values) == 0: + continue + + if not array_equivalent(self_values, other_values): + return False + + return True + + def equal_levels(self, other): + """ + Return True if the levels of both MultiIndex objects are the same + + """ + if self.nlevels != other.nlevels: + return False + + for i in range(self.nlevels): + if not self.levels[i].equals(other.levels[i]): + return False + return True + + def union(self, other, sort=None): + """ + Form the union of two MultiIndex objects + + Parameters + ---------- + other : MultiIndex or array / Index of tuples + sort : False or None, default None + Whether to sort the resulting Index. + + * None : Sort the result, except when + + 1. `self` and `other` are equal. + 2. `self` has length 0. + 3. Some values in `self` or `other` cannot be compared. + A RuntimeWarning is issued in this case. + + * False : do not sort the result. + + .. versionadded:: 0.24.0 + + .. versionchanged:: 0.24.1 + + Changed the default value from ``True`` to ``None`` + (without change in behaviour). + + Returns + ------- + Index + + >>> index.union(index2) + """ + self._validate_sort_keyword(sort) + self._assert_can_do_setop(other) + other, result_names = self._convert_can_do_setop(other) + + if len(other) == 0 or self.equals(other): + return self + + # TODO: Index.union returns other when `len(self)` is 0. + + uniq_tuples = lib.fast_unique_multiple([self._ndarray_values, + other._ndarray_values], + sort=sort) + + return MultiIndex.from_arrays(lzip(*uniq_tuples), sortorder=0, + names=result_names) + + def intersection(self, other, sort=False): + """ + Form the intersection of two MultiIndex objects. + + Parameters + ---------- + other : MultiIndex or array / Index of tuples + sort : False or None, default False + Sort the resulting MultiIndex if possible + + .. versionadded:: 0.24.0 + + .. versionchanged:: 0.24.1 + + Changed the default from ``True`` to ``False``, to match + behaviour from before 0.24.0 + + Returns + ------- + Index + """ + self._validate_sort_keyword(sort) + self._assert_can_do_setop(other) + other, result_names = self._convert_can_do_setop(other) + + if self.equals(other): + return self + + self_tuples = self._ndarray_values + other_tuples = other._ndarray_values + uniq_tuples = set(self_tuples) & set(other_tuples) + + if sort is None: + uniq_tuples = sorted(uniq_tuples) + + if len(uniq_tuples) == 0: + return MultiIndex(levels=self.levels, + codes=[[]] * self.nlevels, + names=result_names, verify_integrity=False) + else: + return MultiIndex.from_arrays(lzip(*uniq_tuples), sortorder=0, + names=result_names) + + def difference(self, other, sort=None): + """ + Compute set difference of two MultiIndex objects + + Parameters + ---------- + other : MultiIndex + sort : False or None, default None + Sort the resulting MultiIndex if possible + + .. versionadded:: 0.24.0 + + .. versionchanged:: 0.24.1 + + Changed the default value from ``True`` to ``None`` + (without change in behaviour). + + Returns + ------- + diff : MultiIndex + """ + self._validate_sort_keyword(sort) + self._assert_can_do_setop(other) + other, result_names = self._convert_can_do_setop(other) + + if len(other) == 0: + return self + + if self.equals(other): + return MultiIndex(levels=self.levels, + codes=[[]] * self.nlevels, + names=result_names, verify_integrity=False) + + this = self._get_unique_index() + + indexer = this.get_indexer(other) + indexer = indexer.take((indexer != -1).nonzero()[0]) + + label_diff = np.setdiff1d(np.arange(this.size), indexer, + assume_unique=True) + difference = this.values.take(label_diff) + if sort is None: + difference = sorted(difference) + + if len(difference) == 0: + return MultiIndex(levels=[[]] * self.nlevels, + codes=[[]] * self.nlevels, + names=result_names, verify_integrity=False) + else: + return MultiIndex.from_tuples(difference, sortorder=0, + names=result_names) + + @Appender(_index_shared_docs['astype']) + def astype(self, dtype, copy=True): + dtype = pandas_dtype(dtype) + if is_categorical_dtype(dtype): + msg = '> 1 ndim Categorical are not supported at this time' + raise NotImplementedError(msg) + elif not is_object_dtype(dtype): + msg = ('Setting {cls} dtype to anything other than object ' + 'is not supported').format(cls=self.__class__) + raise TypeError(msg) + elif copy is True: + return self._shallow_copy() + return self + + def _convert_can_do_setop(self, other): + result_names = self.names + + if not hasattr(other, 'names'): + if len(other) == 0: + other = MultiIndex(levels=[[]] * self.nlevels, + codes=[[]] * self.nlevels, + verify_integrity=False) + else: + msg = 'other must be a MultiIndex or a list of tuples' + try: + other = MultiIndex.from_tuples(other) + except TypeError: + raise TypeError(msg) + else: + result_names = self.names if self.names == other.names else None + return other, result_names + + def insert(self, loc, item): + """ + Make new MultiIndex inserting new item at location + + Parameters + ---------- + loc : int + item : tuple + Must be same length as number of levels in the MultiIndex + + Returns + ------- + new_index : Index + """ + # Pad the key with empty strings if lower levels of the key + # aren't specified: + if not isinstance(item, tuple): + item = (item, ) + ('', ) * (self.nlevels - 1) + elif len(item) != self.nlevels: + raise ValueError('Item must have length equal to number of ' + 'levels.') + + new_levels = [] + new_codes = [] + for k, level, level_codes in zip(item, self.levels, self.codes): + if k not in level: + # have to insert into level + # must insert at end otherwise you have to recompute all the + # other codes + lev_loc = len(level) + level = level.insert(lev_loc, k) + else: + lev_loc = level.get_loc(k) + + new_levels.append(level) + new_codes.append(np.insert( + ensure_int64(level_codes), loc, lev_loc)) + + return MultiIndex(levels=new_levels, codes=new_codes, + names=self.names, verify_integrity=False) + + def delete(self, loc): + """ + Make new index with passed location deleted + + Returns + ------- + new_index : MultiIndex + """ + new_codes = [np.delete(level_codes, loc) for level_codes in self.codes] + return MultiIndex(levels=self.levels, codes=new_codes, + names=self.names, verify_integrity=False) + + def _wrap_joined_index(self, joined, other): + names = self.names if self.names == other.names else None + return MultiIndex.from_tuples(joined, names=names) + + @Appender(Index.isin.__doc__) + def isin(self, values, level=None): + if level is None: + values = MultiIndex.from_tuples(values, + names=self.names).values + return algos.isin(self.values, values) + else: + num = self._get_level_number(level) + levs = self.levels[num] + level_codes = self.codes[num] + + sought_labels = levs.isin(values).nonzero()[0] + if levs.size == 0: + return np.zeros(len(level_codes), dtype=np.bool_) + else: + return np.lib.arraysetops.in1d(level_codes, sought_labels) + + +MultiIndex._add_numeric_methods_disabled() +MultiIndex._add_numeric_methods_add_sub_disabled() +MultiIndex._add_logical_methods_disabled() + + +def _sparsify(label_list, start=0, sentinel=''): + pivoted = lzip(*label_list) + k = len(label_list) + + result = pivoted[:start + 1] + prev = pivoted[start] + + for cur in pivoted[start + 1:]: + sparse_cur = [] + + for i, (p, t) in enumerate(zip(prev, cur)): + if i == k - 1: + sparse_cur.append(t) + result.append(sparse_cur) + break + + if p == t: + sparse_cur.append(sentinel) + else: + sparse_cur.extend(cur[i:]) + result.append(sparse_cur) + break + + prev = cur + + return lzip(*result) + + +def _get_na_rep(dtype): + return {np.datetime64: 'NaT', np.timedelta64: 'NaT'}.get(dtype, 'NaN') diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/numeric.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/numeric.py new file mode 100644 index 0000000000000000000000000000000000000000..379464f4fced66f75849fd4ad43d483bcbd1ecfe --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/numeric.py @@ -0,0 +1,450 @@ +import warnings + +import numpy as np + +from pandas._libs import index as libindex +import pandas.compat as compat +from pandas.util._decorators import Appender, cache_readonly + +from pandas.core.dtypes.common import ( + is_bool, is_bool_dtype, is_dtype_equal, is_extension_array_dtype, is_float, + is_integer_dtype, is_scalar, needs_i8_conversion, pandas_dtype) +import pandas.core.dtypes.concat as _concat +from pandas.core.dtypes.missing import isna + +from pandas.core import algorithms +import pandas.core.common as com +import pandas.core.indexes.base as ibase +from pandas.core.indexes.base import ( + Index, InvalidIndexError, _index_shared_docs) +from pandas.core.ops import get_op_result_name + +_num_index_shared_docs = dict() + + +class NumericIndex(Index): + """ + Provide numeric type operations + + This is an abstract class + + """ + _is_numeric_dtype = True + + def __new__(cls, data=None, dtype=None, copy=False, name=None, + fastpath=None): + + if fastpath is not None: + warnings.warn("The 'fastpath' keyword is deprecated, and will be " + "removed in a future version.", + FutureWarning, stacklevel=2) + if fastpath: + return cls._simple_new(data, name=name) + + # is_scalar, generators handled in coerce_to_ndarray + data = cls._coerce_to_ndarray(data) + + if issubclass(data.dtype.type, compat.string_types): + cls._string_data_error(data) + + if copy or not is_dtype_equal(data.dtype, cls._default_dtype): + subarr = np.array(data, dtype=cls._default_dtype, copy=copy) + cls._assert_safe_casting(data, subarr) + else: + subarr = data + + if name is None and hasattr(data, 'name'): + name = data.name + return cls._simple_new(subarr, name=name) + + @Appender(_index_shared_docs['_maybe_cast_slice_bound']) + def _maybe_cast_slice_bound(self, label, side, kind): + assert kind in ['ix', 'loc', 'getitem', None] + + # we will try to coerce to integers + return self._maybe_cast_indexer(label) + + @Appender(_index_shared_docs['_shallow_copy']) + def _shallow_copy(self, values=None, **kwargs): + if values is not None and not self._can_hold_na: + # Ensure we are not returning an Int64Index with float data: + return self._shallow_copy_with_infer(values=values, **kwargs) + return (super(NumericIndex, self)._shallow_copy(values=values, + **kwargs)) + + def _convert_for_op(self, value): + """ Convert value to be insertable to ndarray """ + + if is_bool(value) or is_bool_dtype(value): + # force conversion to object + # so we don't lose the bools + raise TypeError + + return value + + def _convert_tolerance(self, tolerance, target): + tolerance = np.asarray(tolerance) + if target.size != tolerance.size and tolerance.size > 1: + raise ValueError('list-like tolerance size must match ' + 'target index size') + if not np.issubdtype(tolerance.dtype, np.number): + if tolerance.ndim > 0: + raise ValueError(('tolerance argument for %s must contain ' + 'numeric elements if it is list type') % + (type(self).__name__,)) + else: + raise ValueError(('tolerance argument for %s must be numeric ' + 'if it is a scalar: %r') % + (type(self).__name__, tolerance)) + return tolerance + + @classmethod + def _assert_safe_casting(cls, data, subarr): + """ + Subclasses need to override this only if the process of casting data + from some accepted dtype to the internal dtype(s) bears the risk of + truncation (e.g. float to int). + """ + pass + + def _concat_same_dtype(self, indexes, name): + return _concat._concat_index_same_dtype(indexes).rename(name) + + @property + def is_all_dates(self): + """ + Checks that all the labels are datetime objects + """ + return False + + @Appender(Index.insert.__doc__) + def insert(self, loc, item): + # treat NA values as nans: + if is_scalar(item) and isna(item): + item = self._na_value + return super(NumericIndex, self).insert(loc, item) + + +_num_index_shared_docs['class_descr'] = """ + Immutable ndarray implementing an ordered, sliceable set. The basic object + storing axis labels for all pandas objects. %(klass)s is a special case + of `Index` with purely %(ltype)s labels. %(extra)s + + Parameters + ---------- + data : array-like (1-dimensional) + dtype : NumPy dtype (default: %(dtype)s) + copy : bool + Make a copy of input ndarray + name : object + Name to be stored in the index + + Attributes + ---------- + None + + Methods + ------- + None + + See Also + -------- + Index : The base pandas Index type. + + Notes + ----- + An Index instance can **only** contain hashable objects. +""" + +_int64_descr_args = dict( + klass='Int64Index', + ltype='integer', + dtype='int64', + extra='' +) + + +class IntegerIndex(NumericIndex): + """ + This is an abstract class for Int64Index, UInt64Index. + """ + + def __contains__(self, key): + """ + Check if key is a float and has a decimal. If it has, return False. + """ + hash(key) + try: + if is_float(key) and int(key) != key: + return False + return key in self._engine + except (OverflowError, TypeError, ValueError): + return False + + +class Int64Index(IntegerIndex): + __doc__ = _num_index_shared_docs['class_descr'] % _int64_descr_args + + _typ = 'int64index' + _can_hold_na = False + _engine_type = libindex.Int64Engine + _default_dtype = np.int64 + + @property + def inferred_type(self): + """Always 'integer' for ``Int64Index``""" + return 'integer' + + @property + def asi8(self): + # do not cache or you'll create a memory leak + return self.values.view('i8') + + @Appender(_index_shared_docs['_convert_scalar_indexer']) + def _convert_scalar_indexer(self, key, kind=None): + assert kind in ['ix', 'loc', 'getitem', 'iloc', None] + + # don't coerce ilocs to integers + if kind != 'iloc': + key = self._maybe_cast_indexer(key) + return (super(Int64Index, self) + ._convert_scalar_indexer(key, kind=kind)) + + def _wrap_joined_index(self, joined, other): + name = get_op_result_name(self, other) + return Int64Index(joined, name=name) + + @classmethod + def _assert_safe_casting(cls, data, subarr): + """ + Ensure incoming data can be represented as ints. + """ + if not issubclass(data.dtype.type, np.signedinteger): + if not np.array_equal(data, subarr): + raise TypeError('Unsafe NumPy casting, you must ' + 'explicitly cast') + + +Int64Index._add_numeric_methods() +Int64Index._add_logical_methods() + +_uint64_descr_args = dict( + klass='UInt64Index', + ltype='unsigned integer', + dtype='uint64', + extra='' +) + + +class UInt64Index(IntegerIndex): + __doc__ = _num_index_shared_docs['class_descr'] % _uint64_descr_args + + _typ = 'uint64index' + _can_hold_na = False + _engine_type = libindex.UInt64Engine + _default_dtype = np.uint64 + + @property + def inferred_type(self): + """Always 'integer' for ``UInt64Index``""" + return 'integer' + + @property + def asi8(self): + # do not cache or you'll create a memory leak + return self.values.view('u8') + + @Appender(_index_shared_docs['_convert_scalar_indexer']) + def _convert_scalar_indexer(self, key, kind=None): + assert kind in ['ix', 'loc', 'getitem', 'iloc', None] + + # don't coerce ilocs to integers + if kind != 'iloc': + key = self._maybe_cast_indexer(key) + return (super(UInt64Index, self) + ._convert_scalar_indexer(key, kind=kind)) + + @Appender(_index_shared_docs['_convert_arr_indexer']) + def _convert_arr_indexer(self, keyarr): + # Cast the indexer to uint64 if possible so + # that the values returned from indexing are + # also uint64. + keyarr = com.asarray_tuplesafe(keyarr) + if is_integer_dtype(keyarr): + return com.asarray_tuplesafe(keyarr, dtype=np.uint64) + return keyarr + + @Appender(_index_shared_docs['_convert_index_indexer']) + def _convert_index_indexer(self, keyarr): + # Cast the indexer to uint64 if possible so + # that the values returned from indexing are + # also uint64. + if keyarr.is_integer(): + return keyarr.astype(np.uint64) + return keyarr + + def _wrap_joined_index(self, joined, other): + name = get_op_result_name(self, other) + return UInt64Index(joined, name=name) + + @classmethod + def _assert_safe_casting(cls, data, subarr): + """ + Ensure incoming data can be represented as uints. + """ + if not issubclass(data.dtype.type, np.unsignedinteger): + if not np.array_equal(data, subarr): + raise TypeError('Unsafe NumPy casting, you must ' + 'explicitly cast') + + +UInt64Index._add_numeric_methods() +UInt64Index._add_logical_methods() + +_float64_descr_args = dict( + klass='Float64Index', + dtype='float64', + ltype='float', + extra='' +) + + +class Float64Index(NumericIndex): + __doc__ = _num_index_shared_docs['class_descr'] % _float64_descr_args + + _typ = 'float64index' + _engine_type = libindex.Float64Engine + _default_dtype = np.float64 + + @property + def inferred_type(self): + """Always 'floating' for ``Float64Index``""" + return 'floating' + + @Appender(_index_shared_docs['astype']) + def astype(self, dtype, copy=True): + dtype = pandas_dtype(dtype) + if needs_i8_conversion(dtype): + msg = ('Cannot convert Float64Index to dtype {dtype}; integer ' + 'values are required for conversion').format(dtype=dtype) + raise TypeError(msg) + elif (is_integer_dtype(dtype) and + not is_extension_array_dtype(dtype)) and self.hasnans: + # TODO(jreback); this can change once we have an EA Index type + # GH 13149 + raise ValueError('Cannot convert NA to integer') + return super(Float64Index, self).astype(dtype, copy=copy) + + @Appender(_index_shared_docs['_convert_scalar_indexer']) + def _convert_scalar_indexer(self, key, kind=None): + assert kind in ['ix', 'loc', 'getitem', 'iloc', None] + + if kind == 'iloc': + return self._validate_indexer('positional', key, kind) + + return key + + @Appender(_index_shared_docs['_convert_slice_indexer']) + def _convert_slice_indexer(self, key, kind=None): + # if we are not a slice, then we are done + if not isinstance(key, slice): + return key + + if kind == 'iloc': + return super(Float64Index, self)._convert_slice_indexer(key, + kind=kind) + + # translate to locations + return self.slice_indexer(key.start, key.stop, key.step, kind=kind) + + def _format_native_types(self, na_rep='', float_format=None, decimal='.', + quoting=None, **kwargs): + from pandas.io.formats.format import FloatArrayFormatter + formatter = FloatArrayFormatter(self.values, na_rep=na_rep, + float_format=float_format, + decimal=decimal, quoting=quoting, + fixed_width=False) + return formatter.get_result_as_array() + + def get_value(self, series, key): + """ we always want to get an index value, never a value """ + if not is_scalar(key): + raise InvalidIndexError + + k = com.values_from_object(key) + loc = self.get_loc(k) + new_values = com.values_from_object(series)[loc] + + return new_values + + def equals(self, other): + """ + Determines if two Index objects contain the same elements. + """ + if self is other: + return True + + if not isinstance(other, Index): + return False + + # need to compare nans locations and make sure that they are the same + # since nans don't compare equal this is a bit tricky + try: + if not isinstance(other, Float64Index): + other = self._constructor(other) + if (not is_dtype_equal(self.dtype, other.dtype) or + self.shape != other.shape): + return False + left, right = self._ndarray_values, other._ndarray_values + return ((left == right) | (self._isnan & other._isnan)).all() + except (TypeError, ValueError): + return False + + def __contains__(self, other): + if super(Float64Index, self).__contains__(other): + return True + + try: + # if other is a sequence this throws a ValueError + return np.isnan(other) and self.hasnans + except ValueError: + try: + return len(other) <= 1 and ibase._try_get_item(other) in self + except TypeError: + pass + except TypeError: + pass + + return False + + @Appender(_index_shared_docs['get_loc']) + def get_loc(self, key, method=None, tolerance=None): + try: + if np.all(np.isnan(key)) or is_bool(key): + nan_idxs = self._nan_idxs + try: + return nan_idxs.item() + except (ValueError, IndexError): + # should only need to catch ValueError here but on numpy + # 1.7 .item() can raise IndexError when NaNs are present + if not len(nan_idxs): + raise KeyError(key) + return nan_idxs + except (TypeError, NotImplementedError): + pass + return super(Float64Index, self).get_loc(key, method=method, + tolerance=tolerance) + + @cache_readonly + def is_unique(self): + return super(Float64Index, self).is_unique and self._nan_idxs.size < 2 + + @Appender(Index.isin.__doc__) + def isin(self, values, level=None): + if level is not None: + self._validate_index_level(level) + return algorithms.isin(np.array(self), values) + + +Float64Index._add_numeric_methods() +Float64Index._add_logical_methods_disabled() diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/period.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/period.py new file mode 100644 index 0000000000000000000000000000000000000000..a4bd7f9017eb402f90a6f6c401e10579c3661bb4 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/period.py @@ -0,0 +1,966 @@ +# pylint: disable=E1101,E1103,W0232 +from datetime import datetime, timedelta +import warnings + +import numpy as np + +from pandas._libs import index as libindex +from pandas._libs.tslibs import ( + NaT, frequencies as libfrequencies, iNaT, resolution) +from pandas._libs.tslibs.period import ( + DIFFERENT_FREQ, IncompatibleFrequency, Period) +from pandas.util._decorators import Appender, Substitution, cache_readonly + +from pandas.core.dtypes.common import ( + is_bool_dtype, is_datetime64_any_dtype, is_float, is_float_dtype, + is_integer, is_integer_dtype, pandas_dtype) + +from pandas import compat +from pandas.core import common as com +from pandas.core.accessor import delegate_names +from pandas.core.algorithms import unique1d +from pandas.core.arrays.period import ( + PeriodArray, period_array, validate_dtype_freq) +from pandas.core.base import _shared_docs +import pandas.core.indexes.base as ibase +from pandas.core.indexes.base import _index_shared_docs, ensure_index +from pandas.core.indexes.datetimelike import ( + DatetimeIndexOpsMixin, DatetimelikeDelegateMixin) +from pandas.core.indexes.datetimes import DatetimeIndex, Index, Int64Index +from pandas.core.missing import isna +from pandas.core.ops import get_op_result_name +from pandas.core.tools.datetimes import DateParseError, parse_time_string + +from pandas.tseries import frequencies +from pandas.tseries.offsets import DateOffset, Tick + +_index_doc_kwargs = dict(ibase._index_doc_kwargs) +_index_doc_kwargs.update( + dict(target_klass='PeriodIndex or list of Periods')) + + +# --- Period index sketch + + +def _new_PeriodIndex(cls, **d): + # GH13277 for unpickling + values = d.pop('data') + if values.dtype == 'int64': + freq = d.pop('freq', None) + values = PeriodArray(values, freq=freq) + return cls._simple_new(values, **d) + else: + return cls(values, **d) + + +class PeriodDelegateMixin(DatetimelikeDelegateMixin): + """ + Delegate from PeriodIndex to PeriodArray. + """ + _delegate_class = PeriodArray + _delegated_properties = PeriodArray._datetimelike_ops + _delegated_methods = ( + set(PeriodArray._datetimelike_methods) | {'_addsub_int_array'} + ) + _raw_properties = {'is_leap_year'} + + +@delegate_names(PeriodArray, + PeriodDelegateMixin._delegated_properties, + typ='property') +@delegate_names(PeriodArray, + PeriodDelegateMixin._delegated_methods, + typ="method", + overwrite=True) +class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin): + """ + Immutable ndarray holding ordinal values indicating regular periods in + time such as particular years, quarters, months, etc. + + Index keys are boxed to Period objects which carries the metadata (eg, + frequency information). + + Parameters + ---------- + data : array-like (1-dimensional), optional + Optional period-like data to construct index with + copy : bool + Make a copy of input ndarray + freq : string or period object, optional + One of pandas period strings or corresponding objects + start : starting value, period-like, optional + If data is None, used as the start point in generating regular + period data. + + .. deprecated:: 0.24.0 + + periods : int, optional, > 0 + Number of periods to generate, if generating index. Takes precedence + over end argument + + .. deprecated:: 0.24.0 + + end : end value, period-like, optional + If periods is none, generated index will extend to first conforming + period on or just past end argument + + .. deprecated:: 0.24.0 + + year : int, array, or Series, default None + month : int, array, or Series, default None + quarter : int, array, or Series, default None + day : int, array, or Series, default None + hour : int, array, or Series, default None + minute : int, array, or Series, default None + second : int, array, or Series, default None + tz : object, default None + Timezone for converting datetime64 data to Periods + dtype : str or PeriodDtype, default None + + Attributes + ---------- + day + dayofweek + dayofyear + days_in_month + daysinmonth + end_time + freq + freqstr + hour + is_leap_year + minute + month + quarter + qyear + second + start_time + week + weekday + weekofyear + year + + Methods + ------- + asfreq + strftime + to_timestamp + + Notes + ----- + Creating a PeriodIndex based on `start`, `periods`, and `end` has + been deprecated in favor of :func:`period_range`. + + Examples + -------- + >>> idx = pd.PeriodIndex(year=year_arr, quarter=q_arr) + + See Also + --------- + Index : The base pandas Index type. + Period : Represents a period of time. + DatetimeIndex : Index with datetime64 data. + TimedeltaIndex : Index of timedelta64 data. + period_range : Create a fixed-frequency PeriodIndex. + """ + _typ = 'periodindex' + _attributes = ['name', 'freq'] + + # define my properties & methods for delegation + _is_numeric_dtype = False + _infer_as_myclass = True + + _data = None # type: PeriodArray + + _engine_type = libindex.PeriodEngine + + # ------------------------------------------------------------------------ + # Index Constructors + + def __new__(cls, data=None, ordinal=None, freq=None, start=None, end=None, + periods=None, tz=None, dtype=None, copy=False, name=None, + **fields): + + valid_field_set = {'year', 'month', 'day', 'quarter', + 'hour', 'minute', 'second'} + + if not set(fields).issubset(valid_field_set): + raise TypeError('__new__() got an unexpected keyword argument {}'. + format(list(set(fields) - valid_field_set)[0])) + + if name is None and hasattr(data, 'name'): + name = data.name + + if data is None and ordinal is None: + # range-based. + data, freq2 = PeriodArray._generate_range(start, end, periods, + freq, fields) + # PeriodArray._generate range does validate that fields is + # empty when really using the range-based constructor. + if not fields: + msg = ("Creating a PeriodIndex by passing range " + "endpoints is deprecated. Use " + "`pandas.period_range` instead.") + # period_range differs from PeriodIndex for cases like + # start="2000", periods=4 + # PeriodIndex interprets that as A-DEC freq. + # period_range interprets it as 'D' freq. + cond = ( + freq is None and ( + (start and not isinstance(start, Period)) or + (end and not isinstance(end, Period)) + ) + ) + if cond: + msg += ( + " Note that the default `freq` may differ. Pass " + "'freq=\"{}\"' to ensure the same output." + ).format(freq2.freqstr) + warnings.warn(msg, FutureWarning, stacklevel=2) + freq = freq2 + + data = PeriodArray(data, freq=freq) + else: + freq = validate_dtype_freq(dtype, freq) + + # PeriodIndex allow PeriodIndex(period_index, freq=different) + # Let's not encourage that kind of behavior in PeriodArray. + + if freq and isinstance(data, cls) and data.freq != freq: + # TODO: We can do some of these with no-copy / coercion? + # e.g. D -> 2D seems to be OK + data = data.asfreq(freq) + + if data is None and ordinal is not None: + # we strangely ignore `ordinal` if data is passed. + ordinal = np.asarray(ordinal, dtype=np.int64) + data = PeriodArray(ordinal, freq) + else: + # don't pass copy here, since we copy later. + data = period_array(data=data, freq=freq) + + if copy: + data = data.copy() + + return cls._simple_new(data, name=name) + + @classmethod + def _simple_new(cls, values, name=None, freq=None, **kwargs): + """ + Create a new PeriodIndex. + + Parameters + ---------- + values : PeriodArray, PeriodIndex, Index[int64], ndarray[int64] + Values that can be converted to a PeriodArray without inference + or coercion. + + """ + # TODO: raising on floats is tested, but maybe not useful. + # Should the callers know not to pass floats? + # At the very least, I think we can ensure that lists aren't passed. + if isinstance(values, list): + values = np.asarray(values) + if is_float_dtype(values): + raise TypeError("PeriodIndex._simple_new does not accept floats.") + if freq: + freq = Period._maybe_convert_freq(freq) + values = PeriodArray(values, freq=freq) + + if not isinstance(values, PeriodArray): + raise TypeError("PeriodIndex._simple_new only accepts PeriodArray") + result = object.__new__(cls) + result._data = values + # For groupby perf. See note in indexes/base about _index_data + result._index_data = values._data + result.name = name + result._reset_identity() + return result + + # ------------------------------------------------------------------------ + # Data + + @property + def values(self): + return np.asarray(self) + + @property + def freq(self): + return self._data.freq + + @freq.setter + def freq(self, value): + value = Period._maybe_convert_freq(value) + # TODO: When this deprecation is enforced, PeriodIndex.freq can + # be removed entirely, and we'll just inherit. + msg = ('Setting {cls}.freq has been deprecated and will be ' + 'removed in a future version; use {cls}.asfreq instead. ' + 'The {cls}.freq setter is not guaranteed to work.') + warnings.warn(msg.format(cls=type(self).__name__), + FutureWarning, stacklevel=2) + # PeriodArray._freq isn't actually mutable. We set the private _freq + # here, but people shouldn't be doing this anyway. + self._data._freq = value + + def _shallow_copy(self, values=None, **kwargs): + # TODO: simplify, figure out type of values + if values is None: + values = self._data + + if isinstance(values, type(self)): + values = values._values + + if not isinstance(values, PeriodArray): + if (isinstance(values, np.ndarray) and + is_integer_dtype(values.dtype)): + values = PeriodArray(values, freq=self.freq) + else: + # in particular, I would like to avoid period_array here. + # Some people seem to be calling use with unexpected types + # Index.difference -> ndarray[Period] + # DatetimelikeIndexOpsMixin.repeat -> ndarray[ordinal] + # I think that once all of Datetime* are EAs, we can simplify + # this quite a bit. + values = period_array(values, freq=self.freq) + + # We don't allow changing `freq` in _shallow_copy. + validate_dtype_freq(self.dtype, kwargs.get('freq')) + attributes = self._get_attributes_dict() + + attributes.update(kwargs) + if not len(values) and 'dtype' not in kwargs: + attributes['dtype'] = self.dtype + return self._simple_new(values, **attributes) + + def _shallow_copy_with_infer(self, values=None, **kwargs): + """ we always want to return a PeriodIndex """ + return self._shallow_copy(values=values, **kwargs) + + @property + def _box_func(self): + """Maybe box an ordinal or Period""" + # TODO(DatetimeArray): Avoid double-boxing + # PeriodArray takes care of boxing already, so we need to check + # whether we're given an ordinal or a Period. It seems like some + # places outside of indexes/period.py are calling this _box_func, + # but passing data that's already boxed. + def func(x): + if isinstance(x, Period) or x is NaT: + return x + else: + return Period._from_ordinal(ordinal=x, freq=self.freq) + return func + + def _maybe_convert_timedelta(self, other): + """ + Convert timedelta-like input to an integer multiple of self.freq + + Parameters + ---------- + other : timedelta, np.timedelta64, DateOffset, int, np.ndarray + + Returns + ------- + converted : int, np.ndarray[int64] + + Raises + ------ + IncompatibleFrequency : if the input cannot be written as a multiple + of self.freq. Note IncompatibleFrequency subclasses ValueError. + """ + if isinstance( + other, (timedelta, np.timedelta64, Tick, np.ndarray)): + offset = frequencies.to_offset(self.freq.rule_code) + if isinstance(offset, Tick): + # _check_timedeltalike_freq_compat will raise if incompatible + delta = self._data._check_timedeltalike_freq_compat(other) + return delta + elif isinstance(other, DateOffset): + freqstr = other.rule_code + base = libfrequencies.get_base_alias(freqstr) + if base == self.freq.rule_code: + return other.n + + msg = DIFFERENT_FREQ.format(cls=type(self).__name__, + own_freq=self.freqstr, + other_freq=other.freqstr) + raise IncompatibleFrequency(msg) + elif is_integer(other): + # integer is passed to .shift via + # _add_datetimelike_methods basically + # but ufunc may pass integer to _add_delta + return other + + # raise when input doesn't have freq + msg = DIFFERENT_FREQ.format(cls=type(self).__name__, + own_freq=self.freqstr, + other_freq=None) + raise IncompatibleFrequency(msg) + + # ------------------------------------------------------------------------ + # Rendering Methods + + def _format_native_types(self, na_rep=u'NaT', quoting=None, **kwargs): + # just dispatch, return ndarray + return self._data._format_native_types(na_rep=na_rep, + quoting=quoting, + **kwargs) + + def _mpl_repr(self): + # how to represent ourselves to matplotlib + return self.astype(object).values + + @property + def _formatter_func(self): + return self.array._formatter(boxed=False) + + # ------------------------------------------------------------------------ + # Indexing + + @cache_readonly + def _engine(self): + return self._engine_type(lambda: self, len(self)) + + @Appender(_index_shared_docs['contains']) + def __contains__(self, key): + if isinstance(key, Period): + if key.freq != self.freq: + return False + else: + return key.ordinal in self._engine + else: + try: + self.get_loc(key) + return True + except Exception: + return False + + contains = __contains__ + + @cache_readonly + def _int64index(self): + return Int64Index._simple_new(self.asi8, name=self.name) + + # ------------------------------------------------------------------------ + # Index Methods + + def _coerce_scalar_to_index(self, item): + """ + we need to coerce a scalar to a compat for our index type + + Parameters + ---------- + item : scalar item to coerce + """ + return PeriodIndex([item], **self._get_attributes_dict()) + + def __array__(self, dtype=None): + if is_integer_dtype(dtype): + return self.asi8 + else: + return self.astype(object).values + + def __array_wrap__(self, result, context=None): + """ + Gets called after a ufunc. Needs additional handling as + PeriodIndex stores internal data as int dtype + + Replace this to __numpy_ufunc__ in future version + """ + if isinstance(context, tuple) and len(context) > 0: + func = context[0] + if func is np.add: + pass + elif func is np.subtract: + name = self.name + left = context[1][0] + right = context[1][1] + if (isinstance(left, PeriodIndex) and + isinstance(right, PeriodIndex)): + name = left.name if left.name == right.name else None + return Index(result, name=name) + elif isinstance(left, Period) or isinstance(right, Period): + return Index(result, name=name) + elif isinstance(func, np.ufunc): + if 'M->M' not in func.types: + msg = "ufunc '{0}' not supported for the PeriodIndex" + # This should be TypeError, but TypeError cannot be raised + # from here because numpy catches. + raise ValueError(msg.format(func.__name__)) + + if is_bool_dtype(result): + return result + # the result is object dtype array of Period + # cannot pass _simple_new as it is + return type(self)(result, freq=self.freq, name=self.name) + + def asof_locs(self, where, mask): + """ + where : array of timestamps + mask : array of booleans where data is not NA + + """ + where_idx = where + if isinstance(where_idx, DatetimeIndex): + where_idx = PeriodIndex(where_idx.values, freq=self.freq) + + locs = self._ndarray_values[mask].searchsorted( + where_idx._ndarray_values, side='right') + + locs = np.where(locs > 0, locs - 1, 0) + result = np.arange(len(self))[mask].take(locs) + + first = mask.argmax() + result[(locs == 0) & (where_idx._ndarray_values < + self._ndarray_values[first])] = -1 + + return result + + @Appender(_index_shared_docs['astype']) + def astype(self, dtype, copy=True, how='start'): + dtype = pandas_dtype(dtype) + + if is_datetime64_any_dtype(dtype): + # 'how' is index-specific, isn't part of the EA interface. + tz = getattr(dtype, 'tz', None) + return self.to_timestamp(how=how).tz_localize(tz) + + # TODO: should probably raise on `how` here, so we don't ignore it. + return super(PeriodIndex, self).astype(dtype, copy=copy) + + @Substitution(klass='PeriodIndex') + @Appender(_shared_docs['searchsorted']) + def searchsorted(self, value, side='left', sorter=None): + if isinstance(value, Period): + if value.freq != self.freq: + msg = DIFFERENT_FREQ.format(cls=type(self).__name__, + own_freq=self.freqstr, + other_freq=value.freqstr) + raise IncompatibleFrequency(msg) + value = value.ordinal + elif isinstance(value, compat.string_types): + try: + value = Period(value, freq=self.freq).ordinal + except DateParseError: + raise KeyError("Cannot interpret '{}' as period".format(value)) + + return self._ndarray_values.searchsorted(value, side=side, + sorter=sorter) + + @property + def is_all_dates(self): + return True + + @property + def is_full(self): + """ + Returns True if this PeriodIndex is range-like in that all Periods + between start and end are present, in order. + """ + if len(self) == 0: + return True + if not self.is_monotonic: + raise ValueError('Index is not monotonic') + values = self.asi8 + return ((values[1:] - values[:-1]) < 2).all() + + @property + def inferred_type(self): + # b/c data is represented as ints make sure we can't have ambiguous + # indexing + return 'period' + + def get_value(self, series, key): + """ + Fast lookup of value from 1-dimensional ndarray. Only use this if you + know what you're doing + """ + s = com.values_from_object(series) + try: + return com.maybe_box(self, + super(PeriodIndex, self).get_value(s, key), + series, key) + except (KeyError, IndexError): + try: + asdt, parsed, reso = parse_time_string(key, self.freq) + grp = resolution.Resolution.get_freq_group(reso) + freqn = resolution.get_freq_group(self.freq) + + vals = self._ndarray_values + + # if our data is higher resolution than requested key, slice + if grp < freqn: + iv = Period(asdt, freq=(grp, 1)) + ord1 = iv.asfreq(self.freq, how='S').ordinal + ord2 = iv.asfreq(self.freq, how='E').ordinal + + if ord2 < vals[0] or ord1 > vals[-1]: + raise KeyError(key) + + pos = np.searchsorted(self._ndarray_values, [ord1, ord2]) + key = slice(pos[0], pos[1] + 1) + return series[key] + elif grp == freqn: + key = Period(asdt, freq=self.freq).ordinal + return com.maybe_box(self, self._engine.get_value(s, key), + series, key) + else: + raise KeyError(key) + except TypeError: + pass + + period = Period(key, self.freq) + key = period.value if isna(period) else period.ordinal + return com.maybe_box(self, self._engine.get_value(s, key), + series, key) + + @Appender(_index_shared_docs['get_indexer'] % _index_doc_kwargs) + def get_indexer(self, target, method=None, limit=None, tolerance=None): + target = ensure_index(target) + + if hasattr(target, 'freq') and target.freq != self.freq: + msg = DIFFERENT_FREQ.format(cls=type(self).__name__, + own_freq=self.freqstr, + other_freq=target.freqstr) + raise IncompatibleFrequency(msg) + + if isinstance(target, PeriodIndex): + target = target.asi8 + + if tolerance is not None: + tolerance = self._convert_tolerance(tolerance, target) + return Index.get_indexer(self._int64index, target, method, + limit, tolerance) + + def _get_unique_index(self, dropna=False): + """ + wrap Index._get_unique_index to handle NaT + """ + res = super(PeriodIndex, self)._get_unique_index(dropna=dropna) + if dropna: + res = res.dropna() + return res + + @Appender(Index.unique.__doc__) + def unique(self, level=None): + # override the Index.unique method for performance GH#23083 + if level is not None: + # this should never occur, but is retained to make the signature + # match Index.unique + self._validate_index_level(level) + + values = self._ndarray_values + result = unique1d(values) + return self._shallow_copy(result) + + def get_loc(self, key, method=None, tolerance=None): + """ + Get integer location for requested label + + Returns + ------- + loc : int + """ + try: + return self._engine.get_loc(key) + except KeyError: + if is_integer(key): + raise + + try: + asdt, parsed, reso = parse_time_string(key, self.freq) + key = asdt + except TypeError: + pass + except DateParseError: + # A string with invalid format + raise KeyError("Cannot interpret '{}' as period".format(key)) + + try: + key = Period(key, freq=self.freq) + except ValueError: + # we cannot construct the Period + # as we have an invalid type + raise KeyError(key) + + try: + ordinal = iNaT if key is NaT else key.ordinal + if tolerance is not None: + tolerance = self._convert_tolerance(tolerance, + np.asarray(key)) + return self._int64index.get_loc(ordinal, method, tolerance) + + except KeyError: + raise KeyError(key) + + def _maybe_cast_slice_bound(self, label, side, kind): + """ + If label is a string or a datetime, cast it to Period.ordinal according + to resolution. + + Parameters + ---------- + label : object + side : {'left', 'right'} + kind : {'ix', 'loc', 'getitem'} + + Returns + ------- + bound : Period or object + + Notes + ----- + Value of `side` parameter should be validated in caller. + + """ + assert kind in ['ix', 'loc', 'getitem'] + + if isinstance(label, datetime): + return Period(label, freq=self.freq) + elif isinstance(label, compat.string_types): + try: + _, parsed, reso = parse_time_string(label, self.freq) + bounds = self._parsed_string_to_bounds(reso, parsed) + return bounds[0 if side == 'left' else 1] + except Exception: + raise KeyError(label) + elif is_integer(label) or is_float(label): + self._invalid_indexer('slice', label) + + return label + + def _parsed_string_to_bounds(self, reso, parsed): + if reso == 'year': + t1 = Period(year=parsed.year, freq='A') + elif reso == 'month': + t1 = Period(year=parsed.year, month=parsed.month, freq='M') + elif reso == 'quarter': + q = (parsed.month - 1) // 3 + 1 + t1 = Period(year=parsed.year, quarter=q, freq='Q-DEC') + elif reso == 'day': + t1 = Period(year=parsed.year, month=parsed.month, day=parsed.day, + freq='D') + elif reso == 'hour': + t1 = Period(year=parsed.year, month=parsed.month, day=parsed.day, + hour=parsed.hour, freq='H') + elif reso == 'minute': + t1 = Period(year=parsed.year, month=parsed.month, day=parsed.day, + hour=parsed.hour, minute=parsed.minute, freq='T') + elif reso == 'second': + t1 = Period(year=parsed.year, month=parsed.month, day=parsed.day, + hour=parsed.hour, minute=parsed.minute, + second=parsed.second, freq='S') + else: + raise KeyError(reso) + return (t1.asfreq(self.freq, how='start'), + t1.asfreq(self.freq, how='end')) + + def _get_string_slice(self, key): + if not self.is_monotonic: + raise ValueError('Partial indexing only valid for ' + 'ordered time series') + + key, parsed, reso = parse_time_string(key, self.freq) + grp = resolution.Resolution.get_freq_group(reso) + freqn = resolution.get_freq_group(self.freq) + if reso in ['day', 'hour', 'minute', 'second'] and not grp < freqn: + raise KeyError(key) + + t1, t2 = self._parsed_string_to_bounds(reso, parsed) + return slice(self.searchsorted(t1.ordinal, side='left'), + self.searchsorted(t2.ordinal, side='right')) + + def _convert_tolerance(self, tolerance, target): + tolerance = DatetimeIndexOpsMixin._convert_tolerance(self, tolerance, + target) + if target.size != tolerance.size and tolerance.size > 1: + raise ValueError('list-like tolerance size must match ' + 'target index size') + return self._maybe_convert_timedelta(tolerance) + + def insert(self, loc, item): + if not isinstance(item, Period) or self.freq != item.freq: + return self.astype(object).insert(loc, item) + + idx = np.concatenate((self[:loc].asi8, np.array([item.ordinal]), + self[loc:].asi8)) + return self._shallow_copy(idx) + + def join(self, other, how='left', level=None, return_indexers=False, + sort=False): + """ + See Index.join + """ + self._assert_can_do_setop(other) + + result = Int64Index.join(self, other, how=how, level=level, + return_indexers=return_indexers, + sort=sort) + + if return_indexers: + result, lidx, ridx = result + return self._apply_meta(result), lidx, ridx + return self._apply_meta(result) + + def _assert_can_do_setop(self, other): + super(PeriodIndex, self)._assert_can_do_setop(other) + + if not isinstance(other, PeriodIndex): + raise ValueError('can only call with other PeriodIndex-ed objects') + + if self.freq != other.freq: + msg = DIFFERENT_FREQ.format(cls=type(self).__name__, + own_freq=self.freqstr, + other_freq=other.freqstr) + raise IncompatibleFrequency(msg) + + def _wrap_setop_result(self, other, result): + name = get_op_result_name(self, other) + result = self._apply_meta(result) + result.name = name + return result + + def _apply_meta(self, rawarr): + if not isinstance(rawarr, PeriodIndex): + rawarr = PeriodIndex._simple_new(rawarr, freq=self.freq, + name=self.name) + return rawarr + + def __setstate__(self, state): + """Necessary for making this object picklable""" + + if isinstance(state, dict): + super(PeriodIndex, self).__setstate__(state) + + elif isinstance(state, tuple): + + # < 0.15 compat + if len(state) == 2: + nd_state, own_state = state + data = np.empty(nd_state[1], dtype=nd_state[2]) + np.ndarray.__setstate__(data, nd_state) + + # backcompat + freq = Period._maybe_convert_freq(own_state[1]) + + else: # pragma: no cover + data = np.empty(state) + np.ndarray.__setstate__(self, state) + freq = None # ? + + data = PeriodArray(data, freq=freq) + self._data = data + + else: + raise Exception("invalid pickle state") + + _unpickle_compat = __setstate__ + + @property + def flags(self): + """ return the ndarray.flags for the underlying data """ + warnings.warn("{obj}.flags is deprecated and will be removed " + "in a future version".format(obj=type(self).__name__), + FutureWarning, stacklevel=2) + return self._ndarray_values.flags + + def item(self): + """ + return the first element of the underlying data as a python + scalar + """ + # TODO(DatetimeArray): remove + if len(self) == 1: + return self[0] + else: + # copy numpy's message here because Py26 raises an IndexError + raise ValueError('can only convert an array of size 1 to a ' + 'Python scalar') + + @property + def data(self): + """ return the data pointer of the underlying data """ + warnings.warn("{obj}.data is deprecated and will be removed " + "in a future version".format(obj=type(self).__name__), + FutureWarning, stacklevel=2) + return np.asarray(self._data).data + + @property + def base(self): + """ return the base object if the memory of the underlying data is + shared + """ + warnings.warn("{obj}.base is deprecated and will be removed " + "in a future version".format(obj=type(self).__name__), + FutureWarning, stacklevel=2) + return np.asarray(self._data) + + +PeriodIndex._add_comparison_ops() +PeriodIndex._add_numeric_methods_disabled() +PeriodIndex._add_logical_methods_disabled() +PeriodIndex._add_datetimelike_methods() + + +def period_range(start=None, end=None, periods=None, freq=None, name=None): + """ + Return a fixed frequency PeriodIndex, with day (calendar) as the default + frequency + + Parameters + ---------- + start : string or period-like, default None + Left bound for generating periods + end : string or period-like, default None + Right bound for generating periods + periods : integer, default None + Number of periods to generate + freq : string or DateOffset, optional + Frequency alias. By default the freq is taken from `start` or `end` + if those are Period objects. Otherwise, the default is ``"D"`` for + daily frequency. + + name : string, default None + Name of the resulting PeriodIndex + + Returns + ------- + prng : PeriodIndex + + Notes + ----- + Of the three parameters: ``start``, ``end``, and ``periods``, exactly two + must be specified. + + To learn more about the frequency strings, please see `this link + `__. + + Examples + -------- + + >>> pd.period_range(start='2017-01-01', end='2018-01-01', freq='M') + PeriodIndex(['2017-01', '2017-02', '2017-03', '2017-04', '2017-05', + '2017-06', '2017-06', '2017-07', '2017-08', '2017-09', + '2017-10', '2017-11', '2017-12', '2018-01'], + dtype='period[M]', freq='M') + + If ``start`` or ``end`` are ``Period`` objects, they will be used as anchor + endpoints for a ``PeriodIndex`` with frequency matching that of the + ``period_range`` constructor. + + >>> pd.period_range(start=pd.Period('2017Q1', freq='Q'), + ... end=pd.Period('2017Q2', freq='Q'), freq='M') + PeriodIndex(['2017-03', '2017-04', '2017-05', '2017-06'], + dtype='period[M]', freq='M') + """ + if com.count_not_none(start, end, periods) != 2: + raise ValueError('Of the three parameters: start, end, and periods, ' + 'exactly two must be specified') + if freq is None and (not isinstance(start, Period) + and not isinstance(end, Period)): + freq = 'D' + + data, freq = PeriodArray._generate_range(start, end, periods, freq, + fields={}) + data = PeriodArray(data, freq=freq) + return PeriodIndex(data, name=name) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/range.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/range.py new file mode 100644 index 0000000000000000000000000000000000000000..5aafe9734b6a063b1978249e17f7b551658f1449 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/range.py @@ -0,0 +1,702 @@ +from datetime import timedelta +import operator +from sys import getsizeof +import warnings + +import numpy as np + +from pandas._libs import index as libindex, lib +import pandas.compat as compat +from pandas.compat import get_range_parameters, lrange, range +from pandas.compat.numpy import function as nv +from pandas.util._decorators import Appender, cache_readonly + +from pandas.core.dtypes import concat as _concat +from pandas.core.dtypes.common import ( + is_int64_dtype, is_integer, is_scalar, is_timedelta64_dtype) +from pandas.core.dtypes.generic import ( + ABCDataFrame, ABCSeries, ABCTimedeltaIndex) + +from pandas.core import ops +import pandas.core.common as com +import pandas.core.indexes.base as ibase +from pandas.core.indexes.base import Index, _index_shared_docs +from pandas.core.indexes.numeric import Int64Index + + +class RangeIndex(Int64Index): + """ + Immutable Index implementing a monotonic integer range. + + RangeIndex is a memory-saving special case of Int64Index limited to + representing monotonic ranges. Using RangeIndex may in some instances + improve computing speed. + + This is the default index type used + by DataFrame and Series when no explicit index is provided by the user. + + Parameters + ---------- + start : int (default: 0), or other RangeIndex instance + If int and "stop" is not given, interpreted as "stop" instead. + stop : int (default: 0) + step : int (default: 1) + name : object, optional + Name to be stored in the index + copy : bool, default False + Unused, accepted for homogeneity with other index types. + + Attributes + ---------- + None + + Methods + ------- + from_range + + See Also + -------- + Index : The base pandas Index type. + Int64Index : Index of int64 data. + """ + + _typ = 'rangeindex' + _engine_type = libindex.Int64Engine + + # -------------------------------------------------------------------- + # Constructors + + def __new__(cls, start=None, stop=None, step=None, + dtype=None, copy=False, name=None, fastpath=None): + + if fastpath is not None: + warnings.warn("The 'fastpath' keyword is deprecated, and will be " + "removed in a future version.", + FutureWarning, stacklevel=2) + if fastpath: + return cls._simple_new(start, stop, step, name=name) + + cls._validate_dtype(dtype) + + # RangeIndex + if isinstance(start, RangeIndex): + if name is None: + name = start.name + return cls._simple_new(name=name, + **dict(start._get_data_as_items())) + + # validate the arguments + def ensure_int(value, field): + msg = ("RangeIndex(...) must be called with integers," + " {value} was passed for {field}") + if not is_scalar(value): + raise TypeError(msg.format(value=type(value).__name__, + field=field)) + try: + new_value = int(value) + assert(new_value == value) + except (TypeError, ValueError, AssertionError): + raise TypeError(msg.format(value=type(value).__name__, + field=field)) + + return new_value + + if com._all_none(start, stop, step): + msg = "RangeIndex(...) must be called with integers" + raise TypeError(msg) + elif start is None: + start = 0 + else: + start = ensure_int(start, 'start') + if stop is None: + stop = start + start = 0 + else: + stop = ensure_int(stop, 'stop') + if step is None: + step = 1 + elif step == 0: + raise ValueError("Step must not be zero") + else: + step = ensure_int(step, 'step') + + return cls._simple_new(start, stop, step, name) + + @classmethod + def from_range(cls, data, name=None, dtype=None, **kwargs): + """ Create RangeIndex from a range (py3), or xrange (py2) object. """ + if not isinstance(data, range): + raise TypeError( + '{0}(...) must be called with object coercible to a ' + 'range, {1} was passed'.format(cls.__name__, repr(data))) + + start, stop, step = get_range_parameters(data) + return RangeIndex(start, stop, step, dtype=dtype, name=name, **kwargs) + + @classmethod + def _simple_new(cls, start, stop=None, step=None, name=None, + dtype=None, **kwargs): + result = object.__new__(cls) + + # handle passed None, non-integers + if start is None and stop is None: + # empty + start, stop, step = 0, 0, 1 + + if start is None or not is_integer(start): + try: + + return RangeIndex(start, stop, step, name=name, **kwargs) + except TypeError: + return Index(start, stop, step, name=name, **kwargs) + + result._start = start + result._stop = stop or 0 + result._step = step or 1 + result.name = name + for k, v in compat.iteritems(kwargs): + setattr(result, k, v) + + result._reset_identity() + return result + + # -------------------------------------------------------------------- + + @staticmethod + def _validate_dtype(dtype): + """ require dtype to be None or int64 """ + if not (dtype is None or is_int64_dtype(dtype)): + raise TypeError('Invalid to pass a non-int64 dtype to RangeIndex') + + @cache_readonly + def _constructor(self): + """ return the class to use for construction """ + return Int64Index + + @cache_readonly + def _data(self): + return np.arange(self._start, self._stop, self._step, dtype=np.int64) + + @cache_readonly + def _int64index(self): + return Int64Index._simple_new(self._data, name=self.name) + + def _get_data_as_items(self): + """ return a list of tuples of start, stop, step """ + return [('start', self._start), + ('stop', self._stop), + ('step', self._step)] + + def __reduce__(self): + d = self._get_attributes_dict() + d.update(dict(self._get_data_as_items())) + return ibase._new_Index, (self.__class__, d), None + + # -------------------------------------------------------------------- + # Rendering Methods + + def _format_attrs(self): + """ + Return a list of tuples of the (attr, formatted_value) + """ + attrs = self._get_data_as_items() + if self.name is not None: + attrs.append(('name', ibase.default_pprint(self.name))) + return attrs + + def _format_data(self, name=None): + # we are formatting thru the attributes + return None + + # -------------------------------------------------------------------- + + @cache_readonly + def nbytes(self): + """ + Return the number of bytes in the underlying data + On implementations where this is undetermined (PyPy) + assume 24 bytes for each value + """ + return sum(getsizeof(getattr(self, v), 24) for v in + ['_start', '_stop', '_step']) + + def memory_usage(self, deep=False): + """ + Memory usage of my values + + Parameters + ---------- + deep : bool + Introspect the data deeply, interrogate + `object` dtypes for system-level memory consumption + + Returns + ------- + bytes used + + Notes + ----- + Memory usage does not include memory consumed by elements that + are not components of the array if deep=False + + See Also + -------- + numpy.ndarray.nbytes + """ + return self.nbytes + + @property + def dtype(self): + return np.dtype(np.int64) + + @property + def is_unique(self): + """ return if the index has unique values """ + return True + + @cache_readonly + def is_monotonic_increasing(self): + return self._step > 0 or len(self) <= 1 + + @cache_readonly + def is_monotonic_decreasing(self): + return self._step < 0 or len(self) <= 1 + + @property + def has_duplicates(self): + return False + + def tolist(self): + return lrange(self._start, self._stop, self._step) + + @Appender(_index_shared_docs['_shallow_copy']) + def _shallow_copy(self, values=None, **kwargs): + if values is None: + name = kwargs.get("name", self.name) + return RangeIndex._simple_new( + name=name, **dict(self._get_data_as_items())) + else: + kwargs.setdefault('name', self.name) + return self._int64index._shallow_copy(values, **kwargs) + + @Appender(ibase._index_shared_docs['copy']) + def copy(self, name=None, deep=False, dtype=None, **kwargs): + self._validate_dtype(dtype) + if name is None: + name = self.name + return RangeIndex._simple_new( + name=name, **dict(self._get_data_as_items())) + + def _minmax(self, meth): + no_steps = len(self) - 1 + if no_steps == -1: + return np.nan + elif ((meth == 'min' and self._step > 0) or + (meth == 'max' and self._step < 0)): + return self._start + + return self._start + self._step * no_steps + + def min(self, axis=None, skipna=True): + """The minimum value of the RangeIndex""" + nv.validate_minmax_axis(axis) + return self._minmax('min') + + def max(self, axis=None, skipna=True): + """The maximum value of the RangeIndex""" + nv.validate_minmax_axis(axis) + return self._minmax('max') + + def argsort(self, *args, **kwargs): + """ + Returns the indices that would sort the index and its + underlying data. + + Returns + ------- + argsorted : numpy array + + See Also + -------- + numpy.ndarray.argsort + """ + nv.validate_argsort(args, kwargs) + + if self._step > 0: + return np.arange(len(self)) + else: + return np.arange(len(self) - 1, -1, -1) + + def equals(self, other): + """ + Determines if two Index objects contain the same elements. + """ + if isinstance(other, RangeIndex): + ls = len(self) + lo = len(other) + return (ls == lo == 0 or + ls == lo == 1 and + self._start == other._start or + ls == lo and + self._start == other._start and + self._step == other._step) + + return super(RangeIndex, self).equals(other) + + def intersection(self, other, sort=False): + """ + Form the intersection of two Index objects. + + Parameters + ---------- + other : Index or array-like + sort : False or None, default False + Sort the resulting index if possible + + .. versionadded:: 0.24.0 + + .. versionchanged:: 0.24.1 + + Changed the default to ``False`` to match the behaviour + from before 0.24.0. + + Returns + ------- + intersection : Index + """ + self._validate_sort_keyword(sort) + + if self.equals(other): + return self._get_reconciled_name_object(other) + + if not isinstance(other, RangeIndex): + return super(RangeIndex, self).intersection(other, sort=sort) + + if not len(self) or not len(other): + return RangeIndex._simple_new(None) + + first = self[::-1] if self._step < 0 else self + second = other[::-1] if other._step < 0 else other + + # check whether intervals intersect + # deals with in- and decreasing ranges + int_low = max(first._start, second._start) + int_high = min(first._stop, second._stop) + if int_high <= int_low: + return RangeIndex._simple_new(None) + + # Method hint: linear Diophantine equation + # solve intersection problem + # performance hint: for identical step sizes, could use + # cheaper alternative + gcd, s, t = first._extended_gcd(first._step, second._step) + + # check whether element sets intersect + if (first._start - second._start) % gcd: + return RangeIndex._simple_new(None) + + # calculate parameters for the RangeIndex describing the + # intersection disregarding the lower bounds + tmp_start = first._start + (second._start - first._start) * \ + first._step // gcd * s + new_step = first._step * second._step // gcd + new_index = RangeIndex._simple_new(tmp_start, int_high, new_step) + + # adjust index to limiting interval + new_index._start = new_index._min_fitting_element(int_low) + + if (self._step < 0 and other._step < 0) is not (new_index._step < 0): + new_index = new_index[::-1] + if sort is None: + new_index = new_index.sort_values() + return new_index + + def _min_fitting_element(self, lower_limit): + """Returns the smallest element greater than or equal to the limit""" + no_steps = -(-(lower_limit - self._start) // abs(self._step)) + return self._start + abs(self._step) * no_steps + + def _max_fitting_element(self, upper_limit): + """Returns the largest element smaller than or equal to the limit""" + no_steps = (upper_limit - self._start) // abs(self._step) + return self._start + abs(self._step) * no_steps + + def _extended_gcd(self, a, b): + """ + Extended Euclidean algorithms to solve Bezout's identity: + a*x + b*y = gcd(x, y) + Finds one particular solution for x, y: s, t + Returns: gcd, s, t + """ + s, old_s = 0, 1 + t, old_t = 1, 0 + r, old_r = b, a + while r: + quotient = old_r // r + old_r, r = r, old_r - quotient * r + old_s, s = s, old_s - quotient * s + old_t, t = t, old_t - quotient * t + return old_r, old_s, old_t + + def union(self, other): + """ + Form the union of two Index objects and sorts if possible + + Parameters + ---------- + other : Index or array-like + + Returns + ------- + union : Index + """ + self._assert_can_do_setop(other) + if len(other) == 0 or self.equals(other) or len(self) == 0: + return super(RangeIndex, self).union(other) + + if isinstance(other, RangeIndex): + start_s, step_s = self._start, self._step + end_s = self._start + self._step * (len(self) - 1) + start_o, step_o = other._start, other._step + end_o = other._start + other._step * (len(other) - 1) + if self._step < 0: + start_s, step_s, end_s = end_s, -step_s, start_s + if other._step < 0: + start_o, step_o, end_o = end_o, -step_o, start_o + if len(self) == 1 and len(other) == 1: + step_s = step_o = abs(self._start - other._start) + elif len(self) == 1: + step_s = step_o + elif len(other) == 1: + step_o = step_s + start_r = min(start_s, start_o) + end_r = max(end_s, end_o) + if step_o == step_s: + if ((start_s - start_o) % step_s == 0 and + (start_s - end_o) <= step_s and + (start_o - end_s) <= step_s): + return RangeIndex(start_r, end_r + step_s, step_s) + if ((step_s % 2 == 0) and + (abs(start_s - start_o) <= step_s / 2) and + (abs(end_s - end_o) <= step_s / 2)): + return RangeIndex(start_r, end_r + step_s / 2, step_s / 2) + elif step_o % step_s == 0: + if ((start_o - start_s) % step_s == 0 and + (start_o + step_s >= start_s) and + (end_o - step_s <= end_s)): + return RangeIndex(start_r, end_r + step_s, step_s) + elif step_s % step_o == 0: + if ((start_s - start_o) % step_o == 0 and + (start_s + step_o >= start_o) and + (end_s - step_o <= end_o)): + return RangeIndex(start_r, end_r + step_o, step_o) + + return self._int64index.union(other) + + @Appender(_index_shared_docs['join']) + def join(self, other, how='left', level=None, return_indexers=False, + sort=False): + if how == 'outer' and self is not other: + # note: could return RangeIndex in more circumstances + return self._int64index.join(other, how, level, return_indexers, + sort) + + return super(RangeIndex, self).join(other, how, level, return_indexers, + sort) + + def _concat_same_dtype(self, indexes, name): + return _concat._concat_rangeindex_same_dtype(indexes).rename(name) + + def __len__(self): + """ + return the length of the RangeIndex + """ + return max(0, -(-(self._stop - self._start) // self._step)) + + @property + def size(self): + return len(self) + + def __getitem__(self, key): + """ + Conserve RangeIndex type for scalar and slice keys. + """ + super_getitem = super(RangeIndex, self).__getitem__ + + if is_scalar(key): + if not lib.is_integer(key): + raise IndexError("only integers, slices (`:`), " + "ellipsis (`...`), numpy.newaxis (`None`) " + "and integer or boolean " + "arrays are valid indices") + n = com.cast_scalar_indexer(key) + if n != key: + return super_getitem(key) + if n < 0: + n = len(self) + key + if n < 0 or n > len(self) - 1: + raise IndexError("index {key} is out of bounds for axis 0 " + "with size {size}".format(key=key, + size=len(self))) + return self._start + n * self._step + + if isinstance(key, slice): + + # This is basically PySlice_GetIndicesEx, but delegation to our + # super routines if we don't have integers + + length = len(self) + + # complete missing slice information + step = 1 if key.step is None else key.step + if key.start is None: + start = length - 1 if step < 0 else 0 + else: + start = key.start + + if start < 0: + start += length + if start < 0: + start = -1 if step < 0 else 0 + if start >= length: + start = length - 1 if step < 0 else length + + if key.stop is None: + stop = -1 if step < 0 else length + else: + stop = key.stop + + if stop < 0: + stop += length + if stop < 0: + stop = -1 + if stop > length: + stop = length + + # delegate non-integer slices + if (start != int(start) or + stop != int(stop) or + step != int(step)): + return super_getitem(key) + + # convert indexes to values + start = self._start + self._step * start + stop = self._start + self._step * stop + step = self._step * step + + return RangeIndex._simple_new(start, stop, step, name=self.name) + + # fall back to Int64Index + return super_getitem(key) + + def __floordiv__(self, other): + if isinstance(other, (ABCSeries, ABCDataFrame)): + return NotImplemented + + if is_integer(other) and other != 0: + if (len(self) == 0 or + self._start % other == 0 and + self._step % other == 0): + start = self._start // other + step = self._step // other + stop = start + len(self) * step + return RangeIndex._simple_new( + start, stop, step, name=self.name) + if len(self) == 1: + start = self._start // other + return RangeIndex._simple_new( + start, start + 1, 1, name=self.name) + return self._int64index // other + + @classmethod + def _add_numeric_methods_binary(cls): + """ add in numeric methods, specialized to RangeIndex """ + + def _make_evaluate_binop(op, step=False): + """ + Parameters + ---------- + op : callable that accepts 2 parms + perform the binary op + step : callable, optional, default to False + op to apply to the step parm if not None + if False, use the existing step + """ + + def _evaluate_numeric_binop(self, other): + if isinstance(other, (ABCSeries, ABCDataFrame)): + return NotImplemented + elif isinstance(other, ABCTimedeltaIndex): + # Defer to TimedeltaIndex implementation + return NotImplemented + elif isinstance(other, (timedelta, np.timedelta64)): + # GH#19333 is_integer evaluated True on timedelta64, + # so we need to catch these explicitly + return op(self._int64index, other) + elif is_timedelta64_dtype(other): + # Must be an np.ndarray; GH#22390 + return op(self._int64index, other) + + other = self._validate_for_numeric_binop(other, op) + attrs = self._get_attributes_dict() + attrs = self._maybe_update_attributes(attrs) + + left, right = self, other + + try: + # apply if we have an override + if step: + with np.errstate(all='ignore'): + rstep = step(left._step, right) + + # we don't have a representable op + # so return a base index + if not is_integer(rstep) or not rstep: + raise ValueError + + else: + rstep = left._step + + with np.errstate(all='ignore'): + rstart = op(left._start, right) + rstop = op(left._stop, right) + + result = RangeIndex(rstart, + rstop, + rstep, + **attrs) + + # for compat with numpy / Int64Index + # even if we can represent as a RangeIndex, return + # as a Float64Index if we have float-like descriptors + if not all(is_integer(x) for x in + [rstart, rstop, rstep]): + result = result.astype('float64') + + return result + + except (ValueError, TypeError, ZeroDivisionError): + # Defer to Int64Index implementation + return op(self._int64index, other) + # TODO: Do attrs get handled reliably? + + name = '__{name}__'.format(name=op.__name__) + return compat.set_function_name(_evaluate_numeric_binop, name, cls) + + cls.__add__ = _make_evaluate_binop(operator.add) + cls.__radd__ = _make_evaluate_binop(ops.radd) + cls.__sub__ = _make_evaluate_binop(operator.sub) + cls.__rsub__ = _make_evaluate_binop(ops.rsub) + cls.__mul__ = _make_evaluate_binop(operator.mul, step=operator.mul) + cls.__rmul__ = _make_evaluate_binop(ops.rmul, step=ops.rmul) + cls.__truediv__ = _make_evaluate_binop(operator.truediv, + step=operator.truediv) + cls.__rtruediv__ = _make_evaluate_binop(ops.rtruediv, + step=ops.rtruediv) + if not compat.PY3: + cls.__div__ = _make_evaluate_binop(operator.div, step=operator.div) + cls.__rdiv__ = _make_evaluate_binop(ops.rdiv, step=ops.rdiv) + + +RangeIndex._add_numeric_methods() +RangeIndex._add_logical_methods() diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/timedeltas.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/timedeltas.py new file mode 100644 index 0000000000000000000000000000000000000000..cbe5ae198838f6216743a1dba08e917e2e86e490 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/indexes/timedeltas.py @@ -0,0 +1,804 @@ +""" implement the TimedeltaIndex """ +from datetime import datetime +import warnings + +import numpy as np + +from pandas._libs import ( + NaT, Timedelta, index as libindex, join as libjoin, lib) +import pandas.compat as compat +from pandas.util._decorators import Appender, Substitution + +from pandas.core.dtypes.common import ( + _TD_DTYPE, ensure_int64, is_float, is_integer, is_list_like, is_scalar, + is_timedelta64_dtype, is_timedelta64_ns_dtype, pandas_dtype) +import pandas.core.dtypes.concat as _concat +from pandas.core.dtypes.missing import isna + +from pandas.core.accessor import delegate_names +from pandas.core.arrays import datetimelike as dtl +from pandas.core.arrays.timedeltas import TimedeltaArray, _is_convertible_to_td +from pandas.core.base import _shared_docs +import pandas.core.common as com +from pandas.core.indexes.base import Index, _index_shared_docs +from pandas.core.indexes.datetimelike import ( + DatetimeIndexOpsMixin, DatetimelikeDelegateMixin, maybe_unwrap_index, + wrap_arithmetic_op) +from pandas.core.indexes.numeric import Int64Index +from pandas.core.ops import get_op_result_name + +from pandas.tseries.frequencies import to_offset + + +def _make_wrapped_arith_op(opname): + + meth = getattr(TimedeltaArray, opname) + + def method(self, other): + result = meth(self._data, maybe_unwrap_index(other)) + return wrap_arithmetic_op(self, other, result) + + method.__name__ = opname + return method + + +class TimedeltaDelegateMixin(DatetimelikeDelegateMixin): + # Most attrs are dispatched via datetimelike_{ops,methods} + # Some are "raw" methods, the result is not not re-boxed in an Index + # We also have a few "extra" attrs, which may or may not be raw, + # which we we dont' want to expose in the .dt accessor. + _delegate_class = TimedeltaArray + _delegated_properties = (TimedeltaArray._datetimelike_ops + [ + 'components', + ]) + _delegated_methods = TimedeltaArray._datetimelike_methods + [ + '_box_values', + ] + _raw_properties = { + 'components', + } + _raw_methods = { + 'to_pytimedelta', + } + + +@delegate_names(TimedeltaArray, + TimedeltaDelegateMixin._delegated_properties, + typ="property") +@delegate_names(TimedeltaArray, + TimedeltaDelegateMixin._delegated_methods, + typ="method", overwrite=False) +class TimedeltaIndex(DatetimeIndexOpsMixin, dtl.TimelikeOps, Int64Index, + TimedeltaDelegateMixin): + """ + Immutable ndarray of timedelta64 data, represented internally as int64, and + which can be boxed to timedelta objects + + Parameters + ---------- + data : array-like (1-dimensional), optional + Optional timedelta-like data to construct index with + unit : unit of the arg (D,h,m,s,ms,us,ns) denote the unit, optional + which is an integer/float number + freq : string or pandas offset object, optional + One of pandas date offset strings or corresponding objects. The string + 'infer' can be passed in order to set the frequency of the index as the + inferred frequency upon creation + copy : bool + Make a copy of input ndarray + start : starting value, timedelta-like, optional + If data is None, start is used as the start point in generating regular + timedelta data. + + .. deprecated:: 0.24.0 + + periods : int, optional, > 0 + Number of periods to generate, if generating index. Takes precedence + over end argument + + .. deprecated:: 0.24.0 + + end : end time, timedelta-like, optional + If periods is none, generated index will extend to first conforming + time on or just past end argument + + .. deprecated:: 0.24. 0 + + closed : string or None, default None + Make the interval closed with respect to the given frequency to + the 'left', 'right', or both sides (None) + + .. deprecated:: 0.24. 0 + + name : object + Name to be stored in the index + + Attributes + ---------- + days + seconds + microseconds + nanoseconds + components + inferred_freq + + Methods + ------- + to_pytimedelta + to_series + round + floor + ceil + to_frame + + See Also + --------- + Index : The base pandas Index type. + Timedelta : Represents a duration between two dates or times. + DatetimeIndex : Index of datetime64 data. + PeriodIndex : Index of Period data. + timedelta_range : Create a fixed-frequency TimedeltaIndex. + + Notes + ----- + To learn more about the frequency strings, please see `this link + `__. + + Creating a TimedeltaIndex based on `start`, `periods`, and `end` has + been deprecated in favor of :func:`timedelta_range`. + """ + + _typ = 'timedeltaindex' + _join_precedence = 10 + + def _join_i8_wrapper(joinf, **kwargs): + return DatetimeIndexOpsMixin._join_i8_wrapper( + joinf, dtype='m8[ns]', **kwargs) + + _inner_indexer = _join_i8_wrapper(libjoin.inner_join_indexer_int64) + _outer_indexer = _join_i8_wrapper(libjoin.outer_join_indexer_int64) + _left_indexer = _join_i8_wrapper(libjoin.left_join_indexer_int64) + _left_indexer_unique = _join_i8_wrapper( + libjoin.left_join_indexer_unique_int64, with_indexers=False) + + _engine_type = libindex.TimedeltaEngine + + _comparables = ['name', 'freq'] + _attributes = ['name', 'freq'] + _is_numeric_dtype = True + _infer_as_myclass = True + + _freq = None + + _box_func = TimedeltaArray._box_func + _bool_ops = TimedeltaArray._bool_ops + _object_ops = TimedeltaArray._object_ops + _field_ops = TimedeltaArray._field_ops + _datetimelike_ops = TimedeltaArray._datetimelike_ops + _datetimelike_methods = TimedeltaArray._datetimelike_methods + _other_ops = TimedeltaArray._other_ops + + # ------------------------------------------------------------------- + # Constructors + + def __new__(cls, data=None, unit=None, freq=None, start=None, end=None, + periods=None, closed=None, dtype=_TD_DTYPE, copy=False, + name=None, verify_integrity=None): + + if verify_integrity is not None: + warnings.warn("The 'verify_integrity' argument is deprecated, " + "will be removed in a future version.", + FutureWarning, stacklevel=2) + else: + verify_integrity = True + + if data is None: + freq, freq_infer = dtl.maybe_infer_freq(freq) + warnings.warn("Creating a TimedeltaIndex by passing range " + "endpoints is deprecated. Use " + "`pandas.timedelta_range` instead.", + FutureWarning, stacklevel=2) + result = TimedeltaArray._generate_range(start, end, periods, freq, + closed=closed) + return cls._simple_new(result._data, freq=freq, name=name) + + if is_scalar(data): + raise TypeError('{cls}() must be called with a ' + 'collection of some kind, {data} was passed' + .format(cls=cls.__name__, data=repr(data))) + + if isinstance(data, TimedeltaArray): + if copy: + data = data.copy() + return cls._simple_new(data, name=name, freq=freq) + + if (isinstance(data, TimedeltaIndex) and + freq is None and name is None): + if copy: + return data.copy() + else: + return data._shallow_copy() + + # - Cases checked above all return/raise before reaching here - # + + tdarr = TimedeltaArray._from_sequence(data, freq=freq, unit=unit, + dtype=dtype, copy=copy) + return cls._simple_new(tdarr._data, freq=tdarr.freq, name=name) + + @classmethod + def _simple_new(cls, values, name=None, freq=None, dtype=_TD_DTYPE): + # `dtype` is passed by _shallow_copy in corner cases, should always + # be timedelta64[ns] if present + if not isinstance(values, TimedeltaArray): + values = TimedeltaArray._simple_new(values, dtype=dtype, + freq=freq) + else: + if freq is None: + freq = values.freq + assert isinstance(values, TimedeltaArray), type(values) + assert dtype == _TD_DTYPE, dtype + assert values.dtype == 'm8[ns]', values.dtype + + tdarr = TimedeltaArray._simple_new(values._data, freq=freq) + result = object.__new__(cls) + result._data = tdarr + result.name = name + # For groupby perf. See note in indexes/base about _index_data + result._index_data = tdarr._data + + result._reset_identity() + return result + + # ------------------------------------------------------------------- + + def __setstate__(self, state): + """Necessary for making this object picklable""" + if isinstance(state, dict): + super(TimedeltaIndex, self).__setstate__(state) + else: + raise Exception("invalid pickle state") + _unpickle_compat = __setstate__ + + def _maybe_update_attributes(self, attrs): + """ Update Index attributes (e.g. freq) depending on op """ + freq = attrs.get('freq', None) + if freq is not None: + # no need to infer if freq is None + attrs['freq'] = 'infer' + return attrs + + # ------------------------------------------------------------------- + # Rendering Methods + + @property + def _formatter_func(self): + from pandas.io.formats.format import _get_format_timedelta64 + return _get_format_timedelta64(self, box=True) + + def _format_native_types(self, na_rep='NaT', date_format=None, **kwargs): + from pandas.io.formats.format import Timedelta64Formatter + return Timedelta64Formatter(values=self, + nat_rep=na_rep, + justify='all').get_result() + + # ------------------------------------------------------------------- + # Wrapping TimedeltaArray + + __mul__ = _make_wrapped_arith_op("__mul__") + __rmul__ = _make_wrapped_arith_op("__rmul__") + __floordiv__ = _make_wrapped_arith_op("__floordiv__") + __rfloordiv__ = _make_wrapped_arith_op("__rfloordiv__") + __mod__ = _make_wrapped_arith_op("__mod__") + __rmod__ = _make_wrapped_arith_op("__rmod__") + __divmod__ = _make_wrapped_arith_op("__divmod__") + __rdivmod__ = _make_wrapped_arith_op("__rdivmod__") + __truediv__ = _make_wrapped_arith_op("__truediv__") + __rtruediv__ = _make_wrapped_arith_op("__rtruediv__") + if compat.PY2: + __div__ = __truediv__ + __rdiv__ = __rtruediv__ + + # Compat for frequency inference, see GH#23789 + _is_monotonic_increasing = Index.is_monotonic_increasing + _is_monotonic_decreasing = Index.is_monotonic_decreasing + _is_unique = Index.is_unique + + @property + def _box_func(self): + return lambda x: Timedelta(x, unit='ns') + + def __getitem__(self, key): + result = self._data.__getitem__(key) + if is_scalar(result): + return result + return type(self)(result, name=self.name) + + # ------------------------------------------------------------------- + + @Appender(_index_shared_docs['astype']) + def astype(self, dtype, copy=True): + dtype = pandas_dtype(dtype) + if is_timedelta64_dtype(dtype) and not is_timedelta64_ns_dtype(dtype): + # Have to repeat the check for 'timedelta64' (not ns) dtype + # so that we can return a numeric index, since pandas will return + # a TimedeltaIndex when dtype='timedelta' + result = self._data.astype(dtype, copy=copy) + if self.hasnans: + return Index(result, name=self.name) + return Index(result.astype('i8'), name=self.name) + return DatetimeIndexOpsMixin.astype(self, dtype, copy=copy) + + def union(self, other): + """ + Specialized union for TimedeltaIndex objects. If combine + overlapping ranges with the same DateOffset, will be much + faster than Index.union + + Parameters + ---------- + other : TimedeltaIndex or array-like + + Returns + ------- + y : Index or TimedeltaIndex + """ + self._assert_can_do_setop(other) + + if len(other) == 0 or self.equals(other) or len(self) == 0: + return super(TimedeltaIndex, self).union(other) + + if not isinstance(other, TimedeltaIndex): + try: + other = TimedeltaIndex(other) + except (TypeError, ValueError): + pass + this, other = self, other + + if this._can_fast_union(other): + return this._fast_union(other) + else: + result = Index.union(this, other) + if isinstance(result, TimedeltaIndex): + if result.freq is None: + result.freq = to_offset(result.inferred_freq) + return result + + def join(self, other, how='left', level=None, return_indexers=False, + sort=False): + """ + See Index.join + """ + if _is_convertible_to_index(other): + try: + other = TimedeltaIndex(other) + except (TypeError, ValueError): + pass + + return Index.join(self, other, how=how, level=level, + return_indexers=return_indexers, + sort=sort) + + def _wrap_joined_index(self, joined, other): + name = get_op_result_name(self, other) + if (isinstance(other, TimedeltaIndex) and self.freq == other.freq and + self._can_fast_union(other)): + joined = self._shallow_copy(joined, name=name) + return joined + else: + return self._simple_new(joined, name) + + def _can_fast_union(self, other): + if not isinstance(other, TimedeltaIndex): + return False + + freq = self.freq + + if freq is None or freq != other.freq: + return False + + if not self.is_monotonic or not other.is_monotonic: + return False + + if len(self) == 0 or len(other) == 0: + return True + + # to make our life easier, "sort" the two ranges + if self[0] <= other[0]: + left, right = self, other + else: + left, right = other, self + + right_start = right[0] + left_end = left[-1] + + # Only need to "adjoin", not overlap + return (right_start == left_end + freq) or right_start in left + + def _fast_union(self, other): + if len(other) == 0: + return self.view(type(self)) + + if len(self) == 0: + return other.view(type(self)) + + # to make our life easier, "sort" the two ranges + if self[0] <= other[0]: + left, right = self, other + else: + left, right = other, self + + left_end = left[-1] + right_end = right[-1] + + # concatenate + if left_end < right_end: + loc = right.searchsorted(left_end, side='right') + right_chunk = right.values[loc:] + dates = _concat._concat_compat((left.values, right_chunk)) + return self._shallow_copy(dates) + else: + return left + + def intersection(self, other): + """ + Specialized intersection for TimedeltaIndex objects. May be much faster + than Index.intersection + + Parameters + ---------- + other : TimedeltaIndex or array-like + + Returns + ------- + y : Index or TimedeltaIndex + """ + self._assert_can_do_setop(other) + + if self.equals(other): + return self._get_reconciled_name_object(other) + + if not isinstance(other, TimedeltaIndex): + try: + other = TimedeltaIndex(other) + except (TypeError, ValueError): + pass + result = Index.intersection(self, other) + return result + + if len(self) == 0: + return self + if len(other) == 0: + return other + # to make our life easier, "sort" the two ranges + if self[0] <= other[0]: + left, right = self, other + else: + left, right = other, self + + end = min(left[-1], right[-1]) + start = right[0] + + if end < start: + return type(self)(data=[]) + else: + lslice = slice(*left.slice_locs(start, end)) + left_chunk = left.values[lslice] + return self._shallow_copy(left_chunk) + + def _maybe_promote(self, other): + if other.inferred_type == 'timedelta': + other = TimedeltaIndex(other) + return self, other + + def get_value(self, series, key): + """ + Fast lookup of value from 1-dimensional ndarray. Only use this if you + know what you're doing + """ + + if _is_convertible_to_td(key): + key = Timedelta(key) + return self.get_value_maybe_box(series, key) + + try: + return com.maybe_box(self, Index.get_value(self, series, key), + series, key) + except KeyError: + try: + loc = self._get_string_slice(key) + return series[loc] + except (TypeError, ValueError, KeyError): + pass + + try: + return self.get_value_maybe_box(series, key) + except (TypeError, ValueError, KeyError): + raise KeyError(key) + + def get_value_maybe_box(self, series, key): + if not isinstance(key, Timedelta): + key = Timedelta(key) + values = self._engine.get_value(com.values_from_object(series), key) + return com.maybe_box(self, values, series, key) + + def get_loc(self, key, method=None, tolerance=None): + """ + Get integer location for requested label + + Returns + ------- + loc : int + """ + if is_list_like(key) or (isinstance(key, datetime) and key is not NaT): + # GH#20464 datetime check here is to ensure we don't allow + # datetime objects to be incorrectly treated as timedelta + # objects; NaT is a special case because it plays a double role + # as Not-A-Timedelta + raise TypeError + + if isna(key): + key = NaT + + if tolerance is not None: + # try converting tolerance now, so errors don't get swallowed by + # the try/except clauses below + tolerance = self._convert_tolerance(tolerance, np.asarray(key)) + + if _is_convertible_to_td(key): + key = Timedelta(key) + return Index.get_loc(self, key, method, tolerance) + + try: + return Index.get_loc(self, key, method, tolerance) + except (KeyError, ValueError, TypeError): + try: + return self._get_string_slice(key) + except (TypeError, KeyError, ValueError): + pass + + try: + stamp = Timedelta(key) + return Index.get_loc(self, stamp, method, tolerance) + except (KeyError, ValueError): + raise KeyError(key) + + def _maybe_cast_slice_bound(self, label, side, kind): + """ + If label is a string, cast it to timedelta according to resolution. + + + Parameters + ---------- + label : object + side : {'left', 'right'} + kind : {'ix', 'loc', 'getitem'} + + Returns + ------- + label : object + + """ + assert kind in ['ix', 'loc', 'getitem', None] + + if isinstance(label, compat.string_types): + parsed = Timedelta(label) + lbound = parsed.round(parsed.resolution) + if side == 'left': + return lbound + else: + return (lbound + to_offset(parsed.resolution) - + Timedelta(1, 'ns')) + elif ((is_integer(label) or is_float(label)) and + not is_timedelta64_dtype(label)): + self._invalid_indexer('slice', label) + + return label + + def _get_string_slice(self, key): + if is_integer(key) or is_float(key) or key is NaT: + self._invalid_indexer('slice', key) + loc = self._partial_td_slice(key) + return loc + + def _partial_td_slice(self, key): + + # given a key, try to figure out a location for a partial slice + if not isinstance(key, compat.string_types): + return key + + raise NotImplementedError + + @Substitution(klass='TimedeltaIndex') + @Appender(_shared_docs['searchsorted']) + def searchsorted(self, value, side='left', sorter=None): + if isinstance(value, (np.ndarray, Index)): + value = np.array(value, dtype=_TD_DTYPE, copy=False) + else: + value = Timedelta(value).asm8.view(_TD_DTYPE) + + return self.values.searchsorted(value, side=side, sorter=sorter) + + def is_type_compatible(self, typ): + return typ == self.inferred_type or typ == 'timedelta' + + @property + def inferred_type(self): + return 'timedelta64' + + @property + def is_all_dates(self): + return True + + def insert(self, loc, item): + """ + Make new Index inserting new item at location + + Parameters + ---------- + loc : int + item : object + if not either a Python datetime or a numpy integer-like, returned + Index dtype will be object rather than datetime. + + Returns + ------- + new_index : Index + """ + # try to convert if possible + if _is_convertible_to_td(item): + try: + item = Timedelta(item) + except Exception: + pass + elif is_scalar(item) and isna(item): + # GH 18295 + item = self._na_value + + freq = None + if isinstance(item, Timedelta) or (is_scalar(item) and isna(item)): + + # check freq can be preserved on edge cases + if self.freq is not None: + if ((loc == 0 or loc == -len(self)) and + item + self.freq == self[0]): + freq = self.freq + elif (loc == len(self)) and item - self.freq == self[-1]: + freq = self.freq + item = Timedelta(item).asm8.view(_TD_DTYPE) + + try: + new_tds = np.concatenate((self[:loc].asi8, [item.view(np.int64)], + self[loc:].asi8)) + return self._shallow_copy(new_tds, freq=freq) + + except (AttributeError, TypeError): + + # fall back to object index + if isinstance(item, compat.string_types): + return self.astype(object).insert(loc, item) + raise TypeError( + "cannot insert TimedeltaIndex with incompatible label") + + def delete(self, loc): + """ + Make a new TimedeltaIndex with passed location(s) deleted. + + Parameters + ---------- + loc: int, slice or array of ints + Indicate which sub-arrays to remove. + + Returns + ------- + new_index : TimedeltaIndex + """ + new_tds = np.delete(self.asi8, loc) + + freq = 'infer' + if is_integer(loc): + if loc in (0, -len(self), -1, len(self) - 1): + freq = self.freq + else: + if is_list_like(loc): + loc = lib.maybe_indices_to_slice( + ensure_int64(np.array(loc)), len(self)) + if isinstance(loc, slice) and loc.step in (1, None): + if (loc.start in (0, None) or loc.stop in (len(self), None)): + freq = self.freq + + return TimedeltaIndex(new_tds, name=self.name, freq=freq) + + +TimedeltaIndex._add_comparison_ops() +TimedeltaIndex._add_numeric_methods_unary() +TimedeltaIndex._add_logical_methods_disabled() +TimedeltaIndex._add_datetimelike_methods() + + +def _is_convertible_to_index(other): + """ + return a boolean whether I can attempt conversion to a TimedeltaIndex + """ + if isinstance(other, TimedeltaIndex): + return True + elif (len(other) > 0 and + other.inferred_type not in ('floating', 'mixed-integer', 'integer', + 'mixed-integer-float', 'mixed')): + return True + return False + + +def timedelta_range(start=None, end=None, periods=None, freq=None, + name=None, closed=None): + """ + Return a fixed frequency TimedeltaIndex, with day as the default + frequency + + Parameters + ---------- + start : string or timedelta-like, default None + Left bound for generating timedeltas + end : string or timedelta-like, default None + Right bound for generating timedeltas + periods : integer, default None + Number of periods to generate + freq : string or DateOffset, default 'D' + Frequency strings can have multiples, e.g. '5H' + name : string, default None + Name of the resulting TimedeltaIndex + closed : string, default None + Make the interval closed with respect to the given frequency to + the 'left', 'right', or both sides (None) + + Returns + ------- + rng : TimedeltaIndex + + Notes + ----- + Of the four parameters ``start``, ``end``, ``periods``, and ``freq``, + exactly three must be specified. If ``freq`` is omitted, the resulting + ``TimedeltaIndex`` will have ``periods`` linearly spaced elements between + ``start`` and ``end`` (closed on both sides). + + To learn more about the frequency strings, please see `this link + `__. + + Examples + -------- + + >>> pd.timedelta_range(start='1 day', periods=4) + TimedeltaIndex(['1 days', '2 days', '3 days', '4 days'], + dtype='timedelta64[ns]', freq='D') + + The ``closed`` parameter specifies which endpoint is included. The default + behavior is to include both endpoints. + + >>> pd.timedelta_range(start='1 day', periods=4, closed='right') + TimedeltaIndex(['2 days', '3 days', '4 days'], + dtype='timedelta64[ns]', freq='D') + + The ``freq`` parameter specifies the frequency of the TimedeltaIndex. + Only fixed frequencies can be passed, non-fixed frequencies such as + 'M' (month end) will raise. + + >>> pd.timedelta_range(start='1 day', end='2 days', freq='6H') + TimedeltaIndex(['1 days 00:00:00', '1 days 06:00:00', '1 days 12:00:00', + '1 days 18:00:00', '2 days 00:00:00'], + dtype='timedelta64[ns]', freq='6H') + + Specify ``start``, ``end``, and ``periods``; the frequency is generated + automatically (linearly spaced). + + >>> pd.timedelta_range(start='1 day', end='5 days', periods=4) + TimedeltaIndex(['1 days 00:00:00', '2 days 08:00:00', '3 days 16:00:00', + '5 days 00:00:00'], + dtype='timedelta64[ns]', freq=None) + """ + if freq is None and com._any_none(periods, start, end): + freq = 'D' + + freq, freq_infer = dtl.maybe_infer_freq(freq) + tdarr = TimedeltaArray._generate_range(start, end, periods, freq, + closed=closed) + return TimedeltaIndex._simple_new(tdarr._data, freq=tdarr.freq, name=name) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/extension/numpy_/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/extension/numpy_/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/extension/numpy_/test_numpy.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/extension/numpy_/test_numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..4c93d5ee0b9d7ce11673ad3ce563be0ba372410d --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/extension/numpy_/test_numpy.py @@ -0,0 +1,182 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import compat +from pandas.core.arrays.numpy_ import PandasArray, PandasDtype +import pandas.util.testing as tm + +from .. import base + + +@pytest.fixture +def dtype(): + return PandasDtype(np.dtype('float')) + + +@pytest.fixture +def data(allow_in_pandas, dtype): + return PandasArray(np.arange(1, 101, dtype=dtype._dtype)) + + +@pytest.fixture +def data_missing(allow_in_pandas): + return PandasArray(np.array([np.nan, 1.0])) + + +@pytest.fixture +def data_for_sorting(allow_in_pandas): + """Length-3 array with a known sort order. + + This should be three items [B, C, A] with + A < B < C + """ + return PandasArray( + np.array([1, 2, 0]) + ) + + +@pytest.fixture +def data_missing_for_sorting(allow_in_pandas): + """Length-3 array with a known sort order. + + This should be three items [B, NA, A] with + A < B and NA missing. + """ + return PandasArray( + np.array([1, np.nan, 0]) + ) + + +@pytest.fixture +def data_for_grouping(allow_in_pandas): + """Data for factorization, grouping, and unique tests. + + Expected to be like [B, B, NA, NA, A, A, B, C] + + Where A < B < C and NA is missing + """ + a, b, c = np.arange(3) + return PandasArray(np.array( + [b, b, np.nan, np.nan, a, a, b, c] + )) + + +class BaseNumPyTests(object): + pass + + +class TestCasting(BaseNumPyTests, base.BaseCastingTests): + pass + + +class TestConstructors(BaseNumPyTests, base.BaseConstructorsTests): + @pytest.mark.skip(reason="We don't register our dtype") + # We don't want to register. This test should probably be split in two. + def test_from_dtype(self, data): + pass + + +class TestDtype(BaseNumPyTests, base.BaseDtypeTests): + + @pytest.mark.skip(reason="Incorrect expected.") + # we unsurprisingly clash with a NumPy name. + def test_check_dtype(self, data): + pass + + +class TestGetitem(BaseNumPyTests, base.BaseGetitemTests): + pass + + +class TestGroupby(BaseNumPyTests, base.BaseGroupbyTests): + pass + + +class TestInterface(BaseNumPyTests, base.BaseInterfaceTests): + pass + + +class TestMethods(BaseNumPyTests, base.BaseMethodsTests): + + @pytest.mark.skip(reason="TODO: remove?") + def test_value_counts(self, all_data, dropna): + pass + + @pytest.mark.skip(reason="Incorrect expected") + # We have a bool dtype, so the result is an ExtensionArray + # but expected is not + def test_combine_le(self, data_repeated): + super(TestMethods, self).test_combine_le(data_repeated) + + +class TestArithmetics(BaseNumPyTests, base.BaseArithmeticOpsTests): + divmod_exc = None + series_scalar_exc = None + frame_scalar_exc = None + series_array_exc = None + + def test_divmod_series_array(self, data): + s = pd.Series(data) + self._check_divmod_op(s, divmod, data, exc=None) + + @pytest.mark.skip("We implement ops") + def test_error(self, data, all_arithmetic_operators): + pass + + def test_arith_series_with_scalar(self, data, all_arithmetic_operators): + if (compat.PY2 and + all_arithmetic_operators in {'__div__', '__rdiv__'}): + raise pytest.skip( + "Matching NumPy int / int -> float behavior." + ) + super(TestArithmetics, self).test_arith_series_with_scalar( + data, all_arithmetic_operators + ) + + def test_arith_series_with_array(self, data, all_arithmetic_operators): + if (compat.PY2 and + all_arithmetic_operators in {'__div__', '__rdiv__'}): + raise pytest.skip( + "Matching NumPy int / int -> float behavior." + ) + super(TestArithmetics, self).test_arith_series_with_array( + data, all_arithmetic_operators + ) + + +class TestPrinting(BaseNumPyTests, base.BasePrintingTests): + pass + + +class TestNumericReduce(BaseNumPyTests, base.BaseNumericReduceTests): + + def check_reduce(self, s, op_name, skipna): + result = getattr(s, op_name)(skipna=skipna) + # avoid coercing int -> float. Just cast to the actual numpy type. + expected = getattr(s.astype(s.dtype._dtype), op_name)(skipna=skipna) + tm.assert_almost_equal(result, expected) + + +class TestBooleanReduce(BaseNumPyTests, base.BaseBooleanReduceTests): + pass + + +class TestMising(BaseNumPyTests, base.BaseMissingTests): + pass + + +class TestReshaping(BaseNumPyTests, base.BaseReshapingTests): + + @pytest.mark.skip("Incorrect parent test") + # not actually a mixed concat, since we concat int and int. + def test_concat_mixed_dtypes(self, data): + super(TestReshaping, self).test_concat_mixed_dtypes(data) + + +class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): + pass + + +class TestParsing(BaseNumPyTests, base.BaseParsingTests): + pass diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/extension/numpy_/test_numpy_nested.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/extension/numpy_/test_numpy_nested.py new file mode 100644 index 0000000000000000000000000000000000000000..cf9b34dd08798cf7f6cff377e9a36a8e67a0d64f --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/extension/numpy_/test_numpy_nested.py @@ -0,0 +1,286 @@ +""" +Tests for PandasArray with nested data. Users typically won't create +these objects via `pd.array`, but they can show up through `.array` +on a Series with nested data. + +We partition these tests into their own file, as many of the base +tests fail, as they aren't appropriate for nested data. It is easier +to have a seperate file with its own data generating fixtures, than +trying to skip based upon the value of a fixture. +""" +import pytest + +import pandas as pd +from pandas.core.arrays.numpy_ import PandasArray, PandasDtype + +from .. import base + +# For NumPy <1.16, np.array([np.nan, (1,)]) raises +# ValueError: setting an array element with a sequence. +np = pytest.importorskip('numpy', minversion='1.16.0') + + +@pytest.fixture +def dtype(): + return PandasDtype(np.dtype('object')) + + +@pytest.fixture +def data(allow_in_pandas, dtype): + return pd.Series([(i,) for i in range(100)]).array + + +@pytest.fixture +def data_missing(allow_in_pandas): + return PandasArray(np.array([np.nan, (1,)])) + + +@pytest.fixture +def data_for_sorting(allow_in_pandas): + """Length-3 array with a known sort order. + + This should be three items [B, C, A] with + A < B < C + """ + # Use an empty tuple for first element, then remove, + # to disable np.array's shape inference. + return PandasArray( + np.array([(), (2,), (3,), (1,)])[1:] + ) + + +@pytest.fixture +def data_missing_for_sorting(allow_in_pandas): + """Length-3 array with a known sort order. + + This should be three items [B, NA, A] with + A < B and NA missing. + """ + return PandasArray( + np.array([(1,), np.nan, (0,)]) + ) + + +@pytest.fixture +def data_for_grouping(allow_in_pandas): + """Data for factorization, grouping, and unique tests. + + Expected to be like [B, B, NA, NA, A, A, B, C] + + Where A < B < C and NA is missing + """ + a, b, c = (1,), (2,), (3,) + return PandasArray(np.array( + [b, b, np.nan, np.nan, a, a, b, c] + )) + + +skip_nested = pytest.mark.skip(reason="Skipping for nested PandasArray") + + +class BaseNumPyTests(object): + pass + + +class TestCasting(BaseNumPyTests, base.BaseCastingTests): + + @skip_nested + def test_astype_str(self, data): + pass + + +class TestConstructors(BaseNumPyTests, base.BaseConstructorsTests): + @pytest.mark.skip(reason="We don't register our dtype") + # We don't want to register. This test should probably be split in two. + def test_from_dtype(self, data): + pass + + @skip_nested + def test_array_from_scalars(self, data): + pass + + +class TestDtype(BaseNumPyTests, base.BaseDtypeTests): + + @pytest.mark.skip(reason="Incorrect expected.") + # we unsurprisingly clash with a NumPy name. + def test_check_dtype(self, data): + pass + + +class TestGetitem(BaseNumPyTests, base.BaseGetitemTests): + + @skip_nested + def test_getitem_scalar(self, data): + pass + + @skip_nested + def test_take_series(self, data): + pass + + +class TestGroupby(BaseNumPyTests, base.BaseGroupbyTests): + @skip_nested + def test_groupby_extension_apply(self, data_for_grouping, op): + pass + + +class TestInterface(BaseNumPyTests, base.BaseInterfaceTests): + @skip_nested + def test_array_interface(self, data): + # NumPy array shape inference + pass + + +class TestMethods(BaseNumPyTests, base.BaseMethodsTests): + + @pytest.mark.skip(reason="TODO: remove?") + def test_value_counts(self, all_data, dropna): + pass + + @pytest.mark.skip(reason="Incorrect expected") + # We have a bool dtype, so the result is an ExtensionArray + # but expected is not + def test_combine_le(self, data_repeated): + super(TestMethods, self).test_combine_le(data_repeated) + + @skip_nested + def test_combine_add(self, data_repeated): + # Not numeric + pass + + @skip_nested + def test_shift_fill_value(self, data): + # np.array shape inference. Shift implementation fails. + super().test_shift_fill_value(data) + + @skip_nested + def test_unique(self, data, box, method): + # Fails creating expected + pass + + @skip_nested + def test_fillna_copy_frame(self, data_missing): + # The "scalar" for this array isn't a scalar. + pass + + @skip_nested + def test_fillna_copy_series(self, data_missing): + # The "scalar" for this array isn't a scalar. + pass + + @skip_nested + def test_hash_pandas_object_works(self, data, as_frame): + # ndarray of tuples not hashable + pass + + @skip_nested + def test_searchsorted(self, data_for_sorting, as_series): + # Test setup fails. + pass + + @skip_nested + def test_where_series(self, data, na_value, as_frame): + # Test setup fails. + pass + + @skip_nested + def test_repeat(self, data, repeats, as_series, use_numpy): + # Fails creating expected + pass + + +class TestPrinting(BaseNumPyTests, base.BasePrintingTests): + pass + + +class TestMissing(BaseNumPyTests, base.BaseMissingTests): + + @skip_nested + def test_fillna_scalar(self, data_missing): + # Non-scalar "scalar" values. + pass + + @skip_nested + def test_fillna_series_method(self, data_missing, method): + # Non-scalar "scalar" values. + pass + + @skip_nested + def test_fillna_series(self, data_missing): + # Non-scalar "scalar" values. + pass + + @skip_nested + def test_fillna_frame(self, data_missing): + # Non-scalar "scalar" values. + pass + + +class TestReshaping(BaseNumPyTests, base.BaseReshapingTests): + + @pytest.mark.skip("Incorrect parent test") + # not actually a mixed concat, since we concat int and int. + def test_concat_mixed_dtypes(self, data): + super(TestReshaping, self).test_concat_mixed_dtypes(data) + + @skip_nested + def test_merge(self, data, na_value): + # Fails creating expected + pass + + @skip_nested + def test_merge_on_extension_array(self, data): + # Fails creating expected + pass + + @skip_nested + def test_merge_on_extension_array_duplicates(self, data): + # Fails creating expected + pass + + +class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): + + @skip_nested + def test_setitem_scalar_series(self, data, box_in_series): + pass + + @skip_nested + def test_setitem_sequence(self, data, box_in_series): + pass + + @skip_nested + def test_setitem_sequence_mismatched_length_raises(self, data, as_array): + pass + + @skip_nested + def test_setitem_sequence_broadcasts(self, data, box_in_series): + pass + + @skip_nested + def test_setitem_loc_scalar_mixed(self, data): + pass + + @skip_nested + def test_setitem_loc_scalar_multiple_homogoneous(self, data): + pass + + @skip_nested + def test_setitem_iloc_scalar_mixed(self, data): + pass + + @skip_nested + def test_setitem_iloc_scalar_multiple_homogoneous(self, data): + pass + + @skip_nested + def test_setitem_mask_broadcast(self, data, setter): + pass + + @skip_nested + def test_setitem_scalar_key_sequence_raise(self, data): + pass + + +# Skip Arithmetics, NumericReduce, BooleanReduce, Parsing diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/c7/c74d2ae636ee870a8481925779f774dc b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/c7/c74d2ae636ee870a8481925779f774dc new file mode 100644 index 0000000000000000000000000000000000000000..aa807e7fcc112ff4fb79a988bafe2e5f1e11e981 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/c7/c74d2ae636ee870a8481925779f774dc differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/c7/c75302ae8d17e6a1208d81500dee8374 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/c7/c75302ae8d17e6a1208d81500dee8374 new file mode 100644 index 0000000000000000000000000000000000000000..f5552f8c944eee30e544d231d6070469732bf4e5 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/c7/c75302ae8d17e6a1208d81500dee8374 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d1/d123dede94a361777e70fbf795c9e570 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d1/d123dede94a361777e70fbf795c9e570 new file mode 100644 index 0000000000000000000000000000000000000000..cb803815c83ac4bc44629320377f203d7b672d68 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d1/d123dede94a361777e70fbf795c9e570 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d1/d17ab7a8d18aac471dc86102919b9761 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d1/d17ab7a8d18aac471dc86102919b9761 new file mode 100644 index 0000000000000000000000000000000000000000..a93b84357a1414ff0ba880a20609c83e94449fad Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d1/d17ab7a8d18aac471dc86102919b9761 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d2/d2fb5e6a536385daa8ceaf3b3d5c66e2 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d2/d2fb5e6a536385daa8ceaf3b3d5c66e2 new file mode 100644 index 0000000000000000000000000000000000000000..66242fededb09f2a1c8ee8d56e96a98607aedec4 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d2/d2fb5e6a536385daa8ceaf3b3d5c66e2 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d542d897e0a56258b631e410d644f533 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d542d897e0a56258b631e410d644f533 new file mode 100644 index 0000000000000000000000000000000000000000..16173f0a39c062e747ab6ad259bf565626a5d7f0 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d542d897e0a56258b631e410d644f533 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d54f0365ef0fa550f623f4781ad165c4 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d54f0365ef0fa550f623f4781ad165c4 new file mode 100644 index 0000000000000000000000000000000000000000..4935348475ab03c1b805b7f167b52c816236e10a Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d54f0365ef0fa550f623f4781ad165c4 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d550edc1377ffb307290e59c33e18fad b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d550edc1377ffb307290e59c33e18fad new file mode 100644 index 0000000000000000000000000000000000000000..ba97da81dfd5b8a7824965060f70deaa9e03a431 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d550edc1377ffb307290e59c33e18fad differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d57571af04f4f323f4369077e12cef29 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d57571af04f4f323f4369077e12cef29 new file mode 100644 index 0000000000000000000000000000000000000000..3fb975783f32d2b5e5a2ec2be1f02fbc6efefd14 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d57571af04f4f323f4369077e12cef29 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d5796b3f542676bd8697eed05f93812c b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d5796b3f542676bd8697eed05f93812c new file mode 100644 index 0000000000000000000000000000000000000000..0a6687ede50a372a4a298e77aad1a8be24d70edd Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d5796b3f542676bd8697eed05f93812c differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d59b70f189d01eb59f7da41c7863f926 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d59b70f189d01eb59f7da41c7863f926 new file mode 100644 index 0000000000000000000000000000000000000000..4977b2a9697010b9a0928bc49671e6c8e50ed4d1 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/d5/d59b70f189d01eb59f7da41c7863f926 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/da/dab7165d657e02f7d3766be2e949a778 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/da/dab7165d657e02f7d3766be2e949a778 new file mode 100644 index 0000000000000000000000000000000000000000..03f05baf4bad6739fe0c535bbc94c4c16002b335 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/da/dab7165d657e02f7d3766be2e949a778 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/da/dab75db6c5ccb7c1fe5d47af21ffb6d6 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/da/dab75db6c5ccb7c1fe5d47af21ffb6d6 new file mode 100644 index 0000000000000000000000000000000000000000..715364ac079a0b09430952fc940ca9ded1b07035 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/da/dab75db6c5ccb7c1fe5d47af21ffb6d6 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/da/dabfb3df01fc347bc3cadfba8c611a17 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/da/dabfb3df01fc347bc3cadfba8c611a17 new file mode 100644 index 0000000000000000000000000000000000000000..c930a133fd70466fd75c9aea84a75084fccea828 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/da/dabfb3df01fc347bc3cadfba8c611a17 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/da/dae5f8a4d79f014d940c5d25acb3f83c b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/da/dae5f8a4d79f014d940c5d25acb3f83c new file mode 100644 index 0000000000000000000000000000000000000000..ab2c3edd9a756c71cf0d7028b986892856281669 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/da/dae5f8a4d79f014d940c5d25acb3f83c differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/da/daeb2b154e1bcb9a67ac7342c741fc2a b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/da/daeb2b154e1bcb9a67ac7342c741fc2a new file mode 100644 index 0000000000000000000000000000000000000000..51463e96ec7171b3d30642e627d2e77bda43f863 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/da/daeb2b154e1bcb9a67ac7342c741fc2a differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df0b6b7fa5226e3ca4422c936173a7ba b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df0b6b7fa5226e3ca4422c936173a7ba new file mode 100644 index 0000000000000000000000000000000000000000..45f0d1468f681e17d898aae5bd0be4c897fae819 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df0b6b7fa5226e3ca4422c936173a7ba differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df16a68334c2a067357324972477fc90 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df16a68334c2a067357324972477fc90 new file mode 100644 index 0000000000000000000000000000000000000000..2f94906cc31ec68271856f1f33b4088e9adf03ef Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df16a68334c2a067357324972477fc90 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df281770ea45a556df08ce31a0817113 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df281770ea45a556df08ce31a0817113 new file mode 100644 index 0000000000000000000000000000000000000000..cf37dd603d32f0b4d9e65af857b0c842bf0531a4 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df281770ea45a556df08ce31a0817113 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df50238eb26bc1069cee5f420dacfc91 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df50238eb26bc1069cee5f420dacfc91 new file mode 100644 index 0000000000000000000000000000000000000000..d1ea71c580f8e8ae3108777097f5e3dc16913f96 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df50238eb26bc1069cee5f420dacfc91 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df5da61e72b6771baac7bc02dcb9097f b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df5da61e72b6771baac7bc02dcb9097f new file mode 100644 index 0000000000000000000000000000000000000000..f6549b1373de46692aa5ab6bf8481efd4ef1b840 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df5da61e72b6771baac7bc02dcb9097f differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df62c9c7faaa7fbac7663ab017fb3de4 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df62c9c7faaa7fbac7663ab017fb3de4 new file mode 100644 index 0000000000000000000000000000000000000000..65abb063f705c51f8767c74e2de4f7421a2e08b7 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df62c9c7faaa7fbac7663ab017fb3de4 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df74c25b58bd56dc7508ef9abe8b48f8 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df74c25b58bd56dc7508ef9abe8b48f8 new file mode 100644 index 0000000000000000000000000000000000000000..53b46614ee9dd39bf416a832702ee22593321857 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df74c25b58bd56dc7508ef9abe8b48f8 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df8150c36bf65390682933fabb571d55 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df8150c36bf65390682933fabb571d55 new file mode 100644 index 0000000000000000000000000000000000000000..1c7826196186ae886a32d456c1190de5dca0a91b Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df8150c36bf65390682933fabb571d55 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df83ea208528d1ef94f58b7967361708 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df83ea208528d1ef94f58b7967361708 new file mode 100644 index 0000000000000000000000000000000000000000..130eaedd7b866c0c93217ab331a2a6b7e24cb813 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/df83ea208528d1ef94f58b7967361708 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/dfb2b6bee6df7e6751aa5faae08a3353 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/dfb2b6bee6df7e6751aa5faae08a3353 new file mode 100644 index 0000000000000000000000000000000000000000..de72367bc054085da7c54e09596c0614836d3dab Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/dfb2b6bee6df7e6751aa5faae08a3353 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/dfd43405458465371169ef59f29c2c5d b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/dfd43405458465371169ef59f29c2c5d new file mode 100644 index 0000000000000000000000000000000000000000..6aed8fa2075be4271d393570fa951a8228873bda Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/df/dfd43405458465371169ef59f29c2c5d differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e0/e0323d8d6dd79cb3dcf213285f4c6757 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e0/e0323d8d6dd79cb3dcf213285f4c6757 new file mode 100644 index 0000000000000000000000000000000000000000..9d7a69567c0f4e28ea0dc1baa2b19f0270d7e73c Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e0/e0323d8d6dd79cb3dcf213285f4c6757 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e0/e054de96ffedb2a59af304902aa4e3a2 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e0/e054de96ffedb2a59af304902aa4e3a2 new file mode 100644 index 0000000000000000000000000000000000000000..dfe05915acf80cf5654c2b5a434c848abb25d5e4 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e0/e054de96ffedb2a59af304902aa4e3a2 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e0/e08bbd21dc117607ab330a4ad13d6678 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e0/e08bbd21dc117607ab330a4ad13d6678 new file mode 100644 index 0000000000000000000000000000000000000000..58eddf5216dfc9d24b00bfcb22bc6c55d837c148 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e0/e08bbd21dc117607ab330a4ad13d6678 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e0/e0a866f1837a2e3991b3c05656285686 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e0/e0a866f1837a2e3991b3c05656285686 new file mode 100644 index 0000000000000000000000000000000000000000..3d107b9ff1bf381db1b09e62499c039b328d0efb Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e0/e0a866f1837a2e3991b3c05656285686 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e0/e0b8623b089743cabf1072cadc010739 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e0/e0b8623b089743cabf1072cadc010739 new file mode 100644 index 0000000000000000000000000000000000000000..139e0baed9f3c9f9ef733930f38e61c55a63707e Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e0/e0b8623b089743cabf1072cadc010739 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e2/e2e254d175d7a63a6de9d9e9809d90d6 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e2/e2e254d175d7a63a6de9d9e9809d90d6 new file mode 100644 index 0000000000000000000000000000000000000000..94b4b331a8ecb2f12c69d3aea5492213a8af2171 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e2/e2e254d175d7a63a6de9d9e9809d90d6 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e2/e2f51e93dd0cf095b986b0ff1064b207 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e2/e2f51e93dd0cf095b986b0ff1064b207 new file mode 100644 index 0000000000000000000000000000000000000000..1ac6a0b250417566ca7b0e698cbe9b0b327c47dd Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e2/e2f51e93dd0cf095b986b0ff1064b207 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e3/e393eb16298cb578f368d993613d583e b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e3/e393eb16298cb578f368d993613d583e new file mode 100644 index 0000000000000000000000000000000000000000..b0fe0a6ec4c3380d2b5fdf6c30d39a891b209f72 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e3/e393eb16298cb578f368d993613d583e differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e3/e3b211a16342f27a08fddedfc5a1b491 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e3/e3b211a16342f27a08fddedfc5a1b491 new file mode 100644 index 0000000000000000000000000000000000000000..48b60fb876c3779e0206221822bf9df39097bd4e Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e3/e3b211a16342f27a08fddedfc5a1b491 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e3/e3b54efab9e1bb922fd0053a14a69566 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e3/e3b54efab9e1bb922fd0053a14a69566 new file mode 100644 index 0000000000000000000000000000000000000000..edd8b67d58846bf5b26e36ddaa1f435f138275d1 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e3/e3b54efab9e1bb922fd0053a14a69566 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e4/e42d8e4befa39ffe78b64bec844b4c3b b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e4/e42d8e4befa39ffe78b64bec844b4c3b new file mode 100644 index 0000000000000000000000000000000000000000..547234a1fd2409f2b6eaeaa3daf96185ea87749d Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e4/e42d8e4befa39ffe78b64bec844b4c3b differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e4/e4327b9698761ea23b4a099e14d4ad51 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e4/e4327b9698761ea23b4a099e14d4ad51 new file mode 100644 index 0000000000000000000000000000000000000000..638cb3b686e7933265a1495e50f889607094b428 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e4/e4327b9698761ea23b4a099e14d4ad51 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e4/e44e78d3ad99a02a162894be35da4a0e b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e4/e44e78d3ad99a02a162894be35da4a0e new file mode 100644 index 0000000000000000000000000000000000000000..28f7ff40dc95c020357a2875aec82664caa36662 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e4/e44e78d3ad99a02a162894be35da4a0e differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e4/e456ad2f1198486505b0c0409f1f16a2 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e4/e456ad2f1198486505b0c0409f1f16a2 new file mode 100644 index 0000000000000000000000000000000000000000..e1b6d0b14bb8fc6df39219ed8104a115d76d5c0b Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/e4/e456ad2f1198486505b0c0409f1f16a2 differ