repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
SpM-lab/irbasis3
[ "f4e5e7a96ed886cb0f44c4d0c7413ec4696cd364" ]
[ "test/test_scipost_sample_code.py" ]
[ "# Copyright (C) 2020-2022 Markus Wallerberger, Hiroshi Shinaoka, and others\n# SPDX-License-Identifier: MIT\n\n\n# Sample codes in the SciPost review paper\n\ndef test_sample1():\n # Compute IR basis for fermions and \\Lambda = \\beta * \\omega_max = 1000\n import sparse_ir\n import numpy as np\n\n lambda_ = 1000\n eps = 1e-8 # cut-off value for singular values\n b_xy = sparse_ir.DimensionlessBasis('F', lambda_, eps)\n\n # All singular values\n print(\"singular values: \", b_xy.s)\n print(\"u_0(0.1)\", b_xy.u[0](0.1))\n print(\"v_0(0.1)\", b_xy.v[0](0.1))\n\n print(\"n-th derivative of u_l(x) and v_l(y)\")\n for n in range(1,3):\n u_n = b_xy.u.deriv(n)\n v_n = b_xy.v.deriv(n)\n print(\" n= \", n, u_n[0](0.1))\n print(\" n= \", n, v_n[0](0.1))\n\n # Compute u_{ln} as a matrix for the first\n # 10 non-nagative fermionic Matsubara frequencies\n # Fermionic/bosonic frequencies are denoted by odd/even integers.\n hatF_t = b_xy.uhat(2*np.arange(10)+1)\n print(hatF_t.shape)\n\n\ndef test_sample2():\n # Compute IR basis for fermions and \\beta = 100 and \\omega_max = 10\n import sparse_ir\n import numpy as np\n\n lambda_ = 1000\n beta = 100\n wmax = lambda_/beta\n eps = 1e-8 # cut-off value for singular values\n b = sparse_ir.FiniteTempBasis('F', beta, wmax, eps=eps)\n\n x = y = 0.1\n tau = 0.5 * beta * (x+1)\n omega = wmax * y\n\n # All singular values\n print(\"singular values: \", b.s)\n print(\"U_0(0.1)\", b.u[0](tau))\n print(\"V_0(0.1)\", b.v[0](omega))\n\n print(\"n-th derivative of U_l(tau) and V_l(omega)\")\n for n in range(1,3):\n u_n = b.u.deriv(n)\n v_n = b.v.deriv(n)\n print(\" n= \", n, u_n[0](tau))\n print(\" n= \", n, v_n[0](omega))\n\n # Compute u_{ln} as a matrix for the first\n # 10 non-nagative fermionic Matsubara frequencies\n # Fermionic/bosonic frequencies are denoted by odd/even integers.\n hatF_t = b.uhat(2*np.arange(10)+1)\n print(hatF_t.shape)\n\ndef test_sample3():\n import sparse_ir\n import numpy as np\n from numpy.fft import fftn, ifftn\n\n beta = 1e+3\n lambda_ = 1e+5\n\n wmax = lambda_/beta\n eps = 1e-15\n print(\"wmax\", wmax)\n\n b = sparse_ir.FiniteTempBasis('F', beta , wmax, eps=eps)\n print(\"Number of basis functions\", b.size)\n\n # Sparse sampling in tau\n smpl_tau = sparse_ir.TauSampling(b)\n\n # Sparse sampling in Matsubara frequencies\n smpl_matsu = sparse_ir.MatsubaraSampling(b)\n\n # Parameters\n nk_lin = 64\n U, kps = 2.0, np.array([nk_lin, nk_lin])\n nw = smpl_matsu.sampling_points.size\n ntau = smpl_tau.sampling_points.size\n\n # Generate k mesh and non-interacting band energies\n nk = np.prod(kps)\n kgrid = [2*np.pi*np.arange(kp)/kp for kp in kps]\n k1, k2 = np.meshgrid(*kgrid, indexing='ij')\n ek = -2*(np.cos(k1) + np.cos(k2))\n iw = 1j*np.pi*smpl_matsu.sampling_points/beta\n\n # G(iw, k): (nw, nk)\n gkf = 1.0 / (iw[:,None] - ek.ravel()[None,:])\n\n # G(l, k): (L, nk)\n gkl = smpl_matsu.fit(gkf)\n\n # G(tau, k): (ntau, nk)\n gkt = smpl_tau.evaluate(gkl)\n\n # G(tau, r): (ntau, nk)\n grt = np.fft.fftn(gkt.reshape(ntau, *kps), axes=(1,2)).\\\n reshape(ntau, nk)\n\n # Sigma(tau, r): (ntau, nk)\n srt = U*U*grt*grt*grt[::-1,:]\n\n # Sigma(l, r): (L, nk)\n srl = smpl_tau.fit(srt)\n\n # Sigma(iw, r): (nw, nk)\n srf = smpl_matsu.evaluate(srl)\n\n # Sigma(l, r): (L, nk)\n srl = smpl_tau.fit(srt)\n\n # Sigma(iw, r): (nw, nk)\n srf = smpl_matsu.evaluate(srl)\n\n # Sigma(iw, k): (nw, kps[0], kps[1])\n srf = srf.reshape(nw, *kps)\n skf = ifftn(srf, axes=(1,2))/nk**2\n" ]
[ [ "numpy.meshgrid", "numpy.arange", "numpy.cos", "numpy.fft.ifftn", "numpy.prod", "numpy.array" ] ]
glypher/matmih
[ "387477c9743fe6162c91b979d4909a0330c36943" ]
[ "data.py" ]
[ "\"\"\"data.py: Helper classes to hold dataset information\n\"\"\"\n__author__ = \"Mihai Matei\"\n__license__ = \"BSD\"\n__email__ = \"[email protected]\"\n\nimport numpy as np\nimport pandas as pd\nimport dill\nimport random\nimport time\nfrom sklearn.model_selection import train_test_split\n\n\nclass DataSet:\n def __init__(self, data_set, feature_column='features', target_column='target'):\n assert isinstance(data_set, pd.core.frame.DataFrame), 'Only panda dataframe is supported currently!'\n self.__data_set = data_set\n self._features_column = feature_column\n self._target_column = target_column\n self._train_set = None\n self._validation_set = None\n self._test_set = None\n try:\n self._classes = self.__data_set[self._target_column].cat.categories.to_numpy()\n except AttributeError:\n self._classes = []\n self._classIds = np.array(range(len(self.classes)))\n\n def split_data(self, splits, stratify=False, shuffle=True, augment_callback=None, filter_callback=None, sequencial=False):\n \"\"\"\n Splits the data into the train, validation, test sets\n :param splits: percentage tuple found in splits (train, validation, test)\n :param stratify: if the classes density distribution should be maintained in the split,\n :param shuffle: if the data should be split randomly\n :param augment_callback: optional callback to augment the data\n :param filter_callback: optional callback to filter the data after each split\n :param sequencial: if the split must not be done randomly by in a sequencial manner |train|validation|test\n \"\"\"\n train_percentage, validation_percentage, test_percentage = splits\n assert (train_percentage + validation_percentage + test_percentage == 1)\n\n # augment the data before the split\n data_set = self.__data_set\n if augment_callback:\n data_set = augment_callback(data_set)\n\n if test_percentage > 0:\n if sequencial:\n size = int((1-test_percentage) * len(data_set))\n train_val_ds, test_ds = data_set.iloc[:size], data_set.iloc[size:]\n else:\n # no class distribution on test set - we want to keep it as random as possible\n train_val_ds, test_ds = train_test_split(data_set, test_size=test_percentage,\n shuffle=shuffle, random_state=int(round(time.time())),\n stratify=None)\n\n # make sure that there is at least one of each target class in the test set\n for cl in self.classes:\n if len(test_ds[test_ds[self._target_column] == cl]) == 0:\n idx = random.choice(train_val_ds.index[train_val_ds[self._target_column] == cl].tolist())\n test_ds = test_ds.append(train_val_ds.loc[idx].copy(), ignore_index=True)\n train_val_ds = train_val_ds.drop(index=idx)\n if len(self._classes) > 0:\n test_ds = test_ds.copy()\n test_ds[self._target_column] = pd.Categorical(test_ds[self._target_column],\n categories=data_set[self._target_column].cat.categories)\n else:\n test_ds = None\n train_val_ds = data_set\n\n # filter the test and remaining set so that they do not have any features in common\n if filter_callback:\n train_val_ds, test_ds = filter_callback(train_val_ds, test_ds)\n\n # compute the new test percentage\n validation_percentage = validation_percentage * len(data_set) / len(train_val_ds)\n\n if validation_percentage > 0:\n if sequencial:\n size = int((1-validation_percentage) * len(train_val_ds))\n train_ds, validation_ds = train_val_ds.iloc[:size], train_val_ds.iloc[size:]\n else:\n # now split the train and validation set preserving the class distribution\n train_ds, validation_ds = train_test_split(train_val_ds, test_size=validation_percentage,\n shuffle=shuffle, random_state=int(round(time.time())),\n stratify=train_val_ds[self._target_column] if stratify else None)\n\n # make sure that there is at least one of each target class in the validation set\n for cl in self.classes:\n if len(validation_ds[validation_ds[self._target_column] == cl]) == 0:\n idx = random.choice(train_ds.index[train_ds[self._target_column] == cl].tolist())\n validation_ds = validation_ds.append(train_ds.loc[idx].copy(), ignore_index=True)\n train_ds = train_ds.drop(index=idx)\n if len(self._classes) > 0:\n validation_ds = validation_ds.copy()\n validation_ds[self._target_column] = pd.Categorical(validation_ds[self._target_column],\n categories=data_set[self._target_column].cat.categories)\n else:\n train_ds = train_val_ds\n validation_ds = None\n\n # filter the test and remaining set so that they do not have any features in common\n if filter_callback:\n train_ds, validation_ds = filter_callback(train_ds, validation_ds)\n\n self._train_set = train_ds\n self._validation_set = validation_ds\n self._test_set = test_ds\n\n @property\n def train_set(self):\n return self._train_set\n\n @property\n def validation_set(self):\n return self._validation_set\n\n @property\n def test_set(self):\n return self._test_set\n\n @property\n def train_features(self):\n return self._train_set[self._features_column]\n\n @property\n def train_target(self):\n return self._train_set[self._target_column]\n\n @property\n def validation_features(self):\n if self._validation_set is None:\n return None\n return self._validation_set[self._features_column]\n\n @property\n def validation_target(self):\n if self._validation_set is None:\n return None\n return self._validation_set[self._target_column]\n\n @property\n def test_features(self):\n if self._test_set is None:\n return None\n return self._test_set[self._features_column]\n\n @property\n def test_target(self):\n if self._test_set is None:\n return None\n return self._test_set[self._target_column]\n\n @property\n def classes(self):\n return self._classes\n\n @property\n def class_ids(self):\n return self._classIds\n\n\nclass StoreLocal:\n def __init__(self, path):\n self._path = path\n\n def save(self, obj):\n with open(self._path, \"wb\") as f:\n dill.dump(obj, f)\n\n def load(self):\n with open(self._path, \"rb\") as f:\n return dill.load(f)\n" ]
[ [ "pandas.Categorical" ] ]
BILLXZY1215/CycleGAN-Music-Style-Transfer
[ "ddd76b0be163b86caac003ae30f255466441e3c6" ]
[ "main.py" ]
[ "import argparse\nimport os\nimport tensorflow as tf\nfrom model import cyclegan\nfrom style_classifier import Classifer\ntf.compat.v1.set_random_seed(19)\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = os.environ['SGE_GPU']\n\nparser = argparse.ArgumentParser(description='')\nparser.add_argument('--dataset_dir', dest='dataset_dir',\n default='JAZZ2ROCK', help='path of the dataset')\nparser.add_argument('--dataset_A_dir', dest='dataset_A_dir',\n default='JC_J', help='path of the dataset of domain A')\nparser.add_argument('--dataset_B_dir', dest='dataset_B_dir',\n default='JC_C', help='path of the dataset of domain B')\nparser.add_argument('--epoch', dest='epoch', type=int,\n default=100, help='# of epoch')\nparser.add_argument('--epoch_step', dest='epoch_step',\n type=int, default=10, help='# of epoch to decay lr')\nparser.add_argument('--batch_size', dest='batch_size',\n type=int, default=16, help='# images in batch')\nparser.add_argument('--train_size', dest='train_size',\n type=int, default=1e8, help='# images used to train')\nparser.add_argument('--load_size', dest='load_size', type=int,\n default=286, help='scale images to this size')\nparser.add_argument('--fine_size', dest='fine_size', type=int,\n default=128, help='then crop to this size')\nparser.add_argument('--time_step', dest='time_step', type=int,\n default=64, help='time step of pianoroll')\nparser.add_argument('--pitch_range', dest='pitch_range',\n type=int, default=84, help='pitch range of pianoroll')\nparser.add_argument('--ngf', dest='ngf', type=int, default=64,\n help='# of gen filters in first conv layer')\nparser.add_argument('--ndf', dest='ndf', type=int, default=64,\n help='# of discri filters in first conv layer')\nparser.add_argument('--input_nc', dest='input_nc', type=int,\n default=1, help='# of input image channels')\nparser.add_argument('--output_nc', dest='output_nc', type=int,\n default=1, help='# of output image channels')\nparser.add_argument('--lr', dest='lr', type=float,\n default=0.0002, help='initial learning rate for adam')\nparser.add_argument('--beta1', dest='beta1', type=float,\n default=0.5, help='momentum term of adam')\nparser.add_argument('--which_direction', dest='which_direction',\n default='AtoB', help='AtoB or BtoA')\nparser.add_argument('--phase', dest='phase',\n default='train', help='train, test')\nparser.add_argument('--save_freq', dest='save_freq', type=int,\n default=1000, help='save a model every save_freq iterations')\nparser.add_argument('--print_freq', dest='print_freq', type=int, default=100,\n help='print the debug information every print_freq iterations')\nparser.add_argument('--continue_train', dest='continue_train', type=bool, default=False,\n help='if continue training, load the latest model: 1: true, 0: false')\nparser.add_argument('--checkpoint_dir', dest='checkpoint_dir',\n default='./checkpoint', help='models are saved here')\nparser.add_argument('--sample_dir', dest='sample_dir',\n default='./samples', help='sample are saved here')\nparser.add_argument('--test_dir', dest='test_dir',\n default='./test', help='test sample are saved here')\nparser.add_argument('--log_dir', dest='log_dir',\n default='./log', help='logs are saved here')\nparser.add_argument('--L1_lambda', dest='L1_lambda', type=float,\n default=10.0, help='weight on L1 term in objective')\nparser.add_argument('--gamma', dest='gamma', type=float,\n default=1.0, help='weight of extra discriminators')\nparser.add_argument('--use_midi_G', dest='use_midi_G', type=bool,\n default=False, help='select generator for midinet')\nparser.add_argument('--use_midi_D', dest='use_midi_D', type=bool,\n default=False, help='select disciminator for midinet')\nparser.add_argument('--use_lsgan', dest='use_lsgan', type=bool,\n default=False, help='gan loss defined in lsgan')\nparser.add_argument('--max_size', dest='max_size', type=int, default=50,\n help='max size of image pool, 0 means do not use image pool')\nparser.add_argument('--sigma_c', dest='sigma_c', type=float,\n default=1.0, help='sigma of gaussian noise of classifiers')\nparser.add_argument('--sigma_d', dest='sigma_d', type=float,\n default=1.0, help='sigma of gaussian noise of discriminators')\nparser.add_argument('--model', dest='model', default='base',\n help='three different models, base, partial, full')\nparser.add_argument('--type', dest='type', default='cyclegan',\n help='cyclegan or classifier')\n\nargs = parser.parse_args()\n\n\ndef main(_):\n if not os.path.exists(args.checkpoint_dir):\n os.makedirs(args.checkpoint_dir)\n if not os.path.exists(args.sample_dir):\n os.makedirs(args.sample_dir)\n if not os.path.exists(args.test_dir):\n os.makedirs(args.test_dir)\n\n tfconfig = tf.compat.v1.ConfigProto(allow_soft_placement=True)\n tfconfig.gpu_options.allow_growth = True\n with tf.compat.v1.Session(config=tfconfig) as sess:\n\n if args.type == 'cyclegan':\n model = cyclegan(sess, args)\n model.train(args) if args.phase == 'train' else model.test(args)\n\n if args.type == 'classifier':\n classifier = Classifer(sess, args)\n classifier.train(\n args) if args.phase == 'train' else classifier.test(args)\n\n\nif __name__ == '__main__':\n tf.compat.v1.app.run()\n" ]
[ [ "tensorflow.compat.v1.Session", "tensorflow.compat.v1.set_random_seed", "tensorflow.compat.v1.ConfigProto", "tensorflow.compat.v1.app.run" ] ]
zumaia/salud-app
[ "3a8333b3fe5474c479b407c0f45f888ec949c330" ]
[ "model_codes/heart.py" ]
[ "import numpy as np\r\nimport pandas as pd\r\nfrom sklearn import ensemble\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix\r\nimport joblib\r\n\r\ndf = pd.read_csv(\"../data/heart.csv\")\r\n\r\ncategorical_val = []\r\ncontinous_val = []\r\nfor column in df.columns:\r\n if len(df[column].unique()) <= 10:\r\n categorical_val.append(column)\r\n else:\r\n continous_val.append(column)\r\n\r\ncategorical_val.remove('target')\r\ndataset = pd.get_dummies(df, columns = categorical_val)\r\n\r\ncols = ['cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach', 'exang'] \r\nX = df[cols]\r\ny = dataset.target\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\r\n\r\nprint('Set de entrenamiento: X:{}, y:{}'.format(X_train.shape, y_train.shape))\r\nprint('Set de prueba: X:{}, y:{}'.format(X_test.shape, y_test.shape))\r\n\r\nmodel = ensemble.RandomForestClassifier()\r\nmodel.fit(X_train, y_train)\r\ny_pred = model.predict(X_test)\r\nprint('Precisión : {}'.format(accuracy_score(y_test, y_pred)))\r\n\r\nclf_report = classification_report(y_test, y_pred)\r\nprint('Informe de clasificación')\r\nprint(\"---------------------\")\r\nprint(clf_report)\r\nprint(\"_____________________\")\r\n\r\njoblib.dump(model,r\"../heart_model.pkl\")\r\n" ]
[ [ "pandas.read_csv", "sklearn.ensemble.RandomForestClassifier", "sklearn.metrics.accuracy_score", "sklearn.model_selection.train_test_split", "sklearn.metrics.classification_report", "pandas.get_dummies" ] ]
TadaSanar/GPyOpt_DFT
[ "36124c2faf718c97a7d613e1729bfa519404c0f5" ]
[ "GPyOpt/acquisitions/EI.py" ]
[ "# Copyright (c) 2016, the GPyOpt Authors\n# Licensed under the BSD 3-clause license (see LICENSE.txt)\n\nfrom .base import AcquisitionBase\nfrom ..util.general import get_quantiles\n\nimport numpy as np\n\nclass AcquisitionEI(AcquisitionBase):\n \"\"\"\n Expected improvement acquisition function\n\n :param model: GPyOpt class of model\n :param space: GPyOpt class of domain\n :param optimizer: optimizer of the acquisition. Should be a GPyOpt optimizer\n :param cost_withGradients: function\n :param jitter: positive value to make the acquisition more explorative.\n\n .. Note:: allows to compute the Improvement per unit of cost\n\n \"\"\"\n\n analytical_gradient_prediction = True\n\n def __init__(self, model, space, optimizer=None, cost_withGradients=None, jitter=0.01):\n self.optimizer = optimizer\n super(AcquisitionEI, self).__init__(model, space, optimizer, cost_withGradients=cost_withGradients)\n self.jitter = jitter\n\n @staticmethod\n def fromConfig(model, space, optimizer, cost_withGradients, config):\n return AcquisitionEI(model, space, optimizer, cost_withGradients, jitter=config['jitter'])\n\n def _compute_acq(self, x):\n \"\"\"\n Computes the Expected Improvement per unit of cost\n \"\"\"\n m, s = self.model.predict(x)\n fmin = self.model.get_fmin()\n phi, Phi, u = get_quantiles(self.jitter, fmin, m, s)\n f_acqu = s * (u * Phi + phi)\n return f_acqu\n\n def _compute_acq_withGradients(self, x):\n \"\"\"\n Computes the Expected Improvement and its derivative (has a very easy derivative!)\n \"\"\"\n if np.any(np.isnan(x)):\n print('x value: ', x)\n \n fmin = self.model.get_fmin()\n m, s, dmdx, dsdx = self.model.predict_withGradients(x)\n phi, Phi, u = get_quantiles(self.jitter, fmin, m, s)\n f_acqu = s * (u * Phi + phi)\n df_acqu = dsdx * phi - Phi * dmdx\n return f_acqu, df_acqu\n" ]
[ [ "numpy.isnan" ] ]
carapas/delta-interpolator
[ "f4078ceebb0a46759949722e0f169e682e64c1be" ]
[ "src/geometry/vector.py" ]
[ "import torch\n\n\n# batch*n\ndef normalize_vector(v, return_mag=False, eps: float = 1e-8):\n batch = v.shape[0]\n v_mag = torch.sqrt(v.pow(2).sum(1))\n v_mag = torch.max(v_mag, torch.autograd.Variable(torch.FloatTensor([eps]).type_as(v)))\n v_mag = v_mag.view(batch, 1).expand(batch, v.shape[1])\n v = v / v_mag\n if return_mag:\n return v, v_mag[:, 0]\n else:\n return v\n\n\ndef cross_product(u, v):\n \"\"\"\n Cross operation on batched vectors of shape (..., 3)\n \"\"\"\n i = u[..., 1] * v[..., 2] - u[..., 2] * v[..., 1]\n j = u[..., 2] * v[..., 0] - u[..., 0] * v[..., 2]\n k = u[..., 0] * v[..., 1] - u[..., 1] * v[..., 0]\n out = torch.cat((i.unsqueeze(-1), j.unsqueeze(-1), k.unsqueeze(-1)), dim=-1)\n return out\n" ]
[ [ "torch.FloatTensor" ] ]
NeilDG/NeuralNets-Experiment3
[ "f0d2f788eeca49f803f65810c155491ce687cf9e" ]
[ "trainers/shading_trainer.py" ]
[ "# -*- coding: utf-8 -*-\n# Shading trainer used for training.\nimport kornia\n\nfrom model import ffa_gan as ffa\nfrom model import vanilla_cycle_gan as cycle_gan\nfrom model import unet_gan\nimport constants\nimport torch\nimport torch.cuda.amp as amp\nimport itertools\nimport numpy as np\nimport torch.nn as nn\nfrom utils import plot_utils\nfrom custom_losses import ssim_loss\nimport lpips\n\nclass ShadingTrainer:\n\n def __init__(self, gpu_device, opts):\n self.gpu_device = gpu_device\n self.g_lr = opts.g_lr\n self.d_lr = opts.d_lr\n self.use_bce = opts.use_bce\n self.light_angle = opts.light_angle\n self.light_angle = self.normalize(self.light_angle)\n\n self.lpips_loss = lpips.LPIPS(net = 'vgg').to(self.gpu_device)\n self.ssim_loss = ssim_loss.SSIM()\n self.l1_loss = nn.L1Loss()\n self.bce_loss = nn.BCEWithLogitsLoss()\n\n num_blocks = opts.num_blocks\n self.batch_size = opts.batch_size\n net_config = opts.net_config\n\n if(net_config == 1):\n self.G_A = cycle_gan.Generator(input_nc=4, output_nc=3, n_residual_blocks=num_blocks).to(self.gpu_device)\n elif(net_config == 2):\n self.G_A = unet_gan.UnetGenerator(input_nc=4, output_nc=3, num_downs=num_blocks).to(self.gpu_device)\n elif (net_config == 3):\n self.G_A = cycle_gan.Generator(input_nc=4, output_nc=3, n_residual_blocks=num_blocks, has_dropout=False).to(self.gpu_device)\n elif (net_config == 4):\n self.G_A = cycle_gan.GeneratorV2(input_nc=4, output_nc=3, n_residual_blocks=num_blocks, has_dropout=False, multiply=True).to(self.gpu_device)\n else:\n self.G_A = cycle_gan.GeneratorV2(input_nc=4, output_nc=3, n_residual_blocks=num_blocks, has_dropout=False, multiply=False).to(self.gpu_device)\n\n self.D_A = cycle_gan.Discriminator(input_nc=3, use_bce=self.use_bce).to(self.gpu_device) # use CycleGAN's discriminator\n\n self.visdom_reporter = plot_utils.VisdomReporter()\n self.optimizerG = torch.optim.Adam(itertools.chain(self.G_A.parameters()), lr=self.g_lr)\n self.optimizerD = torch.optim.Adam(itertools.chain(self.D_A.parameters()), lr=self.d_lr)\n self.schedulerG = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizerG, patience=100000 / self.batch_size, threshold=0.00005)\n self.schedulerD = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizerD, patience=100000 / self.batch_size, threshold=0.00005)\n self.initialize_dict()\n\n self.fp16_scaler = amp.GradScaler() # for automatic mixed precision\n\n def initialize_dict(self):\n # what to store in visdom?\n self.losses_dict = {}\n self.losses_dict[constants.G_LOSS_KEY] = []\n self.losses_dict[constants.D_OVERALL_LOSS_KEY] = []\n self.losses_dict[constants.LIKENESS_LOSS_KEY] = []\n self.losses_dict[constants.LPIP_LOSS_KEY] = []\n self.losses_dict[constants.SSIM_LOSS_KEY] = []\n self.losses_dict[constants.G_ADV_LOSS_KEY] = []\n self.losses_dict[constants.D_A_FAKE_LOSS_KEY] = []\n self.losses_dict[constants.D_A_REAL_LOSS_KEY] = []\n\n self.caption_dict = {}\n self.caption_dict[constants.G_LOSS_KEY] = \"G loss per iteration\"\n self.caption_dict[constants.D_OVERALL_LOSS_KEY] = \"D loss per iteration\"\n self.caption_dict[constants.LIKENESS_LOSS_KEY] = \"L1 loss per iteration\"\n self.caption_dict[constants.LPIP_LOSS_KEY] = \"LPIPS loss per iteration\"\n self.caption_dict[constants.SSIM_LOSS_KEY] = \"SSIM loss per iteration\"\n self.caption_dict[constants.G_ADV_LOSS_KEY] = \"G adv loss per iteration\"\n self.caption_dict[constants.D_A_FAKE_LOSS_KEY] = \"D(A) fake loss per iteration\"\n self.caption_dict[constants.D_A_REAL_LOSS_KEY] = \"D(A) real loss per iteration\"\n\n def normalize(self, light_angle):\n std = light_angle / 360.0\n min = -1.0\n max = 1.0\n scaled = std * (max - min) + min\n\n return scaled\n\n def adversarial_loss(self, pred, target):\n if (self.use_bce == 0):\n return self.l1_loss(pred, target)\n else:\n return self.bce_loss(pred, target)\n\n def l1_loss(self, pred, target):\n return self.l1_loss(pred, target)\n\n def bce_loss_term(self, pred, target):\n return self.bce_loss(pred, target)\n\n def lpip_loss(self, pred, target):\n result = torch.squeeze(self.lpips_loss(pred, target))\n result = torch.mean(result)\n return result\n\n def ssim_loss(self, pred, target):\n return kornia.losses.ssim_loss(pred, target)\n\n def update_penalties(self, adv_weight, l1_weight, lpip_weight, ssim_weight, bce_weight):\n # what penalties to use for losses?\n self.adv_weight = adv_weight\n self.l1_weight = l1_weight\n self.lpip_weight = lpip_weight\n self.ssim_weight = ssim_weight\n self.bce_weight = bce_weight\n\n # save hyperparameters for bookeeping\n HYPERPARAMS_PATH = \"checkpoint/\" + constants.SHADING_VERSION + \"_\" + constants.ITERATION + \".config\"\n with open(HYPERPARAMS_PATH, \"w\") as f:\n print(\"Version: \", constants.SHADING_CHECKPATH, file=f)\n print(\"Learning rate for G: \", str(self.g_lr), file=f)\n print(\"Learning rate for D: \", str(self.d_lr), file=f)\n print(\"====================================\", file=f)\n print(\"Adv weight: \", str(self.adv_weight), file=f)\n print(\"Likeness weight: \", str(self.l1_weight), file=f)\n print(\"LPIP weight: \", str(self.lpip_weight), file=f)\n print(\"SSIM weight: \", str(self.ssim_weight), file=f)\n print(\"BCE weight: \", str(self.bce_weight), file=f)\n\n def train(self, a_tensor, b_tensor):\n with amp.autocast():\n light_tensor = torch.unsqueeze(torch.full_like(a_tensor[:, 0, :, :], self.light_angle), 1)\n a_input = torch.cat([a_tensor, light_tensor], 1)\n a2b = self.G_A(a_input)\n\n self.D_A.train()\n self.optimizerD.zero_grad()\n\n prediction = self.D_A(b_tensor)\n real_tensor = torch.ones_like(prediction)\n fake_tensor = torch.zeros_like(prediction)\n\n D_A_real_loss = self.adversarial_loss(self.D_A(b_tensor), real_tensor) * self.adv_weight\n D_A_fake_loss = self.adversarial_loss(self.D_A(a2b.detach()), fake_tensor) * self.adv_weight\n\n errD = D_A_real_loss + D_A_fake_loss\n\n self.fp16_scaler.scale(errD).backward()\n if (self.fp16_scaler.scale(errD).item() > 0.2):\n self.fp16_scaler.step(self.optimizerD)\n self.schedulerD.step(errD)\n\n self.G_A.train()\n self.optimizerG.zero_grad()\n\n light_tensor = torch.unsqueeze(torch.full_like(a_tensor[:, 0, :, :], self.light_angle), 1)\n a_input = torch.cat([a_tensor, light_tensor], 1)\n a2b = self.G_A(a_input)\n\n likeness_loss = self.l1_loss(a2b, b_tensor) * self.l1_weight\n lpip_loss = self.lpip_loss(a2b, b_tensor) * self.lpip_weight\n ssim_loss = self.ssim_loss(a2b, b_tensor) * self.ssim_weight\n bce_loss_val = self.bce_loss_term(a2b, b_tensor) * self.bce_weight\n\n prediction = self.D_A(a2b)\n real_tensor = torch.ones_like(prediction)\n A_adv_loss = self.adversarial_loss(prediction, real_tensor) * self.adv_weight\n\n errG = A_adv_loss + likeness_loss + lpip_loss + ssim_loss + bce_loss_val\n\n self.fp16_scaler.scale(errG).backward()\n self.fp16_scaler.step(self.optimizerG)\n self.schedulerG.step(errG)\n self.fp16_scaler.update()\n\n # what to put to losses dict for visdom reporting?\n self.losses_dict[constants.G_LOSS_KEY].append(errG.item())\n self.losses_dict[constants.D_OVERALL_LOSS_KEY].append(errD.item())\n self.losses_dict[constants.LIKENESS_LOSS_KEY].append(likeness_loss.item())\n self.losses_dict[constants.LPIP_LOSS_KEY].append(lpip_loss.item())\n self.losses_dict[constants.SSIM_LOSS_KEY].append(ssim_loss.item())\n self.losses_dict[constants.G_ADV_LOSS_KEY].append(A_adv_loss.item())\n self.losses_dict[constants.D_A_FAKE_LOSS_KEY].append(D_A_fake_loss.item())\n self.losses_dict[constants.D_A_REAL_LOSS_KEY].append(D_A_real_loss.item())\n\n def test(self, a_tensor):\n with torch.no_grad():\n light_tensor = torch.unsqueeze(torch.full_like(a_tensor[:, 0, :, :], self.light_angle), 1)\n a_input = torch.cat([a_tensor, light_tensor], 1)\n a2b = self.G_A(a_input)\n return a2b\n\n def visdom_plot(self, iteration):\n self.visdom_reporter.plot_finegrain_loss(\"a2b_loss\", iteration, self.losses_dict, self.caption_dict, constants.SHADING_CHECKPATH)\n\n def visdom_visualize(self, a_tensor, b_tensor, a_test, b_test):\n with torch.no_grad():\n light_tensor = torch.unsqueeze(torch.full_like(a_tensor[:, 0, :, :], self.light_angle), 1)\n a_input = torch.cat([a_tensor, light_tensor], 1)\n a2b = self.G_A(a_input)\n\n test_light_tensor = torch.unsqueeze(torch.full_like(a_test[:, 0, :, :], self.light_angle), 1)\n a_test_input = torch.cat([a_test, test_light_tensor], 1)\n test_a2b = self.G_A(a_test_input)\n\n self.visdom_reporter.plot_image(a_tensor, \"Training A images - \" + constants.SHADING_VERSION + constants.ITERATION)\n self.visdom_reporter.plot_image(a2b, \"Training A2B images - \" + constants.SHADING_VERSION + constants.ITERATION)\n self.visdom_reporter.plot_image(b_tensor, \"B images - \" + constants.SHADING_VERSION + constants.ITERATION)\n\n self.visdom_reporter.plot_image(a_test, \"Test A images - \" + constants.SHADING_VERSION + constants.ITERATION)\n self.visdom_reporter.plot_image(test_a2b, \"Test A2B images - \" + constants.SHADING_VERSION + constants.ITERATION)\n self.visdom_reporter.plot_image(b_test, \"Test B images - \" + constants.SHADING_VERSION + constants.ITERATION)\n\n def visdom_infer(self, rw_tensor):\n with torch.no_grad():\n rw_light_tensor = torch.unsqueeze(torch.full_like(rw_tensor[:, 0, :, :], self.light_angle), 1)\n rw_input = torch.cat([rw_tensor, rw_light_tensor], 1)\n rw2b = self.G_A(rw_input)\n\n self.visdom_reporter.plot_image(rw_tensor, \"Real World images - \" + constants.SHADING_VERSION + constants.ITERATION)\n self.visdom_reporter.plot_image(rw2b, \"Real World A2B images - \" + constants.SHADING_VERSION + constants.ITERATION)\n\n\n def load_saved_state(self, checkpoint):\n self.G_A.load_state_dict(checkpoint[constants.GENERATOR_KEY + \"A\"])\n self.D_A.load_state_dict(checkpoint[constants.DISCRIMINATOR_KEY + \"A\"])\n self.optimizerG.load_state_dict(checkpoint[constants.GENERATOR_KEY + constants.OPTIMIZER_KEY])\n self.optimizerD.load_state_dict(checkpoint[constants.DISCRIMINATOR_KEY + constants.OPTIMIZER_KEY])\n self.schedulerG.load_state_dict(checkpoint[constants.GENERATOR_KEY + \"scheduler\"])\n self.schedulerD.load_state_dict(checkpoint[constants.DISCRIMINATOR_KEY + \"scheduler\"])\n\n def save_states_checkpt(self, epoch, iteration):\n save_dict = {'epoch': epoch, 'iteration': iteration}\n netGA_state_dict = self.G_A.state_dict()\n netDA_state_dict = self.D_A.state_dict()\n\n optimizerG_state_dict = self.optimizerG.state_dict()\n optimizerD_state_dict = self.optimizerD.state_dict()\n\n schedulerG_state_dict = self.schedulerG.state_dict()\n schedulerD_state_dict = self.schedulerD.state_dict()\n\n save_dict[constants.GENERATOR_KEY + \"A\"] = netGA_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + \"A\"] = netDA_state_dict\n\n save_dict[constants.GENERATOR_KEY + constants.OPTIMIZER_KEY] = optimizerG_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + constants.OPTIMIZER_KEY] = optimizerD_state_dict\n\n save_dict[constants.GENERATOR_KEY + \"scheduler\"] = schedulerG_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + \"scheduler\"] = schedulerD_state_dict\n\n torch.save(save_dict, constants.SHADING_CHECKPATH + \".checkpt\")\n print(\"Saved model state: %s Epoch: %d\" % (len(save_dict), (epoch + 1)))\n\n def save_states(self, epoch, iteration):\n save_dict = {'epoch': epoch, 'iteration': iteration}\n netGA_state_dict = self.G_A.state_dict()\n netDA_state_dict = self.D_A.state_dict()\n\n optimizerG_state_dict = self.optimizerG.state_dict()\n optimizerD_state_dict = self.optimizerD.state_dict()\n\n schedulerG_state_dict = self.schedulerG.state_dict()\n schedulerD_state_dict = self.schedulerD.state_dict()\n\n save_dict[constants.GENERATOR_KEY + \"A\"] = netGA_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + \"A\"] = netDA_state_dict\n\n save_dict[constants.GENERATOR_KEY + constants.OPTIMIZER_KEY] = optimizerG_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + constants.OPTIMIZER_KEY] = optimizerD_state_dict\n\n save_dict[constants.GENERATOR_KEY + \"scheduler\"] = schedulerG_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + \"scheduler\"] = schedulerD_state_dict\n\n torch.save(save_dict, constants.SHADING_CHECKPATH)\n print(\"Saved model state: %s Epoch: %d\" % (len(save_dict), (epoch + 1)))\n\nclass ShadingTrainerAlbedo:\n\n def __init__(self, gpu_device, opts):\n self.gpu_device = gpu_device\n self.g_lr = opts.g_lr\n self.d_lr = opts.d_lr\n self.use_bce = opts.use_bce\n self.light_angle = opts.light_angle\n self.light_angle = self.normalize(self.light_angle)\n\n self.lpips_loss = lpips.LPIPS(net = 'vgg').to(self.gpu_device)\n self.ssim_loss = ssim_loss.SSIM()\n self.l1_loss = nn.L1Loss()\n self.bce_loss = nn.BCEWithLogitsLoss()\n\n num_blocks = opts.num_blocks\n self.batch_size = opts.batch_size\n net_config = opts.net_config\n\n if(net_config == 1):\n self.G_A = cycle_gan.Generator(input_nc=7, output_nc=3, n_residual_blocks=num_blocks).to(self.gpu_device)\n elif(net_config == 2):\n self.G_A = unet_gan.UnetGenerator(input_nc=7, output_nc=3, num_downs=num_blocks).to(self.gpu_device)\n elif(net_config == 3):\n self.G_A = ffa.FFAWithBackbone(input_nc=7, blocks = num_blocks).to(self.gpu_device)\n elif (net_config == 4):\n self.G_A = cycle_gan.Generator(input_nc=7, output_nc=3, n_residual_blocks=num_blocks, has_dropout=False).to(self.gpu_device)\n elif (net_config == 5):\n self.G_A = cycle_gan.GeneratorV2(input_nc=7, output_nc=3, n_residual_blocks=num_blocks, has_dropout=False, multiply=True).to(self.gpu_device)\n else:\n self.G_A = cycle_gan.GeneratorV2(input_nc=7, output_nc=3, n_residual_blocks=num_blocks, has_dropout=False, multiply=False).to(self.gpu_device)\n\n self.D_A = cycle_gan.Discriminator(input_nc=3, use_bce=self.use_bce).to(self.gpu_device) # use CycleGAN's discriminator\n\n self.visdom_reporter = plot_utils.VisdomReporter()\n self.optimizerG = torch.optim.Adam(itertools.chain(self.G_A.parameters()), lr=self.g_lr)\n self.optimizerD = torch.optim.Adam(itertools.chain(self.D_A.parameters()), lr=self.d_lr)\n self.schedulerG = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizerG, patience=100000 / self.batch_size, threshold=0.00005)\n self.schedulerD = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizerD, patience=100000 / self.batch_size, threshold=0.00005)\n self.initialize_dict()\n\n self.fp16_scaler = amp.GradScaler() # for automatic mixed precision\n\n def initialize_dict(self):\n # what to store in visdom?\n self.losses_dict = {}\n self.losses_dict[constants.G_LOSS_KEY] = []\n self.losses_dict[constants.D_OVERALL_LOSS_KEY] = []\n self.losses_dict[constants.LIKENESS_LOSS_KEY] = []\n self.losses_dict[constants.LPIP_LOSS_KEY] = []\n self.losses_dict[constants.SSIM_LOSS_KEY] = []\n self.losses_dict[constants.G_ADV_LOSS_KEY] = []\n self.losses_dict[constants.D_A_FAKE_LOSS_KEY] = []\n self.losses_dict[constants.D_A_REAL_LOSS_KEY] = []\n\n self.caption_dict = {}\n self.caption_dict[constants.G_LOSS_KEY] = \"G loss per iteration\"\n self.caption_dict[constants.D_OVERALL_LOSS_KEY] = \"D loss per iteration\"\n self.caption_dict[constants.LIKENESS_LOSS_KEY] = \"L1 loss per iteration\"\n self.caption_dict[constants.LPIP_LOSS_KEY] = \"LPIPS loss per iteration\"\n self.caption_dict[constants.SSIM_LOSS_KEY] = \"SSIM loss per iteration\"\n self.caption_dict[constants.G_ADV_LOSS_KEY] = \"G adv loss per iteration\"\n self.caption_dict[constants.D_A_FAKE_LOSS_KEY] = \"D(A) fake loss per iteration\"\n self.caption_dict[constants.D_A_REAL_LOSS_KEY] = \"D(A) real loss per iteration\"\n\n def normalize(self, light_angle):\n std = light_angle / 360.0\n min = -1.0\n max = 1.0\n scaled = std * (max - min) + min\n\n return scaled\n\n def adversarial_loss(self, pred, target):\n if (self.use_bce == 0):\n return self.l1_loss(pred, target)\n else:\n return self.bce_loss(pred, target)\n\n def l1_loss(self, pred, target):\n return self.l1_loss(pred, target)\n\n def bce_loss_term(self, pred, target):\n return self.bce_loss(pred, target)\n\n def lpip_loss(self, pred, target):\n result = torch.squeeze(self.lpips_loss(pred, target))\n result = torch.mean(result)\n return result\n\n def ssim_loss(self, pred, target):\n return kornia.losses.ssim_loss(pred, target)\n\n def update_penalties(self, adv_weight, l1_weight, lpip_weight, ssim_weight, bce_weight):\n # what penalties to use for losses?\n self.adv_weight = adv_weight\n self.l1_weight = l1_weight\n self.lpip_weight = lpip_weight\n self.ssim_weight = ssim_weight\n self.bce_weight = bce_weight\n\n # save hyperparameters for bookeeping\n HYPERPARAMS_PATH = \"checkpoint/\" + constants.SHADING_VERSION + \"_\" + constants.ITERATION + \".config\"\n with open(HYPERPARAMS_PATH, \"w\") as f:\n print(\"Version: \", constants.SHADING_CHECKPATH, file=f)\n print(\"Learning rate for G: \", str(self.g_lr), file=f)\n print(\"Learning rate for D: \", str(self.d_lr), file=f)\n print(\"====================================\", file=f)\n print(\"Adv weight: \", str(self.adv_weight), file=f)\n print(\"Likeness weight: \", str(self.l1_weight), file=f)\n print(\"LPIP weight: \", str(self.lpip_weight), file=f)\n print(\"SSIM weight: \", str(self.ssim_weight), file=f)\n print(\"BCE weight: \", str(self.bce_weight), file=f)\n\n def train(self, input_tensor, albedo_tensor, result_tensor):\n with amp.autocast():\n light_tensor = torch.unsqueeze(torch.full_like(input_tensor[:, 0, :, :], self.light_angle), 1)\n a_input = torch.cat([input_tensor, albedo_tensor, light_tensor], 1)\n a2b = self.G_A(a_input)\n\n self.D_A.train()\n self.optimizerD.zero_grad()\n\n prediction = self.D_A(result_tensor)\n real_tensor = torch.ones_like(prediction)\n fake_tensor = torch.zeros_like(prediction)\n\n D_A_real_loss = self.adversarial_loss(self.D_A(result_tensor), real_tensor) * self.adv_weight\n D_A_fake_loss = self.adversarial_loss(self.D_A(a2b.detach()), fake_tensor) * self.adv_weight\n\n errD = D_A_real_loss + D_A_fake_loss\n\n self.fp16_scaler.scale(errD).backward()\n if (self.fp16_scaler.scale(errD).item() > 0.2):\n self.fp16_scaler.step(self.optimizerD)\n self.schedulerD.step(errD)\n\n self.G_A.train()\n self.optimizerG.zero_grad()\n\n light_tensor = torch.unsqueeze(torch.full_like(input_tensor[:, 0, :, :], self.light_angle), 1)\n a_input = torch.cat([input_tensor, albedo_tensor, light_tensor], 1)\n a2b = self.G_A(a_input)\n\n likeness_loss = self.l1_loss(a2b, result_tensor) * self.l1_weight\n lpip_loss = self.lpip_loss(a2b, result_tensor) * self.lpip_weight\n ssim_loss = self.ssim_loss(a2b, result_tensor) * self.ssim_weight\n bce_loss_val = self.bce_loss_term(a2b, result_tensor) * self.bce_weight\n\n prediction = self.D_A(a2b)\n real_tensor = torch.ones_like(prediction)\n A_adv_loss = self.adversarial_loss(prediction, real_tensor) * self.adv_weight\n\n errG = A_adv_loss + likeness_loss + lpip_loss + ssim_loss + bce_loss_val\n\n self.fp16_scaler.scale(errG).backward()\n self.fp16_scaler.step(self.optimizerG)\n self.schedulerG.step(errG)\n self.fp16_scaler.update()\n\n # what to put to losses dict for visdom reporting?\n self.losses_dict[constants.G_LOSS_KEY].append(errG.item())\n self.losses_dict[constants.D_OVERALL_LOSS_KEY].append(errD.item())\n self.losses_dict[constants.LIKENESS_LOSS_KEY].append(likeness_loss.item())\n self.losses_dict[constants.LPIP_LOSS_KEY].append(lpip_loss.item())\n self.losses_dict[constants.SSIM_LOSS_KEY].append(ssim_loss.item())\n self.losses_dict[constants.G_ADV_LOSS_KEY].append(A_adv_loss.item())\n self.losses_dict[constants.D_A_FAKE_LOSS_KEY].append(D_A_fake_loss.item())\n self.losses_dict[constants.D_A_REAL_LOSS_KEY].append(D_A_real_loss.item())\n\n def test(self, input_tensor, albedo_tensor):\n with torch.no_grad():\n light_tensor = torch.unsqueeze(torch.full_like(input_tensor[:, 0, :, :], self.light_angle), 1)\n a_input = torch.cat([input_tensor, albedo_tensor, light_tensor], 1)\n a2b = self.G_A(a_input)\n return a2b\n\n def visdom_plot(self, iteration):\n self.visdom_reporter.plot_finegrain_loss(\"a2b_loss\", iteration, self.losses_dict, self.caption_dict, constants.SHADING_CHECKPATH)\n\n def visdom_visualize(self, input_tensor, albedo_tensor, result_tensor, input_test, albedo_test, result_test):\n with torch.no_grad():\n light_tensor = torch.unsqueeze(torch.full_like(input_tensor[:, 0, :, :], self.light_angle), 1)\n a_input = torch.cat([input_tensor, albedo_tensor, light_tensor], 1)\n a2b = self.G_A(a_input)\n\n test_light_tensor = torch.unsqueeze(torch.full_like(input_test[:, 0, :, :], self.light_angle), 1)\n a_test_input = torch.cat([input_test, albedo_test, test_light_tensor], 1)\n test_a2b = self.G_A(a_test_input)\n\n input_tensor = (input_tensor * 0.5) + 0.5\n input_test = (input_test * 0.5) + 0.5\n\n self.visdom_reporter.plot_image(input_tensor, \"Training A images - \" + constants.SHADING_VERSION + constants.ITERATION, False)\n self.visdom_reporter.plot_image(albedo_tensor, \"Training Albedo images - \" + constants.SHADING_VERSION + constants.ITERATION)\n self.visdom_reporter.plot_image(a2b, \"Training A2B images - \" + constants.SHADING_VERSION + constants.ITERATION)\n self.visdom_reporter.plot_image(result_tensor, \"B images - \" + constants.SHADING_VERSION + constants.ITERATION)\n\n self.visdom_reporter.plot_image(input_test, \"Test A images - \" + constants.SHADING_VERSION + constants.ITERATION, False)\n self.visdom_reporter.plot_image(albedo_test, \"Test Albedo images - \" + constants.SHADING_VERSION + constants.ITERATION)\n self.visdom_reporter.plot_image(test_a2b, \"Test A2B images - \" + constants.SHADING_VERSION + constants.ITERATION)\n self.visdom_reporter.plot_image(result_test, \"Test B images - \" + constants.SHADING_VERSION + constants.ITERATION)\n\n # def visdom_infer(self, rw_tensor):\n # with torch.no_grad():\n # rw_light_tensor = torch.unsqueeze(torch.full_like(rw_tensor[:, 0, :, :], self.light_angle), 1)\n # rw_input = torch.cat([rw_tensor, rw_light_tensor], 1)\n # rw2b = self.G_A(rw_input)\n #\n # self.visdom_reporter.plot_image(rw_tensor, \"Real World images - \" + constants.SHADING_VERSION + constants.ITERATION)\n # self.visdom_reporter.plot_image(rw2b, \"Real World A2B images - \" + constants.SHADING_VERSION + constants.ITERATION)\n\n\n def load_saved_state(self, checkpoint):\n self.G_A.load_state_dict(checkpoint[constants.GENERATOR_KEY + \"A\"])\n self.D_A.load_state_dict(checkpoint[constants.DISCRIMINATOR_KEY + \"A\"])\n self.optimizerG.load_state_dict(checkpoint[constants.GENERATOR_KEY + constants.OPTIMIZER_KEY])\n self.optimizerD.load_state_dict(checkpoint[constants.DISCRIMINATOR_KEY + constants.OPTIMIZER_KEY])\n self.schedulerG.load_state_dict(checkpoint[constants.GENERATOR_KEY + \"scheduler\"])\n self.schedulerD.load_state_dict(checkpoint[constants.DISCRIMINATOR_KEY + \"scheduler\"])\n\n def save_states_checkpt(self, epoch, iteration):\n save_dict = {'epoch': epoch, 'iteration': iteration}\n netGA_state_dict = self.G_A.state_dict()\n netDA_state_dict = self.D_A.state_dict()\n\n optimizerG_state_dict = self.optimizerG.state_dict()\n optimizerD_state_dict = self.optimizerD.state_dict()\n\n schedulerG_state_dict = self.schedulerG.state_dict()\n schedulerD_state_dict = self.schedulerD.state_dict()\n\n save_dict[constants.GENERATOR_KEY + \"A\"] = netGA_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + \"A\"] = netDA_state_dict\n\n save_dict[constants.GENERATOR_KEY + constants.OPTIMIZER_KEY] = optimizerG_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + constants.OPTIMIZER_KEY] = optimizerD_state_dict\n\n save_dict[constants.GENERATOR_KEY + \"scheduler\"] = schedulerG_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + \"scheduler\"] = schedulerD_state_dict\n\n torch.save(save_dict, constants.SHADING_CHECKPATH + \".checkpt\")\n print(\"Saved model state: %s Epoch: %d\" % (len(save_dict), (epoch + 1)))\n\n def save_states(self, epoch, iteration):\n save_dict = {'epoch': epoch, 'iteration': iteration}\n netGA_state_dict = self.G_A.state_dict()\n netDA_state_dict = self.D_A.state_dict()\n\n optimizerG_state_dict = self.optimizerG.state_dict()\n optimizerD_state_dict = self.optimizerD.state_dict()\n\n schedulerG_state_dict = self.schedulerG.state_dict()\n schedulerD_state_dict = self.schedulerD.state_dict()\n\n save_dict[constants.GENERATOR_KEY + \"A\"] = netGA_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + \"A\"] = netDA_state_dict\n\n save_dict[constants.GENERATOR_KEY + constants.OPTIMIZER_KEY] = optimizerG_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + constants.OPTIMIZER_KEY] = optimizerD_state_dict\n\n save_dict[constants.GENERATOR_KEY + \"scheduler\"] = schedulerG_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + \"scheduler\"] = schedulerD_state_dict\n\n torch.save(save_dict, constants.SHADING_CHECKPATH)\n print(\"Saved model state: %s Epoch: %d\" % (len(save_dict), (epoch + 1)))\n\n\nclass ShadingTrainerBasic:\n\n def __init__(self, gpu_device, opts):\n self.gpu_device = gpu_device\n self.g_lr = opts.g_lr\n self.d_lr = opts.d_lr\n self.use_bce = opts.use_bce\n\n self.lpips_loss = lpips.LPIPS(net = 'vgg').to(self.gpu_device)\n self.ssim_loss = ssim_loss.SSIM()\n self.l1_loss = nn.L1Loss()\n self.bce_loss = nn.BCEWithLogitsLoss()\n\n num_blocks = opts.num_blocks\n self.batch_size = opts.batch_size\n net_config = opts.net_config\n\n if(net_config == 1):\n self.G_A = cycle_gan.Generator(input_nc=3, output_nc=3, n_residual_blocks=num_blocks).to(self.gpu_device)\n elif(net_config == 2):\n self.G_A = unet_gan.UnetGenerator(input_nc=3, output_nc=3, num_downs=num_blocks).to(self.gpu_device)\n elif(net_config == 3):\n self.G_A = ffa.FFAWithBackbone(input_nc=3, blocks = num_blocks).to(self.gpu_device)\n elif (net_config == 4):\n self.G_A = cycle_gan.Generator(input_nc=3, output_nc=3, n_residual_blocks=num_blocks, has_dropout=False).to(self.gpu_device)\n elif (net_config == 5):\n self.G_A = cycle_gan.GeneratorV2(input_nc=3, output_nc=3, n_residual_blocks=num_blocks, has_dropout=False, multiply=True).to(self.gpu_device)\n else:\n self.G_A = cycle_gan.GeneratorV2(input_nc=3, output_nc=3, n_residual_blocks=num_blocks, has_dropout=False, multiply=False).to(self.gpu_device)\n\n self.D_A = cycle_gan.Discriminator(input_nc=3, use_bce=self.use_bce).to(self.gpu_device) # use CycleGAN's discriminator\n\n self.visdom_reporter = plot_utils.VisdomReporter()\n self.optimizerG = torch.optim.Adam(itertools.chain(self.G_A.parameters()), lr=self.g_lr)\n self.optimizerD = torch.optim.Adam(itertools.chain(self.D_A.parameters()), lr=self.d_lr)\n self.schedulerG = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizerG, patience=100000 / self.batch_size, threshold=0.00005)\n self.schedulerD = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizerD, patience=100000 / self.batch_size, threshold=0.00005)\n self.initialize_dict()\n\n self.fp16_scaler = amp.GradScaler() # for automatic mixed precision\n\n def initialize_dict(self):\n # what to store in visdom?\n self.losses_dict = {}\n self.losses_dict[constants.G_LOSS_KEY] = []\n self.losses_dict[constants.D_OVERALL_LOSS_KEY] = []\n self.losses_dict[constants.LIKENESS_LOSS_KEY] = []\n self.losses_dict[constants.LPIP_LOSS_KEY] = []\n self.losses_dict[constants.SSIM_LOSS_KEY] = []\n self.losses_dict[constants.G_ADV_LOSS_KEY] = []\n self.losses_dict[constants.D_A_FAKE_LOSS_KEY] = []\n self.losses_dict[constants.D_A_REAL_LOSS_KEY] = []\n\n self.caption_dict = {}\n self.caption_dict[constants.G_LOSS_KEY] = \"G loss per iteration\"\n self.caption_dict[constants.D_OVERALL_LOSS_KEY] = \"D loss per iteration\"\n self.caption_dict[constants.LIKENESS_LOSS_KEY] = \"L1 loss per iteration\"\n self.caption_dict[constants.LPIP_LOSS_KEY] = \"LPIPS loss per iteration\"\n self.caption_dict[constants.SSIM_LOSS_KEY] = \"SSIM loss per iteration\"\n self.caption_dict[constants.G_ADV_LOSS_KEY] = \"G adv loss per iteration\"\n self.caption_dict[constants.D_A_FAKE_LOSS_KEY] = \"D(A) fake loss per iteration\"\n self.caption_dict[constants.D_A_REAL_LOSS_KEY] = \"D(A) real loss per iteration\"\n\n def normalize(self, light_angle):\n std = light_angle / 360.0\n min = -1.0\n max = 1.0\n scaled = std * (max - min) + min\n\n return scaled\n\n def adversarial_loss(self, pred, target):\n if (self.use_bce == 0):\n return self.l1_loss(pred, target)\n else:\n return self.bce_loss(pred, target)\n\n def l1_loss(self, pred, target):\n return self.l1_loss(pred, target)\n\n def bce_loss_term(self, pred, target):\n return self.bce_loss(pred, target)\n\n def lpip_loss(self, pred, target):\n result = torch.squeeze(self.lpips_loss(pred, target))\n result = torch.mean(result)\n return result\n\n def ssim_loss(self, pred, target):\n return kornia.losses.ssim_loss(pred, target)\n\n def update_penalties(self, adv_weight, l1_weight, lpip_weight, ssim_weight, bce_weight):\n # what penalties to use for losses?\n self.adv_weight = adv_weight\n self.l1_weight = l1_weight\n self.lpip_weight = lpip_weight\n self.ssim_weight = ssim_weight\n self.bce_weight = bce_weight\n\n # save hyperparameters for bookeeping\n # HYPERPARAMS_PATH = \"checkpoint/\" + constants.SHADING_VERSION + \"_\" + constants.ITERATION + \".config\"\n # with open(HYPERPARAMS_PATH, \"w\") as f:\n # print(\"Version: \", constants.SHADING_CHECKPATH, file=f)\n # print(\"Learning rate for G: \", str(self.g_lr), file=f)\n # print(\"Learning rate for D: \", str(self.d_lr), file=f)\n # print(\"====================================\", file=f)\n # print(\"Adv weight: \", str(self.adv_weight), file=f)\n # print(\"Likeness weight: \", str(self.l1_weight), file=f)\n # print(\"LPIP weight: \", str(self.lpip_weight), file=f)\n # print(\"SSIM weight: \", str(self.ssim_weight), file=f)\n # print(\"BCE weight: \", str(self.bce_weight), file=f)\n\n def train(self, input_tensor, result_tensor):\n with amp.autocast():\n a2b = self.G_A(input_tensor)\n\n self.D_A.train()\n self.optimizerD.zero_grad()\n\n prediction = self.D_A(result_tensor)\n real_tensor = torch.ones_like(prediction)\n fake_tensor = torch.zeros_like(prediction)\n\n D_A_real_loss = self.adversarial_loss(self.D_A(result_tensor), real_tensor) * self.adv_weight\n D_A_fake_loss = self.adversarial_loss(self.D_A(a2b.detach()), fake_tensor) * self.adv_weight\n\n errD = D_A_real_loss + D_A_fake_loss\n\n self.fp16_scaler.scale(errD).backward()\n if (self.fp16_scaler.scale(errD).item() > 0.2):\n self.fp16_scaler.step(self.optimizerD)\n self.schedulerD.step(errD)\n\n self.G_A.train()\n self.optimizerG.zero_grad()\n\n a2b = self.G_A(input_tensor)\n\n likeness_loss = self.l1_loss(a2b, result_tensor) * self.l1_weight\n lpip_loss = self.lpip_loss(a2b, result_tensor) * self.lpip_weight\n ssim_loss = self.ssim_loss(a2b, result_tensor) * self.ssim_weight\n bce_loss_val = self.bce_loss_term(a2b, result_tensor) * self.bce_weight\n\n prediction = self.D_A(a2b)\n real_tensor = torch.ones_like(prediction)\n A_adv_loss = self.adversarial_loss(prediction, real_tensor) * self.adv_weight\n\n errG = A_adv_loss + likeness_loss + lpip_loss + ssim_loss + bce_loss_val\n\n self.fp16_scaler.scale(errG).backward()\n self.fp16_scaler.step(self.optimizerG)\n self.schedulerG.step(errG)\n self.fp16_scaler.update()\n\n # what to put to losses dict for visdom reporting?\n self.losses_dict[constants.G_LOSS_KEY].append(errG.item())\n self.losses_dict[constants.D_OVERALL_LOSS_KEY].append(errD.item())\n self.losses_dict[constants.LIKENESS_LOSS_KEY].append(likeness_loss.item())\n self.losses_dict[constants.LPIP_LOSS_KEY].append(lpip_loss.item())\n self.losses_dict[constants.SSIM_LOSS_KEY].append(ssim_loss.item())\n self.losses_dict[constants.G_ADV_LOSS_KEY].append(A_adv_loss.item())\n self.losses_dict[constants.D_A_FAKE_LOSS_KEY].append(D_A_fake_loss.item())\n self.losses_dict[constants.D_A_REAL_LOSS_KEY].append(D_A_real_loss.item())\n\n def test(self, input_tensor):\n with torch.no_grad():\n a2b = self.G_A(input_tensor)\n return a2b\n\n def visdom_plot(self, iteration):\n self.visdom_reporter.plot_finegrain_loss(\"a2b_loss\", iteration, self.losses_dict, self.caption_dict, constants.SHADING_CHECKPATH)\n\n def visdom_visualize(self, input_tensor, result_tensor, input_test, result_test):\n with torch.no_grad():\n a2b = self.G_A(input_tensor)\n test_a2b = self.G_A(input_test)\n\n input_tensor = (input_tensor * 0.5) + 0.5\n input_test = (input_test * 0.5) + 0.5\n\n self.visdom_reporter.plot_image(input_tensor, \"Training A images - \" + constants.SHADING_VERSION + constants.ITERATION, False)\n self.visdom_reporter.plot_image(a2b, \"Training A2B images - \" + constants.SHADING_VERSION + constants.ITERATION)\n self.visdom_reporter.plot_image(result_tensor, \"B images - \" + constants.SHADING_VERSION + constants.ITERATION)\n\n self.visdom_reporter.plot_image(input_test, \"Test A images - \" + constants.SHADING_VERSION + constants.ITERATION, False)\n self.visdom_reporter.plot_image(test_a2b, \"Test A2B images - \" + constants.SHADING_VERSION + constants.ITERATION)\n self.visdom_reporter.plot_image(result_test, \"Test B images - \" + constants.SHADING_VERSION + constants.ITERATION)\n\n def visdom_infer(self, rw_tensor):\n with torch.no_grad():\n # rw_light_tensor = torch.unsqueeze(torch.full_like(rw_tensor[:, 0, :, :], self.light_angle), 1)\n # rw_input = torch.cat([rw_tensor, rw_light_tensor], 1)\n # rw2b = self.G_A(rw_input)\n rw2b = self.G_A(rw_tensor)\n\n self.visdom_reporter.plot_image(rw_tensor, \"Real World images - \" + constants.SHADING_VERSION + constants.ITERATION)\n self.visdom_reporter.plot_image(rw2b, \"Real World A2B images - \" + constants.SHADING_VERSION + constants.ITERATION)\n\n\n def load_saved_state(self, checkpoint):\n self.G_A.load_state_dict(checkpoint[constants.GENERATOR_KEY + \"A\"])\n self.D_A.load_state_dict(checkpoint[constants.DISCRIMINATOR_KEY + \"A\"])\n self.optimizerG.load_state_dict(checkpoint[constants.GENERATOR_KEY + constants.OPTIMIZER_KEY])\n self.optimizerD.load_state_dict(checkpoint[constants.DISCRIMINATOR_KEY + constants.OPTIMIZER_KEY])\n self.schedulerG.load_state_dict(checkpoint[constants.GENERATOR_KEY + \"scheduler\"])\n self.schedulerD.load_state_dict(checkpoint[constants.DISCRIMINATOR_KEY + \"scheduler\"])\n\n def save_states_checkpt(self, epoch, iteration, last_metric):\n save_dict = {'epoch': epoch, 'iteration': iteration, constants.LAST_METRIC_KEY: last_metric}\n netGA_state_dict = self.G_A.state_dict()\n netDA_state_dict = self.D_A.state_dict()\n\n optimizerG_state_dict = self.optimizerG.state_dict()\n optimizerD_state_dict = self.optimizerD.state_dict()\n\n schedulerG_state_dict = self.schedulerG.state_dict()\n schedulerD_state_dict = self.schedulerD.state_dict()\n\n save_dict[constants.GENERATOR_KEY + \"A\"] = netGA_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + \"A\"] = netDA_state_dict\n\n save_dict[constants.GENERATOR_KEY + constants.OPTIMIZER_KEY] = optimizerG_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + constants.OPTIMIZER_KEY] = optimizerD_state_dict\n\n save_dict[constants.GENERATOR_KEY + \"scheduler\"] = schedulerG_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + \"scheduler\"] = schedulerD_state_dict\n\n torch.save(save_dict, constants.SHADING_CHECKPATH + \".checkpt\")\n print(\"Saved model state: %s Epoch: %d\" % (len(save_dict), (epoch + 1)))\n\n def save_states(self, epoch, iteration, last_metric):\n save_dict = {'epoch': epoch, 'iteration': iteration, constants.LAST_METRIC_KEY: last_metric}\n netGA_state_dict = self.G_A.state_dict()\n netDA_state_dict = self.D_A.state_dict()\n\n optimizerG_state_dict = self.optimizerG.state_dict()\n optimizerD_state_dict = self.optimizerD.state_dict()\n\n schedulerG_state_dict = self.schedulerG.state_dict()\n schedulerD_state_dict = self.schedulerD.state_dict()\n\n save_dict[constants.GENERATOR_KEY + \"A\"] = netGA_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + \"A\"] = netDA_state_dict\n\n save_dict[constants.GENERATOR_KEY + constants.OPTIMIZER_KEY] = optimizerG_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + constants.OPTIMIZER_KEY] = optimizerD_state_dict\n\n save_dict[constants.GENERATOR_KEY + \"scheduler\"] = schedulerG_state_dict\n save_dict[constants.DISCRIMINATOR_KEY + \"scheduler\"] = schedulerD_state_dict\n\n torch.save(save_dict, constants.SHADING_CHECKPATH)\n print(\"Saved model state: %s Epoch: %d\" % (len(save_dict), (epoch + 1)))" ]
[ [ "torch.mean", "torch.ones_like", "torch.optim.lr_scheduler.ReduceLROnPlateau", "torch.cat", "torch.zeros_like", "torch.cuda.amp.autocast", "torch.cuda.amp.GradScaler", "torch.nn.BCEWithLogitsLoss", "torch.no_grad", "torch.full_like", "torch.nn.L1Loss", "torch.save" ] ]
Eric030577/dissertation-master
[ "99e96a60f97259c6d8589f58073cf4fa0a7da4bc" ]
[ "yolov4-keras-master/nets/loss.py" ]
[ "import numpy as np\r\nimport tensorflow as tf\r\nfrom keras import backend as K\r\nfrom nets.ious import box_ciou\r\n\r\n\r\n# ---------------------------------------------------#\r\n# smooth_labels\r\n# ---------------------------------------------------#\r\ndef _smooth_labels(y_true, label_smoothing):\r\n num_classes = tf.cast(K.shape(y_true)[-1], dtype=K.floatx())\r\n label_smoothing = K.constant(label_smoothing, dtype=K.floatx())\r\n return y_true * (1.0 - label_smoothing) + label_smoothing / num_classes\r\n\r\n\r\n# ---------------------------------------------------#\r\n# Adjust each feature layer of the predicted value to the true value\r\n# ---------------------------------------------------#\r\ndef yolo_head(feats, anchors, num_classes, input_shape, calc_loss=False):\r\n num_anchors = len(anchors)\r\n # [1, 1, 1, num_anchors, 2]\r\n anchors_tensor = K.reshape(K.constant(anchors), [1, 1, 1, num_anchors, 2])\r\n\r\n # Get x, y grid\r\n # (13, 13, 1, 2)\r\n grid_shape = K.shape(feats)[1:3] # height, width\r\n grid_y = K.tile(K.reshape(K.arange(0, stop=grid_shape[0]), [-1, 1, 1, 1]),\r\n [1, grid_shape[1], 1, 1])\r\n grid_x = K.tile(K.reshape(K.arange(0, stop=grid_shape[1]), [1, -1, 1, 1]),\r\n [grid_shape[0], 1, 1, 1])\r\n grid = K.concatenate([grid_x, grid_y])\r\n grid = K.cast(grid, K.dtype(feats))\r\n\r\n # (batch_size,13,13,3,85)\r\n feats = K.reshape(feats, [-1, grid_shape[0], grid_shape[1], num_anchors, num_classes + 5])\r\n\r\n # Adjust the predicted value to the ground truth\r\n # box_xy centre\r\n # box_wh width and height\r\n box_xy = (K.sigmoid(feats[..., :2]) + grid) / K.cast(grid_shape[::-1], K.dtype(feats))\r\n box_wh = K.exp(feats[..., 2:4]) * anchors_tensor / K.cast(input_shape[::-1], K.dtype(feats))\r\n box_confidence = K.sigmoid(feats[..., 4:5])\r\n box_class_probs = K.sigmoid(feats[..., 5:])\r\n\r\n # The following parameters are returned when calculating loss\r\n if calc_loss == True:\r\n return grid, feats, box_xy, box_wh\r\n return box_xy, box_wh, box_confidence, box_class_probs\r\n\r\n\r\n# ---------------------------------------------------#\r\n# Used to calculate the iou of each predicted box and the ground truth box\r\n# ---------------------------------------------------#\r\ndef box_iou(b1, b2):\r\n # 13,13,3,1,4\r\n # Calculate the coordinates of the upper left corner and the lower right corner\r\n b1 = K.expand_dims(b1, -2)\r\n b1_xy = b1[..., :2]\r\n b1_wh = b1[..., 2:4]\r\n b1_wh_half = b1_wh / 2.\r\n b1_mins = b1_xy - b1_wh_half\r\n b1_maxes = b1_xy + b1_wh_half\r\n\r\n # 1,n,4\r\n # Calculate the coordinates of the upper left and lower right corners\r\n b2 = K.expand_dims(b2, 0)\r\n b2_xy = b2[..., :2]\r\n b2_wh = b2[..., 2:4]\r\n b2_wh_half = b2_wh / 2.\r\n b2_mins = b2_xy - b2_wh_half\r\n b2_maxes = b2_xy + b2_wh_half\r\n\r\n # Calculate overlap area\r\n intersect_mins = K.maximum(b1_mins, b2_mins)\r\n intersect_maxes = K.minimum(b1_maxes, b2_maxes)\r\n intersect_wh = K.maximum(intersect_maxes - intersect_mins, 0.)\r\n intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1]\r\n b1_area = b1_wh[..., 0] * b1_wh[..., 1]\r\n b2_area = b2_wh[..., 0] * b2_wh[..., 1]\r\n iou = intersect_area / (b1_area + b2_area - intersect_area)\r\n\r\n return iou\r\n\r\n\r\n# ---------------------------------------------------#\r\n# loss值计算\r\n# ---------------------------------------------------#\r\ndef yolo_loss(args, anchors, num_classes, ignore_thresh=.5, label_smoothing=0.1, print_loss=False):\r\n # 一共有三层\r\n num_layers = len(anchors) // 3\r\n\r\n # 将预测结果和实际ground truth分开,args是[*model_body.output, *y_true]\r\n # y_true是一个列表,包含三个特征层,shape分别为(m,13,13,3,85),(m,26,26,3,85),(m,52,52,3,85)。\r\n # yolo_outputs是一个列表,包含三个特征层,shape分别为(m,13,13,255),(m,26,26,255),(m,52,52,255)。\r\n y_true = args[num_layers:]\r\n yolo_outputs = args[:num_layers]\r\n\r\n # 先验框\r\n # 678为142,110, 192,243, 459,401\r\n # 345为36,75, 76,55, 72,146\r\n # 012为12,16, 19,36, 40,28 \r\n anchor_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]] if num_layers == 3 else [[3, 4, 5], [1, 2, 3]]\r\n\r\n # 得到input_shpae为608,608 \r\n input_shape = K.cast(K.shape(yolo_outputs[0])[1:3] * 32, K.dtype(y_true[0]))\r\n\r\n loss = 0\r\n\r\n # 取出每一张图片\r\n # m的值就是batch_size\r\n m = K.shape(yolo_outputs[0])[0]\r\n mf = K.cast(m, K.dtype(yolo_outputs[0]))\r\n\r\n # y_true是一个列表,包含三个特征层,shape分别为(m,13,13,3,85),(m,26,26,3,85),(m,52,52,3,85)。\r\n # yolo_outputs是一个列表,包含三个特征层,shape分别为(m,13,13,255),(m,26,26,255),(m,52,52,255)。\r\n for l in range(num_layers):\r\n # 以第一个特征层(m,13,13,3,85)为例子\r\n # 取出该特征层中存在目标的点的位置。(m,13,13,3,1)\r\n object_mask = y_true[l][..., 4:5]\r\n # 取出其对应的种类(m,13,13,3,80)\r\n true_class_probs = y_true[l][..., 5:]\r\n if label_smoothing:\r\n true_class_probs = _smooth_labels(true_class_probs, label_smoothing)\r\n\r\n # 将yolo_outputs的特征层输出进行处理\r\n # grid为网格结构(13,13,1,2),raw_pred为尚未处理的预测结果(m,13,13,3,85)\r\n # 还有解码后的xy,wh,(m,13,13,3,2)\r\n grid, raw_pred, pred_xy, pred_wh = yolo_head(yolo_outputs[l],\r\n anchors[anchor_mask[l]], num_classes, input_shape, calc_loss=True)\r\n\r\n # 这个是解码后的预测的box的位置\r\n # (m,13,13,3,4)\r\n pred_box = K.concatenate([pred_xy, pred_wh])\r\n\r\n # 找到负样本群组,第一步是创建一个数组,[]\r\n ignore_mask = tf.TensorArray(K.dtype(y_true[0]), size=1, dynamic_size=True)\r\n object_mask_bool = K.cast(object_mask, 'bool')\r\n\r\n # 对每一张图片计算ignore_mask\r\n def loop_body(b, ignore_mask):\r\n # 取出第b副图内,真实存在的所有的box的参数\r\n # n,4\r\n true_box = tf.boolean_mask(y_true[l][b, ..., 0:4], object_mask_bool[b, ..., 0])\r\n # 计算预测结果与真实情况的iou\r\n # pred_box为13,13,3,4\r\n # 计算的结果是每个pred_box和其它所有真实框的iou\r\n # 13,13,3,n\r\n iou = box_iou(pred_box[b], true_box)\r\n\r\n # 13,13,3\r\n best_iou = K.max(iou, axis=-1)\r\n\r\n # 如果某些预测框和真实框的重合程度大于0.5,则忽略。\r\n ignore_mask = ignore_mask.write(b, K.cast(best_iou < ignore_thresh, K.dtype(true_box)))\r\n return b + 1, ignore_mask\r\n\r\n # 遍历所有的图片\r\n _, ignore_mask = K.control_flow_ops.while_loop(lambda b, *args: b < m, loop_body, [0, ignore_mask])\r\n\r\n # 将每幅图的内容压缩,进行处理\r\n ignore_mask = ignore_mask.stack()\r\n # (m,13,13,3,1)\r\n ignore_mask = K.expand_dims(ignore_mask, -1)\r\n\r\n box_loss_scale = 2 - y_true[l][..., 2:3] * y_true[l][..., 3:4]\r\n\r\n # Calculate ciou loss as location loss\r\n raw_true_box = y_true[l][..., 0:4]\r\n ciou = box_ciou(pred_box, raw_true_box)\r\n ciou_loss = object_mask * box_loss_scale * (1 - ciou)\r\n ciou_loss = K.sum(ciou_loss) / mf\r\n location_loss = ciou_loss\r\n\r\n # 如果该位置本来有框,那么计算1与置信度的交叉熵\r\n # 如果该位置本来没有框,而且满足best_iou<ignore_thresh,则被认定为负样本\r\n # best_iou<ignore_thresh用于限制负样本数量\r\n confidence_loss = object_mask * K.binary_crossentropy(object_mask, raw_pred[..., 4:5], from_logits=True) + \\\r\n (1 - object_mask) * K.binary_crossentropy(object_mask, raw_pred[..., 4:5],\r\n from_logits=True) * ignore_mask\r\n\r\n class_loss = object_mask * K.binary_crossentropy(true_class_probs, raw_pred[..., 5:], from_logits=True)\r\n\r\n confidence_loss = K.sum(confidence_loss) / mf\r\n class_loss = K.sum(class_loss) / mf\r\n loss += location_loss + confidence_loss + class_loss\r\n # if print_loss:\r\n # loss = tf.Print(loss, [loss, location_loss, confidence_loss, class_loss, K.sum(ignore_mask)], message='loss: ')\r\n return loss\r\n" ]
[ [ "tensorflow.boolean_mask" ] ]
TomMonks/meta-py
[ "a28e6cc434692fefff8b81e3b12a40a66e71a20c" ]
[ "metapy/tsp/bruteforce.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nFunctions and classes to enable bruteforce solution of the TSP.\r\nNote Bruteforce is inefficient after tours exceed 5 cities\r\n\"\"\"\r\n\r\n\r\nimport itertools as ite\r\nimport numpy as np\r\nfrom sympy.utilities.iterables import multiset_permutations\r\n\r\nfrom metapy.tsp.objective import tour_cost\r\nfrom metapy.tsp.init_solutions import random_tour\r\nfrom metapy.tsp.tsp_utility import append_base, trim_base\r\n \r\nclass BruteForceSolver(object):\r\n \"\"\"\r\n Enumerates all permutations of a given list of cities and calculates\r\n waits. Note for n cities there are n! permutations! BruteForceSolver is\r\n too slow for tours beyond 10 cities.\r\n \"\"\"\r\n def __init__(self, init_solution, objective, maximisation=False):\r\n \"\"\"\r\n Constructor Method\r\n \r\n Params:\r\n -------\r\n init_solution, np.ndarray\r\n initial tour\r\n objective, Object\r\n Class that implements .evaluate() interface\r\n \"\"\"\r\n self._objective = objective\r\n self._init_solution = init_solution\r\n\r\n if maximisation:\r\n self._negate = 1.0\r\n elif not maximisation:\r\n self._negate = -1.0\r\n else:\r\n raise ValueError('parameter maximisation must be bool True|False')\r\n\r\n #list of best solutions in case of multiple optima\r\n self.best_solutions = [init_solution]\r\n self._best_cost = self._objective.evaluate(init_solution) * self._negate\r\n\r\n def _get_best_cost(self):\r\n return self._best_cost * self._negate\r\n \r\n def solve(self):\r\n \"\"\"\r\n Enumerate all costs to find the minimum.\r\n Store solution(s)\r\n \"\"\"\r\n \r\n #pick a random start city and then permute the rest and rejoin.\r\n origin = np.array([self._init_solution[0]])\r\n for current_tour in ite.permutations(self._init_solution[1:]):\r\n current_tour = np.concatenate([origin, current_tour])\r\n cost = self._objective.evaluate(current_tour) * self._negate\r\n \r\n if self._best_cost == cost:\r\n self._best_cost = cost\r\n self.best_solutions.append(current_tour)\r\n \r\n elif cost > self._best_cost:\r\n self._best_cost = cost\r\n self.best_solutions = [current_tour]\r\n\r\n def _all_permutations(self, tour):\r\n \"\"\"\r\n Returns a list of lists containing all permutations of a\r\n tour. The base_city is appended to each_list\r\n \"\"\"\r\n return [np.array(x) for x in ite.permutations(tour)]\r\n\r\n best_cost = property(_get_best_cost)\r\n \r\n \r\n \r\n \r\nclass RandomSearch(object):\r\n \"\"\"\r\n A simple global optimisation algorithm - encapsulates Random Search. \r\n The algorithm is completely explorative and randomly\r\n samples a tour and compares if it is better than the current\r\n best.\r\n \"\"\"\r\n def __init__(self, init_solution, objective, max_iter=1000, maximisation=False):\r\n \"\"\"\r\n Constructor Method\r\n\r\n Parameters:\r\n ---------\r\n init_solution -- initial tour\r\n matrix -- matrix of travel costs\r\n \"\"\"\r\n self._objective = objective\r\n self._init_solution = init_solution\r\n self._max_iter = max_iter\r\n\r\n if maximisation:\r\n self._negate = 1.0\r\n elif not maximisation:\r\n self._negate = -1.0\r\n else:\r\n raise ValueError('parameter maximisation must be bool True|False')\r\n\r\n #list of best solutions in case of multiple optima\r\n self.best_solutions = [init_solution]\r\n self._best_cost = self._objective.evaluate(init_solution) * self._negate\r\n\r\n def _get_best_cost(self):\r\n return self._best_cost * self._negate\r\n \r\n def solve(self):\r\n '''\r\n Random search.\r\n \r\n Loop until all iterations are complete. \r\n Sample a random tour on each iterations and compare to best.\r\n \r\n '''\r\n \r\n for iteration in range(self._max_iter):\r\n sample_tour = np.random.permutation(self._init_solution)\r\n sample_cost = self._objective.evaluate(sample_tour) * self._negate\r\n\r\n if self.best_cost == sample_cost:\r\n self.best_solutions.append(sample_tour)\r\n\r\n elif sample_cost > self._best_cost:\r\n self.best_solutions = [sample_tour]\r\n self._best_cost = sample_cost\r\n \r\n best_cost = property(_get_best_cost)\r\n" ]
[ [ "numpy.concatenate", "numpy.array", "numpy.random.permutation" ] ]
zafir-stojanovski/laser-hockey
[ "c0b21b5c9704554638e9f45c42b751d156bdc260" ]
[ "utils/utils.py" ]
[ "import numpy as np\nfrom matplotlib import pyplot as plt\nfrom pathlib import Path\nimport pickle\nimport shutil\nfrom tabulate import tabulate\nimport random\nfrom copy import deepcopy\nfrom laserhockey.hockey_env import CENTER_X, CENTER_Y, SCALE\n\n\ndef running_mean(x, N):\n cumsum = np.cumsum(np.insert(x, 0, 0))\n return (cumsum[N:] - cumsum[:-N]) / float(N)\n\n\ndef soft_update(target, source, tau):\n for target_param, param in zip(target.parameters(), source.parameters()):\n target_param.data.copy_(\n target_param.data * (1.0 - tau) + param.data * tau\n )\n\n\ndef hard_update(target, source):\n for target_param, param in zip(target.parameters(), source.parameters()):\n target_param.data.copy_(param.data)\n\n\ndef poll_opponent(opponents):\n return random.choice(opponents)\n\n\ndef dist_positions(p1, p2):\n return np.sqrt(np.sum(np.asarray(p1 - p2) ** 2, axis=-1))\n\n\ndef compute_reward_closeness_to_puck(transition):\n observation = np.asarray(transition[2])\n reward_closeness_to_puck = 0\n if (observation[-6] + CENTER_X) < CENTER_X and observation[-4] <= 0:\n dist_to_puck = dist_positions(observation[:2], observation[-6:-4])\n max_dist = 250. / SCALE\n max_reward = -30. # max (negative) reward through this proxy\n factor = max_reward / (max_dist * 250 / 2)\n reward_closeness_to_puck += dist_to_puck * factor # Proxy reward for being close to puck in the own half\n\n return reward_closeness_to_puck\n\n\ndef compute_winning_reward(transition, is_player_one):\n r = 0\n\n if transition[4]:\n if transition[5]['winner'] == 0: # tie\n r += 0\n elif transition[5]['winner'] == 1 and is_player_one: # you won\n r += 10\n elif transition[5]['winner'] == -1 and not is_player_one:\n r += 10\n else: # opponent won\n r -= 10\n return r\n\n\ndef recompute_rewards(match, username):\n transitions = match['transitions']\n is_player_one = match['player_one'] == username\n new_transitions = []\n for transition in transitions:\n new_transition = list(deepcopy(transition))\n new_transition[3] = compute_winning_reward(transition, is_player_one) + \\\n compute_reward_closeness_to_puck(transition)\n new_transition[5]['reward_closeness_to_puck']\n new_transitions.append(tuple(new_transition))\n\n return new_transitions\n\n\nclass Logger:\n \"\"\"\n The Logger class is used printing statistics, saving/loading models and plotting.\n\n Parameters\n ----------\n prefix_path : Path\n The variable is used for specifying the root of the path where the plots and models are saved.\n mode: str\n The variable specifies in which mode we are currently running. (shooting | defense | normal)\n cleanup: bool\n The variable specifies whether the logging folder should be cleaned up.\n quiet: boolean\n This variable is used to specify whether the prints are hidden or not.\n \"\"\"\n\n def __init__(self, prefix_path, mode, cleanup=False, quiet=False) -> None:\n self.prefix_path = Path(prefix_path)\n\n self.agents_prefix_path = self.prefix_path.joinpath('agents')\n self.plots_prefix_path = self.prefix_path.joinpath('plots')\n self.arrays_prefix_path = self.prefix_path.joinpath('arrays')\n\n self.prefix_path.mkdir(exist_ok=True)\n\n if cleanup:\n self._cleanup()\n\n self.quiet = quiet\n\n if not self.quiet:\n print(f\"Running in mode: {mode}\")\n\n def info(self, message):\n print(message)\n\n def save_model(self, model, filename):\n savepath = self.agents_prefix_path.joinpath(filename).with_suffix('.pkl')\n with open(savepath, 'wb') as outp:\n pickle.dump(model, outp, pickle.HIGHEST_PROTOCOL)\n\n def print_episode_info(self, game_outcome, episode_counter, step, total_reward, epsilon=None, touched=None,\n opponent=None):\n if not self.quiet:\n padding = 8 if game_outcome == 0 else 0\n msg_string = '{} {:>4}: Done after {:>3} steps. \\tReward: {:<15}'.format(\n \" \" * padding, episode_counter, step + 1, round(total_reward, 4))\n\n if touched is not None:\n msg_string = '{}Touched: {:<15}'.format(msg_string, int(touched))\n\n if epsilon is not None:\n msg_string = '{}Eps: {:<5}'.format(msg_string, round(epsilon, 2))\n\n if opponent is not None:\n msg_string = '{}\\tOpp: {}'.format(msg_string, opponent)\n\n print(msg_string)\n\n def print_stats(self, rew_stats, touch_stats, won_stats, lost_stats):\n if not self.quiet:\n print(tabulate([['Mean reward', np.around(np.mean(rew_stats), 3)],\n ['Mean touch', np.around(np.mean(list(touch_stats.values())), 3)],\n ['Mean won', np.around(np.mean(list(won_stats.values())), 3)],\n ['Mean lost', np.around(np.mean(list(lost_stats.values())), 3)]], tablefmt='grid'))\n\n def load_model(self, filename):\n if filename is None:\n load_path = self.agents_prefix_path.joinpath('agent.pkl')\n else:\n load_path = Path(filename)\n with open(load_path, 'rb') as inp:\n return pickle.load(inp)\n\n def hist(self, data, title, filename=None, show=True):\n plt.figure()\n plt.hist(data, density=True)\n plt.title(title)\n\n plt.savefig(self.reward_prefix_path.joinpath(filename).with_suffix('.pdf'))\n if show:\n plt.show()\n plt.close()\n\n def plot_running_mean(self, data, title, filename=None, show=True, v_milestones=None):\n data_np = np.asarray(data)\n mean = running_mean(data_np, 1000)\n self._plot(mean, title, filename, show)\n\n def plot_evaluation_stats(self, data, eval_freq, filename):\n style = {\n 'weak': 'dotted',\n 'strong': 'solid'\n }\n\n xlen = 0\n for opponent in data.keys():\n stats = data[opponent]\n xlen = len(stats['won'])\n x = np.arange(eval_freq, eval_freq * xlen + 1, eval_freq)\n plt.plot(\n x,\n stats['won'],\n label=f'Won vs {opponent} opponent',\n color='blue',\n linestyle=style[opponent]\n )\n plt.plot(\n x,\n stats['lost'],\n label=f'Lost vs {opponent} opponent',\n color='red',\n linestyle=style[opponent]\n )\n\n self.to_csv(stats['won'], f'{opponent}_won')\n\n ticks = labels = np.arange(eval_freq, eval_freq * xlen + 1, eval_freq)\n plt.xticks(ticks, labels, rotation=45)\n plt.ylim((0, 1))\n plt.xlim((eval_freq, xlen * eval_freq))\n plt.title('Evaluation statistics')\n plt.xlabel('Number of training episodes')\n plt.ylabel('Percentage of lost/won games in evaluation')\n\n lgd = plt.legend(bbox_to_anchor=(1.5, 1))\n plt.savefig(\n self.plots_prefix_path.joinpath(filename).with_suffix('.pdf'),\n bbox_extra_artists=(lgd,),\n bbox_inches='tight'\n )\n plt.close()\n\n def plot(self, data, title, filename=None, show=True):\n self._plot(data, title, filename, show)\n\n def plot_intermediate_stats(self, data, show=True):\n self._plot((data[\"won\"], data[\"lost\"]), \"Evaluation won vs loss\", \"evaluation-won-loss\", show, ylim=(0, 1))\n\n for key in data.keys() - [\"won\", \"lost\"]:\n title = f'Evaluation {key} mean'\n filename = f'evaluation-{key}.pdf'\n\n self._plot(data[key], title, filename, show)\n\n def _plot(self, data, title, filename=None, show=True, ylim=None, v_milestones=None):\n plt.figure()\n # Plotting Won vs lost\n if isinstance(data, tuple):\n plt.plot(data[0], label=\"Won\", color=\"blue\")\n plt.plot(data[1], label=\"Lost\", color='red')\n plt.ylim(*ylim)\n plt.legend()\n else:\n plt.plot(data)\n plt.title(title)\n\n if v_milestones is not None:\n plt.vlines(\n v_milestones,\n linestyles='dashed',\n colors='orange',\n label='Added self as opponent',\n linewidths=0.5,\n ymin=np.min(data),\n ymax=np.max(data)\n )\n\n plt.savefig(self.plots_prefix_path.joinpath(filename).with_suffix('.pdf'))\n if show:\n plt.show()\n\n plt.close()\n\n def to_csv(self, data, filename):\n savepath = self.arrays_prefix_path.joinpath(filename).with_suffix('.csv')\n np.savetxt(savepath, data, delimiter=',')\n\n def save_array(self, data, filename):\n savepath = self.arrays_prefix_path.joinpath(filename).with_suffix('.pkl')\n with open(savepath, 'wb') as outp:\n pickle.dump(data, outp, pickle.HIGHEST_PROTOCOL)\n\n def load_array(self, filename):\n loadpath = self.arrays_prefix_path.joinpath(filename).with_suffix('.pkl')\n with open(loadpath, 'rb') as inp:\n return pickle.load(inp)\n\n def _cleanup(self):\n shutil.rmtree(self.agents_prefix_path, ignore_errors=True)\n shutil.rmtree(self.plots_prefix_path, ignore_errors=True)\n shutil.rmtree(self.arrays_prefix_path, ignore_errors=True)\n self.agents_prefix_path.mkdir(exist_ok=True)\n self.plots_prefix_path.mkdir(exist_ok=True)\n self.arrays_prefix_path.mkdir(exist_ok=True)\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.asarray", "matplotlib.pyplot.plot", "numpy.max", "numpy.mean", "numpy.arange", "numpy.insert", "matplotlib.pyplot.close", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "numpy.min", "matplotlib.pyplot.ylim", "numpy.savetxt", "matplotlib.pyplot.show", "matplotlib.pyplot.hist", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlim", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks" ] ]
ksterx/kxnet
[ "a638c072005549b86f73a734a62d78aeca697df2" ]
[ "utils/analyzer.py" ]
[ "# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.6.0\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# +\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport torch\nimport numpy as np\n\n# import seaborn as sns\n# from data_transformation_euler import vec_similarity\n# -\n\ndef analyzer(pred_df, target_df, savepath, num, size):\n e_trans3d = (\n torch.tensor(pred_df.loc[:, [\"e_x\", \"e_y\", \"e_z\"]].values)\n .norm(dim=1, keepdim=True)\n .numpy()\n )\n a = torch.tensor(pred_df.loc[:, [\"e_x_2d\", \"e_y_2d\"]].values)\n a[:, 0], a[:, 1] = a[:, 0] * size[0], a[:, 1] * size[1]\n e_trans2d = a.norm(dim=1, keepdim=True).numpy()\n\n n_pred = torch.tensor(pred_df.loc[:, [\"nx\", \"ny\", \"nz\"]].values)\n n_target = torch.tensor(target_df.loc[:, [\"nx\", \"ny\", \"nz\"]].values)\n _, e_orient = vec_similarity(n_pred, n_target)\n\n pred_df = pred_df.join(\n pd.DataFrame(\n np.concatenate([e_trans3d, e_trans2d, e_orient.numpy()], 1),\n columns=[\"e_trans3d\", \"e_trans2d\", \"e_orient\"],\n )\n )\n\n # The roll error must be in the range; [-180, 180]\n for i in range(len(pred_df)):\n if pred_df.at[i, \"e_gamma\"] > 180:\n pred_df.at[i, \"e_gamma\"] = pred_df.at[i, \"e_gamma\"] - 360\n\n elif pred_df.at[i, \"e_gamma\"] < -180:\n pred_df.at[i, \"e_gamma\"] = 360 + pred_df.at[i, \"e_gamma\"]\n\n pred_df.to_csv(savepath + \"/pred_{:03d}.csv\".format(num), index=False)\n\n report = \"\"\"\n Error MAE SD\n ===================================\n 3D [mm]: %.2f %.2f\n 2D [px]: %.2f %.2f\n Orient [deg]: %.2f %.2f\n Joint [deg]: %.2f %.2f\n Rotate [deg]: %.2f %.2f\n \"\"\" % (\n pred_df[\"e_trans3d\"].mean(),\n pred_df[\"e_trans3d\"].std(),\n pred_df[\"e_trans2d\"].mean(),\n pred_df[\"e_trans2d\"].std(),\n abs(pred_df[\"e_orient\"]).mean(),\n pred_df[\"e_orient\"].std(),\n abs(pred_df[\"e_phi\"]).mean(),\n pred_df[\"e_phi\"].std(),\n abs(pred_df[\"e_gamma\"]).mean(),\n pred_df[\"e_gamma\"].std(),\n )\n\n with open(savepath + \"/report.md\", mode=\"w\") as f:\n f.write(report)\n\n print(report)\n\n\ndef vec_similarity(a, b):\n cosine = (a * b).sum(dim=1, keepdim=True) / (\n torch.norm(a, dim=1, keepdim=True) * torch.norm(b, dim=1, keepdim=True)\n )\n angle = cosine.acos() * 180 / np.pi\n\n return cosine, angle\n\n\nif __name__ == \"__main__\":\n p_path = input(\"pred_xxx.csv path: \")\n t_path = input(\"val_xxx.csv path: \")\n s_path = input(\"artifact path: \")\n ds_num = int(input(\"Dataset: #\"))\n p_df = pd.read_csv(p_path)\n t_df = pd.read_csv(t_path)\n analyzer(p_df, t_df, s_path, ds_num, (224, 224))\n\n\n" ]
[ [ "pandas.read_csv", "torch.norm", "torch.tensor" ] ]
wszenic/rl-collaborative-agents
[ "a89e8f3abb19313fe6666551f5985c0a3ed0523c" ]
[ "main.py" ]
[ "import logging\nimport os\n\nimport click\nimport neptune.new as neptune\nimport numpy as np\nimport optuna\nfrom unityagents import UnityEnvironment\n\nfrom src.agents.maddpg import MADDPGAgent\nfrom src.config.config import settings\nfrom src.structs import EnvFeedback\n\n\[email protected](chain=True, invoke_without_command=True)\ndef run():\n logging.info(\"Running the ml-monitoring project\")\n\n\[email protected](\"evaluate\", short_help=\"Run the agent based on saved weights\")\ndef evaluate():\n logging.info(\"Setting up the environment for evaluation\")\n env, multi_agent, scores, brain_name = setup_environment(read_saved_model=True, no_graphics=False)\n\n env_info = env.reset(train_mode=False)[brain_name]\n start_state = env_info.vector_observations\n\n score = act_during_episode(multi_agent, env, start_state, brain_name, use_noise=False)\n print(f\"Evaluation score = {score}\")\n env.close()\n\n\[email protected](\"optimize\", short_help='Train with hyperparameter optimization')\ndef optimize():\n study = optuna.create_study(direction='maximize')\n study.optimize(run_with_suggested_settings, n_trials=200, gc_after_trial=True, n_jobs=1)\n\n\ndef run_with_suggested_settings(trial):\n global settings\n settings.epochs_with_noise = trial.suggest_int('epochs_with_noise', 0, 1000)\n settings.actor_learning_rate = trial.suggest_loguniform('actor_learning_rate', 1e-6, 1e-1)\n settings.critic_learning_rate = trial.suggest_loguniform('critic_learning_rate', 1e-6, 1e-1)\n settings.gamma = trial.suggest_float('gamma', 0.5, 0.9999)\n settings.tau = trial.suggest_loguniform('tau', 1e-5, 1e-1)\n settings.update_freq = trial.suggest_int('update_freq', 0, 500)\n settings.actor_size_1 = trial.suggest_int('actor_size_1', 64, 1024)\n settings.actor_size_2 = trial.suggest_int('actor_size_2', 64, 1024)\n settings.critic_size_1 = trial.suggest_int('critic_size_1', 64, 1024)\n settings.critic_size_2 = trial.suggest_int('critic_size_2', 64, 1024)\n settings.batch_size = trial.suggest_int('batch_size', 12, 2048)\n settings.buffer_size = trial.suggest_int('buffer_size', 1e5, 1e8)\n settings.alpha = trial.suggest_float('alpha', float(0), float(1))\n settings.beta = trial.suggest_float('beta', float(0), float(1))\n settings.noise_std = trial.suggest_float('noise_std', float(0), float(1))\n\n return objective(log=True)\n\n\[email protected](\"train\", short_help=\"Train the reinforcement learning model\")\[email protected](\n \"-l\",\n \"--log\",\n help=\"Flag whether the experiment should be logged to neptune.ai\",\n required=False\n)\ndef train(log: bool):\n best_score = objective(log)\n print(f\"Best score = {best_score}\")\n\n\ndef objective(log: bool = True):\n best_average = 0\n env, multi_agent, scores, brain_name = setup_environment(read_saved_model=False, no_graphics=True)\n use_noise = True\n if log:\n neptune_log = log_to_neptune()\n\n for episode in range(settings.max_epoch):\n if episode > settings.epochs_with_noise:\n use_noise = False\n env_info = env.reset(train_mode=True)[brain_name]\n multi_agent.reset()\n start_state = env_info.vector_observations\n score = act_during_episode(multi_agent, env, start_state, brain_name, use_noise)\n\n if log:\n neptune_log['best_average'].log(np.mean(scores[-100:]))\n neptune_log['score'].log(score)\n scores.append(score)\n\n episode_score = np.mean(scores[-100:])\n\n if episode % 1 == 0:\n print(\n f\"Ep: {episode} | Score: {score:.2f} | Max: {np.max(scores):.2f} \"\n f\"| Avg: {episode_score:.4f}\")\n\n if episode_score > best_average:\n best_average = episode_score\n if episode % settings.checkpoint_every == 0:\n multi_agent.save()\n\n if log:\n neptune_log.stop()\n multi_agent.save()\n env.close()\n\n return best_average\n\n\ndef setup_environment(read_saved_model=False, no_graphics=True):\n env = UnityEnvironment(file_name=settings.unity_env_location, no_graphics=no_graphics)\n brain_name = env.brain_names[0]\n brain = env.brains[brain_name]\n\n env_info = env.reset(train_mode=True)[brain_name]\n\n state = env_info.vector_observations[0]\n\n multi_agent = MADDPGAgent(state_size=len(state), action_size=brain.vector_action_space_size,\n read_saved_model=read_saved_model)\n\n scores = []\n\n return env, multi_agent, scores, brain_name\n\n\ndef act_during_episode(multi_agent, env, state, brain_name, use_noise):\n score = []\n while True:\n action = multi_agent.act(state, use_noise)\n\n env_info = env.step(action)[brain_name]\n\n env_response = EnvFeedback(state, action, env_info.rewards, env_info.vector_observations,\n env_info.local_done)\n\n multi_agent.step(env_response)\n\n score += [env_response.reward]\n state = env_response.next_state\n if any(env_response.done):\n break\n return np.max(np.sum(np.array(score), axis=0))\n\n\ndef log_to_neptune():\n neptune_run = neptune.init(\n project=\"wsz/RL-Tenis\",\n api_token=os.getenv('NEPTUNE_TOKEN')\n )\n\n neptune_run['parameters'] = {\n 'ACTOR_LEARNING_RATE': settings.actor_learning_rate,\n 'CRITIC_LEARNING_RATE': settings.critic_learning_rate,\n 'GAMMA': settings.gamma,\n 'TAU': settings.tau,\n 'BATCH_SIZE': settings.batch_size,\n 'ACTOR_MID_1': settings.actor_size_1,\n 'ACTOR_MID_2': settings.actor_size_2,\n 'CRITIC_CONCAT_1': settings.critic_size_1,\n 'CRITIC_CONCAT_2': settings.critic_size_2,\n 'EPOCHS_WITH_NOISE': settings.epochs_with_noise,\n 'BUFFER_SIZE': settings.buffer_size,\n 'ALPHA': settings.alpha,\n 'BETA': settings.beta,\n 'NOISE_STD': settings.noise_std,\n 'UPDATE_FREQ': settings.update_freq\n }\n return neptune_run\n\n\nif __name__ == \"__main__\":\n run()\n" ]
[ [ "numpy.max", "numpy.array", "numpy.mean" ] ]
eslavich/MiriTE
[ "05e25e1222e854fef5a72011f6618fa8fb5eaaff" ]
[ "miri/datamodels/miri_flatfield_model.py" ]
[ "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\"\"\"\n\nAn extension to the standard STScI data model for MIRI pixel flat-field \ndata. Essentially the same as the MIRI measured data model.\n\n:Reference:\n\nThe STScI jwst.datamodels documentation. See\nhttps://jwst-pipeline.readthedocs.io/en/latest/jwst/datamodels/index.html\n\n:History:\n\n10 Jan 2013: Created\n21 Jan 2013: Included data type in metadata.\n05 Feb 2013: Reformatted test code using \"with\" context manager.\n Modified to use functions from MiriDataModel.\n08 Feb 2013: Replaced 'to_fits' with more generic 'save' method.\n19 Feb 2013: Changed MiriImageModel to MiriMeasuredModel to allow\n flat field cubes (Vincent Geers, DIAS).\n10 Dec 2013: Delimiter in MIRI schema names changed from \".\" to \"_\".\n09 Jul 2014: JWST reference flags table added.\n29 Aug 2014: Included new reference file keywords (REFTYPE, AUTHOR, PEDIGREE)\n25 Sep 2014: Updated the reference flags. insert_value_column function\n used to convert between 3 column and 4 column flag tables.\n TYPE and REFTYPE are no longer identical.\n13 Oct 2014: Re-instated SKYFLAT as valid type, for MIRI Imager.\n09 Dec 2014: Metadata added to example data product.\n11 Mar 2015: group_integration_time changed to group_time.\n20 Aug 2015: Duplicated parts of schema now reference STScI model.\n20 Nov 2015: Resurrected the PIXELFLAT option.\n16 Feb 2016: Default pedigree for SKYFLAT changed from 'GROUND' to 'DUMMY'.\n23 Mar 2016: Set default fill value to 1.0.\n08 Jun 2016: Corrected typo in set_exposure_type. Added \"detector\" to\n constructor arguments.\n15 Jun 2017: meta.reffile schema level removed to match changes in the\n JWST build 7.1 data models release. meta.reffile.type also\n changed to meta.reftype. TYPE keyword replaced by DATAMODL.\n Do not set observation or target metadata. Neither are\n appropriate for a reference file.\n12 Jul 2017: Replaced \"clobber\" parameter with \"overwrite\".\n17 Nov 2017: Added more DQ flags.\n26 Sep 2018: Added a REFTYPE of 'FLAT-TA' for an on-board TA flat field,\n with DATATYPE defined as 'TARGET'.\n30 Oct 2018: Reimplemented the flatfield models so the different varieties\n are distinguished by inheritance rather than a constructor\n parameter. PIXELFLAT is no longer used.\n30 Jan 2019: self.meta.model_type now set to the name of the STScI data\n model this model is designed to match (skipped if there isn't\n a corresponding model defined in ancestry.py).\n08 Feb 2019: Update the PEDIGREE keyword if the flat type changes, regardless\n of what has been read from the file.\n07 Oct 2019: Updated flat_reference_flags to include only standard flag\n names. Removed '.yaml' suffix from schema references.\n26 Mar 2020: Ensure the model_type remains as originally defined when saving\n to a file.\n \n@author: Steven Beard (UKATC), Vincent Geers (UKATC)\n\n\"\"\"\n\nimport warnings\nimport numpy as np\n#import numpy.ma as ma\n\n# Import the MIRI measured data model.\nfrom miri.datamodels.ancestry import get_my_model_type\nfrom miri.datamodels.dqflags import insert_value_column\nfrom miri.datamodels.miri_measured_model import MiriMeasuredModel, HasDataErrAndDq\n\n# List all classes and global functions here.\n__all__ = ['flat_reference_flags', 'MiriFlatfieldModel',\n 'MiriTargetFlatfieldModel', 'MiriFringeFlatfieldModel',\n 'MiriTargetFlatfieldModel']\n\n# The new JWST flat-field reference flags\nflat_reference_setup = \\\n [(0, 'DO_NOT_USE', 'Bad pixel. Do not use.'),\n (1, 'NON_SCIENCE', 'Pixel not on science portion of detector'),\n (2, 'UNRELIABLE_FLAT', 'Flat variance large'),\n (3, 'DROPOUT', 'Data derived from incomplete input'), # Was CDP_PARTIAL_DATA \n (4, 'UNRELIABLE_SLOPE', 'Data of low quality'), # Was CDP_LOW_QUAL\n (5, 'UNRELIABLE_ERROR', 'Data without reliable error estimate'),\n (6, 'NO_FLAT_FIELD', 'No flat-field data available'),\n (7, 'OTHER_BAD_PIXEL', 'Diffraction pattern')] # Was DIFF_PATTERN\nflat_reference_flags = insert_value_column( flat_reference_setup )\n\n\nclass MiriFlatfieldModel(MiriMeasuredModel):\n \"\"\"\n \n A data model for MIRI flat-field data.\n \n :Parameters:\n \n init: shape tuple, file path, file object, pyfits.HDUList, numpy array\n An optional initializer for the data model, which can have one\n of the following forms:\n \n * None: A default data model with no shape. (If a data array is\n provided in the mask parameter, the shape is derived from the\n array.)\n * Shape tuple: Initialize with empty data of the given shape.\n * File path: Initialize from the given file.\n * Readable file object: Initialize from the given file object.\n * pyfits.HDUList: Initialize from the given pyfits.HDUList.\n \n data: numpy array (optional)\n An array containing the flat-field data.\n If a data parameter is provided, its contents overwrite the\n data initialized by the init parameter.\n err: numpy array (optional)\n An array containing the error data.\n Must be broadcastable onto the data array.\n dq: numpy array (optional)\n An array containing the quality data.\n Must be broadcastable onto the data array.\n dq_def: list of tuples or numpy record array (optional)\n Either: A list of tuples containing (value:int, name:str, title:str),\n giving the meaning of values stored in the data quality array. For\n example: [(0, 'good','Good data'), (1, 'dead', 'Dead Pixel'),\n (2, 'hot', 'Hot Pixel')];\n Or: A numpy record array containing the same information as above.\n If not specified, it will default to the MIRI reserved flags.\n flattype: str (optional)\n A string giving the specific kind of flat-field contained\n in the data object: 'SkyFlat', 'PixelFlat' or 'FringeFlat' or 'Target'.\n If not given, the type defaults to the generic term 'FLAT'.\n detector: str (optional)\n The name of the detector associated with this fiat-field data.\n \\*\\*kwargs:\n All other keyword arguments are passed to the DataModel initialiser.\n See the jwst.datamodels documentation for the meaning of these keywords.\n \n \"\"\"\n # All flat-field models use exactly the same schema.\n schema_url = \"miri_flatfield.schema\"\n _default_dq_def = flat_reference_flags\n\n def __init__(self, init=None, data=None, dq=None, err=None,\n dq_def=None, flattype='', detector=None, **kwargs):\n \"\"\"\n \n Initialises the MiriFlatfieldModel class.\n \n Parameters: See class doc string.\n\n \"\"\"\n super(MiriFlatfieldModel, self).__init__(init=init, data=data,\n dq=dq, err=err,\n dq_def=dq_def, **kwargs)\n # Missing sections of the flat-field should be filled with 1.0\n HasDataErrAndDq.set_data_fill( self, 1.0 )\n\n # Data type is flat-field.\n datatype = 'FLAT'\n update_pedigree = False\n if not flattype:\n # Set to the default type, if not already defined\n if not self.meta.reftype:\n self.meta.reftype = 'FLAT'\n else:\n # Remember the existing reference type, if there is one\n if self.meta.reftype is not None and self.meta.reftype:\n existing_reftype = str(self.meta.reftype)\n else:\n existing_reftype = ''\n\n ftupper = flattype.upper()\n if \"FRINGE\" in ftupper:\n self.meta.reftype = \"FRINGE\"\n elif \"SKY\" in ftupper:\n self.meta.reftype = \"SKYFLAT\"\n elif \"PIX\" in ftupper:\n # The reference type 'PIXELFLAT' is no longer used.\n warnings.warn(\"PIXELFLAT is no longer used. REFTYPE set to FLAT.\")\n self.meta.reftype = \"FLAT\"\n elif \"TA\" in ftupper:\n self.meta.reftype = \"FLAT-TA\"\n datatype = 'TARGET'\n else:\n # Pixel flat is just FLAT. \n self.meta.reftype = \"FLAT\"\n \n # Warn if an existing reference type is being changed.\n if existing_reftype:\n if self.meta.reftype != existing_reftype:\n # Update the PEDIGREE if the flat type has changed.\n update_pedigree = True\n strg = \"Flat-field type will be changed from \\'%s\\' \" % existing_reftype\n strg += \"to \\'%s\\'.\" % str(self.meta.reftype)\n warnings.warn(strg)\n\n # Initialise the model type\n self._init_data_type()\n # This is a reference data model.\n self._reference_model()\n \n # The default pedigree is 'DUMMY' for a sky flat and 'GROUND'\n # for everything else.\n if not self.meta.pedigree or update_pedigree:\n if \"SKY\" in self.meta.reftype:\n self.meta.pedigree = 'DUMMY'\n else:\n self.meta.pedigree = 'GROUND'\n\n # Define the detector identifier, if specified.\n if detector is not None:\n self.meta.instrument.detector = detector\n \n # Define the exposure type (if not already contained in the data model)\n # NOTE: This will only define an exposure type when a valid detector\n # is defined in the metadata.\n if not self.meta.exposure.type:\n self.set_exposure_type( datatype=datatype )\n \n # The fill value for a flat-field is 1.0\n self._data_fill = 1.0\n self._data_fill_value = 1.0\n\n def _init_data_type(self):\n # Initialise the data model type\n model_type = get_my_model_type( self.__class__.__name__ )\n self.meta.model_type = model_type \n\n def on_save(self, path):\n super(MiriFlatfieldModel, self).on_save(path)\n # Re-initialise data type on save\n self._init_data_type()\n\n\nclass MiriSkyFlatfieldModel(MiriFlatfieldModel):\n \"\"\"\n \n A variation of MiriFlatfieldModel used to maintain SKY flats.\n The structure is identical to MiriFlatfieldModel, except the\n REFTYPE is defined as 'SKYFLAT'.\n \n :Parameters:\n \n init: shape tuple, file path, file object, pyfits.HDUList, numpy array\n An optional initializer for the data model, which can have one\n of the following forms:\n \n * None: A default data model with no shape. (If a data array is\n provided in the mask parameter, the shape is derived from the\n array.)\n * Shape tuple: Initialize with empty data of the given shape.\n * File path: Initialize from the given file.\n * Readable file object: Initialize from the given file object.\n * pyfits.HDUList: Initialize from the given pyfits.HDUList.\n \n data: numpy array (optional)\n An array containing the flat-field data.\n If a data parameter is provided, its contents overwrite the\n data initialized by the init parameter.\n err: numpy array (optional)\n An array containing the error data.\n Must be broadcastable onto the data array.\n dq: numpy array (optional)\n An array containing the quality data.\n Must be broadcastable onto the data array.\n dq_def: list of tuples or numpy record array (optional)\n Either: A list of tuples containing (value:int, name:str, title:str),\n giving the meaning of values stored in the data quality array. For\n example: [(0, 'good','Good data'), (1, 'dead', 'Dead Pixel'),\n (2, 'hot', 'Hot Pixel')];\n Or: A numpy record array containing the same information as above.\n If not specified, it will default to the MIRI reserved flags.\n detector: str (optional)\n The name of the detector associated with this fiat-field data.\n \\*\\*kwargs:\n All other keyword arguments are passed to the DataModel initialiser.\n See the jwst.datamodels documentation for the meaning of these keywords.\n \n \"\"\"\n # All flat-field models use exactly the same schema.\n schema_url = \"miri_flatfield.schema\"\n _default_dq_def = flat_reference_flags\n\n def __init__(self, init=None, data=None, dq=None, err=None,\n dq_def=None, detector=None, **kwargs):\n \"\"\"\n \n Initialises the MiriSkyFlatfieldModel class.\n \n Parameters: See class doc string.\n\n \"\"\"\n # Call the parent constructor with the appropriate flat-field type.\n super(MiriSkyFlatfieldModel, self).__init__(init=init, data=data,\n dq=dq, err=err,\n dq_def=dq_def,\n flattype='SKYFLAT',\n detector=detector,\n **kwargs)\n\n\nclass MiriFringeFlatfieldModel(MiriFlatfieldModel):\n \"\"\"\n \n A variation of MiriFlatfieldModel used to maintain FRINGE flats.\n The structure is identical to MiriFlatfieldModel, except the\n REFTYPE is defined as 'FRINGE'.\n\n See MIRI-RP-00510-NLC for information on fringing.\n\n :Parameters:\n \n init: shape tuple, file path, file object, pyfits.HDUList, numpy array\n An optional initializer for the data model, which can have one\n of the following forms:\n \n * None: A default data model with no shape. (If a data array is\n provided in the mask parameter, the shape is derived from the\n array.)\n * Shape tuple: Initialize with empty data of the given shape.\n * File path: Initialize from the given file.\n * Readable file object: Initialize from the given file object.\n * pyfits.HDUList: Initialize from the given pyfits.HDUList.\n \n data: numpy array (optional)\n An array containing the flat-field data.\n If a data parameter is provided, its contents overwrite the\n data initialized by the init parameter.\n err: numpy array (optional)\n An array containing the error data.\n Must be broadcastable onto the data array.\n dq: numpy array (optional)\n An array containing the quality data.\n Must be broadcastable onto the data array.\n dq_def: list of tuples or numpy record array (optional)\n Either: A list of tuples containing (value:int, name:str, title:str),\n giving the meaning of values stored in the data quality array. For\n example: [(0, 'good','Good data'), (1, 'dead', 'Dead Pixel'),\n (2, 'hot', 'Hot Pixel')];\n Or: A numpy record array containing the same information as above.\n If not specified, it will default to the MIRI reserved flags.\n detector: str (optional)\n The name of the detector associated with this fiat-field data.\n \\*\\*kwargs:\n All other keyword arguments are passed to the DataModel initialiser.\n See the jwst.datamodels documentation for the meaning of these keywords.\n \n \"\"\"\n # All flat-field models use exactly the same schema.\n schema_url = \"miri_flatfield.schema\"\n _default_dq_def = flat_reference_flags\n\n def __init__(self, init=None, data=None, dq=None, err=None,\n dq_def=None, detector=None, **kwargs):\n \"\"\"\n \n Initialises the MiriFringeFlatfieldModel class.\n \n Parameters: See class doc string.\n\n \"\"\"\n # Call the parent constructor with the appropriate flat-field type.\n super(MiriFringeFlatfieldModel, self).__init__(init=init, data=data,\n dq=dq, err=err,\n dq_def=dq_def,\n flattype='FRINGE',\n detector=detector,\n **kwargs)\n\n\nclass MiriTargetFlatfieldModel(MiriFlatfieldModel):\n \"\"\"\n \n A variation of MiriFlatfieldModel used to maintain TARGET flats.\n The structure is identical to MiriFlatfieldModel, except the\n REFTYPE is defined as 'TA-FLAT'.\n \n :Parameters:\n \n init: shape tuple, file path, file object, pyfits.HDUList, numpy array\n An optional initializer for the data model, which can have one\n of the following forms:\n \n * None: A default data model with no shape. (If a data array is\n provided in the mask parameter, the shape is derived from the\n array.)\n * Shape tuple: Initialize with empty data of the given shape.\n * File path: Initialize from the given file.\n * Readable file object: Initialize from the given file object.\n * pyfits.HDUList: Initialize from the given pyfits.HDUList.\n \n data: numpy array (optional)\n An array containing the flat-field data.\n If a data parameter is provided, its contents overwrite the\n data initialized by the init parameter.\n err: numpy array (optional)\n An array containing the error data.\n Must be broadcastable onto the data array.\n dq: numpy array (optional)\n An array containing the quality data.\n Must be broadcastable onto the data array.\n dq_def: list of tuples or numpy record array (optional)\n Either: A list of tuples containing (value:int, name:str, title:str),\n giving the meaning of values stored in the data quality array. For\n example: [(0, 'good','Good data'), (1, 'dead', 'Dead Pixel'),\n (2, 'hot', 'Hot Pixel')];\n Or: A numpy record array containing the same information as above.\n If not specified, it will default to the MIRI reserved flags.\n detector: str (optional)\n The name of the detector associated with this fiat-field data.\n \\*\\*kwargs:\n All other keyword arguments are passed to the DataModel initialiser.\n See the jwst.datamodels documentation for the meaning of these keywords.\n \n \"\"\"\n # All flat-field models use exactly the same schema.\n schema_url = \"miri_flatfield.schema\"\n _default_dq_def = flat_reference_flags\n\n def __init__(self, init=None, data=None, dq=None, err=None,\n dq_def=None, detector=None, **kwargs):\n \"\"\"\n \n Initialises the MiriTargetFlatfieldModel class.\n \n Parameters: See class doc string.\n\n \"\"\"\n # Call the parent constructor with the appropriate flat-field type.\n super(MiriTargetFlatfieldModel, self).__init__(init=init, data=data,\n dq=dq, err=err,\n dq_def=dq_def,\n flattype='TA',\n detector=detector,\n **kwargs)\n\n#\n# A minimal test is run when this file is run as a main program.\n# For a more substantial test see miri/datamodels/tests.\n#\nif __name__ == '__main__':\n print(\"Testing the MiriFlatfieldModel module.\")\n\n PLOTTING = False\n SAVE_FILES = False\n\n data3x3 = np.array([[1.0,1.2,1.1],[1.3,1.2,1.0],[1.1,0.8,0.9]])\n err3x3 = np.array([[1.,1.,1.],[2.,2.,2.],[1.,1.,1.]])\n dq3x3 = np.array([[0,1,0],[1,0,1],[0,1,0]])\n\n print(\"\\nFlat-field data with data + err + dq:\")\n with MiriFlatfieldModel(data=data3x3, err=err3x3, dq=dq3x3,\n dq_def=flat_reference_flags) as testdata:\n # Add some example metadata.\n testdata.set_instrument_metadata(detector='MIRIFUSHORT',\n channel='1',\n ccc_pos='OPEN',\n deck_temperature=11.0,\n detector_temperature=6.0)\n testdata.set_exposure_metadata(readpatt='FAST',\n nints=1, ngroups=1,\n frame_time=1.0,\n integration_time=10.0,\n group_time=10.0,\n reset_time=0, frame_resets=3)\n testdata.set_subarray_metadata('FULL')\n testdata.set_housekeeping_metadata('UK', author='MIRI team',\n version='1.0', date='TODAY',\n useafter='',\n description='Test data')\n print(testdata)\n print(\"Filled data:\\n\", testdata.data_filled)\n if PLOTTING:\n testdata.plot(description=\"testdata\")\n if SAVE_FILES:\n testdata.save(\"test_flatfield_model1.fits\", overwrite=True)\n del testdata\n\n print(\"\\nFRINGE Flat-field data with data + err + dq:\")\n with MiriFringeFlatfieldModel(data=data3x3, err=err3x3, dq=dq3x3,\n dq_def=flat_reference_flags,\n detector='MIRIFUSHORT') as testdata2:\n # Add some example metadata.\n testdata2.set_instrument_metadata(detector='MIRIFUSHORT',\n channel='1',\n ccc_pos='OPEN',\n deck_temperature=11.0,\n detector_temperature=6.0)\n testdata2.set_exposure_metadata(readpatt='FAST',\n nints=1, ngroups=1,\n frame_time=1.0,\n integration_time=10.0,\n group_time=10.0,\n reset_time=0, frame_resets=3)\n testdata2.set_subarray_metadata('FULL')\n testdata2.set_housekeeping_metadata('UK', author='MIRI team',\n version='1.0', date='TODAY',\n useafter='',\n description='Test data')\n print(testdata2)\n print(\"Filled data:\\n\", testdata2.data_filled)\n if PLOTTING:\n testdata2.plot(description=\"testdata2\")\n if SAVE_FILES:\n testdata2.save(\"test_flatfield_model2.fits\", overwrite=True)\n del testdata2\n\n print(\"Test finished.\")\n" ]
[ [ "numpy.array" ] ]
kaharjan/xalpha
[ "66f0fe574c6dfc1eef836e4d13e9eced0b995a30" ]
[ "xalpha/realtime.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nmodule for realtime watch and notfication\n\"\"\"\n# deprecated\n# 该模块与现在的主线进展关系不大,可用性不强,\n# xalpha 不应过度干涉通知或可能的自动交易部分\n# 因此该模块可能随时不再支持\n\nimport datetime as dt\nimport smtplib\nfrom email.header import Header\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr, parseaddr\nfrom re import match\nimport pandas as pd\n\nfrom xalpha.cons import today_obj, rget\nfrom xalpha.info import fundinfo\nfrom xalpha.trade import trade\n\n\ndef _format_addr(s):\n \"\"\"\n parse the email sender and receiver, Chinese encode and support\n\n :param s: eg. 'name <[email protected]>, name2 <[email protected]>'\n \"\"\"\n name, addr = parseaddr(s)\n return formataddr((Header(name, \"utf-8\").encode(), addr))\n\n\ndef mail(\n title,\n content,\n sender=None,\n receiver=None,\n password=None,\n server=None,\n port=None,\n sender_name=\"sender\",\n receiver_name=None,\n):\n \"\"\"\n send email\n\n :param title: str, title of the email\n :param content: str, content of the email, plain text only\n :param conf: all other paramters can be import as a dictionay, eg.conf = {'sender': '[email protected]',\n 'sender_name':'name', 'receiver':['[email protected]','[email protected]'], 'password':'123456',\n 'server':'smtp.bb.com','port':123, 'receiver_name':['me','guest']}.\n The receiver_name and sender_name options can be omitted.\n \"\"\"\n ret = True\n try:\n if receiver_name is None:\n receiver_name = [\"receiver\" for _ in receiver]\n msg = MIMEText(content, \"plain\", \"utf-8\")\n msg[\"From\"] = _format_addr(\"%s <%s>\" % (sender_name, sender))\n # 括号里的对应发件人邮箱昵称、发件人邮箱账号\n receivestr = \"\"\n for i, s in enumerate(receiver):\n receivestr += receiver_name[i]\n receivestr += \" <\"\n receivestr += s\n receivestr += \">, \"\n msg[\"To\"] = _format_addr(receivestr) # 括号里的对应收件人邮箱昵称、收件人邮箱账号\n msg[\"Subject\"] = title # 邮件的主题,即标题\n\n server = smtplib.SMTP_SSL(server, port) # 发件人邮箱中的SMTP服务器和端口号\n server.login(sender, password) # 括号中对应的是发件人邮箱账号、邮箱密码\n server.sendmail(\n sender, receiver, msg.as_string()\n ) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件\n server.quit()\n except Exception:\n ret = False\n return ret\n\n\nclass rtdata:\n \"\"\"\n get real time data of specific funds\n\n :param code: string of six digitals for funds\n \"\"\"\n\n def __init__(self, code):\n url = \"http://fundgz.1234567.com.cn/js/\" + code + \".js\"\n page = rget(url)\n self.code = code\n self.rtvalue = float(match(r'.*\"gsz\":\"(\\d*\\.\\d*)\",.*', page.text)[1])\n self.name = match(r'.*\"name\":\"([^,]*)\",.*', page.text)[1]\n self.time = dt.datetime.strptime(\n match(r'.*\"gztime\":\"([\\d\\s\\-\\:]*)\".*', page.text)[1], \"%Y-%m-%d %H:%M\"\n )\n\n\ndef rfundinfo(\n code, round_label=0, dividend_label=0, fetch=False, save=False, path=\"\", form=\"csv\"\n):\n \"\"\"\n give a fundinfo object with todays estimate netvalue at running time\n\n :param code: string of six digitals for funds\n :param fetch: boolean, when open the fetch option, info class will try fetching from local files first in the init\n :param save: boolean, when open the save option, info classes automatically save the class to files\n :param path: string, the file path prefix of IO\n :param form: string, the format of IO, options including: 'csv'\n :returns: the fundinfo object\n \"\"\"\n fundobj = fundinfo(\n code,\n round_label=round_label,\n dividend_label=dividend_label,\n fetch=fetch,\n save=save,\n path=path,\n form=form,\n )\n rt = rtdata(code)\n rtdate = dt.datetime.combine(rt.time, dt.time.min)\n rtvalue = rt.rtvalue\n if (rtdate - fundobj.price.iloc[-1].date).days > 0:\n fundobj.price = fundobj.price.append(\n pd.DataFrame(\n [[rtdate, rtvalue, fundobj.price.iloc[-1].totvalue, 0]],\n columns=[\"date\", \"netvalue\", \"totvalue\", \"comment\"],\n ),\n ignore_index=True,\n )\n return fundobj\n\n\nclass review:\n \"\"\"\n review policys and give the realtime purchase suggestions\n\n :param policylist: list of policy object\n :param namelist: list of names of corresponding policy, default as 0 to n-1\n :param date: object of datetime, check date, today is prefered, date other than is not guaranteed\n \"\"\"\n\n def __init__(self, policylist, namelist=None, date=today_obj()):\n self.warn = []\n self.message = []\n self.policylist = policylist\n if namelist is None:\n self.namelist = [i for i in range(len(policylist))]\n else:\n self.namelist = namelist\n assert len(self.policylist) == len(self.namelist)\n for i, policy in enumerate(policylist):\n row = policy.status[policy.status[\"date\"] == date]\n if len(row) == 1:\n warn = (\n policy.aim.name,\n policy.aim.code,\n row.iloc[0].loc[policy.aim.code],\n self.namelist[i],\n )\n self.warn.append(warn)\n if warn[2] > 0:\n sug = \"买入%s元\" % warn[2]\n elif warn[2] < 0:\n ratio = -warn[2] / 0.005 * 100\n share = (\n trade(fundinfo(warn[1]), policy.status)\n .briefdailyreport()\n .get(\"currentshare\", 0)\n )\n share = -warn[2] / 0.005 * share\n sug = \"卖出%s%%的份额,也即%s份额\" % (ratio, share)\n self.message.append(\n \"根据%s计划,建议%s,%s(%s)\" % (warn[3], sug, warn[0], warn[1])\n )\n self.content = \"\\n\".join(map(str, self.message))\n\n def __str__(self):\n return self.content\n\n def notification(self, conf):\n \"\"\"\n send email of self.content, at least support for qq email sender\n\n :param conf: the configuration dictionary for email send settings, no ** before the dict in needed.\n eg.conf = {'sender': '[email protected]',\n 'sender_name':'name', 'receiver':['[email protected]','[email protected]'], 'password':'123456',\n 'server':'smtp.bb.com','port':123, 'receiver_name':['me','guest']}.\n The receiver_name and sender_name options can be omitted.\n \"\"\"\n if self.content:\n ret = mail(\"Notification\", self.content, **conf)\n if ret:\n print(\"邮件发送成功\")\n else:\n print(\"邮件发送失败\")\n else:\n print(\"没有提醒待发送\")\n" ]
[ [ "pandas.DataFrame" ] ]
sethvargo/vaex
[ "c610324316b2c0a14b8ceac2a30e202adc9da28b", "c610324316b2c0a14b8ceac2a30e202adc9da28b" ]
[ "tests/arrow/conversion_test.py", "tests/encoding_test.py" ]
[ "import numpy as np\nimport pyarrow as pa\nimport pytest\nfrom vaex import array_types \nimport vaex.arrow.convert\n\n\nbools = [False, True, True]\n\n\ndef test_bool():\n b = np.array(bools)\n b_arrow = array_types.to_arrow(b)\n assert b_arrow.to_pylist() == bools\n b = array_types.to_numpy(b_arrow)\n assert b.tolist() == bools\n\n\ndef test_bool_sliced():\n b = np.array(bools)\n b_arrow = array_types.to_arrow(b)\n assert b_arrow.to_pylist() == bools\n b_arrow = b_arrow[1:]\n b = array_types.to_numpy(b_arrow)\n assert b.tolist() == bools[1:]\n\n\ndef test_float_sliced():\n x_original = np.arange(10)\n x = x_original\n x_arrow = array_types.to_arrow(x)\n assert x_arrow.to_pylist() == x_original.tolist()\n x_arrow = x_arrow[3:]\n assert x_arrow.to_pylist() == x_original[3:].tolist()\n x = array_types.to_numpy(x_arrow)\n assert x.tolist() == x_original[3:].tolist()\n\n\ndef test_float_sliced_masked():\n x_original = np.arange(5)\n mask = x_original > 2\n x_original = np.ma.array(x_original, mask=mask)\n x = x_original\n x_arrow = array_types.to_arrow(x)\n assert x_arrow.to_pylist() == x_original.tolist()\n x_arrow = x_arrow[2:]\n assert x_arrow.to_pylist() == x_original[2:].tolist()\n x = array_types.to_numpy(x_arrow)\n assert x.tolist() == x_original[2:].tolist()\n\n\ndef test_string_sliced():\n values = [\"a\", \"bb\", \"ccc\", \"dddd\"]\n ar = pa.array(values)\n assert vaex.arrow.convert.column_from_arrow_array(ar).tolist() == values\n assert vaex.arrow.convert.column_from_arrow_array(ar[1:]).tolist() == values[1:]\n assert vaex.arrow.convert.column_from_arrow_array(ar[1:3]).tolist() == values[1:3] != values[1:]\n\n\ndef test_keep_masked_data_values():\n x_original = np.arange(5, dtype='f8')\n mask = x_original > 2\n xm = np.ma.array(x_original, mask=mask)\n assert xm[-1] is np.ma.masked\n assert xm.data[-1] == 4\n x_arrow = array_types.to_arrow(xm)\n assert x_arrow.to_pylist()[-1] == None\n data_buffer = x_arrow.buffers()[1]\n x_arrow_data = np.frombuffer(data_buffer, dtype='f8')\n assert x_arrow_data[-1] == 4\n", "import vaex.encoding\nimport numpy as np\nimport pyarrow as pa\n\[email protected]('blobtest')\nclass encoding:\n @staticmethod\n def encode(encoding, data):\n return {'someblob': encoding.add_blob(data['someblob'])}\n\n @staticmethod\n def decode(encoding, data):\n return {'someblob': encoding.get_blob(data['someblob'])}\n\n\ndef test_encoding():\n encoding = vaex.encoding.Encoding()\n data = encoding.encode('blobtest', {'someblob': b'1234'})\n wiredata = vaex.encoding.serialize(data, encoding)\n\n encoding = vaex.encoding.Encoding()\n data = vaex.encoding.deserialize(wiredata, encoding)\n values = encoding.decode('blobtest', data)\n assert values['someblob'] == b'1234'\n\n\ndef test_encoding_arrow(array_factory_arrow):\n x = array_factory_arrow(np.arange(10, dtype='i1'))\n encoding = vaex.encoding.Encoding()\n data = encoding.encode('arrow-array', x)\n wiredata = vaex.encoding.serialize(data, encoding)\n\n encoding = vaex.encoding.Encoding()\n data = vaex.encoding.deserialize(wiredata, encoding)\n value = encoding.decode('arrow-array', data)\n assert value.type == pa.int8()\n assert value.to_pylist() == x.to_pylist()\n\n\ndef test_encoding_numpy():\n x = np.arange(10, dtype='>f4')\n encoding = vaex.encoding.Encoding()\n data = encoding.encode('ndarray', x)\n wiredata = vaex.encoding.serialize(data, encoding)\n\n encoding = vaex.encoding.Encoding()\n data = vaex.encoding.deserialize(wiredata, encoding)\n value = encoding.decode('ndarray', data)\n assert np.all(value == x)\n\n\ndef test_encoding_numpy_masked():\n x = np.arange(10, dtype='>f4')\n mask = x > 4\n x = np.ma.array(x, mask=mask)\n encoding = vaex.encoding.Encoding()\n data = encoding.encode('ndarray', x)\n wiredata = vaex.encoding.serialize(data, encoding)\n\n encoding = vaex.encoding.Encoding()\n data = vaex.encoding.deserialize(wiredata, encoding)\n value = encoding.decode('ndarray', data)\n assert np.all(value == x)\n assert np.all(value.mask == x.mask)\n\n\ndef test_encoding_numpy_datetime():\n x = np.arange('2001', '2005', dtype='M')\n encoding = vaex.encoding.Encoding()\n data = encoding.encode('ndarray', x)\n wiredata = vaex.encoding.serialize(data, encoding)\n\n encoding = vaex.encoding.Encoding()\n data = vaex.encoding.deserialize(wiredata, encoding)\n value = encoding.decode('ndarray', data)\n assert np.all(value == x)\n\n\ndef test_encoding_numpy_timedelta():\n x = np.arange('2001', '2005', dtype='M')\n x = x - x[0]\n encoding = vaex.encoding.Encoding()\n data = encoding.encode('ndarray', x)\n wiredata = vaex.encoding.serialize(data, encoding)\n\n encoding = vaex.encoding.Encoding()\n data = vaex.encoding.deserialize(wiredata, encoding)\n value = encoding.decode('ndarray', data)\n assert np.all(value == x)\n\n\ndef test_encoding_numpy_string_objects():\n x = np.array(['vaex', 'is', None, 'fast'])\n encoding = vaex.encoding.Encoding()\n data = encoding.encode('ndarray', x)\n wiredata = vaex.encoding.serialize(data, encoding)\n\n encoding = vaex.encoding.Encoding()\n data = vaex.encoding.deserialize(wiredata, encoding)\n value = encoding.decode('ndarray', data)\n assert np.all(value == x)\n\n\ndef test_encoding_dtype():\n dtype = np.dtype('>f8')\n encoding = vaex.encoding.Encoding()\n data = encoding.encode('dtype', dtype)\n wiredata = vaex.encoding.serialize(data, encoding)\n\n encoding = vaex.encoding.Encoding()\n data = vaex.encoding.deserialize(wiredata, encoding)\n print(data)\n value = encoding.decode('dtype', data)\n assert value == dtype\n assert value.is_numpy\n" ]
[ [ "numpy.ma.array", "numpy.arange", "numpy.array", "numpy.frombuffer" ], [ "numpy.arange", "numpy.dtype", "numpy.all", "numpy.ma.array", "numpy.array" ] ]
eschnett/kotekan
[ "81918288147435cef8ad52db05da0988c999a7dd" ]
[ "tests/test_vissharedmemreaderwriter.py" ]
[ "# === Start Python 2/3 compatibility\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nfrom future.builtins import * # noqa pylint: disable=W0401, W0614\nfrom future.builtins.disabled import * # noqa pylint: disable=W0401, W0614\n\n# == End Python 2/3 compatibility\n\nimport logging\nimport numpy as np\nimport os\nimport posix_ipc\nimport pytest\nimport re\nimport signal\nfrom subprocess import Popen\nimport shutil\nimport tempfile\nimport threading\nfrom time import sleep\n\nfrom comet import Manager\n\nfrom kotekan import runner, shared_memory_buffer\n\n# use tempfile creation to get exclusive random strings\nuseless_file = tempfile.NamedTemporaryFile()\nfname_buf = \"calBuffer_\" + os.path.split(useless_file.name)[-1]\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\[email protected]()\ndef comet_broker():\n broker_path = shutil.which(\"comet\")\n if not broker_path:\n pytest.skip(\n \"Make sure PYTHONPATH is set to where the comet dataset broker is installed.\"\n )\n\n with tempfile.NamedTemporaryFile(mode=\"w\") as f_out:\n # Start comet with a random port\n broker = Popen(\n [broker_path, \"-p\", \"0\", \"--recover\", \"False\"], stdout=f_out, stderr=f_out\n )\n sleep(3)\n\n # Find port in the log\n regex = re.compile(\"Selected random port: ([0-9]+)$\")\n log = open(f_out.name, \"r\").read().split(\"\\n\")\n port = None\n for line in log:\n print(line)\n match = regex.search(line)\n if match:\n port = match.group(1)\n print(\"Test found comet port in log: %s\" % port)\n break\n if not match:\n print(\"Could not find comet port in logs.\")\n exit(1)\n\n try:\n yield port\n finally:\n pid = broker.pid\n os.kill(pid, signal.SIGINT)\n broker.terminate()\n log = open(f_out.name, \"r\").read().split(\"\\n\")\n for line in log:\n print(line)\n\n\[email protected](scope=\"module\")\ndef semaphore():\n sem = posix_ipc.Semaphore(fname_buf)\n yield sem\n sem.release()\n sem.unlink()\n\n\nparams = {\n \"num_elements\": 7,\n \"num_ev\": 0,\n \"total_frames\": 8,\n \"cadence\": 1.0,\n \"mode\": \"change_state\",\n \"dataset_manager\": {\"use_dataset_broker\": True},\n}\n\nstart_time = 1_500_000_000\nflagging_update_time = start_time + 4\ngain_update_time = start_time + 5\nparams_fakevis = {\n \"freq_ids\": [1, 2, 3, 4, 7, 10],\n \"num_frames\": params[\"total_frames\"],\n \"mode\": params[\"mode\"],\n \"wait\": True,\n \"start_time\": start_time,\n \"state_changes\": [\n {\"timestamp\": flagging_update_time, \"type\": \"flags\"},\n {\"timestamp\": gain_update_time, \"type\": \"gains\"},\n ],\n}\n\nparams_writer_stage = {\"num_samples\": 5, \"name\": fname_buf}\n\n\[email protected]()\ndef vis_data(tmpdir_factory, comet_broker):\n\n # keeping all the data this test produced here (probably do not need it)\n # using FakeVisBuffer to produce fake data\n fakevis_buffer = runner.FakeVisBuffer(**params_fakevis)\n\n # pass comet port to kotekan\n params[\"dataset_manager\"][\"ds_broker_port\"] = comet_broker\n\n # KotekanStageTester is used to run kotekan with my config\n test = runner.KotekanStageTester(\n stage_type=\"VisSharedMemWriter\",\n stage_config=params_writer_stage,\n buffers_in=fakevis_buffer,\n buffers_out=None,\n global_config=params,\n )\n yield test\n\n\n# This test still needs to run alone, because multiple comet instances would have conflicts\n# accessing redis.\[email protected]\ndef test_shared_mem_buffer(vis_data, comet_broker):\n # start kotekan writer in a thread, to read before it's done (it will delete the shm on exit)\n threading.Thread(target=vis_data.run).start()\n ds_manager = Manager(\"localhost\", comet_broker)\n sleep(2)\n reader = []\n view_size = [2, 8, 17]\n\n for i in range(len(view_size)):\n reader.append(\n shared_memory_buffer.SharedMemoryReader(fname_buf, view_size[i], ds_manager)\n )\n\n for i in range(len(reader)):\n assert reader[i].num_time == params_writer_stage[\"num_samples\"]\n assert reader[i].num_freq == len(params_fakevis[\"freq_ids\"])\n\n i = 0\n visraw = [None] * len(view_size)\n with pytest.raises(shared_memory_buffer.SharedMemoryError):\n # Give this some extra time, because maybe it's just reading nothing a few times, but make\n # sure it eventually raises because the shared memory got removed by the writer.\n while i <= params[\"total_frames\"] * 2:\n sleep(0.5)\n for j in range(len(reader)):\n visraw[j] = reader[j].update()\n assert visraw[j].num_time == reader[j].view_size\n check_visraw(visraw[j])\n i += 1\n assert i >= params[\"total_frames\"] / 2\n\n\ndef check_visraw(visraw):\n \"\"\"Test content of valid frames.\"\"\"\n num_freq = len(params_fakevis[\"freq_ids\"])\n num_ev = params[\"num_ev\"]\n num_elements = params[\"num_elements\"]\n valid = visraw.valid_frames.astype(np.bool)\n\n num_time = visraw.num_time\n assert visraw.num_freq == len(params_fakevis[\"freq_ids\"])\n\n num_prod = int(num_elements * (num_elements + 1) / 2)\n\n # check valid frames only\n assert (visraw.num_prod[valid] == num_prod).all()\n assert (visraw.metadata[\"num_elements\"][valid] == num_elements).all()\n assert (visraw.metadata[\"num_ev\"][valid] == num_ev).all()\n\n # check gain/flag update IDs VisRaw got from comet\n assert (\n visraw.update_id[\"flags\"][valid & (visraw.time[\"ctime\"] < flagging_update_time)]\n == \"None\"\n ).all()\n assert (\n visraw.update_id[\"gains\"][valid & (visraw.time[\"ctime\"] < gain_update_time)]\n == \"None\"\n ).all()\n assert (\n visraw.update_id[\"flags\"][\n valid & (visraw.time[\"ctime\"] >= flagging_update_time)\n ]\n == \"flag_update_0\"\n ).all()\n assert (\n visraw.update_id[\"gains\"][valid & (visraw.time[\"ctime\"] >= gain_update_time)]\n == \"gain_update_0\"\n ).all()\n\n evals = visraw.data[\"eval\"]\n evecs = visraw.data[\"evec\"]\n erms = visraw.data[\"erms\"]\n\n # Check datasets are present\n assert evals.shape == (num_time, num_freq, num_ev)\n assert evecs.shape == (num_time, num_freq, num_ev * num_elements)\n assert erms.shape == (num_time, num_freq)\n\n evecs = evecs.reshape(num_time, num_freq, num_ev, num_elements)\n\n # Check that the datasets have the correct values\n assert (evals == np.arange(num_ev)[np.newaxis, np.newaxis, :]).all()\n assert (\n evecs.real == np.arange(num_ev)[np.newaxis, np.newaxis, :, np.newaxis]\n ).all()\n assert (\n evecs.imag == np.arange(num_elements)[np.newaxis, np.newaxis, np.newaxis, :]\n ).all()\n assert (erms[valid] == 1).all()\n\n ftime = visraw.time[\"fpga_count\"]\n ctime = visraw.time[\"ctime\"]\n freq = visraw.metadata[\"freq_id\"]\n\n # check \"default\" test pattern in vis\n vis = visraw.data[\"vis\"].view(np.complex64)\n assert vis.shape == (num_time, num_freq, num_prod)\n i = 0\n for time_slot_vis, time_slot_valid in zip(vis, visraw.valid_frames):\n f = 0\n for frame, valid in zip(time_slot_vis, time_slot_valid):\n if valid:\n assert (frame.real[0] == ftime[i].astype(np.float32)).all()\n assert (frame.real[1] == ctime[i].astype(np.float32)).all()\n assert frame.real[2] == freq[i][f].astype(np.float32)\n assert (frame.real[3:] == 0).all()\n k = num_elements\n l = 0\n m = 0\n for j in range(num_prod):\n if j == l:\n assert frame.imag[j] == m\n l += k\n k -= 1\n m += 1\n else:\n assert frame.imag[j] == 0\n f += 1\n i += 1\n\n if num_time > 0:\n # find last valid timestamp\n valid_times = visraw.time[valid]\n return num_time, valid_times[-1][\"fpga_count\"]\n return 0, None\n" ]
[ [ "numpy.arange" ] ]
hpides/zeus
[ "a8143ae2a7dea6b9ede36a87c32f1be91804113f" ]
[ "python/benchmark.py" ]
[ "# To use this script look at the bottom\n\nimport sys, threading, subprocess, os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\npath = os.path.join(os.getcwd(), \"output\")\n# Threading\n\nclass Engine (threading.Thread):\n def __init__(self, kind, time, fixed, buffer, serializer, batches, added, removed, ports):\n threading.Thread.__init__(self)\n self.cmd = [\"java\",\"-Xms10g\", \"-Xmx10g\", \"-jar\", \"benchmark/target/engine-jar-with-dependencies.jar\"]\n self.kind = [\"--type\", kind]\n self.cmd.extend(self.kind)\n self.timeout = time+10\n self.time = [\"--timeInSeconds\", str(time)]\n self.cmd.extend(self.time)\n self.buffer = [\"--networkBufferSize\", str(buffer)]\n self.cmd.extend(self.buffer)\n self.fixed = [\"--fixedQueries\", str(fixed)]\n self.cmd.extend(self.fixed)\n self.serializer = [\"--serializer\", serializer]\n self.cmd.extend(self.serializer)\n self.batches = [\"--batchesAmount\", str(batches)]\n self.cmd.extend(self.batches)\n self.added = [\"--newQueriesPerBatch\", str(added)]\n self.cmd.extend(self.added)\n self.removed = [\"--removeQueriesPerBatch\", str(removed)]\n self.cmd.extend(self.removed)\n self.host = [\"--generatorHost\", \"127.0.0.1\"]\n self.cmd.extend(self.host)\n self.cmd.extend(ports)\n \n def run(self):\n try:\n c = subprocess.run(self.cmd, timeout=self.timeout)\n print(c)\n except subprocess.TimeoutExpired:\n print('Engine Timed Out')\n\nclass Generator (threading.Thread):\n def __init__(self, kind, events, time, serializer, ports):\n threading.Thread.__init__(self)\n self.cmd = [\"java\",\"-Xms10g\", \"-Xmx10g\", \"-jar\", \"benchmark/target/generator-jar-with-dependencies.jar\"]\n self.kind = [\"--type\", kind]\n self.cmd.extend(self.kind)\n self.timeout = time+10\n self.time = [\"--timeInSeconds\", str(time)]\n self.cmd.extend(self.time)\n self.events = [\"--eventsPerSecond\", str(events)]\n self.cmd.extend(self.events)\n self.serializer = [\"--serializer\", serializer]\n self.cmd.extend(self.serializer)\n self.sources = [\"--amountOfSources\", str(int(len(ports)/2))]\n self.cmd.extend(self.sources)\n self.cmd.extend(ports)\n \n def run(self):\n try:\n c = subprocess.run(self.cmd, timeout=self.timeout)\n print(c)\n except subprocess.TimeoutExpired:\n print('Generator Timed Out')\n\ndef executeJava(kind, events, time, buffer, serializer, fixed, batches, added, removed, sources, datatype): \n ports = []\n if(datatype == \"basic\"):\n if(sources == 1):\n ports = [\"--basicPort1\", \"7000\"]\n else:\n ports =[\"--basicPort1\", \"7000\", \"--basicPort2\", \"7001\"]\n else:\n if(sources == 1):\n ports = [\"--auctionSourcePort\", \"7000\"]\n else:\n ports =[\"--auctionSourcePort\", \"7000\", \"--bidSourcePort\", \"7001\"]\n\n generator = Generator(\n datatype,\n events,\n time,\n serializer,\n ports\n )\n engine = Engine(\n kind,\n time+5,\n fixed,\n buffer,\n serializer,\n batches,\n added,\n removed,\n ports\n )\n\n generator.start()\n engine.start()\n\n return [engine, generator]\n\ndef calc():\n data = []\n files = os.listdir(path)\n for file in files:\n if(file.startswith(\"sink\") and file.endswith(\".csv\")):\n data.append({\n \"name\": file.split(\"_\")[2],\n \"latency\": pd.read_csv(os.path.join(path, file)),\n \"events\": pd.read_csv(os.path.join(path, [f for f in files if f.endswith(file.split(\"t\")[-1])and f.startswith(\"socket\")][0]))\n })\n events = {}\n eventTimeLatency = {}\n processingTimeLatency = {}\n for f in data:\n e = f[\"events\"][\"events\"]\n events[f[\"name\"]] = [\n np.mean(e),\n np.min(e),\n np.max(e),\n np.percentile(e, 0.25),\n np.percentile(e, 0.75),\n ]\n f[\"latency\"][\"eventTime\"] = f[\"latency\"][\"eventTime\"]/1000000\n l = f[\"latency\"][\"eventTimeLatency\"] = f[\"latency\"][\"ejectionTime\"]-f[\"latency\"][\"eventTime\"]\n eventTimeLatency[f[\"name\"]] = [\n np.mean(l),\n np.min(l),\n np.max(l),\n np.percentile(l, 0.25),\n np.percentile(l, 0.75),\n ]\n p = f[\"latency\"][\"processingTimeLatency\"] = f[\"latency\"][\"ejectionTime\"]-f[\"latency\"][\"processingTime\"]\n processingTimeLatency[f[\"name\"]] = [\n np.mean(p),\n np.min(p),\n np.max(p),\n np.percentile(p, 0.25),\n np.percentile(p, 0.75),\n ]\n print(\"Throughput\")\n print(pd.DataFrame(events, index=[\"Mean\", \"Min\", \"Max\", \"25%\", \"75%\"]))\n fig = plt.figure()\n for d in data:\n plt.plot(d[\"events\"][\"events\"], label=d[\"name\"], ls=\"-.\")\n plt.ylabel(\"Events per second\")\n plt.legend()\n plt.savefig(\"throughput.png\", bbox_inches=\"tight\", pad_inches=0.3)\n plt.figure()\n plt.boxplot([d[\"events\"][\"events\"] for d in data], labels=[d[\"name\"] for d in data])\n plt.ylabel(\"Events per second\")\n plt.savefig(\"throughput-boxplot.png\", bbox_inches=\"tight\", pad_inches=0.3)\n print(\"Event Time Latency\")\n print(pd.DataFrame(eventTimeLatency, index=[\"Mean\", \"Min\", \"Max\", \"25%\", \"75%\"]))\n plt.figure()\n for d in data:\n plt.plot(d[\"latency\"][\"eventTimeLatency\"], label=d[\"name\"], ls=\"-.\")\n plt.ylabel(\"Time in ms\")\n plt.legend()\n plt.savefig(\"eventTimeLatency.png\", bbox_inches=\"tight\", pad_inches=0.3)\n plt.figure()\n plt.boxplot([d[\"latency\"][\"eventTimeLatency\"] for d in data], labels=[d[\"name\"] for d in data])\n plt.ylabel(\"Time in ms\")\n plt.savefig(\"eventTimeLatency-boxplot.png\", bbox_inches=\"tight\", pad_inches=0.3)\n print(\"Processing Time Latency\")\n print(pd.DataFrame(processingTimeLatency, index=[\"Mean\", \"Min\", \"Max\", \"25%\", \"75%\"]))\n plt.figure()\n for d in data:\n plt.plot(d[\"latency\"][\"processingTimeLatency\"], label=d[\"name\"], ls=\"-.\")\n plt.ylabel(\"Time in ms\")\n plt.legend()\n plt.savefig(\"processingTimeLatency.png\", bbox_inches=\"tight\", pad_inches=0.3)\n plt.figure()\n plt.boxplot([d[\"latency\"][\"processingTimeLatency\"] for d in data], labels=[d[\"name\"] for d in data])\n plt.ylabel(\"Time in ms\")\n plt.savefig(\"processingTime-boxplot.png\", bbox_inches=\"tight\", pad_inches=0.3)\n\n\ndef executeTest(kind, size, time, buffer, queries, dynamic, sources, datatype):\n runtime = 30 if time == \"s\" else 60 if time == \"m\" else 120 if time == \"l\" else 90\n buffersize =10 if buffer == \"s\" else 20 if buffer == \"m\" else 30 if buffer == \"l\" else 15\n eventamount = 50000 if size == \"s\" else 100000 if size == \"m\" else 200000 if size == \"l\" else 75000\n threads = executeJava(\n kind,\n eventamount,\n runtime,\n buffersize,\n \"custom\",\n queries,\n int(runtime/10) if dynamic else 0,\n queries if dynamic else 0,\n queries if dynamic else 0,\n sources,\n datatype\n )\n for t in threads:\n t.join()\n\n# to execute a Test use the execute Test method with the following params\n# kind: what will get executed as test in java e.g. bfilter, hotcat etc\n# size: how many events shall be dispatched per second: either \"s\",\"m\" or \"l\"\n# time: how long shall the test run: either \"s\",\"m\" or \"l\"\n# buffer: how big shall the networkbuffer be: either \"s\",\"m\" or \"l\"\n# queries: how many queries to add: any integer\n# dynamic: if queries should be added during runtime: boolean\n# sources: how many sources are needed: 1 or 2\n# datatype: which data should be generated: either \"nexmark\" or \"basic\"\n\ncalc()\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.boxplot", "numpy.min", "matplotlib.pyplot.figure", "matplotlib.pyplot.savefig", "pandas.DataFrame", "matplotlib.pyplot.plot", "numpy.max", "numpy.percentile", "numpy.mean", "matplotlib.pyplot.ylabel" ] ]
dharwath/DAVEnet-pytorch
[ "23a6482859dd2221350307c9bfb5627a5902f6f0" ]
[ "dataloaders/image_caption_dataset.py" ]
[ "# Author: David Harwath\n# with some functions borrowed from https://github.com/SeanNaren/deepspeech.pytorch\nimport json\nimport librosa\nimport numpy as np\nimport os\nfrom PIL import Image\nimport scipy.signal\nimport torch\nimport torch.nn.functional\nfrom torch.utils.data import Dataset\nimport torchvision.transforms as transforms\n\ndef preemphasis(signal,coeff=0.97):\n \"\"\"perform preemphasis on the input signal.\n \n :param signal: The signal to filter.\n :param coeff: The preemphasis coefficient. 0 is none, default 0.97.\n :returns: the filtered signal.\n \"\"\" \n return np.append(signal[0],signal[1:]-coeff*signal[:-1])\n\nclass ImageCaptionDataset(Dataset):\n def __init__(self, dataset_json_file, audio_conf=None, image_conf=None):\n \"\"\"\n Dataset that manages a set of paired images and audio recordings\n\n :param dataset_json_file\n :param audio_conf: Dictionary containing the sample rate, window and\n the window length/stride in seconds, and normalization to perform (optional)\n :param image_transform: torchvision transform to apply to the images (optional)\n \"\"\"\n with open(dataset_json_file, 'r') as fp:\n data_json = json.load(fp)\n self.data = data_json['data']\n self.image_base_path = data_json['image_base_path']\n self.audio_base_path = data_json['audio_base_path']\n\n if not audio_conf:\n self.audio_conf = {}\n else:\n self.audio_conf = audio_conf\n\n if not image_conf:\n self.image_conf = {}\n else:\n self.image_conf = image_conf\n\n crop_size = self.image_conf.get('crop_size', 224)\n center_crop = self.image_conf.get('center_crop', False)\n\n if center_crop:\n self.image_resize_and_crop = transforms.Compose(\n [transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor()])\n else:\n self.image_resize_and_crop = transforms.Compose(\n [transforms.RandomResizedCrop(crop_size), transforms.ToTensor()])\n\n RGB_mean = self.image_conf.get('RGB_mean', [0.485, 0.456, 0.406])\n RGB_std = self.image_conf.get('RGB_std', [0.229, 0.224, 0.225])\n self.image_normalize = transforms.Normalize(mean=RGB_mean, std=RGB_std)\n\n self.windows = {'hamming': scipy.signal.hamming,\n 'hann': scipy.signal.hann, 'blackman': scipy.signal.blackman,\n 'bartlett': scipy.signal.bartlett}\n\n def _LoadAudio(self, path):\n audio_type = self.audio_conf.get('audio_type', 'melspectrogram')\n if audio_type not in ['melspectrogram', 'spectrogram']:\n raise ValueError('Invalid audio_type specified in audio_conf. Must be one of [melspectrogram, spectrogram]')\n preemph_coef = self.audio_conf.get('preemph_coef', 0.97)\n sample_rate = self.audio_conf.get('sample_rate', 16000)\n window_size = self.audio_conf.get('window_size', 0.025)\n window_stride = self.audio_conf.get('window_stride', 0.01)\n window_type = self.audio_conf.get('window_type', 'hamming')\n num_mel_bins = self.audio_conf.get('num_mel_bins', 40)\n target_length = self.audio_conf.get('target_length', 2048)\n use_raw_length = self.audio_conf.get('use_raw_length', False)\n padval = self.audio_conf.get('padval', 0)\n fmin = self.audio_conf.get('fmin', 20)\n n_fft = self.audio_conf.get('n_fft', int(sample_rate * window_size))\n win_length = int(sample_rate * window_size)\n hop_length = int(sample_rate * window_stride)\n\n # load audio, subtract DC, preemphasis\n y, sr = librosa.load(path, sample_rate)\n if y.size == 0:\n y = np.zeros(200)\n y = y - y.mean()\n y = preemphasis(y, preemph_coef)\n # compute mel spectrogram\n stft = librosa.stft(y, n_fft=n_fft, hop_length=hop_length,\n win_length=win_length,\n window=self.windows.get(window_type, self.windows['hamming']))\n spec = np.abs(stft)**2\n if audio_type == 'melspectrogram':\n mel_basis = librosa.filters.mel(sr, n_fft, n_mels=num_mel_bins, fmin=fmin)\n melspec = np.dot(mel_basis, spec)\n logspec = librosa.power_to_db(melspec, ref=np.max)\n elif audio_type == 'spectrogram':\n logspec = librosa.power_to_db(spec, ref=np.max)\n n_frames = logspec.shape[1]\n if use_raw_length:\n target_length = n_frames\n p = target_length - n_frames\n if p > 0:\n logspec = np.pad(logspec, ((0,0),(0,p)), 'constant',\n constant_values=(padval,padval))\n elif p < 0:\n logspec = logspec[:,0:p]\n n_frames = target_length\n logspec = torch.FloatTensor(logspec)\n return logspec, n_frames\n\n def _LoadImage(self, impath):\n img = Image.open(impath).convert('RGB')\n img = self.image_resize_and_crop(img)\n img = self.image_normalize(img)\n return img\n\n def __getitem__(self, index):\n \"\"\"\n returns: image, audio, nframes\n where image is a FloatTensor of size (3, H, W)\n audio is a FloatTensor of size (N_freq, N_frames) for spectrogram, or (N_frames) for waveform\n nframes is an integer\n \"\"\"\n datum = self.data[index]\n wavpath = os.path.join(self.audio_base_path, datum['wav'])\n imgpath = os.path.join(self.image_base_path, datum['image'])\n audio, nframes = self._LoadAudio(wavpath)\n image = self._LoadImage(imgpath)\n return image, audio, nframes\n\n def __len__(self):\n return len(self.data)" ]
[ [ "numpy.dot", "numpy.abs", "numpy.pad", "numpy.append", "torch.FloatTensor", "numpy.zeros" ] ]
mareksimunek/spark
[ "12b1e91e6b5135f6ed3e59a49abfc2e5a855263a" ]
[ "python/pyspark/sql/tests.py" ]
[ "# -*- encoding: utf-8 -*-\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"\nUnit tests for pyspark.sql; additional tests are implemented as doctests in\nindividual modules.\n\"\"\"\nimport os\nimport sys\nimport subprocess\nimport pydoc\nimport shutil\nimport tempfile\nimport threading\nimport pickle\nimport functools\nimport time\nimport datetime\nimport array\nimport ctypes\nimport warnings\nimport py4j\nfrom contextlib import contextmanager\n\ntry:\n import xmlrunner\nexcept ImportError:\n xmlrunner = None\n\nif sys.version_info[:2] <= (2, 6):\n try:\n import unittest2 as unittest\n except ImportError:\n sys.stderr.write('Please install unittest2 to test with Python 2.6 or earlier')\n sys.exit(1)\nelse:\n import unittest\n\nfrom pyspark.util import _exception_message\n\n_pandas_requirement_message = None\ntry:\n from pyspark.sql.utils import require_minimum_pandas_version\n require_minimum_pandas_version()\nexcept ImportError as e:\n # If Pandas version requirement is not satisfied, skip related tests.\n _pandas_requirement_message = _exception_message(e)\n\n_pyarrow_requirement_message = None\ntry:\n from pyspark.sql.utils import require_minimum_pyarrow_version\n require_minimum_pyarrow_version()\nexcept ImportError as e:\n # If Arrow version requirement is not satisfied, skip related tests.\n _pyarrow_requirement_message = _exception_message(e)\n\n_test_not_compiled_message = None\ntry:\n from pyspark.sql.utils import require_test_compiled\n require_test_compiled()\nexcept Exception as e:\n _test_not_compiled_message = _exception_message(e)\n\n_have_pandas = _pandas_requirement_message is None\n_have_pyarrow = _pyarrow_requirement_message is None\n_test_compiled = _test_not_compiled_message is None\n\nfrom pyspark import SparkContext\nfrom pyspark.sql import SparkSession, SQLContext, HiveContext, Column, Row\nfrom pyspark.sql.types import *\nfrom pyspark.sql.types import UserDefinedType, _infer_type, _make_type_verifier\nfrom pyspark.sql.types import _array_signed_int_typecode_ctype_mappings, _array_type_mappings\nfrom pyspark.sql.types import _array_unsigned_int_typecode_ctype_mappings\nfrom pyspark.sql.types import _merge_type\nfrom pyspark.tests import QuietTest, ReusedPySparkTestCase, PySparkTestCase, SparkSubmitTests\nfrom pyspark.sql.functions import UserDefinedFunction, sha2, lit\nfrom pyspark.sql.window import Window\nfrom pyspark.sql.utils import AnalysisException, ParseException, IllegalArgumentException\n\n\nclass UTCOffsetTimezone(datetime.tzinfo):\n \"\"\"\n Specifies timezone in UTC offset\n \"\"\"\n\n def __init__(self, offset=0):\n self.ZERO = datetime.timedelta(hours=offset)\n\n def utcoffset(self, dt):\n return self.ZERO\n\n def dst(self, dt):\n return self.ZERO\n\n\nclass ExamplePointUDT(UserDefinedType):\n \"\"\"\n User-defined type (UDT) for ExamplePoint.\n \"\"\"\n\n @classmethod\n def sqlType(self):\n return ArrayType(DoubleType(), False)\n\n @classmethod\n def module(cls):\n return 'pyspark.sql.tests'\n\n @classmethod\n def scalaUDT(cls):\n return 'org.apache.spark.sql.test.ExamplePointUDT'\n\n def serialize(self, obj):\n return [obj.x, obj.y]\n\n def deserialize(self, datum):\n return ExamplePoint(datum[0], datum[1])\n\n\nclass ExamplePoint:\n \"\"\"\n An example class to demonstrate UDT in Scala, Java, and Python.\n \"\"\"\n\n __UDT__ = ExamplePointUDT()\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __repr__(self):\n return \"ExamplePoint(%s,%s)\" % (self.x, self.y)\n\n def __str__(self):\n return \"(%s,%s)\" % (self.x, self.y)\n\n def __eq__(self, other):\n return isinstance(other, self.__class__) and \\\n other.x == self.x and other.y == self.y\n\n\nclass PythonOnlyUDT(UserDefinedType):\n \"\"\"\n User-defined type (UDT) for ExamplePoint.\n \"\"\"\n\n @classmethod\n def sqlType(self):\n return ArrayType(DoubleType(), False)\n\n @classmethod\n def module(cls):\n return '__main__'\n\n def serialize(self, obj):\n return [obj.x, obj.y]\n\n def deserialize(self, datum):\n return PythonOnlyPoint(datum[0], datum[1])\n\n @staticmethod\n def foo():\n pass\n\n @property\n def props(self):\n return {}\n\n\nclass PythonOnlyPoint(ExamplePoint):\n \"\"\"\n An example class to demonstrate UDT in only Python\n \"\"\"\n __UDT__ = PythonOnlyUDT()\n\n\nclass MyObject(object):\n def __init__(self, key, value):\n self.key = key\n self.value = value\n\n\nclass SQLTestUtils(object):\n \"\"\"\n This util assumes the instance of this to have 'spark' attribute, having a spark session.\n It is usually used with 'ReusedSQLTestCase' class but can be used if you feel sure the\n the implementation of this class has 'spark' attribute.\n \"\"\"\n\n @contextmanager\n def sql_conf(self, pairs):\n \"\"\"\n A convenient context manager to test some configuration specific logic. This sets\n `value` to the configuration `key` and then restores it back when it exits.\n \"\"\"\n assert isinstance(pairs, dict), \"pairs should be a dictionary.\"\n assert hasattr(self, \"spark\"), \"it should have 'spark' attribute, having a spark session.\"\n\n keys = pairs.keys()\n new_values = pairs.values()\n old_values = [self.spark.conf.get(key, None) for key in keys]\n for key, new_value in zip(keys, new_values):\n self.spark.conf.set(key, new_value)\n try:\n yield\n finally:\n for key, old_value in zip(keys, old_values):\n if old_value is None:\n self.spark.conf.unset(key)\n else:\n self.spark.conf.set(key, old_value)\n\n\nclass ReusedSQLTestCase(ReusedPySparkTestCase, SQLTestUtils):\n @classmethod\n def setUpClass(cls):\n super(ReusedSQLTestCase, cls).setUpClass()\n cls.spark = SparkSession(cls.sc)\n\n @classmethod\n def tearDownClass(cls):\n super(ReusedSQLTestCase, cls).tearDownClass()\n cls.spark.stop()\n\n def assertPandasEqual(self, expected, result):\n msg = (\"DataFrames are not equal: \" +\n \"\\n\\nExpected:\\n%s\\n%s\" % (expected, expected.dtypes) +\n \"\\n\\nResult:\\n%s\\n%s\" % (result, result.dtypes))\n self.assertTrue(expected.equals(result), msg=msg)\n\n\nclass DataTypeTests(unittest.TestCase):\n # regression test for SPARK-6055\n def test_data_type_eq(self):\n lt = LongType()\n lt2 = pickle.loads(pickle.dumps(LongType()))\n self.assertEqual(lt, lt2)\n\n # regression test for SPARK-7978\n def test_decimal_type(self):\n t1 = DecimalType()\n t2 = DecimalType(10, 2)\n self.assertTrue(t2 is not t1)\n self.assertNotEqual(t1, t2)\n t3 = DecimalType(8)\n self.assertNotEqual(t2, t3)\n\n # regression test for SPARK-10392\n def test_datetype_equal_zero(self):\n dt = DateType()\n self.assertEqual(dt.fromInternal(0), datetime.date(1970, 1, 1))\n\n # regression test for SPARK-17035\n def test_timestamp_microsecond(self):\n tst = TimestampType()\n self.assertEqual(tst.toInternal(datetime.datetime.max) % 1000000, 999999)\n\n def test_empty_row(self):\n row = Row()\n self.assertEqual(len(row), 0)\n\n def test_struct_field_type_name(self):\n struct_field = StructField(\"a\", IntegerType())\n self.assertRaises(TypeError, struct_field.typeName)\n\n def test_invalid_create_row(self):\n row_class = Row(\"c1\", \"c2\")\n self.assertRaises(ValueError, lambda: row_class(1, 2, 3))\n\n\nclass SQLTests(ReusedSQLTestCase):\n\n @classmethod\n def setUpClass(cls):\n ReusedSQLTestCase.setUpClass()\n cls.tempdir = tempfile.NamedTemporaryFile(delete=False)\n os.unlink(cls.tempdir.name)\n cls.testData = [Row(key=i, value=str(i)) for i in range(100)]\n cls.df = cls.spark.createDataFrame(cls.testData)\n\n @classmethod\n def tearDownClass(cls):\n ReusedSQLTestCase.tearDownClass()\n shutil.rmtree(cls.tempdir.name, ignore_errors=True)\n\n def test_sqlcontext_reuses_sparksession(self):\n sqlContext1 = SQLContext(self.sc)\n sqlContext2 = SQLContext(self.sc)\n self.assertTrue(sqlContext1.sparkSession is sqlContext2.sparkSession)\n\n def tearDown(self):\n super(SQLTests, self).tearDown()\n\n # tear down test_bucketed_write state\n self.spark.sql(\"DROP TABLE IF EXISTS pyspark_bucket\")\n\n def test_row_should_be_read_only(self):\n row = Row(a=1, b=2)\n self.assertEqual(1, row.a)\n\n def foo():\n row.a = 3\n self.assertRaises(Exception, foo)\n\n row2 = self.spark.range(10).first()\n self.assertEqual(0, row2.id)\n\n def foo2():\n row2.id = 2\n self.assertRaises(Exception, foo2)\n\n def test_range(self):\n self.assertEqual(self.spark.range(1, 1).count(), 0)\n self.assertEqual(self.spark.range(1, 0, -1).count(), 1)\n self.assertEqual(self.spark.range(0, 1 << 40, 1 << 39).count(), 2)\n self.assertEqual(self.spark.range(-2).count(), 0)\n self.assertEqual(self.spark.range(3).count(), 3)\n\n def test_duplicated_column_names(self):\n df = self.spark.createDataFrame([(1, 2)], [\"c\", \"c\"])\n row = df.select('*').first()\n self.assertEqual(1, row[0])\n self.assertEqual(2, row[1])\n self.assertEqual(\"Row(c=1, c=2)\", str(row))\n # Cannot access columns\n self.assertRaises(AnalysisException, lambda: df.select(df[0]).first())\n self.assertRaises(AnalysisException, lambda: df.select(df.c).first())\n self.assertRaises(AnalysisException, lambda: df.select(df[\"c\"]).first())\n\n def test_column_name_encoding(self):\n \"\"\"Ensure that created columns has `str` type consistently.\"\"\"\n columns = self.spark.createDataFrame([('Alice', 1)], ['name', u'age']).columns\n self.assertEqual(columns, ['name', 'age'])\n self.assertTrue(isinstance(columns[0], str))\n self.assertTrue(isinstance(columns[1], str))\n\n def test_explode(self):\n from pyspark.sql.functions import explode, explode_outer, posexplode_outer\n d = [\n Row(a=1, intlist=[1, 2, 3], mapfield={\"a\": \"b\"}),\n Row(a=1, intlist=[], mapfield={}),\n Row(a=1, intlist=None, mapfield=None),\n ]\n rdd = self.sc.parallelize(d)\n data = self.spark.createDataFrame(rdd)\n\n result = data.select(explode(data.intlist).alias(\"a\")).select(\"a\").collect()\n self.assertEqual(result[0][0], 1)\n self.assertEqual(result[1][0], 2)\n self.assertEqual(result[2][0], 3)\n\n result = data.select(explode(data.mapfield).alias(\"a\", \"b\")).select(\"a\", \"b\").collect()\n self.assertEqual(result[0][0], \"a\")\n self.assertEqual(result[0][1], \"b\")\n\n result = [tuple(x) for x in data.select(posexplode_outer(\"intlist\")).collect()]\n self.assertEqual(result, [(0, 1), (1, 2), (2, 3), (None, None), (None, None)])\n\n result = [tuple(x) for x in data.select(posexplode_outer(\"mapfield\")).collect()]\n self.assertEqual(result, [(0, 'a', 'b'), (None, None, None), (None, None, None)])\n\n result = [x[0] for x in data.select(explode_outer(\"intlist\")).collect()]\n self.assertEqual(result, [1, 2, 3, None, None])\n\n result = [tuple(x) for x in data.select(explode_outer(\"mapfield\")).collect()]\n self.assertEqual(result, [('a', 'b'), (None, None), (None, None)])\n\n def test_and_in_expression(self):\n self.assertEqual(4, self.df.filter((self.df.key <= 10) & (self.df.value <= \"2\")).count())\n self.assertRaises(ValueError, lambda: (self.df.key <= 10) and (self.df.value <= \"2\"))\n self.assertEqual(14, self.df.filter((self.df.key <= 3) | (self.df.value < \"2\")).count())\n self.assertRaises(ValueError, lambda: self.df.key <= 3 or self.df.value < \"2\")\n self.assertEqual(99, self.df.filter(~(self.df.key == 1)).count())\n self.assertRaises(ValueError, lambda: not self.df.key == 1)\n\n def test_udf_with_callable(self):\n d = [Row(number=i, squared=i**2) for i in range(10)]\n rdd = self.sc.parallelize(d)\n data = self.spark.createDataFrame(rdd)\n\n class PlusFour:\n def __call__(self, col):\n if col is not None:\n return col + 4\n\n call = PlusFour()\n pudf = UserDefinedFunction(call, LongType())\n res = data.select(pudf(data['number']).alias('plus_four'))\n self.assertEqual(res.agg({'plus_four': 'sum'}).collect()[0][0], 85)\n\n def test_udf_with_partial_function(self):\n d = [Row(number=i, squared=i**2) for i in range(10)]\n rdd = self.sc.parallelize(d)\n data = self.spark.createDataFrame(rdd)\n\n def some_func(col, param):\n if col is not None:\n return col + param\n\n pfunc = functools.partial(some_func, param=4)\n pudf = UserDefinedFunction(pfunc, LongType())\n res = data.select(pudf(data['number']).alias('plus_four'))\n self.assertEqual(res.agg({'plus_four': 'sum'}).collect()[0][0], 85)\n\n def test_udf(self):\n self.spark.catalog.registerFunction(\"twoArgs\", lambda x, y: len(x) + y, IntegerType())\n [row] = self.spark.sql(\"SELECT twoArgs('test', 1)\").collect()\n self.assertEqual(row[0], 5)\n\n # This is to check if a deprecated 'SQLContext.registerFunction' can call its alias.\n sqlContext = self.spark._wrapped\n sqlContext.registerFunction(\"oneArg\", lambda x: len(x), IntegerType())\n [row] = sqlContext.sql(\"SELECT oneArg('test')\").collect()\n self.assertEqual(row[0], 4)\n\n def test_udf2(self):\n self.spark.catalog.registerFunction(\"strlen\", lambda string: len(string), IntegerType())\n self.spark.createDataFrame(self.sc.parallelize([Row(a=\"test\")]))\\\n .createOrReplaceTempView(\"test\")\n [res] = self.spark.sql(\"SELECT strlen(a) FROM test WHERE strlen(a) > 1\").collect()\n self.assertEqual(4, res[0])\n\n def test_udf3(self):\n two_args = self.spark.catalog.registerFunction(\n \"twoArgs\", UserDefinedFunction(lambda x, y: len(x) + y))\n self.assertEqual(two_args.deterministic, True)\n [row] = self.spark.sql(\"SELECT twoArgs('test', 1)\").collect()\n self.assertEqual(row[0], u'5')\n\n def test_udf_registration_return_type_none(self):\n two_args = self.spark.catalog.registerFunction(\n \"twoArgs\", UserDefinedFunction(lambda x, y: len(x) + y, \"integer\"), None)\n self.assertEqual(two_args.deterministic, True)\n [row] = self.spark.sql(\"SELECT twoArgs('test', 1)\").collect()\n self.assertEqual(row[0], 5)\n\n def test_udf_registration_return_type_not_none(self):\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(TypeError, \"Invalid returnType\"):\n self.spark.catalog.registerFunction(\n \"f\", UserDefinedFunction(lambda x, y: len(x) + y, StringType()), StringType())\n\n def test_nondeterministic_udf(self):\n # Test that nondeterministic UDFs are evaluated only once in chained UDF evaluations\n from pyspark.sql.functions import udf\n import random\n udf_random_col = udf(lambda: int(100 * random.random()), IntegerType()).asNondeterministic()\n self.assertEqual(udf_random_col.deterministic, False)\n df = self.spark.createDataFrame([Row(1)]).select(udf_random_col().alias('RAND'))\n udf_add_ten = udf(lambda rand: rand + 10, IntegerType())\n [row] = df.withColumn('RAND_PLUS_TEN', udf_add_ten('RAND')).collect()\n self.assertEqual(row[0] + 10, row[1])\n\n def test_nondeterministic_udf2(self):\n import random\n from pyspark.sql.functions import udf\n random_udf = udf(lambda: random.randint(6, 6), IntegerType()).asNondeterministic()\n self.assertEqual(random_udf.deterministic, False)\n random_udf1 = self.spark.catalog.registerFunction(\"randInt\", random_udf)\n self.assertEqual(random_udf1.deterministic, False)\n [row] = self.spark.sql(\"SELECT randInt()\").collect()\n self.assertEqual(row[0], 6)\n [row] = self.spark.range(1).select(random_udf1()).collect()\n self.assertEqual(row[0], 6)\n [row] = self.spark.range(1).select(random_udf()).collect()\n self.assertEqual(row[0], 6)\n # render_doc() reproduces the help() exception without printing output\n pydoc.render_doc(udf(lambda: random.randint(6, 6), IntegerType()))\n pydoc.render_doc(random_udf)\n pydoc.render_doc(random_udf1)\n pydoc.render_doc(udf(lambda x: x).asNondeterministic)\n\n def test_nondeterministic_udf3(self):\n # regression test for SPARK-23233\n from pyspark.sql.functions import udf\n f = udf(lambda x: x)\n # Here we cache the JVM UDF instance.\n self.spark.range(1).select(f(\"id\"))\n # This should reset the cache to set the deterministic status correctly.\n f = f.asNondeterministic()\n # Check the deterministic status of udf.\n df = self.spark.range(1).select(f(\"id\"))\n deterministic = df._jdf.logicalPlan().projectList().head().deterministic()\n self.assertFalse(deterministic)\n\n def test_nondeterministic_udf_in_aggregate(self):\n from pyspark.sql.functions import udf, sum\n import random\n udf_random_col = udf(lambda: int(100 * random.random()), 'int').asNondeterministic()\n df = self.spark.range(10)\n\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(AnalysisException, \"nondeterministic\"):\n df.groupby('id').agg(sum(udf_random_col())).collect()\n with self.assertRaisesRegexp(AnalysisException, \"nondeterministic\"):\n df.agg(sum(udf_random_col())).collect()\n\n def test_chained_udf(self):\n self.spark.catalog.registerFunction(\"double\", lambda x: x + x, IntegerType())\n [row] = self.spark.sql(\"SELECT double(1)\").collect()\n self.assertEqual(row[0], 2)\n [row] = self.spark.sql(\"SELECT double(double(1))\").collect()\n self.assertEqual(row[0], 4)\n [row] = self.spark.sql(\"SELECT double(double(1) + 1)\").collect()\n self.assertEqual(row[0], 6)\n\n def test_single_udf_with_repeated_argument(self):\n # regression test for SPARK-20685\n self.spark.catalog.registerFunction(\"add\", lambda x, y: x + y, IntegerType())\n row = self.spark.sql(\"SELECT add(1, 1)\").first()\n self.assertEqual(tuple(row), (2, ))\n\n def test_multiple_udfs(self):\n self.spark.catalog.registerFunction(\"double\", lambda x: x * 2, IntegerType())\n [row] = self.spark.sql(\"SELECT double(1), double(2)\").collect()\n self.assertEqual(tuple(row), (2, 4))\n [row] = self.spark.sql(\"SELECT double(double(1)), double(double(2) + 2)\").collect()\n self.assertEqual(tuple(row), (4, 12))\n self.spark.catalog.registerFunction(\"add\", lambda x, y: x + y, IntegerType())\n [row] = self.spark.sql(\"SELECT double(add(1, 2)), add(double(2), 1)\").collect()\n self.assertEqual(tuple(row), (6, 5))\n\n def test_udf_in_filter_on_top_of_outer_join(self):\n from pyspark.sql.functions import udf\n left = self.spark.createDataFrame([Row(a=1)])\n right = self.spark.createDataFrame([Row(a=1)])\n df = left.join(right, on='a', how='left_outer')\n df = df.withColumn('b', udf(lambda x: 'x')(df.a))\n self.assertEqual(df.filter('b = \"x\"').collect(), [Row(a=1, b='x')])\n\n def test_udf_in_filter_on_top_of_join(self):\n # regression test for SPARK-18589\n from pyspark.sql.functions import udf\n left = self.spark.createDataFrame([Row(a=1)])\n right = self.spark.createDataFrame([Row(b=1)])\n f = udf(lambda a, b: a == b, BooleanType())\n df = left.crossJoin(right).filter(f(\"a\", \"b\"))\n self.assertEqual(df.collect(), [Row(a=1, b=1)])\n\n def test_udf_without_arguments(self):\n self.spark.catalog.registerFunction(\"foo\", lambda: \"bar\")\n [row] = self.spark.sql(\"SELECT foo()\").collect()\n self.assertEqual(row[0], \"bar\")\n\n def test_udf_with_array_type(self):\n d = [Row(l=list(range(3)), d={\"key\": list(range(5))})]\n rdd = self.sc.parallelize(d)\n self.spark.createDataFrame(rdd).createOrReplaceTempView(\"test\")\n self.spark.catalog.registerFunction(\"copylist\", lambda l: list(l), ArrayType(IntegerType()))\n self.spark.catalog.registerFunction(\"maplen\", lambda d: len(d), IntegerType())\n [(l1, l2)] = self.spark.sql(\"select copylist(l), maplen(d) from test\").collect()\n self.assertEqual(list(range(3)), l1)\n self.assertEqual(1, l2)\n\n def test_broadcast_in_udf(self):\n bar = {\"a\": \"aa\", \"b\": \"bb\", \"c\": \"abc\"}\n foo = self.sc.broadcast(bar)\n self.spark.catalog.registerFunction(\"MYUDF\", lambda x: foo.value[x] if x else '')\n [res] = self.spark.sql(\"SELECT MYUDF('c')\").collect()\n self.assertEqual(\"abc\", res[0])\n [res] = self.spark.sql(\"SELECT MYUDF('')\").collect()\n self.assertEqual(\"\", res[0])\n\n def test_udf_with_filter_function(self):\n df = self.spark.createDataFrame([(1, \"1\"), (2, \"2\"), (1, \"2\"), (1, \"2\")], [\"key\", \"value\"])\n from pyspark.sql.functions import udf, col\n from pyspark.sql.types import BooleanType\n\n my_filter = udf(lambda a: a < 2, BooleanType())\n sel = df.select(col(\"key\"), col(\"value\")).filter((my_filter(col(\"key\"))) & (df.value < \"2\"))\n self.assertEqual(sel.collect(), [Row(key=1, value='1')])\n\n def test_udf_with_aggregate_function(self):\n df = self.spark.createDataFrame([(1, \"1\"), (2, \"2\"), (1, \"2\"), (1, \"2\")], [\"key\", \"value\"])\n from pyspark.sql.functions import udf, col, sum\n from pyspark.sql.types import BooleanType\n\n my_filter = udf(lambda a: a == 1, BooleanType())\n sel = df.select(col(\"key\")).distinct().filter(my_filter(col(\"key\")))\n self.assertEqual(sel.collect(), [Row(key=1)])\n\n my_copy = udf(lambda x: x, IntegerType())\n my_add = udf(lambda a, b: int(a + b), IntegerType())\n my_strlen = udf(lambda x: len(x), IntegerType())\n sel = df.groupBy(my_copy(col(\"key\")).alias(\"k\"))\\\n .agg(sum(my_strlen(col(\"value\"))).alias(\"s\"))\\\n .select(my_add(col(\"k\"), col(\"s\")).alias(\"t\"))\n self.assertEqual(sel.collect(), [Row(t=4), Row(t=3)])\n\n def test_udf_in_generate(self):\n from pyspark.sql.functions import udf, explode\n df = self.spark.range(5)\n f = udf(lambda x: list(range(x)), ArrayType(LongType()))\n row = df.select(explode(f(*df))).groupBy().sum().first()\n self.assertEqual(row[0], 10)\n\n df = self.spark.range(3)\n res = df.select(\"id\", explode(f(df.id))).collect()\n self.assertEqual(res[0][0], 1)\n self.assertEqual(res[0][1], 0)\n self.assertEqual(res[1][0], 2)\n self.assertEqual(res[1][1], 0)\n self.assertEqual(res[2][0], 2)\n self.assertEqual(res[2][1], 1)\n\n range_udf = udf(lambda value: list(range(value - 1, value + 1)), ArrayType(IntegerType()))\n res = df.select(\"id\", explode(range_udf(df.id))).collect()\n self.assertEqual(res[0][0], 0)\n self.assertEqual(res[0][1], -1)\n self.assertEqual(res[1][0], 0)\n self.assertEqual(res[1][1], 0)\n self.assertEqual(res[2][0], 1)\n self.assertEqual(res[2][1], 0)\n self.assertEqual(res[3][0], 1)\n self.assertEqual(res[3][1], 1)\n\n def test_udf_with_order_by_and_limit(self):\n from pyspark.sql.functions import udf\n my_copy = udf(lambda x: x, IntegerType())\n df = self.spark.range(10).orderBy(\"id\")\n res = df.select(df.id, my_copy(df.id).alias(\"copy\")).limit(1)\n res.explain(True)\n self.assertEqual(res.collect(), [Row(id=0, copy=0)])\n\n def test_udf_registration_returns_udf(self):\n df = self.spark.range(10)\n add_three = self.spark.udf.register(\"add_three\", lambda x: x + 3, IntegerType())\n\n self.assertListEqual(\n df.selectExpr(\"add_three(id) AS plus_three\").collect(),\n df.select(add_three(\"id\").alias(\"plus_three\")).collect()\n )\n\n # This is to check if a 'SQLContext.udf' can call its alias.\n sqlContext = self.spark._wrapped\n add_four = sqlContext.udf.register(\"add_four\", lambda x: x + 4, IntegerType())\n\n self.assertListEqual(\n df.selectExpr(\"add_four(id) AS plus_four\").collect(),\n df.select(add_four(\"id\").alias(\"plus_four\")).collect()\n )\n\n def test_non_existed_udf(self):\n spark = self.spark\n self.assertRaisesRegexp(AnalysisException, \"Can not load class non_existed_udf\",\n lambda: spark.udf.registerJavaFunction(\"udf1\", \"non_existed_udf\"))\n\n # This is to check if a deprecated 'SQLContext.registerJavaFunction' can call its alias.\n sqlContext = spark._wrapped\n self.assertRaisesRegexp(AnalysisException, \"Can not load class non_existed_udf\",\n lambda: sqlContext.registerJavaFunction(\"udf1\", \"non_existed_udf\"))\n\n def test_non_existed_udaf(self):\n spark = self.spark\n self.assertRaisesRegexp(AnalysisException, \"Can not load class non_existed_udaf\",\n lambda: spark.udf.registerJavaUDAF(\"udaf1\", \"non_existed_udaf\"))\n\n def test_linesep_text(self):\n df = self.spark.read.text(\"python/test_support/sql/ages_newlines.csv\", lineSep=\",\")\n expected = [Row(value=u'Joe'), Row(value=u'20'), Row(value=u'\"Hi'),\n Row(value=u'\\nI am Jeo\"\\nTom'), Row(value=u'30'),\n Row(value=u'\"My name is Tom\"\\nHyukjin'), Row(value=u'25'),\n Row(value=u'\"I am Hyukjin\\n\\nI love Spark!\"\\n')]\n self.assertEqual(df.collect(), expected)\n\n tpath = tempfile.mkdtemp()\n shutil.rmtree(tpath)\n try:\n df.write.text(tpath, lineSep=\"!\")\n expected = [Row(value=u'Joe!20!\"Hi!'), Row(value=u'I am Jeo\"'),\n Row(value=u'Tom!30!\"My name is Tom\"'),\n Row(value=u'Hyukjin!25!\"I am Hyukjin'),\n Row(value=u''), Row(value=u'I love Spark!\"'),\n Row(value=u'!')]\n readback = self.spark.read.text(tpath)\n self.assertEqual(readback.collect(), expected)\n finally:\n shutil.rmtree(tpath)\n\n def test_multiline_json(self):\n people1 = self.spark.read.json(\"python/test_support/sql/people.json\")\n people_array = self.spark.read.json(\"python/test_support/sql/people_array.json\",\n multiLine=True)\n self.assertEqual(people1.collect(), people_array.collect())\n\n def test_encoding_json(self):\n people_array = self.spark.read\\\n .json(\"python/test_support/sql/people_array_utf16le.json\",\n multiLine=True, encoding=\"UTF-16LE\")\n expected = [Row(age=30, name=u'Andy'), Row(age=19, name=u'Justin')]\n self.assertEqual(people_array.collect(), expected)\n\n def test_linesep_json(self):\n df = self.spark.read.json(\"python/test_support/sql/people.json\", lineSep=\",\")\n expected = [Row(_corrupt_record=None, name=u'Michael'),\n Row(_corrupt_record=u' \"age\":30}\\n{\"name\":\"Justin\"', name=None),\n Row(_corrupt_record=u' \"age\":19}\\n', name=None)]\n self.assertEqual(df.collect(), expected)\n\n tpath = tempfile.mkdtemp()\n shutil.rmtree(tpath)\n try:\n df = self.spark.read.json(\"python/test_support/sql/people.json\")\n df.write.json(tpath, lineSep=\"!!\")\n readback = self.spark.read.json(tpath, lineSep=\"!!\")\n self.assertEqual(readback.collect(), df.collect())\n finally:\n shutil.rmtree(tpath)\n\n def test_multiline_csv(self):\n ages_newlines = self.spark.read.csv(\n \"python/test_support/sql/ages_newlines.csv\", multiLine=True)\n expected = [Row(_c0=u'Joe', _c1=u'20', _c2=u'Hi,\\nI am Jeo'),\n Row(_c0=u'Tom', _c1=u'30', _c2=u'My name is Tom'),\n Row(_c0=u'Hyukjin', _c1=u'25', _c2=u'I am Hyukjin\\n\\nI love Spark!')]\n self.assertEqual(ages_newlines.collect(), expected)\n\n def test_ignorewhitespace_csv(self):\n tmpPath = tempfile.mkdtemp()\n shutil.rmtree(tmpPath)\n self.spark.createDataFrame([[\" a\", \"b \", \" c \"]]).write.csv(\n tmpPath,\n ignoreLeadingWhiteSpace=False,\n ignoreTrailingWhiteSpace=False)\n\n expected = [Row(value=u' a,b , c ')]\n readback = self.spark.read.text(tmpPath)\n self.assertEqual(readback.collect(), expected)\n shutil.rmtree(tmpPath)\n\n def test_read_multiple_orc_file(self):\n df = self.spark.read.orc([\"python/test_support/sql/orc_partitioned/b=0/c=0\",\n \"python/test_support/sql/orc_partitioned/b=1/c=1\"])\n self.assertEqual(2, df.count())\n\n def test_udf_with_input_file_name(self):\n from pyspark.sql.functions import udf, input_file_name\n sourceFile = udf(lambda path: path, StringType())\n filePath = \"python/test_support/sql/people1.json\"\n row = self.spark.read.json(filePath).select(sourceFile(input_file_name())).first()\n self.assertTrue(row[0].find(\"people1.json\") != -1)\n\n def test_udf_with_input_file_name_for_hadooprdd(self):\n from pyspark.sql.functions import udf, input_file_name\n\n def filename(path):\n return path\n\n sameText = udf(filename, StringType())\n\n rdd = self.sc.textFile('python/test_support/sql/people.json')\n df = self.spark.read.json(rdd).select(input_file_name().alias('file'))\n row = df.select(sameText(df['file'])).first()\n self.assertTrue(row[0].find(\"people.json\") != -1)\n\n rdd2 = self.sc.newAPIHadoopFile(\n 'python/test_support/sql/people.json',\n 'org.apache.hadoop.mapreduce.lib.input.TextInputFormat',\n 'org.apache.hadoop.io.LongWritable',\n 'org.apache.hadoop.io.Text')\n\n df2 = self.spark.read.json(rdd2).select(input_file_name().alias('file'))\n row2 = df2.select(sameText(df2['file'])).first()\n self.assertTrue(row2[0].find(\"people.json\") != -1)\n\n def test_udf_defers_judf_initialization(self):\n # This is separate of UDFInitializationTests\n # to avoid context initialization\n # when udf is called\n\n from pyspark.sql.functions import UserDefinedFunction\n\n f = UserDefinedFunction(lambda x: x, StringType())\n\n self.assertIsNone(\n f._judf_placeholder,\n \"judf should not be initialized before the first call.\"\n )\n\n self.assertIsInstance(f(\"foo\"), Column, \"UDF call should return a Column.\")\n\n self.assertIsNotNone(\n f._judf_placeholder,\n \"judf should be initialized after UDF has been called.\"\n )\n\n def test_udf_with_string_return_type(self):\n from pyspark.sql.functions import UserDefinedFunction\n\n add_one = UserDefinedFunction(lambda x: x + 1, \"integer\")\n make_pair = UserDefinedFunction(lambda x: (-x, x), \"struct<x:integer,y:integer>\")\n make_array = UserDefinedFunction(\n lambda x: [float(x) for x in range(x, x + 3)], \"array<double>\")\n\n expected = (2, Row(x=-1, y=1), [1.0, 2.0, 3.0])\n actual = (self.spark.range(1, 2).toDF(\"x\")\n .select(add_one(\"x\"), make_pair(\"x\"), make_array(\"x\"))\n .first())\n\n self.assertTupleEqual(expected, actual)\n\n def test_udf_shouldnt_accept_noncallable_object(self):\n from pyspark.sql.functions import UserDefinedFunction\n\n non_callable = None\n self.assertRaises(TypeError, UserDefinedFunction, non_callable, StringType())\n\n def test_udf_with_decorator(self):\n from pyspark.sql.functions import lit, udf\n from pyspark.sql.types import IntegerType, DoubleType\n\n @udf(IntegerType())\n def add_one(x):\n if x is not None:\n return x + 1\n\n @udf(returnType=DoubleType())\n def add_two(x):\n if x is not None:\n return float(x + 2)\n\n @udf\n def to_upper(x):\n if x is not None:\n return x.upper()\n\n @udf()\n def to_lower(x):\n if x is not None:\n return x.lower()\n\n @udf\n def substr(x, start, end):\n if x is not None:\n return x[start:end]\n\n @udf(\"long\")\n def trunc(x):\n return int(x)\n\n @udf(returnType=\"double\")\n def as_double(x):\n return float(x)\n\n df = (\n self.spark\n .createDataFrame(\n [(1, \"Foo\", \"foobar\", 3.0)], (\"one\", \"Foo\", \"foobar\", \"float\"))\n .select(\n add_one(\"one\"), add_two(\"one\"),\n to_upper(\"Foo\"), to_lower(\"Foo\"),\n substr(\"foobar\", lit(0), lit(3)),\n trunc(\"float\"), as_double(\"one\")))\n\n self.assertListEqual(\n [tpe for _, tpe in df.dtypes],\n [\"int\", \"double\", \"string\", \"string\", \"string\", \"bigint\", \"double\"]\n )\n\n self.assertListEqual(\n list(df.first()),\n [2, 3.0, \"FOO\", \"foo\", \"foo\", 3, 1.0]\n )\n\n def test_udf_wrapper(self):\n from pyspark.sql.functions import udf\n from pyspark.sql.types import IntegerType\n\n def f(x):\n \"\"\"Identity\"\"\"\n return x\n\n return_type = IntegerType()\n f_ = udf(f, return_type)\n\n self.assertTrue(f.__doc__ in f_.__doc__)\n self.assertEqual(f, f_.func)\n self.assertEqual(return_type, f_.returnType)\n\n class F(object):\n \"\"\"Identity\"\"\"\n def __call__(self, x):\n return x\n\n f = F()\n return_type = IntegerType()\n f_ = udf(f, return_type)\n\n self.assertTrue(f.__doc__ in f_.__doc__)\n self.assertEqual(f, f_.func)\n self.assertEqual(return_type, f_.returnType)\n\n f = functools.partial(f, x=1)\n return_type = IntegerType()\n f_ = udf(f, return_type)\n\n self.assertTrue(f.__doc__ in f_.__doc__)\n self.assertEqual(f, f_.func)\n self.assertEqual(return_type, f_.returnType)\n\n def test_validate_column_types(self):\n from pyspark.sql.functions import udf, to_json\n from pyspark.sql.column import _to_java_column\n\n self.assertTrue(\"Column\" in _to_java_column(\"a\").getClass().toString())\n self.assertTrue(\"Column\" in _to_java_column(u\"a\").getClass().toString())\n self.assertTrue(\"Column\" in _to_java_column(self.spark.range(1).id).getClass().toString())\n\n self.assertRaisesRegexp(\n TypeError,\n \"Invalid argument, not a string or column\",\n lambda: _to_java_column(1))\n\n class A():\n pass\n\n self.assertRaises(TypeError, lambda: _to_java_column(A()))\n self.assertRaises(TypeError, lambda: _to_java_column([]))\n\n self.assertRaisesRegexp(\n TypeError,\n \"Invalid argument, not a string or column\",\n lambda: udf(lambda x: x)(None))\n self.assertRaises(TypeError, lambda: to_json(1))\n\n def test_basic_functions(self):\n rdd = self.sc.parallelize(['{\"foo\":\"bar\"}', '{\"foo\":\"baz\"}'])\n df = self.spark.read.json(rdd)\n df.count()\n df.collect()\n df.schema\n\n # cache and checkpoint\n self.assertFalse(df.is_cached)\n df.persist()\n df.unpersist(True)\n df.cache()\n self.assertTrue(df.is_cached)\n self.assertEqual(2, df.count())\n\n df.createOrReplaceTempView(\"temp\")\n df = self.spark.sql(\"select foo from temp\")\n df.count()\n df.collect()\n\n def test_apply_schema_to_row(self):\n df = self.spark.read.json(self.sc.parallelize([\"\"\"{\"a\":2}\"\"\"]))\n df2 = self.spark.createDataFrame(df.rdd.map(lambda x: x), df.schema)\n self.assertEqual(df.collect(), df2.collect())\n\n rdd = self.sc.parallelize(range(10)).map(lambda x: Row(a=x))\n df3 = self.spark.createDataFrame(rdd, df.schema)\n self.assertEqual(10, df3.count())\n\n def test_infer_schema_to_local(self):\n input = [{\"a\": 1}, {\"b\": \"coffee\"}]\n rdd = self.sc.parallelize(input)\n df = self.spark.createDataFrame(input)\n df2 = self.spark.createDataFrame(rdd, samplingRatio=1.0)\n self.assertEqual(df.schema, df2.schema)\n\n rdd = self.sc.parallelize(range(10)).map(lambda x: Row(a=x, b=None))\n df3 = self.spark.createDataFrame(rdd, df.schema)\n self.assertEqual(10, df3.count())\n\n def test_apply_schema_to_dict_and_rows(self):\n schema = StructType().add(\"b\", StringType()).add(\"a\", IntegerType())\n input = [{\"a\": 1}, {\"b\": \"coffee\"}]\n rdd = self.sc.parallelize(input)\n for verify in [False, True]:\n df = self.spark.createDataFrame(input, schema, verifySchema=verify)\n df2 = self.spark.createDataFrame(rdd, schema, verifySchema=verify)\n self.assertEqual(df.schema, df2.schema)\n\n rdd = self.sc.parallelize(range(10)).map(lambda x: Row(a=x, b=None))\n df3 = self.spark.createDataFrame(rdd, schema, verifySchema=verify)\n self.assertEqual(10, df3.count())\n input = [Row(a=x, b=str(x)) for x in range(10)]\n df4 = self.spark.createDataFrame(input, schema, verifySchema=verify)\n self.assertEqual(10, df4.count())\n\n def test_create_dataframe_schema_mismatch(self):\n input = [Row(a=1)]\n rdd = self.sc.parallelize(range(3)).map(lambda i: Row(a=i))\n schema = StructType([StructField(\"a\", IntegerType()), StructField(\"b\", StringType())])\n df = self.spark.createDataFrame(rdd, schema)\n self.assertRaises(Exception, lambda: df.show())\n\n def test_serialize_nested_array_and_map(self):\n d = [Row(l=[Row(a=1, b='s')], d={\"key\": Row(c=1.0, d=\"2\")})]\n rdd = self.sc.parallelize(d)\n df = self.spark.createDataFrame(rdd)\n row = df.head()\n self.assertEqual(1, len(row.l))\n self.assertEqual(1, row.l[0].a)\n self.assertEqual(\"2\", row.d[\"key\"].d)\n\n l = df.rdd.map(lambda x: x.l).first()\n self.assertEqual(1, len(l))\n self.assertEqual('s', l[0].b)\n\n d = df.rdd.map(lambda x: x.d).first()\n self.assertEqual(1, len(d))\n self.assertEqual(1.0, d[\"key\"].c)\n\n row = df.rdd.map(lambda x: x.d[\"key\"]).first()\n self.assertEqual(1.0, row.c)\n self.assertEqual(\"2\", row.d)\n\n def test_infer_schema(self):\n d = [Row(l=[], d={}, s=None),\n Row(l=[Row(a=1, b='s')], d={\"key\": Row(c=1.0, d=\"2\")}, s=\"\")]\n rdd = self.sc.parallelize(d)\n df = self.spark.createDataFrame(rdd)\n self.assertEqual([], df.rdd.map(lambda r: r.l).first())\n self.assertEqual([None, \"\"], df.rdd.map(lambda r: r.s).collect())\n df.createOrReplaceTempView(\"test\")\n result = self.spark.sql(\"SELECT l[0].a from test where d['key'].d = '2'\")\n self.assertEqual(1, result.head()[0])\n\n df2 = self.spark.createDataFrame(rdd, samplingRatio=1.0)\n self.assertEqual(df.schema, df2.schema)\n self.assertEqual({}, df2.rdd.map(lambda r: r.d).first())\n self.assertEqual([None, \"\"], df2.rdd.map(lambda r: r.s).collect())\n df2.createOrReplaceTempView(\"test2\")\n result = self.spark.sql(\"SELECT l[0].a from test2 where d['key'].d = '2'\")\n self.assertEqual(1, result.head()[0])\n\n def test_infer_schema_not_enough_names(self):\n df = self.spark.createDataFrame([[\"a\", \"b\"]], [\"col1\"])\n self.assertEqual(df.columns, ['col1', '_2'])\n\n def test_infer_schema_fails(self):\n with self.assertRaisesRegexp(TypeError, 'field a'):\n self.spark.createDataFrame(self.spark.sparkContext.parallelize([[1, 1], [\"x\", 1]]),\n schema=[\"a\", \"b\"], samplingRatio=0.99)\n\n def test_infer_nested_schema(self):\n NestedRow = Row(\"f1\", \"f2\")\n nestedRdd1 = self.sc.parallelize([NestedRow([1, 2], {\"row1\": 1.0}),\n NestedRow([2, 3], {\"row2\": 2.0})])\n df = self.spark.createDataFrame(nestedRdd1)\n self.assertEqual(Row(f1=[1, 2], f2={u'row1': 1.0}), df.collect()[0])\n\n nestedRdd2 = self.sc.parallelize([NestedRow([[1, 2], [2, 3]], [1, 2]),\n NestedRow([[2, 3], [3, 4]], [2, 3])])\n df = self.spark.createDataFrame(nestedRdd2)\n self.assertEqual(Row(f1=[[1, 2], [2, 3]], f2=[1, 2]), df.collect()[0])\n\n from collections import namedtuple\n CustomRow = namedtuple('CustomRow', 'field1 field2')\n rdd = self.sc.parallelize([CustomRow(field1=1, field2=\"row1\"),\n CustomRow(field1=2, field2=\"row2\"),\n CustomRow(field1=3, field2=\"row3\")])\n df = self.spark.createDataFrame(rdd)\n self.assertEqual(Row(field1=1, field2=u'row1'), df.first())\n\n def test_create_dataframe_from_dict_respects_schema(self):\n df = self.spark.createDataFrame([{'a': 1}], [\"b\"])\n self.assertEqual(df.columns, ['b'])\n\n def test_create_dataframe_from_objects(self):\n data = [MyObject(1, \"1\"), MyObject(2, \"2\")]\n df = self.spark.createDataFrame(data)\n self.assertEqual(df.dtypes, [(\"key\", \"bigint\"), (\"value\", \"string\")])\n self.assertEqual(df.first(), Row(key=1, value=\"1\"))\n\n def test_select_null_literal(self):\n df = self.spark.sql(\"select null as col\")\n self.assertEqual(Row(col=None), df.first())\n\n def test_apply_schema(self):\n from datetime import date, datetime\n rdd = self.sc.parallelize([(127, -128, -32768, 32767, 2147483647, 1.0,\n date(2010, 1, 1), datetime(2010, 1, 1, 1, 1, 1),\n {\"a\": 1}, (2,), [1, 2, 3], None)])\n schema = StructType([\n StructField(\"byte1\", ByteType(), False),\n StructField(\"byte2\", ByteType(), False),\n StructField(\"short1\", ShortType(), False),\n StructField(\"short2\", ShortType(), False),\n StructField(\"int1\", IntegerType(), False),\n StructField(\"float1\", FloatType(), False),\n StructField(\"date1\", DateType(), False),\n StructField(\"time1\", TimestampType(), False),\n StructField(\"map1\", MapType(StringType(), IntegerType(), False), False),\n StructField(\"struct1\", StructType([StructField(\"b\", ShortType(), False)]), False),\n StructField(\"list1\", ArrayType(ByteType(), False), False),\n StructField(\"null1\", DoubleType(), True)])\n df = self.spark.createDataFrame(rdd, schema)\n results = df.rdd.map(lambda x: (x.byte1, x.byte2, x.short1, x.short2, x.int1, x.float1,\n x.date1, x.time1, x.map1[\"a\"], x.struct1.b, x.list1, x.null1))\n r = (127, -128, -32768, 32767, 2147483647, 1.0, date(2010, 1, 1),\n datetime(2010, 1, 1, 1, 1, 1), 1, 2, [1, 2, 3], None)\n self.assertEqual(r, results.first())\n\n df.createOrReplaceTempView(\"table2\")\n r = self.spark.sql(\"SELECT byte1 - 1 AS byte1, byte2 + 1 AS byte2, \" +\n \"short1 + 1 AS short1, short2 - 1 AS short2, int1 - 1 AS int1, \" +\n \"float1 + 1.5 as float1 FROM table2\").first()\n\n self.assertEqual((126, -127, -32767, 32766, 2147483646, 2.5), tuple(r))\n\n def test_struct_in_map(self):\n d = [Row(m={Row(i=1): Row(s=\"\")})]\n df = self.sc.parallelize(d).toDF()\n k, v = list(df.head().m.items())[0]\n self.assertEqual(1, k.i)\n self.assertEqual(\"\", v.s)\n\n def test_convert_row_to_dict(self):\n row = Row(l=[Row(a=1, b='s')], d={\"key\": Row(c=1.0, d=\"2\")})\n self.assertEqual(1, row.asDict()['l'][0].a)\n df = self.sc.parallelize([row]).toDF()\n df.createOrReplaceTempView(\"test\")\n row = self.spark.sql(\"select l, d from test\").head()\n self.assertEqual(1, row.asDict()[\"l\"][0].a)\n self.assertEqual(1.0, row.asDict()['d']['key'].c)\n\n def test_udt(self):\n from pyspark.sql.types import _parse_datatype_json_string, _infer_type, _make_type_verifier\n from pyspark.sql.tests import ExamplePointUDT, ExamplePoint\n\n def check_datatype(datatype):\n pickled = pickle.loads(pickle.dumps(datatype))\n assert datatype == pickled\n scala_datatype = self.spark._jsparkSession.parseDataType(datatype.json())\n python_datatype = _parse_datatype_json_string(scala_datatype.json())\n assert datatype == python_datatype\n\n check_datatype(ExamplePointUDT())\n structtype_with_udt = StructType([StructField(\"label\", DoubleType(), False),\n StructField(\"point\", ExamplePointUDT(), False)])\n check_datatype(structtype_with_udt)\n p = ExamplePoint(1.0, 2.0)\n self.assertEqual(_infer_type(p), ExamplePointUDT())\n _make_type_verifier(ExamplePointUDT())(ExamplePoint(1.0, 2.0))\n self.assertRaises(ValueError, lambda: _make_type_verifier(ExamplePointUDT())([1.0, 2.0]))\n\n check_datatype(PythonOnlyUDT())\n structtype_with_udt = StructType([StructField(\"label\", DoubleType(), False),\n StructField(\"point\", PythonOnlyUDT(), False)])\n check_datatype(structtype_with_udt)\n p = PythonOnlyPoint(1.0, 2.0)\n self.assertEqual(_infer_type(p), PythonOnlyUDT())\n _make_type_verifier(PythonOnlyUDT())(PythonOnlyPoint(1.0, 2.0))\n self.assertRaises(\n ValueError,\n lambda: _make_type_verifier(PythonOnlyUDT())([1.0, 2.0]))\n\n def test_simple_udt_in_df(self):\n schema = StructType().add(\"key\", LongType()).add(\"val\", PythonOnlyUDT())\n df = self.spark.createDataFrame(\n [(i % 3, PythonOnlyPoint(float(i), float(i))) for i in range(10)],\n schema=schema)\n df.show()\n\n def test_nested_udt_in_df(self):\n schema = StructType().add(\"key\", LongType()).add(\"val\", ArrayType(PythonOnlyUDT()))\n df = self.spark.createDataFrame(\n [(i % 3, [PythonOnlyPoint(float(i), float(i))]) for i in range(10)],\n schema=schema)\n df.collect()\n\n schema = StructType().add(\"key\", LongType()).add(\"val\",\n MapType(LongType(), PythonOnlyUDT()))\n df = self.spark.createDataFrame(\n [(i % 3, {i % 3: PythonOnlyPoint(float(i + 1), float(i + 1))}) for i in range(10)],\n schema=schema)\n df.collect()\n\n def test_complex_nested_udt_in_df(self):\n from pyspark.sql.functions import udf\n\n schema = StructType().add(\"key\", LongType()).add(\"val\", PythonOnlyUDT())\n df = self.spark.createDataFrame(\n [(i % 3, PythonOnlyPoint(float(i), float(i))) for i in range(10)],\n schema=schema)\n df.collect()\n\n gd = df.groupby(\"key\").agg({\"val\": \"collect_list\"})\n gd.collect()\n udf = udf(lambda k, v: [(k, v[0])], ArrayType(df.schema))\n gd.select(udf(*gd)).collect()\n\n def test_udt_with_none(self):\n df = self.spark.range(0, 10, 1, 1)\n\n def myudf(x):\n if x > 0:\n return PythonOnlyPoint(float(x), float(x))\n\n self.spark.catalog.registerFunction(\"udf\", myudf, PythonOnlyUDT())\n rows = [r[0] for r in df.selectExpr(\"udf(id)\").take(2)]\n self.assertEqual(rows, [None, PythonOnlyPoint(1, 1)])\n\n def test_nonparam_udf_with_aggregate(self):\n import pyspark.sql.functions as f\n\n df = self.spark.createDataFrame([(1, 2), (1, 2)])\n f_udf = f.udf(lambda: \"const_str\")\n rows = df.distinct().withColumn(\"a\", f_udf()).collect()\n self.assertEqual(rows, [Row(_1=1, _2=2, a=u'const_str')])\n\n def test_infer_schema_with_udt(self):\n from pyspark.sql.tests import ExamplePoint, ExamplePointUDT\n row = Row(label=1.0, point=ExamplePoint(1.0, 2.0))\n df = self.spark.createDataFrame([row])\n schema = df.schema\n field = [f for f in schema.fields if f.name == \"point\"][0]\n self.assertEqual(type(field.dataType), ExamplePointUDT)\n df.createOrReplaceTempView(\"labeled_point\")\n point = self.spark.sql(\"SELECT point FROM labeled_point\").head().point\n self.assertEqual(point, ExamplePoint(1.0, 2.0))\n\n row = Row(label=1.0, point=PythonOnlyPoint(1.0, 2.0))\n df = self.spark.createDataFrame([row])\n schema = df.schema\n field = [f for f in schema.fields if f.name == \"point\"][0]\n self.assertEqual(type(field.dataType), PythonOnlyUDT)\n df.createOrReplaceTempView(\"labeled_point\")\n point = self.spark.sql(\"SELECT point FROM labeled_point\").head().point\n self.assertEqual(point, PythonOnlyPoint(1.0, 2.0))\n\n def test_apply_schema_with_udt(self):\n from pyspark.sql.tests import ExamplePoint, ExamplePointUDT\n row = (1.0, ExamplePoint(1.0, 2.0))\n schema = StructType([StructField(\"label\", DoubleType(), False),\n StructField(\"point\", ExamplePointUDT(), False)])\n df = self.spark.createDataFrame([row], schema)\n point = df.head().point\n self.assertEqual(point, ExamplePoint(1.0, 2.0))\n\n row = (1.0, PythonOnlyPoint(1.0, 2.0))\n schema = StructType([StructField(\"label\", DoubleType(), False),\n StructField(\"point\", PythonOnlyUDT(), False)])\n df = self.spark.createDataFrame([row], schema)\n point = df.head().point\n self.assertEqual(point, PythonOnlyPoint(1.0, 2.0))\n\n def test_udf_with_udt(self):\n from pyspark.sql.tests import ExamplePoint, ExamplePointUDT\n row = Row(label=1.0, point=ExamplePoint(1.0, 2.0))\n df = self.spark.createDataFrame([row])\n self.assertEqual(1.0, df.rdd.map(lambda r: r.point.x).first())\n udf = UserDefinedFunction(lambda p: p.y, DoubleType())\n self.assertEqual(2.0, df.select(udf(df.point)).first()[0])\n udf2 = UserDefinedFunction(lambda p: ExamplePoint(p.x + 1, p.y + 1), ExamplePointUDT())\n self.assertEqual(ExamplePoint(2.0, 3.0), df.select(udf2(df.point)).first()[0])\n\n row = Row(label=1.0, point=PythonOnlyPoint(1.0, 2.0))\n df = self.spark.createDataFrame([row])\n self.assertEqual(1.0, df.rdd.map(lambda r: r.point.x).first())\n udf = UserDefinedFunction(lambda p: p.y, DoubleType())\n self.assertEqual(2.0, df.select(udf(df.point)).first()[0])\n udf2 = UserDefinedFunction(lambda p: PythonOnlyPoint(p.x + 1, p.y + 1), PythonOnlyUDT())\n self.assertEqual(PythonOnlyPoint(2.0, 3.0), df.select(udf2(df.point)).first()[0])\n\n def test_parquet_with_udt(self):\n from pyspark.sql.tests import ExamplePoint, ExamplePointUDT\n row = Row(label=1.0, point=ExamplePoint(1.0, 2.0))\n df0 = self.spark.createDataFrame([row])\n output_dir = os.path.join(self.tempdir.name, \"labeled_point\")\n df0.write.parquet(output_dir)\n df1 = self.spark.read.parquet(output_dir)\n point = df1.head().point\n self.assertEqual(point, ExamplePoint(1.0, 2.0))\n\n row = Row(label=1.0, point=PythonOnlyPoint(1.0, 2.0))\n df0 = self.spark.createDataFrame([row])\n df0.write.parquet(output_dir, mode='overwrite')\n df1 = self.spark.read.parquet(output_dir)\n point = df1.head().point\n self.assertEqual(point, PythonOnlyPoint(1.0, 2.0))\n\n def test_union_with_udt(self):\n from pyspark.sql.tests import ExamplePoint, ExamplePointUDT\n row1 = (1.0, ExamplePoint(1.0, 2.0))\n row2 = (2.0, ExamplePoint(3.0, 4.0))\n schema = StructType([StructField(\"label\", DoubleType(), False),\n StructField(\"point\", ExamplePointUDT(), False)])\n df1 = self.spark.createDataFrame([row1], schema)\n df2 = self.spark.createDataFrame([row2], schema)\n\n result = df1.union(df2).orderBy(\"label\").collect()\n self.assertEqual(\n result,\n [\n Row(label=1.0, point=ExamplePoint(1.0, 2.0)),\n Row(label=2.0, point=ExamplePoint(3.0, 4.0))\n ]\n )\n\n def test_cast_to_string_with_udt(self):\n from pyspark.sql.tests import ExamplePointUDT, ExamplePoint\n from pyspark.sql.functions import col\n row = (ExamplePoint(1.0, 2.0), PythonOnlyPoint(3.0, 4.0))\n schema = StructType([StructField(\"point\", ExamplePointUDT(), False),\n StructField(\"pypoint\", PythonOnlyUDT(), False)])\n df = self.spark.createDataFrame([row], schema)\n\n result = df.select(col('point').cast('string'), col('pypoint').cast('string')).head()\n self.assertEqual(result, Row(point=u'(1.0, 2.0)', pypoint=u'[3.0, 4.0]'))\n\n def test_column_operators(self):\n ci = self.df.key\n cs = self.df.value\n c = ci == cs\n self.assertTrue(isinstance((- ci - 1 - 2) % 3 * 2.5 / 3.5, Column))\n rcc = (1 + ci), (1 - ci), (1 * ci), (1 / ci), (1 % ci), (1 ** ci), (ci ** 1)\n self.assertTrue(all(isinstance(c, Column) for c in rcc))\n cb = [ci == 5, ci != 0, ci > 3, ci < 4, ci >= 0, ci <= 7]\n self.assertTrue(all(isinstance(c, Column) for c in cb))\n cbool = (ci & ci), (ci | ci), (~ci)\n self.assertTrue(all(isinstance(c, Column) for c in cbool))\n css = cs.contains('a'), cs.like('a'), cs.rlike('a'), cs.asc(), cs.desc(),\\\n cs.startswith('a'), cs.endswith('a'), ci.eqNullSafe(cs)\n self.assertTrue(all(isinstance(c, Column) for c in css))\n self.assertTrue(isinstance(ci.cast(LongType()), Column))\n self.assertRaisesRegexp(ValueError,\n \"Cannot apply 'in' operator against a column\",\n lambda: 1 in cs)\n\n def test_column_getitem(self):\n from pyspark.sql.functions import col\n\n self.assertIsInstance(col(\"foo\")[1:3], Column)\n self.assertIsInstance(col(\"foo\")[0], Column)\n self.assertIsInstance(col(\"foo\")[\"bar\"], Column)\n self.assertRaises(ValueError, lambda: col(\"foo\")[0:10:2])\n\n def test_column_select(self):\n df = self.df\n self.assertEqual(self.testData, df.select(\"*\").collect())\n self.assertEqual(self.testData, df.select(df.key, df.value).collect())\n self.assertEqual([Row(value='1')], df.where(df.key == 1).select(df.value).collect())\n\n def test_freqItems(self):\n vals = [Row(a=1, b=-2.0) if i % 2 == 0 else Row(a=i, b=i * 1.0) for i in range(100)]\n df = self.sc.parallelize(vals).toDF()\n items = df.stat.freqItems((\"a\", \"b\"), 0.4).collect()[0]\n self.assertTrue(1 in items[0])\n self.assertTrue(-2.0 in items[1])\n\n def test_aggregator(self):\n df = self.df\n g = df.groupBy()\n self.assertEqual([99, 100], sorted(g.agg({'key': 'max', 'value': 'count'}).collect()[0]))\n self.assertEqual([Row(**{\"AVG(key#0)\": 49.5})], g.mean().collect())\n\n from pyspark.sql import functions\n self.assertEqual((0, u'99'),\n tuple(g.agg(functions.first(df.key), functions.last(df.value)).first()))\n self.assertTrue(95 < g.agg(functions.approxCountDistinct(df.key)).first()[0])\n self.assertEqual(100, g.agg(functions.countDistinct(df.value)).first()[0])\n\n def test_first_last_ignorenulls(self):\n from pyspark.sql import functions\n df = self.spark.range(0, 100)\n df2 = df.select(functions.when(df.id % 3 == 0, None).otherwise(df.id).alias(\"id\"))\n df3 = df2.select(functions.first(df2.id, False).alias('a'),\n functions.first(df2.id, True).alias('b'),\n functions.last(df2.id, False).alias('c'),\n functions.last(df2.id, True).alias('d'))\n self.assertEqual([Row(a=None, b=1, c=None, d=98)], df3.collect())\n\n def test_approxQuantile(self):\n df = self.sc.parallelize([Row(a=i, b=i+10) for i in range(10)]).toDF()\n for f in [\"a\", u\"a\"]:\n aq = df.stat.approxQuantile(f, [0.1, 0.5, 0.9], 0.1)\n self.assertTrue(isinstance(aq, list))\n self.assertEqual(len(aq), 3)\n self.assertTrue(all(isinstance(q, float) for q in aq))\n aqs = df.stat.approxQuantile([\"a\", u\"b\"], [0.1, 0.5, 0.9], 0.1)\n self.assertTrue(isinstance(aqs, list))\n self.assertEqual(len(aqs), 2)\n self.assertTrue(isinstance(aqs[0], list))\n self.assertEqual(len(aqs[0]), 3)\n self.assertTrue(all(isinstance(q, float) for q in aqs[0]))\n self.assertTrue(isinstance(aqs[1], list))\n self.assertEqual(len(aqs[1]), 3)\n self.assertTrue(all(isinstance(q, float) for q in aqs[1]))\n aqt = df.stat.approxQuantile((u\"a\", \"b\"), [0.1, 0.5, 0.9], 0.1)\n self.assertTrue(isinstance(aqt, list))\n self.assertEqual(len(aqt), 2)\n self.assertTrue(isinstance(aqt[0], list))\n self.assertEqual(len(aqt[0]), 3)\n self.assertTrue(all(isinstance(q, float) for q in aqt[0]))\n self.assertTrue(isinstance(aqt[1], list))\n self.assertEqual(len(aqt[1]), 3)\n self.assertTrue(all(isinstance(q, float) for q in aqt[1]))\n self.assertRaises(ValueError, lambda: df.stat.approxQuantile(123, [0.1, 0.9], 0.1))\n self.assertRaises(ValueError, lambda: df.stat.approxQuantile((\"a\", 123), [0.1, 0.9], 0.1))\n self.assertRaises(ValueError, lambda: df.stat.approxQuantile([\"a\", 123], [0.1, 0.9], 0.1))\n\n def test_corr(self):\n import math\n df = self.sc.parallelize([Row(a=i, b=math.sqrt(i)) for i in range(10)]).toDF()\n corr = df.stat.corr(u\"a\", \"b\")\n self.assertTrue(abs(corr - 0.95734012) < 1e-6)\n\n def test_sampleby(self):\n df = self.sc.parallelize([Row(a=i, b=(i % 3)) for i in range(10)]).toDF()\n sampled = df.stat.sampleBy(u\"b\", fractions={0: 0.5, 1: 0.5}, seed=0)\n self.assertTrue(sampled.count() == 3)\n\n def test_cov(self):\n df = self.sc.parallelize([Row(a=i, b=2 * i) for i in range(10)]).toDF()\n cov = df.stat.cov(u\"a\", \"b\")\n self.assertTrue(abs(cov - 55.0 / 3) < 1e-6)\n\n def test_crosstab(self):\n df = self.sc.parallelize([Row(a=i % 3, b=i % 2) for i in range(1, 7)]).toDF()\n ct = df.stat.crosstab(u\"a\", \"b\").collect()\n ct = sorted(ct, key=lambda x: x[0])\n for i, row in enumerate(ct):\n self.assertEqual(row[0], str(i))\n self.assertTrue(row[1], 1)\n self.assertTrue(row[2], 1)\n\n def test_math_functions(self):\n df = self.sc.parallelize([Row(a=i, b=2 * i) for i in range(10)]).toDF()\n from pyspark.sql import functions\n import math\n\n def get_values(l):\n return [j[0] for j in l]\n\n def assert_close(a, b):\n c = get_values(b)\n diff = [abs(v - c[k]) < 1e-6 for k, v in enumerate(a)]\n return sum(diff) == len(a)\n assert_close([math.cos(i) for i in range(10)],\n df.select(functions.cos(df.a)).collect())\n assert_close([math.cos(i) for i in range(10)],\n df.select(functions.cos(\"a\")).collect())\n assert_close([math.sin(i) for i in range(10)],\n df.select(functions.sin(df.a)).collect())\n assert_close([math.sin(i) for i in range(10)],\n df.select(functions.sin(df['a'])).collect())\n assert_close([math.pow(i, 2 * i) for i in range(10)],\n df.select(functions.pow(df.a, df.b)).collect())\n assert_close([math.pow(i, 2) for i in range(10)],\n df.select(functions.pow(df.a, 2)).collect())\n assert_close([math.pow(i, 2) for i in range(10)],\n df.select(functions.pow(df.a, 2.0)).collect())\n assert_close([math.hypot(i, 2 * i) for i in range(10)],\n df.select(functions.hypot(df.a, df.b)).collect())\n\n def test_rand_functions(self):\n df = self.df\n from pyspark.sql import functions\n rnd = df.select('key', functions.rand()).collect()\n for row in rnd:\n assert row[1] >= 0.0 and row[1] <= 1.0, \"got: %s\" % row[1]\n rndn = df.select('key', functions.randn(5)).collect()\n for row in rndn:\n assert row[1] >= -4.0 and row[1] <= 4.0, \"got: %s\" % row[1]\n\n # If the specified seed is 0, we should use it.\n # https://issues.apache.org/jira/browse/SPARK-9691\n rnd1 = df.select('key', functions.rand(0)).collect()\n rnd2 = df.select('key', functions.rand(0)).collect()\n self.assertEqual(sorted(rnd1), sorted(rnd2))\n\n rndn1 = df.select('key', functions.randn(0)).collect()\n rndn2 = df.select('key', functions.randn(0)).collect()\n self.assertEqual(sorted(rndn1), sorted(rndn2))\n\n def test_string_functions(self):\n from pyspark.sql.functions import col, lit\n df = self.spark.createDataFrame([['nick']], schema=['name'])\n self.assertRaisesRegexp(\n TypeError,\n \"must be the same type\",\n lambda: df.select(col('name').substr(0, lit(1))))\n if sys.version_info.major == 2:\n self.assertRaises(\n TypeError,\n lambda: df.select(col('name').substr(long(0), long(1))))\n\n def test_array_contains_function(self):\n from pyspark.sql.functions import array_contains\n\n df = self.spark.createDataFrame([([\"1\", \"2\", \"3\"],), ([],)], ['data'])\n actual = df.select(array_contains(df.data, 1).alias('b')).collect()\n # The value argument can be implicitly castable to the element's type of the array.\n self.assertEqual([Row(b=True), Row(b=False)], actual)\n\n def test_between_function(self):\n df = self.sc.parallelize([\n Row(a=1, b=2, c=3),\n Row(a=2, b=1, c=3),\n Row(a=4, b=1, c=4)]).toDF()\n self.assertEqual([Row(a=2, b=1, c=3), Row(a=4, b=1, c=4)],\n df.filter(df.a.between(df.b, df.c)).collect())\n\n def test_struct_type(self):\n struct1 = StructType().add(\"f1\", StringType(), True).add(\"f2\", StringType(), True, None)\n struct2 = StructType([StructField(\"f1\", StringType(), True),\n StructField(\"f2\", StringType(), True, None)])\n self.assertEqual(struct1.fieldNames(), struct2.names)\n self.assertEqual(struct1, struct2)\n\n struct1 = StructType().add(\"f1\", StringType(), True).add(\"f2\", StringType(), True, None)\n struct2 = StructType([StructField(\"f1\", StringType(), True)])\n self.assertNotEqual(struct1.fieldNames(), struct2.names)\n self.assertNotEqual(struct1, struct2)\n\n struct1 = (StructType().add(StructField(\"f1\", StringType(), True))\n .add(StructField(\"f2\", StringType(), True, None)))\n struct2 = StructType([StructField(\"f1\", StringType(), True),\n StructField(\"f2\", StringType(), True, None)])\n self.assertEqual(struct1.fieldNames(), struct2.names)\n self.assertEqual(struct1, struct2)\n\n struct1 = (StructType().add(StructField(\"f1\", StringType(), True))\n .add(StructField(\"f2\", StringType(), True, None)))\n struct2 = StructType([StructField(\"f1\", StringType(), True)])\n self.assertNotEqual(struct1.fieldNames(), struct2.names)\n self.assertNotEqual(struct1, struct2)\n\n # Catch exception raised during improper construction\n self.assertRaises(ValueError, lambda: StructType().add(\"name\"))\n\n struct1 = StructType().add(\"f1\", StringType(), True).add(\"f2\", StringType(), True, None)\n for field in struct1:\n self.assertIsInstance(field, StructField)\n\n struct1 = StructType().add(\"f1\", StringType(), True).add(\"f2\", StringType(), True, None)\n self.assertEqual(len(struct1), 2)\n\n struct1 = StructType().add(\"f1\", StringType(), True).add(\"f2\", StringType(), True, None)\n self.assertIs(struct1[\"f1\"], struct1.fields[0])\n self.assertIs(struct1[0], struct1.fields[0])\n self.assertEqual(struct1[0:1], StructType(struct1.fields[0:1]))\n self.assertRaises(KeyError, lambda: struct1[\"f9\"])\n self.assertRaises(IndexError, lambda: struct1[9])\n self.assertRaises(TypeError, lambda: struct1[9.9])\n\n def test_parse_datatype_string(self):\n from pyspark.sql.types import _all_atomic_types, _parse_datatype_string\n for k, t in _all_atomic_types.items():\n if t != NullType:\n self.assertEqual(t(), _parse_datatype_string(k))\n self.assertEqual(IntegerType(), _parse_datatype_string(\"int\"))\n self.assertEqual(DecimalType(1, 1), _parse_datatype_string(\"decimal(1 ,1)\"))\n self.assertEqual(DecimalType(10, 1), _parse_datatype_string(\"decimal( 10,1 )\"))\n self.assertEqual(DecimalType(11, 1), _parse_datatype_string(\"decimal(11,1)\"))\n self.assertEqual(\n ArrayType(IntegerType()),\n _parse_datatype_string(\"array<int >\"))\n self.assertEqual(\n MapType(IntegerType(), DoubleType()),\n _parse_datatype_string(\"map< int, double >\"))\n self.assertEqual(\n StructType([StructField(\"a\", IntegerType()), StructField(\"c\", DoubleType())]),\n _parse_datatype_string(\"struct<a:int, c:double >\"))\n self.assertEqual(\n StructType([StructField(\"a\", IntegerType()), StructField(\"c\", DoubleType())]),\n _parse_datatype_string(\"a:int, c:double\"))\n self.assertEqual(\n StructType([StructField(\"a\", IntegerType()), StructField(\"c\", DoubleType())]),\n _parse_datatype_string(\"a INT, c DOUBLE\"))\n\n def test_metadata_null(self):\n schema = StructType([StructField(\"f1\", StringType(), True, None),\n StructField(\"f2\", StringType(), True, {'a': None})])\n rdd = self.sc.parallelize([[\"a\", \"b\"], [\"c\", \"d\"]])\n self.spark.createDataFrame(rdd, schema)\n\n def test_save_and_load(self):\n df = self.df\n tmpPath = tempfile.mkdtemp()\n shutil.rmtree(tmpPath)\n df.write.json(tmpPath)\n actual = self.spark.read.json(tmpPath)\n self.assertEqual(sorted(df.collect()), sorted(actual.collect()))\n\n schema = StructType([StructField(\"value\", StringType(), True)])\n actual = self.spark.read.json(tmpPath, schema)\n self.assertEqual(sorted(df.select(\"value\").collect()), sorted(actual.collect()))\n\n df.write.json(tmpPath, \"overwrite\")\n actual = self.spark.read.json(tmpPath)\n self.assertEqual(sorted(df.collect()), sorted(actual.collect()))\n\n df.write.save(format=\"json\", mode=\"overwrite\", path=tmpPath,\n noUse=\"this options will not be used in save.\")\n actual = self.spark.read.load(format=\"json\", path=tmpPath,\n noUse=\"this options will not be used in load.\")\n self.assertEqual(sorted(df.collect()), sorted(actual.collect()))\n\n defaultDataSourceName = self.spark.conf.get(\"spark.sql.sources.default\",\n \"org.apache.spark.sql.parquet\")\n self.spark.sql(\"SET spark.sql.sources.default=org.apache.spark.sql.json\")\n actual = self.spark.read.load(path=tmpPath)\n self.assertEqual(sorted(df.collect()), sorted(actual.collect()))\n self.spark.sql(\"SET spark.sql.sources.default=\" + defaultDataSourceName)\n\n csvpath = os.path.join(tempfile.mkdtemp(), 'data')\n df.write.option('quote', None).format('csv').save(csvpath)\n\n shutil.rmtree(tmpPath)\n\n def test_save_and_load_builder(self):\n df = self.df\n tmpPath = tempfile.mkdtemp()\n shutil.rmtree(tmpPath)\n df.write.json(tmpPath)\n actual = self.spark.read.json(tmpPath)\n self.assertEqual(sorted(df.collect()), sorted(actual.collect()))\n\n schema = StructType([StructField(\"value\", StringType(), True)])\n actual = self.spark.read.json(tmpPath, schema)\n self.assertEqual(sorted(df.select(\"value\").collect()), sorted(actual.collect()))\n\n df.write.mode(\"overwrite\").json(tmpPath)\n actual = self.spark.read.json(tmpPath)\n self.assertEqual(sorted(df.collect()), sorted(actual.collect()))\n\n df.write.mode(\"overwrite\").options(noUse=\"this options will not be used in save.\")\\\n .option(\"noUse\", \"this option will not be used in save.\")\\\n .format(\"json\").save(path=tmpPath)\n actual =\\\n self.spark.read.format(\"json\")\\\n .load(path=tmpPath, noUse=\"this options will not be used in load.\")\n self.assertEqual(sorted(df.collect()), sorted(actual.collect()))\n\n defaultDataSourceName = self.spark.conf.get(\"spark.sql.sources.default\",\n \"org.apache.spark.sql.parquet\")\n self.spark.sql(\"SET spark.sql.sources.default=org.apache.spark.sql.json\")\n actual = self.spark.read.load(path=tmpPath)\n self.assertEqual(sorted(df.collect()), sorted(actual.collect()))\n self.spark.sql(\"SET spark.sql.sources.default=\" + defaultDataSourceName)\n\n shutil.rmtree(tmpPath)\n\n def test_stream_trigger(self):\n df = self.spark.readStream.format('text').load('python/test_support/sql/streaming')\n\n # Should take at least one arg\n try:\n df.writeStream.trigger()\n except ValueError:\n pass\n\n # Should not take multiple args\n try:\n df.writeStream.trigger(once=True, processingTime='5 seconds')\n except ValueError:\n pass\n\n # Should not take multiple args\n try:\n df.writeStream.trigger(processingTime='5 seconds', continuous='1 second')\n except ValueError:\n pass\n\n # Should take only keyword args\n try:\n df.writeStream.trigger('5 seconds')\n self.fail(\"Should have thrown an exception\")\n except TypeError:\n pass\n\n def test_stream_read_options(self):\n schema = StructType([StructField(\"data\", StringType(), False)])\n df = self.spark.readStream\\\n .format('text')\\\n .option('path', 'python/test_support/sql/streaming')\\\n .schema(schema)\\\n .load()\n self.assertTrue(df.isStreaming)\n self.assertEqual(df.schema.simpleString(), \"struct<data:string>\")\n\n def test_stream_read_options_overwrite(self):\n bad_schema = StructType([StructField(\"test\", IntegerType(), False)])\n schema = StructType([StructField(\"data\", StringType(), False)])\n df = self.spark.readStream.format('csv').option('path', 'python/test_support/sql/fake') \\\n .schema(bad_schema)\\\n .load(path='python/test_support/sql/streaming', schema=schema, format='text')\n self.assertTrue(df.isStreaming)\n self.assertEqual(df.schema.simpleString(), \"struct<data:string>\")\n\n def test_stream_save_options(self):\n df = self.spark.readStream.format('text').load('python/test_support/sql/streaming') \\\n .withColumn('id', lit(1))\n for q in self.spark._wrapped.streams.active:\n q.stop()\n tmpPath = tempfile.mkdtemp()\n shutil.rmtree(tmpPath)\n self.assertTrue(df.isStreaming)\n out = os.path.join(tmpPath, 'out')\n chk = os.path.join(tmpPath, 'chk')\n q = df.writeStream.option('checkpointLocation', chk).queryName('this_query') \\\n .format('parquet').partitionBy('id').outputMode('append').option('path', out).start()\n try:\n self.assertEqual(q.name, 'this_query')\n self.assertTrue(q.isActive)\n q.processAllAvailable()\n output_files = []\n for _, _, files in os.walk(out):\n output_files.extend([f for f in files if not f.startswith('.')])\n self.assertTrue(len(output_files) > 0)\n self.assertTrue(len(os.listdir(chk)) > 0)\n finally:\n q.stop()\n shutil.rmtree(tmpPath)\n\n def test_stream_save_options_overwrite(self):\n df = self.spark.readStream.format('text').load('python/test_support/sql/streaming')\n for q in self.spark._wrapped.streams.active:\n q.stop()\n tmpPath = tempfile.mkdtemp()\n shutil.rmtree(tmpPath)\n self.assertTrue(df.isStreaming)\n out = os.path.join(tmpPath, 'out')\n chk = os.path.join(tmpPath, 'chk')\n fake1 = os.path.join(tmpPath, 'fake1')\n fake2 = os.path.join(tmpPath, 'fake2')\n q = df.writeStream.option('checkpointLocation', fake1)\\\n .format('memory').option('path', fake2) \\\n .queryName('fake_query').outputMode('append') \\\n .start(path=out, format='parquet', queryName='this_query', checkpointLocation=chk)\n\n try:\n self.assertEqual(q.name, 'this_query')\n self.assertTrue(q.isActive)\n q.processAllAvailable()\n output_files = []\n for _, _, files in os.walk(out):\n output_files.extend([f for f in files if not f.startswith('.')])\n self.assertTrue(len(output_files) > 0)\n self.assertTrue(len(os.listdir(chk)) > 0)\n self.assertFalse(os.path.isdir(fake1)) # should not have been created\n self.assertFalse(os.path.isdir(fake2)) # should not have been created\n finally:\n q.stop()\n shutil.rmtree(tmpPath)\n\n def test_stream_status_and_progress(self):\n df = self.spark.readStream.format('text').load('python/test_support/sql/streaming')\n for q in self.spark._wrapped.streams.active:\n q.stop()\n tmpPath = tempfile.mkdtemp()\n shutil.rmtree(tmpPath)\n self.assertTrue(df.isStreaming)\n out = os.path.join(tmpPath, 'out')\n chk = os.path.join(tmpPath, 'chk')\n\n def func(x):\n time.sleep(1)\n return x\n\n from pyspark.sql.functions import col, udf\n sleep_udf = udf(func)\n\n # Use \"sleep_udf\" to delay the progress update so that we can test `lastProgress` when there\n # were no updates.\n q = df.select(sleep_udf(col(\"value\")).alias('value')).writeStream \\\n .start(path=out, format='parquet', queryName='this_query', checkpointLocation=chk)\n try:\n # \"lastProgress\" will return None in most cases. However, as it may be flaky when\n # Jenkins is very slow, we don't assert it. If there is something wrong, \"lastProgress\"\n # may throw error with a high chance and make this test flaky, so we should still be\n # able to detect broken codes.\n q.lastProgress\n\n q.processAllAvailable()\n lastProgress = q.lastProgress\n recentProgress = q.recentProgress\n status = q.status\n self.assertEqual(lastProgress['name'], q.name)\n self.assertEqual(lastProgress['id'], q.id)\n self.assertTrue(any(p == lastProgress for p in recentProgress))\n self.assertTrue(\n \"message\" in status and\n \"isDataAvailable\" in status and\n \"isTriggerActive\" in status)\n finally:\n q.stop()\n shutil.rmtree(tmpPath)\n\n def test_stream_await_termination(self):\n df = self.spark.readStream.format('text').load('python/test_support/sql/streaming')\n for q in self.spark._wrapped.streams.active:\n q.stop()\n tmpPath = tempfile.mkdtemp()\n shutil.rmtree(tmpPath)\n self.assertTrue(df.isStreaming)\n out = os.path.join(tmpPath, 'out')\n chk = os.path.join(tmpPath, 'chk')\n q = df.writeStream\\\n .start(path=out, format='parquet', queryName='this_query', checkpointLocation=chk)\n try:\n self.assertTrue(q.isActive)\n try:\n q.awaitTermination(\"hello\")\n self.fail(\"Expected a value exception\")\n except ValueError:\n pass\n now = time.time()\n # test should take at least 2 seconds\n res = q.awaitTermination(2.6)\n duration = time.time() - now\n self.assertTrue(duration >= 2)\n self.assertFalse(res)\n finally:\n q.stop()\n shutil.rmtree(tmpPath)\n\n def test_stream_exception(self):\n sdf = self.spark.readStream.format('text').load('python/test_support/sql/streaming')\n sq = sdf.writeStream.format('memory').queryName('query_explain').start()\n try:\n sq.processAllAvailable()\n self.assertEqual(sq.exception(), None)\n finally:\n sq.stop()\n\n from pyspark.sql.functions import col, udf\n from pyspark.sql.utils import StreamingQueryException\n bad_udf = udf(lambda x: 1 / 0)\n sq = sdf.select(bad_udf(col(\"value\")))\\\n .writeStream\\\n .format('memory')\\\n .queryName('this_query')\\\n .start()\n try:\n # Process some data to fail the query\n sq.processAllAvailable()\n self.fail(\"bad udf should fail the query\")\n except StreamingQueryException as e:\n # This is expected\n self.assertTrue(\"ZeroDivisionError\" in e.desc)\n finally:\n sq.stop()\n self.assertTrue(type(sq.exception()) is StreamingQueryException)\n self.assertTrue(\"ZeroDivisionError\" in sq.exception().desc)\n\n def test_query_manager_await_termination(self):\n df = self.spark.readStream.format('text').load('python/test_support/sql/streaming')\n for q in self.spark._wrapped.streams.active:\n q.stop()\n tmpPath = tempfile.mkdtemp()\n shutil.rmtree(tmpPath)\n self.assertTrue(df.isStreaming)\n out = os.path.join(tmpPath, 'out')\n chk = os.path.join(tmpPath, 'chk')\n q = df.writeStream\\\n .start(path=out, format='parquet', queryName='this_query', checkpointLocation=chk)\n try:\n self.assertTrue(q.isActive)\n try:\n self.spark._wrapped.streams.awaitAnyTermination(\"hello\")\n self.fail(\"Expected a value exception\")\n except ValueError:\n pass\n now = time.time()\n # test should take at least 2 seconds\n res = self.spark._wrapped.streams.awaitAnyTermination(2.6)\n duration = time.time() - now\n self.assertTrue(duration >= 2)\n self.assertFalse(res)\n finally:\n q.stop()\n shutil.rmtree(tmpPath)\n\n class ForeachWriterTester:\n\n def __init__(self, spark):\n self.spark = spark\n\n def write_open_event(self, partitionId, epochId):\n self._write_event(\n self.open_events_dir,\n {'partition': partitionId, 'epoch': epochId})\n\n def write_process_event(self, row):\n self._write_event(self.process_events_dir, {'value': 'text'})\n\n def write_close_event(self, error):\n self._write_event(self.close_events_dir, {'error': str(error)})\n\n def write_input_file(self):\n self._write_event(self.input_dir, \"text\")\n\n def open_events(self):\n return self._read_events(self.open_events_dir, 'partition INT, epoch INT')\n\n def process_events(self):\n return self._read_events(self.process_events_dir, 'value STRING')\n\n def close_events(self):\n return self._read_events(self.close_events_dir, 'error STRING')\n\n def run_streaming_query_on_writer(self, writer, num_files):\n self._reset()\n try:\n sdf = self.spark.readStream.format('text').load(self.input_dir)\n sq = sdf.writeStream.foreach(writer).start()\n for i in range(num_files):\n self.write_input_file()\n sq.processAllAvailable()\n finally:\n self.stop_all()\n\n def assert_invalid_writer(self, writer, msg=None):\n self._reset()\n try:\n sdf = self.spark.readStream.format('text').load(self.input_dir)\n sq = sdf.writeStream.foreach(writer).start()\n self.write_input_file()\n sq.processAllAvailable()\n self.fail(\"invalid writer %s did not fail the query\" % str(writer)) # not expected\n except Exception as e:\n if msg:\n assert msg in str(e), \"%s not in %s\" % (msg, str(e))\n\n finally:\n self.stop_all()\n\n def stop_all(self):\n for q in self.spark._wrapped.streams.active:\n q.stop()\n\n def _reset(self):\n self.input_dir = tempfile.mkdtemp()\n self.open_events_dir = tempfile.mkdtemp()\n self.process_events_dir = tempfile.mkdtemp()\n self.close_events_dir = tempfile.mkdtemp()\n\n def _read_events(self, dir, json):\n rows = self.spark.read.schema(json).json(dir).collect()\n dicts = [row.asDict() for row in rows]\n return dicts\n\n def _write_event(self, dir, event):\n import uuid\n with open(os.path.join(dir, str(uuid.uuid4())), 'w') as f:\n f.write(\"%s\\n\" % str(event))\n\n def __getstate__(self):\n return (self.open_events_dir, self.process_events_dir, self.close_events_dir)\n\n def __setstate__(self, state):\n self.open_events_dir, self.process_events_dir, self.close_events_dir = state\n\n def test_streaming_foreach_with_simple_function(self):\n tester = self.ForeachWriterTester(self.spark)\n\n def foreach_func(row):\n tester.write_process_event(row)\n\n tester.run_streaming_query_on_writer(foreach_func, 2)\n self.assertEqual(len(tester.process_events()), 2)\n\n def test_streaming_foreach_with_basic_open_process_close(self):\n tester = self.ForeachWriterTester(self.spark)\n\n class ForeachWriter:\n def open(self, partitionId, epochId):\n tester.write_open_event(partitionId, epochId)\n return True\n\n def process(self, row):\n tester.write_process_event(row)\n\n def close(self, error):\n tester.write_close_event(error)\n\n tester.run_streaming_query_on_writer(ForeachWriter(), 2)\n\n open_events = tester.open_events()\n self.assertEqual(len(open_events), 2)\n self.assertSetEqual(set([e['epoch'] for e in open_events]), {0, 1})\n\n self.assertEqual(len(tester.process_events()), 2)\n\n close_events = tester.close_events()\n self.assertEqual(len(close_events), 2)\n self.assertSetEqual(set([e['error'] for e in close_events]), {'None'})\n\n def test_streaming_foreach_with_open_returning_false(self):\n tester = self.ForeachWriterTester(self.spark)\n\n class ForeachWriter:\n def open(self, partition_id, epoch_id):\n tester.write_open_event(partition_id, epoch_id)\n return False\n\n def process(self, row):\n tester.write_process_event(row)\n\n def close(self, error):\n tester.write_close_event(error)\n\n tester.run_streaming_query_on_writer(ForeachWriter(), 2)\n\n self.assertEqual(len(tester.open_events()), 2)\n\n self.assertEqual(len(tester.process_events()), 0) # no row was processed\n\n close_events = tester.close_events()\n self.assertEqual(len(close_events), 2)\n self.assertSetEqual(set([e['error'] for e in close_events]), {'None'})\n\n def test_streaming_foreach_without_open_method(self):\n tester = self.ForeachWriterTester(self.spark)\n\n class ForeachWriter:\n def process(self, row):\n tester.write_process_event(row)\n\n def close(self, error):\n tester.write_close_event(error)\n\n tester.run_streaming_query_on_writer(ForeachWriter(), 2)\n self.assertEqual(len(tester.open_events()), 0) # no open events\n self.assertEqual(len(tester.process_events()), 2)\n self.assertEqual(len(tester.close_events()), 2)\n\n def test_streaming_foreach_without_close_method(self):\n tester = self.ForeachWriterTester(self.spark)\n\n class ForeachWriter:\n def open(self, partition_id, epoch_id):\n tester.write_open_event(partition_id, epoch_id)\n return True\n\n def process(self, row):\n tester.write_process_event(row)\n\n tester.run_streaming_query_on_writer(ForeachWriter(), 2)\n self.assertEqual(len(tester.open_events()), 2) # no open events\n self.assertEqual(len(tester.process_events()), 2)\n self.assertEqual(len(tester.close_events()), 0)\n\n def test_streaming_foreach_without_open_and_close_methods(self):\n tester = self.ForeachWriterTester(self.spark)\n\n class ForeachWriter:\n def process(self, row):\n tester.write_process_event(row)\n\n tester.run_streaming_query_on_writer(ForeachWriter(), 2)\n self.assertEqual(len(tester.open_events()), 0) # no open events\n self.assertEqual(len(tester.process_events()), 2)\n self.assertEqual(len(tester.close_events()), 0)\n\n def test_streaming_foreach_with_process_throwing_error(self):\n from pyspark.sql.utils import StreamingQueryException\n\n tester = self.ForeachWriterTester(self.spark)\n\n class ForeachWriter:\n def process(self, row):\n raise Exception(\"test error\")\n\n def close(self, error):\n tester.write_close_event(error)\n\n try:\n tester.run_streaming_query_on_writer(ForeachWriter(), 1)\n self.fail(\"bad writer did not fail the query\") # this is not expected\n except StreamingQueryException as e:\n # TODO: Verify whether original error message is inside the exception\n pass\n\n self.assertEqual(len(tester.process_events()), 0) # no row was processed\n close_events = tester.close_events()\n self.assertEqual(len(close_events), 1)\n # TODO: Verify whether original error message is inside the exception\n\n def test_streaming_foreach_with_invalid_writers(self):\n\n tester = self.ForeachWriterTester(self.spark)\n\n def func_with_iterator_input(iter):\n for x in iter:\n print(x)\n\n tester.assert_invalid_writer(func_with_iterator_input)\n\n class WriterWithoutProcess:\n def open(self, partition):\n pass\n\n tester.assert_invalid_writer(WriterWithoutProcess(), \"does not have a 'process'\")\n\n class WriterWithNonCallableProcess():\n process = True\n\n tester.assert_invalid_writer(WriterWithNonCallableProcess(),\n \"'process' in provided object is not callable\")\n\n class WriterWithNoParamProcess():\n def process(self):\n pass\n\n tester.assert_invalid_writer(WriterWithNoParamProcess())\n\n # Abstract class for tests below\n class WithProcess():\n def process(self, row):\n pass\n\n class WriterWithNonCallableOpen(WithProcess):\n open = True\n\n tester.assert_invalid_writer(WriterWithNonCallableOpen(),\n \"'open' in provided object is not callable\")\n\n class WriterWithNoParamOpen(WithProcess):\n def open(self):\n pass\n\n tester.assert_invalid_writer(WriterWithNoParamOpen())\n\n class WriterWithNonCallableClose(WithProcess):\n close = True\n\n tester.assert_invalid_writer(WriterWithNonCallableClose(),\n \"'close' in provided object is not callable\")\n\n def test_streaming_foreachBatch(self):\n q = None\n collected = dict()\n\n def collectBatch(batch_df, batch_id):\n collected[batch_id] = batch_df.collect()\n\n try:\n df = self.spark.readStream.format('text').load('python/test_support/sql/streaming')\n q = df.writeStream.foreachBatch(collectBatch).start()\n q.processAllAvailable()\n self.assertTrue(0 in collected)\n self.assertTrue(len(collected[0]), 2)\n finally:\n if q:\n q.stop()\n\n def test_streaming_foreachBatch_propagates_python_errors(self):\n from pyspark.sql.utils import StreamingQueryException\n\n q = None\n\n def collectBatch(df, id):\n raise Exception(\"this should fail the query\")\n\n try:\n df = self.spark.readStream.format('text').load('python/test_support/sql/streaming')\n q = df.writeStream.foreachBatch(collectBatch).start()\n q.processAllAvailable()\n self.fail(\"Expected a failure\")\n except StreamingQueryException as e:\n self.assertTrue(\"this should fail\" in str(e))\n finally:\n if q:\n q.stop()\n\n def test_help_command(self):\n # Regression test for SPARK-5464\n rdd = self.sc.parallelize(['{\"foo\":\"bar\"}', '{\"foo\":\"baz\"}'])\n df = self.spark.read.json(rdd)\n # render_doc() reproduces the help() exception without printing output\n pydoc.render_doc(df)\n pydoc.render_doc(df.foo)\n pydoc.render_doc(df.take(1))\n\n def test_access_column(self):\n df = self.df\n self.assertTrue(isinstance(df.key, Column))\n self.assertTrue(isinstance(df['key'], Column))\n self.assertTrue(isinstance(df[0], Column))\n self.assertRaises(IndexError, lambda: df[2])\n self.assertRaises(AnalysisException, lambda: df[\"bad_key\"])\n self.assertRaises(TypeError, lambda: df[{}])\n\n def test_column_name_with_non_ascii(self):\n if sys.version >= '3':\n columnName = \"数量\"\n self.assertTrue(isinstance(columnName, str))\n else:\n columnName = unicode(\"数量\", \"utf-8\")\n self.assertTrue(isinstance(columnName, unicode))\n schema = StructType([StructField(columnName, LongType(), True)])\n df = self.spark.createDataFrame([(1,)], schema)\n self.assertEqual(schema, df.schema)\n self.assertEqual(\"DataFrame[数量: bigint]\", str(df))\n self.assertEqual([(\"数量\", 'bigint')], df.dtypes)\n self.assertEqual(1, df.select(\"数量\").first()[0])\n self.assertEqual(1, df.select(df[\"数量\"]).first()[0])\n\n def test_access_nested_types(self):\n df = self.sc.parallelize([Row(l=[1], r=Row(a=1, b=\"b\"), d={\"k\": \"v\"})]).toDF()\n self.assertEqual(1, df.select(df.l[0]).first()[0])\n self.assertEqual(1, df.select(df.l.getItem(0)).first()[0])\n self.assertEqual(1, df.select(df.r.a).first()[0])\n self.assertEqual(\"b\", df.select(df.r.getField(\"b\")).first()[0])\n self.assertEqual(\"v\", df.select(df.d[\"k\"]).first()[0])\n self.assertEqual(\"v\", df.select(df.d.getItem(\"k\")).first()[0])\n\n def test_field_accessor(self):\n df = self.sc.parallelize([Row(l=[1], r=Row(a=1, b=\"b\"), d={\"k\": \"v\"})]).toDF()\n self.assertEqual(1, df.select(df.l[0]).first()[0])\n self.assertEqual(1, df.select(df.r[\"a\"]).first()[0])\n self.assertEqual(1, df.select(df[\"r.a\"]).first()[0])\n self.assertEqual(\"b\", df.select(df.r[\"b\"]).first()[0])\n self.assertEqual(\"b\", df.select(df[\"r.b\"]).first()[0])\n self.assertEqual(\"v\", df.select(df.d[\"k\"]).first()[0])\n\n def test_infer_long_type(self):\n longrow = [Row(f1='a', f2=100000000000000)]\n df = self.sc.parallelize(longrow).toDF()\n self.assertEqual(df.schema.fields[1].dataType, LongType())\n\n # this saving as Parquet caused issues as well.\n output_dir = os.path.join(self.tempdir.name, \"infer_long_type\")\n df.write.parquet(output_dir)\n df1 = self.spark.read.parquet(output_dir)\n self.assertEqual('a', df1.first().f1)\n self.assertEqual(100000000000000, df1.first().f2)\n\n self.assertEqual(_infer_type(1), LongType())\n self.assertEqual(_infer_type(2**10), LongType())\n self.assertEqual(_infer_type(2**20), LongType())\n self.assertEqual(_infer_type(2**31 - 1), LongType())\n self.assertEqual(_infer_type(2**31), LongType())\n self.assertEqual(_infer_type(2**61), LongType())\n self.assertEqual(_infer_type(2**71), LongType())\n\n def test_merge_type(self):\n self.assertEqual(_merge_type(LongType(), NullType()), LongType())\n self.assertEqual(_merge_type(NullType(), LongType()), LongType())\n\n self.assertEqual(_merge_type(LongType(), LongType()), LongType())\n\n self.assertEqual(_merge_type(\n ArrayType(LongType()),\n ArrayType(LongType())\n ), ArrayType(LongType()))\n with self.assertRaisesRegexp(TypeError, 'element in array'):\n _merge_type(ArrayType(LongType()), ArrayType(DoubleType()))\n\n self.assertEqual(_merge_type(\n MapType(StringType(), LongType()),\n MapType(StringType(), LongType())\n ), MapType(StringType(), LongType()))\n with self.assertRaisesRegexp(TypeError, 'key of map'):\n _merge_type(\n MapType(StringType(), LongType()),\n MapType(DoubleType(), LongType()))\n with self.assertRaisesRegexp(TypeError, 'value of map'):\n _merge_type(\n MapType(StringType(), LongType()),\n MapType(StringType(), DoubleType()))\n\n self.assertEqual(_merge_type(\n StructType([StructField(\"f1\", LongType()), StructField(\"f2\", StringType())]),\n StructType([StructField(\"f1\", LongType()), StructField(\"f2\", StringType())])\n ), StructType([StructField(\"f1\", LongType()), StructField(\"f2\", StringType())]))\n with self.assertRaisesRegexp(TypeError, 'field f1'):\n _merge_type(\n StructType([StructField(\"f1\", LongType()), StructField(\"f2\", StringType())]),\n StructType([StructField(\"f1\", DoubleType()), StructField(\"f2\", StringType())]))\n\n self.assertEqual(_merge_type(\n StructType([StructField(\"f1\", StructType([StructField(\"f2\", LongType())]))]),\n StructType([StructField(\"f1\", StructType([StructField(\"f2\", LongType())]))])\n ), StructType([StructField(\"f1\", StructType([StructField(\"f2\", LongType())]))]))\n with self.assertRaisesRegexp(TypeError, 'field f2 in field f1'):\n _merge_type(\n StructType([StructField(\"f1\", StructType([StructField(\"f2\", LongType())]))]),\n StructType([StructField(\"f1\", StructType([StructField(\"f2\", StringType())]))]))\n\n self.assertEqual(_merge_type(\n StructType([StructField(\"f1\", ArrayType(LongType())), StructField(\"f2\", StringType())]),\n StructType([StructField(\"f1\", ArrayType(LongType())), StructField(\"f2\", StringType())])\n ), StructType([StructField(\"f1\", ArrayType(LongType())), StructField(\"f2\", StringType())]))\n with self.assertRaisesRegexp(TypeError, 'element in array field f1'):\n _merge_type(\n StructType([\n StructField(\"f1\", ArrayType(LongType())),\n StructField(\"f2\", StringType())]),\n StructType([\n StructField(\"f1\", ArrayType(DoubleType())),\n StructField(\"f2\", StringType())]))\n\n self.assertEqual(_merge_type(\n StructType([\n StructField(\"f1\", MapType(StringType(), LongType())),\n StructField(\"f2\", StringType())]),\n StructType([\n StructField(\"f1\", MapType(StringType(), LongType())),\n StructField(\"f2\", StringType())])\n ), StructType([\n StructField(\"f1\", MapType(StringType(), LongType())),\n StructField(\"f2\", StringType())]))\n with self.assertRaisesRegexp(TypeError, 'value of map field f1'):\n _merge_type(\n StructType([\n StructField(\"f1\", MapType(StringType(), LongType())),\n StructField(\"f2\", StringType())]),\n StructType([\n StructField(\"f1\", MapType(StringType(), DoubleType())),\n StructField(\"f2\", StringType())]))\n\n self.assertEqual(_merge_type(\n StructType([StructField(\"f1\", ArrayType(MapType(StringType(), LongType())))]),\n StructType([StructField(\"f1\", ArrayType(MapType(StringType(), LongType())))])\n ), StructType([StructField(\"f1\", ArrayType(MapType(StringType(), LongType())))]))\n with self.assertRaisesRegexp(TypeError, 'key of map element in array field f1'):\n _merge_type(\n StructType([StructField(\"f1\", ArrayType(MapType(StringType(), LongType())))]),\n StructType([StructField(\"f1\", ArrayType(MapType(DoubleType(), LongType())))])\n )\n\n def test_filter_with_datetime(self):\n time = datetime.datetime(2015, 4, 17, 23, 1, 2, 3000)\n date = time.date()\n row = Row(date=date, time=time)\n df = self.spark.createDataFrame([row])\n self.assertEqual(1, df.filter(df.date == date).count())\n self.assertEqual(1, df.filter(df.time == time).count())\n self.assertEqual(0, df.filter(df.date > date).count())\n self.assertEqual(0, df.filter(df.time > time).count())\n\n def test_filter_with_datetime_timezone(self):\n dt1 = datetime.datetime(2015, 4, 17, 23, 1, 2, 3000, tzinfo=UTCOffsetTimezone(0))\n dt2 = datetime.datetime(2015, 4, 17, 23, 1, 2, 3000, tzinfo=UTCOffsetTimezone(1))\n row = Row(date=dt1)\n df = self.spark.createDataFrame([row])\n self.assertEqual(0, df.filter(df.date == dt2).count())\n self.assertEqual(1, df.filter(df.date > dt2).count())\n self.assertEqual(0, df.filter(df.date < dt2).count())\n\n def test_time_with_timezone(self):\n day = datetime.date.today()\n now = datetime.datetime.now()\n ts = time.mktime(now.timetuple())\n # class in __main__ is not serializable\n from pyspark.sql.tests import UTCOffsetTimezone\n utc = UTCOffsetTimezone()\n utcnow = datetime.datetime.utcfromtimestamp(ts) # without microseconds\n # add microseconds to utcnow (keeping year,month,day,hour,minute,second)\n utcnow = datetime.datetime(*(utcnow.timetuple()[:6] + (now.microsecond, utc)))\n df = self.spark.createDataFrame([(day, now, utcnow)])\n day1, now1, utcnow1 = df.first()\n self.assertEqual(day1, day)\n self.assertEqual(now, now1)\n self.assertEqual(now, utcnow1)\n\n # regression test for SPARK-19561\n def test_datetime_at_epoch(self):\n epoch = datetime.datetime.fromtimestamp(0)\n df = self.spark.createDataFrame([Row(date=epoch)])\n first = df.select('date', lit(epoch).alias('lit_date')).first()\n self.assertEqual(first['date'], epoch)\n self.assertEqual(first['lit_date'], epoch)\n\n def test_dayofweek(self):\n from pyspark.sql.functions import dayofweek\n dt = datetime.datetime(2017, 11, 6)\n df = self.spark.createDataFrame([Row(date=dt)])\n row = df.select(dayofweek(df.date)).first()\n self.assertEqual(row[0], 2)\n\n def test_decimal(self):\n from decimal import Decimal\n schema = StructType([StructField(\"decimal\", DecimalType(10, 5))])\n df = self.spark.createDataFrame([(Decimal(\"3.14159\"),)], schema)\n row = df.select(df.decimal + 1).first()\n self.assertEqual(row[0], Decimal(\"4.14159\"))\n tmpPath = tempfile.mkdtemp()\n shutil.rmtree(tmpPath)\n df.write.parquet(tmpPath)\n df2 = self.spark.read.parquet(tmpPath)\n row = df2.first()\n self.assertEqual(row[0], Decimal(\"3.14159\"))\n\n def test_dropna(self):\n schema = StructType([\n StructField(\"name\", StringType(), True),\n StructField(\"age\", IntegerType(), True),\n StructField(\"height\", DoubleType(), True)])\n\n # shouldn't drop a non-null row\n self.assertEqual(self.spark.createDataFrame(\n [(u'Alice', 50, 80.1)], schema).dropna().count(),\n 1)\n\n # dropping rows with a single null value\n self.assertEqual(self.spark.createDataFrame(\n [(u'Alice', None, 80.1)], schema).dropna().count(),\n 0)\n self.assertEqual(self.spark.createDataFrame(\n [(u'Alice', None, 80.1)], schema).dropna(how='any').count(),\n 0)\n\n # if how = 'all', only drop rows if all values are null\n self.assertEqual(self.spark.createDataFrame(\n [(u'Alice', None, 80.1)], schema).dropna(how='all').count(),\n 1)\n self.assertEqual(self.spark.createDataFrame(\n [(None, None, None)], schema).dropna(how='all').count(),\n 0)\n\n # how and subset\n self.assertEqual(self.spark.createDataFrame(\n [(u'Alice', 50, None)], schema).dropna(how='any', subset=['name', 'age']).count(),\n 1)\n self.assertEqual(self.spark.createDataFrame(\n [(u'Alice', None, None)], schema).dropna(how='any', subset=['name', 'age']).count(),\n 0)\n\n # threshold\n self.assertEqual(self.spark.createDataFrame(\n [(u'Alice', None, 80.1)], schema).dropna(thresh=2).count(),\n 1)\n self.assertEqual(self.spark.createDataFrame(\n [(u'Alice', None, None)], schema).dropna(thresh=2).count(),\n 0)\n\n # threshold and subset\n self.assertEqual(self.spark.createDataFrame(\n [(u'Alice', 50, None)], schema).dropna(thresh=2, subset=['name', 'age']).count(),\n 1)\n self.assertEqual(self.spark.createDataFrame(\n [(u'Alice', None, 180.9)], schema).dropna(thresh=2, subset=['name', 'age']).count(),\n 0)\n\n # thresh should take precedence over how\n self.assertEqual(self.spark.createDataFrame(\n [(u'Alice', 50, None)], schema).dropna(\n how='any', thresh=2, subset=['name', 'age']).count(),\n 1)\n\n def test_fillna(self):\n schema = StructType([\n StructField(\"name\", StringType(), True),\n StructField(\"age\", IntegerType(), True),\n StructField(\"height\", DoubleType(), True),\n StructField(\"spy\", BooleanType(), True)])\n\n # fillna shouldn't change non-null values\n row = self.spark.createDataFrame([(u'Alice', 10, 80.1, True)], schema).fillna(50).first()\n self.assertEqual(row.age, 10)\n\n # fillna with int\n row = self.spark.createDataFrame([(u'Alice', None, None, None)], schema).fillna(50).first()\n self.assertEqual(row.age, 50)\n self.assertEqual(row.height, 50.0)\n\n # fillna with double\n row = self.spark.createDataFrame(\n [(u'Alice', None, None, None)], schema).fillna(50.1).first()\n self.assertEqual(row.age, 50)\n self.assertEqual(row.height, 50.1)\n\n # fillna with bool\n row = self.spark.createDataFrame(\n [(u'Alice', None, None, None)], schema).fillna(True).first()\n self.assertEqual(row.age, None)\n self.assertEqual(row.spy, True)\n\n # fillna with string\n row = self.spark.createDataFrame([(None, None, None, None)], schema).fillna(\"hello\").first()\n self.assertEqual(row.name, u\"hello\")\n self.assertEqual(row.age, None)\n\n # fillna with subset specified for numeric cols\n row = self.spark.createDataFrame(\n [(None, None, None, None)], schema).fillna(50, subset=['name', 'age']).first()\n self.assertEqual(row.name, None)\n self.assertEqual(row.age, 50)\n self.assertEqual(row.height, None)\n self.assertEqual(row.spy, None)\n\n # fillna with subset specified for string cols\n row = self.spark.createDataFrame(\n [(None, None, None, None)], schema).fillna(\"haha\", subset=['name', 'age']).first()\n self.assertEqual(row.name, \"haha\")\n self.assertEqual(row.age, None)\n self.assertEqual(row.height, None)\n self.assertEqual(row.spy, None)\n\n # fillna with subset specified for bool cols\n row = self.spark.createDataFrame(\n [(None, None, None, None)], schema).fillna(True, subset=['name', 'spy']).first()\n self.assertEqual(row.name, None)\n self.assertEqual(row.age, None)\n self.assertEqual(row.height, None)\n self.assertEqual(row.spy, True)\n\n # fillna with dictionary for boolean types\n row = self.spark.createDataFrame([Row(a=None), Row(a=True)]).fillna({\"a\": True}).first()\n self.assertEqual(row.a, True)\n\n def test_bitwise_operations(self):\n from pyspark.sql import functions\n row = Row(a=170, b=75)\n df = self.spark.createDataFrame([row])\n result = df.select(df.a.bitwiseAND(df.b)).collect()[0].asDict()\n self.assertEqual(170 & 75, result['(a & b)'])\n result = df.select(df.a.bitwiseOR(df.b)).collect()[0].asDict()\n self.assertEqual(170 | 75, result['(a | b)'])\n result = df.select(df.a.bitwiseXOR(df.b)).collect()[0].asDict()\n self.assertEqual(170 ^ 75, result['(a ^ b)'])\n result = df.select(functions.bitwiseNOT(df.b)).collect()[0].asDict()\n self.assertEqual(~75, result['~b'])\n\n def test_expr(self):\n from pyspark.sql import functions\n row = Row(a=\"length string\", b=75)\n df = self.spark.createDataFrame([row])\n result = df.select(functions.expr(\"length(a)\")).collect()[0].asDict()\n self.assertEqual(13, result[\"length(a)\"])\n\n def test_repartitionByRange_dataframe(self):\n schema = StructType([\n StructField(\"name\", StringType(), True),\n StructField(\"age\", IntegerType(), True),\n StructField(\"height\", DoubleType(), True)])\n\n df1 = self.spark.createDataFrame(\n [(u'Bob', 27, 66.0), (u'Alice', 10, 10.0), (u'Bob', 10, 66.0)], schema)\n df2 = self.spark.createDataFrame(\n [(u'Alice', 10, 10.0), (u'Bob', 10, 66.0), (u'Bob', 27, 66.0)], schema)\n\n # test repartitionByRange(numPartitions, *cols)\n df3 = df1.repartitionByRange(2, \"name\", \"age\")\n self.assertEqual(df3.rdd.getNumPartitions(), 2)\n self.assertEqual(df3.rdd.first(), df2.rdd.first())\n self.assertEqual(df3.rdd.take(3), df2.rdd.take(3))\n\n # test repartitionByRange(numPartitions, *cols)\n df4 = df1.repartitionByRange(3, \"name\", \"age\")\n self.assertEqual(df4.rdd.getNumPartitions(), 3)\n self.assertEqual(df4.rdd.first(), df2.rdd.first())\n self.assertEqual(df4.rdd.take(3), df2.rdd.take(3))\n\n # test repartitionByRange(*cols)\n df5 = df1.repartitionByRange(\"name\", \"age\")\n self.assertEqual(df5.rdd.first(), df2.rdd.first())\n self.assertEqual(df5.rdd.take(3), df2.rdd.take(3))\n\n def test_replace(self):\n schema = StructType([\n StructField(\"name\", StringType(), True),\n StructField(\"age\", IntegerType(), True),\n StructField(\"height\", DoubleType(), True)])\n\n # replace with int\n row = self.spark.createDataFrame([(u'Alice', 10, 10.0)], schema).replace(10, 20).first()\n self.assertEqual(row.age, 20)\n self.assertEqual(row.height, 20.0)\n\n # replace with double\n row = self.spark.createDataFrame(\n [(u'Alice', 80, 80.0)], schema).replace(80.0, 82.1).first()\n self.assertEqual(row.age, 82)\n self.assertEqual(row.height, 82.1)\n\n # replace with string\n row = self.spark.createDataFrame(\n [(u'Alice', 10, 80.1)], schema).replace(u'Alice', u'Ann').first()\n self.assertEqual(row.name, u\"Ann\")\n self.assertEqual(row.age, 10)\n\n # replace with subset specified by a string of a column name w/ actual change\n row = self.spark.createDataFrame(\n [(u'Alice', 10, 80.1)], schema).replace(10, 20, subset='age').first()\n self.assertEqual(row.age, 20)\n\n # replace with subset specified by a string of a column name w/o actual change\n row = self.spark.createDataFrame(\n [(u'Alice', 10, 80.1)], schema).replace(10, 20, subset='height').first()\n self.assertEqual(row.age, 10)\n\n # replace with subset specified with one column replaced, another column not in subset\n # stays unchanged.\n row = self.spark.createDataFrame(\n [(u'Alice', 10, 10.0)], schema).replace(10, 20, subset=['name', 'age']).first()\n self.assertEqual(row.name, u'Alice')\n self.assertEqual(row.age, 20)\n self.assertEqual(row.height, 10.0)\n\n # replace with subset specified but no column will be replaced\n row = self.spark.createDataFrame(\n [(u'Alice', 10, None)], schema).replace(10, 20, subset=['name', 'height']).first()\n self.assertEqual(row.name, u'Alice')\n self.assertEqual(row.age, 10)\n self.assertEqual(row.height, None)\n\n # replace with lists\n row = self.spark.createDataFrame(\n [(u'Alice', 10, 80.1)], schema).replace([u'Alice'], [u'Ann']).first()\n self.assertTupleEqual(row, (u'Ann', 10, 80.1))\n\n # replace with dict\n row = self.spark.createDataFrame(\n [(u'Alice', 10, 80.1)], schema).replace({10: 11}).first()\n self.assertTupleEqual(row, (u'Alice', 11, 80.1))\n\n # test backward compatibility with dummy value\n dummy_value = 1\n row = self.spark.createDataFrame(\n [(u'Alice', 10, 80.1)], schema).replace({'Alice': 'Bob'}, dummy_value).first()\n self.assertTupleEqual(row, (u'Bob', 10, 80.1))\n\n # test dict with mixed numerics\n row = self.spark.createDataFrame(\n [(u'Alice', 10, 80.1)], schema).replace({10: -10, 80.1: 90.5}).first()\n self.assertTupleEqual(row, (u'Alice', -10, 90.5))\n\n # replace with tuples\n row = self.spark.createDataFrame(\n [(u'Alice', 10, 80.1)], schema).replace((u'Alice', ), (u'Bob', )).first()\n self.assertTupleEqual(row, (u'Bob', 10, 80.1))\n\n # replace multiple columns\n row = self.spark.createDataFrame(\n [(u'Alice', 10, 80.0)], schema).replace((10, 80.0), (20, 90)).first()\n self.assertTupleEqual(row, (u'Alice', 20, 90.0))\n\n # test for mixed numerics\n row = self.spark.createDataFrame(\n [(u'Alice', 10, 80.0)], schema).replace((10, 80), (20, 90.5)).first()\n self.assertTupleEqual(row, (u'Alice', 20, 90.5))\n\n row = self.spark.createDataFrame(\n [(u'Alice', 10, 80.0)], schema).replace({10: 20, 80: 90.5}).first()\n self.assertTupleEqual(row, (u'Alice', 20, 90.5))\n\n # replace with boolean\n row = (self\n .spark.createDataFrame([(u'Alice', 10, 80.0)], schema)\n .selectExpr(\"name = 'Bob'\", 'age <= 15')\n .replace(False, True).first())\n self.assertTupleEqual(row, (True, True))\n\n # replace string with None and then drop None rows\n row = self.spark.createDataFrame(\n [(u'Alice', 10, 80.0)], schema).replace(u'Alice', None).dropna()\n self.assertEqual(row.count(), 0)\n\n # replace with number and None\n row = self.spark.createDataFrame(\n [(u'Alice', 10, 80.0)], schema).replace([10, 80], [20, None]).first()\n self.assertTupleEqual(row, (u'Alice', 20, None))\n\n # should fail if subset is not list, tuple or None\n with self.assertRaises(ValueError):\n self.spark.createDataFrame(\n [(u'Alice', 10, 80.1)], schema).replace({10: 11}, subset=1).first()\n\n # should fail if to_replace and value have different length\n with self.assertRaises(ValueError):\n self.spark.createDataFrame(\n [(u'Alice', 10, 80.1)], schema).replace([\"Alice\", \"Bob\"], [\"Eve\"]).first()\n\n # should fail if when received unexpected type\n with self.assertRaises(ValueError):\n from datetime import datetime\n self.spark.createDataFrame(\n [(u'Alice', 10, 80.1)], schema).replace(datetime.now(), datetime.now()).first()\n\n # should fail if provided mixed type replacements\n with self.assertRaises(ValueError):\n self.spark.createDataFrame(\n [(u'Alice', 10, 80.1)], schema).replace([\"Alice\", 10], [\"Eve\", 20]).first()\n\n with self.assertRaises(ValueError):\n self.spark.createDataFrame(\n [(u'Alice', 10, 80.1)], schema).replace({u\"Alice\": u\"Bob\", 10: 20}).first()\n\n with self.assertRaisesRegexp(\n TypeError,\n 'value argument is required when to_replace is not a dictionary.'):\n self.spark.createDataFrame(\n [(u'Alice', 10, 80.0)], schema).replace([\"Alice\", \"Bob\"]).first()\n\n def test_capture_analysis_exception(self):\n self.assertRaises(AnalysisException, lambda: self.spark.sql(\"select abc\"))\n self.assertRaises(AnalysisException, lambda: self.df.selectExpr(\"a + b\"))\n\n def test_capture_parse_exception(self):\n self.assertRaises(ParseException, lambda: self.spark.sql(\"abc\"))\n\n def test_capture_illegalargument_exception(self):\n self.assertRaisesRegexp(IllegalArgumentException, \"Setting negative mapred.reduce.tasks\",\n lambda: self.spark.sql(\"SET mapred.reduce.tasks=-1\"))\n df = self.spark.createDataFrame([(1, 2)], [\"a\", \"b\"])\n self.assertRaisesRegexp(IllegalArgumentException, \"1024 is not in the permitted values\",\n lambda: df.select(sha2(df.a, 1024)).collect())\n try:\n df.select(sha2(df.a, 1024)).collect()\n except IllegalArgumentException as e:\n self.assertRegexpMatches(e.desc, \"1024 is not in the permitted values\")\n self.assertRegexpMatches(e.stackTrace,\n \"org.apache.spark.sql.functions\")\n\n def test_with_column_with_existing_name(self):\n keys = self.df.withColumn(\"key\", self.df.key).select(\"key\").collect()\n self.assertEqual([r.key for r in keys], list(range(100)))\n\n # regression test for SPARK-10417\n def test_column_iterator(self):\n\n def foo():\n for x in self.df.key:\n break\n\n self.assertRaises(TypeError, foo)\n\n # add test for SPARK-10577 (test broadcast join hint)\n def test_functions_broadcast(self):\n from pyspark.sql.functions import broadcast\n\n df1 = self.spark.createDataFrame([(1, \"1\"), (2, \"2\")], (\"key\", \"value\"))\n df2 = self.spark.createDataFrame([(1, \"1\"), (2, \"2\")], (\"key\", \"value\"))\n\n # equijoin - should be converted into broadcast join\n plan1 = df1.join(broadcast(df2), \"key\")._jdf.queryExecution().executedPlan()\n self.assertEqual(1, plan1.toString().count(\"BroadcastHashJoin\"))\n\n # no join key -- should not be a broadcast join\n plan2 = df1.crossJoin(broadcast(df2))._jdf.queryExecution().executedPlan()\n self.assertEqual(0, plan2.toString().count(\"BroadcastHashJoin\"))\n\n # planner should not crash without a join\n broadcast(df1)._jdf.queryExecution().executedPlan()\n\n def test_generic_hints(self):\n from pyspark.sql import DataFrame\n\n df1 = self.spark.range(10e10).toDF(\"id\")\n df2 = self.spark.range(10e10).toDF(\"id\")\n\n self.assertIsInstance(df1.hint(\"broadcast\"), DataFrame)\n self.assertIsInstance(df1.hint(\"broadcast\", []), DataFrame)\n\n # Dummy rules\n self.assertIsInstance(df1.hint(\"broadcast\", \"foo\", \"bar\"), DataFrame)\n self.assertIsInstance(df1.hint(\"broadcast\", [\"foo\", \"bar\"]), DataFrame)\n\n plan = df1.join(df2.hint(\"broadcast\"), \"id\")._jdf.queryExecution().executedPlan()\n self.assertEqual(1, plan.toString().count(\"BroadcastHashJoin\"))\n\n def test_sample(self):\n self.assertRaisesRegexp(\n TypeError,\n \"should be a bool, float and number\",\n lambda: self.spark.range(1).sample())\n\n self.assertRaises(\n TypeError,\n lambda: self.spark.range(1).sample(\"a\"))\n\n self.assertRaises(\n TypeError,\n lambda: self.spark.range(1).sample(seed=\"abc\"))\n\n self.assertRaises(\n IllegalArgumentException,\n lambda: self.spark.range(1).sample(-1.0))\n\n def test_toDF_with_schema_string(self):\n data = [Row(key=i, value=str(i)) for i in range(100)]\n rdd = self.sc.parallelize(data, 5)\n\n df = rdd.toDF(\"key: int, value: string\")\n self.assertEqual(df.schema.simpleString(), \"struct<key:int,value:string>\")\n self.assertEqual(df.collect(), data)\n\n # different but compatible field types can be used.\n df = rdd.toDF(\"key: string, value: string\")\n self.assertEqual(df.schema.simpleString(), \"struct<key:string,value:string>\")\n self.assertEqual(df.collect(), [Row(key=str(i), value=str(i)) for i in range(100)])\n\n # field names can differ.\n df = rdd.toDF(\" a: int, b: string \")\n self.assertEqual(df.schema.simpleString(), \"struct<a:int,b:string>\")\n self.assertEqual(df.collect(), data)\n\n # number of fields must match.\n self.assertRaisesRegexp(Exception, \"Length of object\",\n lambda: rdd.toDF(\"key: int\").collect())\n\n # field types mismatch will cause exception at runtime.\n self.assertRaisesRegexp(Exception, \"FloatType can not accept\",\n lambda: rdd.toDF(\"key: float, value: string\").collect())\n\n # flat schema values will be wrapped into row.\n df = rdd.map(lambda row: row.key).toDF(\"int\")\n self.assertEqual(df.schema.simpleString(), \"struct<value:int>\")\n self.assertEqual(df.collect(), [Row(key=i) for i in range(100)])\n\n # users can use DataType directly instead of data type string.\n df = rdd.map(lambda row: row.key).toDF(IntegerType())\n self.assertEqual(df.schema.simpleString(), \"struct<value:int>\")\n self.assertEqual(df.collect(), [Row(key=i) for i in range(100)])\n\n def test_join_without_on(self):\n df1 = self.spark.range(1).toDF(\"a\")\n df2 = self.spark.range(1).toDF(\"b\")\n\n with self.sql_conf({\"spark.sql.crossJoin.enabled\": False}):\n self.assertRaises(AnalysisException, lambda: df1.join(df2, how=\"inner\").collect())\n\n with self.sql_conf({\"spark.sql.crossJoin.enabled\": True}):\n actual = df1.join(df2, how=\"inner\").collect()\n expected = [Row(a=0, b=0)]\n self.assertEqual(actual, expected)\n\n # Regression test for invalid join methods when on is None, Spark-14761\n def test_invalid_join_method(self):\n df1 = self.spark.createDataFrame([(\"Alice\", 5), (\"Bob\", 8)], [\"name\", \"age\"])\n df2 = self.spark.createDataFrame([(\"Alice\", 80), (\"Bob\", 90)], [\"name\", \"height\"])\n self.assertRaises(IllegalArgumentException, lambda: df1.join(df2, how=\"invalid-join-type\"))\n\n # Cartesian products require cross join syntax\n def test_require_cross(self):\n from pyspark.sql.functions import broadcast\n\n df1 = self.spark.createDataFrame([(1, \"1\")], (\"key\", \"value\"))\n df2 = self.spark.createDataFrame([(1, \"1\")], (\"key\", \"value\"))\n\n # joins without conditions require cross join syntax\n self.assertRaises(AnalysisException, lambda: df1.join(df2).collect())\n\n # works with crossJoin\n self.assertEqual(1, df1.crossJoin(df2).count())\n\n def test_conf(self):\n spark = self.spark\n spark.conf.set(\"bogo\", \"sipeo\")\n self.assertEqual(spark.conf.get(\"bogo\"), \"sipeo\")\n spark.conf.set(\"bogo\", \"ta\")\n self.assertEqual(spark.conf.get(\"bogo\"), \"ta\")\n self.assertEqual(spark.conf.get(\"bogo\", \"not.read\"), \"ta\")\n self.assertEqual(spark.conf.get(\"not.set\", \"ta\"), \"ta\")\n self.assertRaisesRegexp(Exception, \"not.set\", lambda: spark.conf.get(\"not.set\"))\n spark.conf.unset(\"bogo\")\n self.assertEqual(spark.conf.get(\"bogo\", \"colombia\"), \"colombia\")\n\n self.assertEqual(spark.conf.get(\"hyukjin\", None), None)\n\n # This returns 'STATIC' because it's the default value of\n # 'spark.sql.sources.partitionOverwriteMode', and `defaultValue` in\n # `spark.conf.get` is unset.\n self.assertEqual(spark.conf.get(\"spark.sql.sources.partitionOverwriteMode\"), \"STATIC\")\n\n # This returns None because 'spark.sql.sources.partitionOverwriteMode' is unset, but\n # `defaultValue` in `spark.conf.get` is set to None.\n self.assertEqual(spark.conf.get(\"spark.sql.sources.partitionOverwriteMode\", None), None)\n\n def test_current_database(self):\n spark = self.spark\n spark.catalog._reset()\n self.assertEquals(spark.catalog.currentDatabase(), \"default\")\n spark.sql(\"CREATE DATABASE some_db\")\n spark.catalog.setCurrentDatabase(\"some_db\")\n self.assertEquals(spark.catalog.currentDatabase(), \"some_db\")\n self.assertRaisesRegexp(\n AnalysisException,\n \"does_not_exist\",\n lambda: spark.catalog.setCurrentDatabase(\"does_not_exist\"))\n\n def test_list_databases(self):\n spark = self.spark\n spark.catalog._reset()\n databases = [db.name for db in spark.catalog.listDatabases()]\n self.assertEquals(databases, [\"default\"])\n spark.sql(\"CREATE DATABASE some_db\")\n databases = [db.name for db in spark.catalog.listDatabases()]\n self.assertEquals(sorted(databases), [\"default\", \"some_db\"])\n\n def test_list_tables(self):\n from pyspark.sql.catalog import Table\n spark = self.spark\n spark.catalog._reset()\n spark.sql(\"CREATE DATABASE some_db\")\n self.assertEquals(spark.catalog.listTables(), [])\n self.assertEquals(spark.catalog.listTables(\"some_db\"), [])\n spark.createDataFrame([(1, 1)]).createOrReplaceTempView(\"temp_tab\")\n spark.sql(\"CREATE TABLE tab1 (name STRING, age INT) USING parquet\")\n spark.sql(\"CREATE TABLE some_db.tab2 (name STRING, age INT) USING parquet\")\n tables = sorted(spark.catalog.listTables(), key=lambda t: t.name)\n tablesDefault = sorted(spark.catalog.listTables(\"default\"), key=lambda t: t.name)\n tablesSomeDb = sorted(spark.catalog.listTables(\"some_db\"), key=lambda t: t.name)\n self.assertEquals(tables, tablesDefault)\n self.assertEquals(len(tables), 2)\n self.assertEquals(len(tablesSomeDb), 2)\n self.assertEquals(tables[0], Table(\n name=\"tab1\",\n database=\"default\",\n description=None,\n tableType=\"MANAGED\",\n isTemporary=False))\n self.assertEquals(tables[1], Table(\n name=\"temp_tab\",\n database=None,\n description=None,\n tableType=\"TEMPORARY\",\n isTemporary=True))\n self.assertEquals(tablesSomeDb[0], Table(\n name=\"tab2\",\n database=\"some_db\",\n description=None,\n tableType=\"MANAGED\",\n isTemporary=False))\n self.assertEquals(tablesSomeDb[1], Table(\n name=\"temp_tab\",\n database=None,\n description=None,\n tableType=\"TEMPORARY\",\n isTemporary=True))\n self.assertRaisesRegexp(\n AnalysisException,\n \"does_not_exist\",\n lambda: spark.catalog.listTables(\"does_not_exist\"))\n\n def test_list_functions(self):\n from pyspark.sql.catalog import Function\n spark = self.spark\n spark.catalog._reset()\n spark.sql(\"CREATE DATABASE some_db\")\n functions = dict((f.name, f) for f in spark.catalog.listFunctions())\n functionsDefault = dict((f.name, f) for f in spark.catalog.listFunctions(\"default\"))\n self.assertTrue(len(functions) > 200)\n self.assertTrue(\"+\" in functions)\n self.assertTrue(\"like\" in functions)\n self.assertTrue(\"month\" in functions)\n self.assertTrue(\"to_date\" in functions)\n self.assertTrue(\"to_timestamp\" in functions)\n self.assertTrue(\"to_unix_timestamp\" in functions)\n self.assertTrue(\"current_database\" in functions)\n self.assertEquals(functions[\"+\"], Function(\n name=\"+\",\n description=None,\n className=\"org.apache.spark.sql.catalyst.expressions.Add\",\n isTemporary=True))\n self.assertEquals(functions, functionsDefault)\n spark.catalog.registerFunction(\"temp_func\", lambda x: str(x))\n spark.sql(\"CREATE FUNCTION func1 AS 'org.apache.spark.data.bricks'\")\n spark.sql(\"CREATE FUNCTION some_db.func2 AS 'org.apache.spark.data.bricks'\")\n newFunctions = dict((f.name, f) for f in spark.catalog.listFunctions())\n newFunctionsSomeDb = dict((f.name, f) for f in spark.catalog.listFunctions(\"some_db\"))\n self.assertTrue(set(functions).issubset(set(newFunctions)))\n self.assertTrue(set(functions).issubset(set(newFunctionsSomeDb)))\n self.assertTrue(\"temp_func\" in newFunctions)\n self.assertTrue(\"func1\" in newFunctions)\n self.assertTrue(\"func2\" not in newFunctions)\n self.assertTrue(\"temp_func\" in newFunctionsSomeDb)\n self.assertTrue(\"func1\" not in newFunctionsSomeDb)\n self.assertTrue(\"func2\" in newFunctionsSomeDb)\n self.assertRaisesRegexp(\n AnalysisException,\n \"does_not_exist\",\n lambda: spark.catalog.listFunctions(\"does_not_exist\"))\n\n def test_list_columns(self):\n from pyspark.sql.catalog import Column\n spark = self.spark\n spark.catalog._reset()\n spark.sql(\"CREATE DATABASE some_db\")\n spark.sql(\"CREATE TABLE tab1 (name STRING, age INT) USING parquet\")\n spark.sql(\"CREATE TABLE some_db.tab2 (nickname STRING, tolerance FLOAT) USING parquet\")\n columns = sorted(spark.catalog.listColumns(\"tab1\"), key=lambda c: c.name)\n columnsDefault = sorted(spark.catalog.listColumns(\"tab1\", \"default\"), key=lambda c: c.name)\n self.assertEquals(columns, columnsDefault)\n self.assertEquals(len(columns), 2)\n self.assertEquals(columns[0], Column(\n name=\"age\",\n description=None,\n dataType=\"int\",\n nullable=True,\n isPartition=False,\n isBucket=False))\n self.assertEquals(columns[1], Column(\n name=\"name\",\n description=None,\n dataType=\"string\",\n nullable=True,\n isPartition=False,\n isBucket=False))\n columns2 = sorted(spark.catalog.listColumns(\"tab2\", \"some_db\"), key=lambda c: c.name)\n self.assertEquals(len(columns2), 2)\n self.assertEquals(columns2[0], Column(\n name=\"nickname\",\n description=None,\n dataType=\"string\",\n nullable=True,\n isPartition=False,\n isBucket=False))\n self.assertEquals(columns2[1], Column(\n name=\"tolerance\",\n description=None,\n dataType=\"float\",\n nullable=True,\n isPartition=False,\n isBucket=False))\n self.assertRaisesRegexp(\n AnalysisException,\n \"tab2\",\n lambda: spark.catalog.listColumns(\"tab2\"))\n self.assertRaisesRegexp(\n AnalysisException,\n \"does_not_exist\",\n lambda: spark.catalog.listColumns(\"does_not_exist\"))\n\n def test_cache(self):\n spark = self.spark\n spark.createDataFrame([(2, 2), (3, 3)]).createOrReplaceTempView(\"tab1\")\n spark.createDataFrame([(2, 2), (3, 3)]).createOrReplaceTempView(\"tab2\")\n self.assertFalse(spark.catalog.isCached(\"tab1\"))\n self.assertFalse(spark.catalog.isCached(\"tab2\"))\n spark.catalog.cacheTable(\"tab1\")\n self.assertTrue(spark.catalog.isCached(\"tab1\"))\n self.assertFalse(spark.catalog.isCached(\"tab2\"))\n spark.catalog.cacheTable(\"tab2\")\n spark.catalog.uncacheTable(\"tab1\")\n self.assertFalse(spark.catalog.isCached(\"tab1\"))\n self.assertTrue(spark.catalog.isCached(\"tab2\"))\n spark.catalog.clearCache()\n self.assertFalse(spark.catalog.isCached(\"tab1\"))\n self.assertFalse(spark.catalog.isCached(\"tab2\"))\n self.assertRaisesRegexp(\n AnalysisException,\n \"does_not_exist\",\n lambda: spark.catalog.isCached(\"does_not_exist\"))\n self.assertRaisesRegexp(\n AnalysisException,\n \"does_not_exist\",\n lambda: spark.catalog.cacheTable(\"does_not_exist\"))\n self.assertRaisesRegexp(\n AnalysisException,\n \"does_not_exist\",\n lambda: spark.catalog.uncacheTable(\"does_not_exist\"))\n\n def test_read_text_file_list(self):\n df = self.spark.read.text(['python/test_support/sql/text-test.txt',\n 'python/test_support/sql/text-test.txt'])\n count = df.count()\n self.assertEquals(count, 4)\n\n def test_BinaryType_serialization(self):\n # Pyrolite version <= 4.9 could not serialize BinaryType with Python3 SPARK-17808\n # The empty bytearray is test for SPARK-21534.\n schema = StructType([StructField('mybytes', BinaryType())])\n data = [[bytearray(b'here is my data')],\n [bytearray(b'and here is some more')],\n [bytearray(b'')]]\n df = self.spark.createDataFrame(data, schema=schema)\n df.collect()\n\n # test for SPARK-16542\n def test_array_types(self):\n # This test need to make sure that the Scala type selected is at least\n # as large as the python's types. This is necessary because python's\n # array types depend on C implementation on the machine. Therefore there\n # is no machine independent correspondence between python's array types\n # and Scala types.\n # See: https://docs.python.org/2/library/array.html\n\n def assertCollectSuccess(typecode, value):\n row = Row(myarray=array.array(typecode, [value]))\n df = self.spark.createDataFrame([row])\n self.assertEqual(df.first()[\"myarray\"][0], value)\n\n # supported string types\n #\n # String types in python's array are \"u\" for Py_UNICODE and \"c\" for char.\n # \"u\" will be removed in python 4, and \"c\" is not supported in python 3.\n supported_string_types = []\n if sys.version_info[0] < 4:\n supported_string_types += ['u']\n # test unicode\n assertCollectSuccess('u', u'a')\n if sys.version_info[0] < 3:\n supported_string_types += ['c']\n # test string\n assertCollectSuccess('c', 'a')\n\n # supported float and double\n #\n # Test max, min, and precision for float and double, assuming IEEE 754\n # floating-point format.\n supported_fractional_types = ['f', 'd']\n assertCollectSuccess('f', ctypes.c_float(1e+38).value)\n assertCollectSuccess('f', ctypes.c_float(1e-38).value)\n assertCollectSuccess('f', ctypes.c_float(1.123456).value)\n assertCollectSuccess('d', sys.float_info.max)\n assertCollectSuccess('d', sys.float_info.min)\n assertCollectSuccess('d', sys.float_info.epsilon)\n\n # supported signed int types\n #\n # The size of C types changes with implementation, we need to make sure\n # that there is no overflow error on the platform running this test.\n supported_signed_int_types = list(\n set(_array_signed_int_typecode_ctype_mappings.keys())\n .intersection(set(_array_type_mappings.keys())))\n for t in supported_signed_int_types:\n ctype = _array_signed_int_typecode_ctype_mappings[t]\n max_val = 2 ** (ctypes.sizeof(ctype) * 8 - 1)\n assertCollectSuccess(t, max_val - 1)\n assertCollectSuccess(t, -max_val)\n\n # supported unsigned int types\n #\n # JVM does not have unsigned types. We need to be very careful to make\n # sure that there is no overflow error.\n supported_unsigned_int_types = list(\n set(_array_unsigned_int_typecode_ctype_mappings.keys())\n .intersection(set(_array_type_mappings.keys())))\n for t in supported_unsigned_int_types:\n ctype = _array_unsigned_int_typecode_ctype_mappings[t]\n assertCollectSuccess(t, 2 ** (ctypes.sizeof(ctype) * 8) - 1)\n\n # all supported types\n #\n # Make sure the types tested above:\n # 1. are all supported types\n # 2. cover all supported types\n supported_types = (supported_string_types +\n supported_fractional_types +\n supported_signed_int_types +\n supported_unsigned_int_types)\n self.assertEqual(set(supported_types), set(_array_type_mappings.keys()))\n\n # all unsupported types\n #\n # Keys in _array_type_mappings is a complete list of all supported types,\n # and types not in _array_type_mappings are considered unsupported.\n # `array.typecodes` are not supported in python 2.\n if sys.version_info[0] < 3:\n all_types = set(['c', 'b', 'B', 'u', 'h', 'H', 'i', 'I', 'l', 'L', 'f', 'd'])\n else:\n all_types = set(array.typecodes)\n unsupported_types = all_types - set(supported_types)\n # test unsupported types\n for t in unsupported_types:\n with self.assertRaises(TypeError):\n a = array.array(t)\n self.spark.createDataFrame([Row(myarray=a)]).collect()\n\n def test_bucketed_write(self):\n data = [\n (1, \"foo\", 3.0), (2, \"foo\", 5.0),\n (3, \"bar\", -1.0), (4, \"bar\", 6.0),\n ]\n df = self.spark.createDataFrame(data, [\"x\", \"y\", \"z\"])\n\n def count_bucketed_cols(names, table=\"pyspark_bucket\"):\n \"\"\"Given a sequence of column names and a table name\n query the catalog and return number o columns which are\n used for bucketing\n \"\"\"\n cols = self.spark.catalog.listColumns(table)\n num = len([c for c in cols if c.name in names and c.isBucket])\n return num\n\n # Test write with one bucketing column\n df.write.bucketBy(3, \"x\").mode(\"overwrite\").saveAsTable(\"pyspark_bucket\")\n self.assertEqual(count_bucketed_cols([\"x\"]), 1)\n self.assertSetEqual(set(data), set(self.spark.table(\"pyspark_bucket\").collect()))\n\n # Test write two bucketing columns\n df.write.bucketBy(3, \"x\", \"y\").mode(\"overwrite\").saveAsTable(\"pyspark_bucket\")\n self.assertEqual(count_bucketed_cols([\"x\", \"y\"]), 2)\n self.assertSetEqual(set(data), set(self.spark.table(\"pyspark_bucket\").collect()))\n\n # Test write with bucket and sort\n df.write.bucketBy(2, \"x\").sortBy(\"z\").mode(\"overwrite\").saveAsTable(\"pyspark_bucket\")\n self.assertEqual(count_bucketed_cols([\"x\"]), 1)\n self.assertSetEqual(set(data), set(self.spark.table(\"pyspark_bucket\").collect()))\n\n # Test write with a list of columns\n df.write.bucketBy(3, [\"x\", \"y\"]).mode(\"overwrite\").saveAsTable(\"pyspark_bucket\")\n self.assertEqual(count_bucketed_cols([\"x\", \"y\"]), 2)\n self.assertSetEqual(set(data), set(self.spark.table(\"pyspark_bucket\").collect()))\n\n # Test write with bucket and sort with a list of columns\n (df.write.bucketBy(2, \"x\")\n .sortBy([\"y\", \"z\"])\n .mode(\"overwrite\").saveAsTable(\"pyspark_bucket\"))\n self.assertSetEqual(set(data), set(self.spark.table(\"pyspark_bucket\").collect()))\n\n # Test write with bucket and sort with multiple columns\n (df.write.bucketBy(2, \"x\")\n .sortBy(\"y\", \"z\")\n .mode(\"overwrite\").saveAsTable(\"pyspark_bucket\"))\n self.assertSetEqual(set(data), set(self.spark.table(\"pyspark_bucket\").collect()))\n\n def _to_pandas(self):\n from datetime import datetime, date\n schema = StructType().add(\"a\", IntegerType()).add(\"b\", StringType())\\\n .add(\"c\", BooleanType()).add(\"d\", FloatType())\\\n .add(\"dt\", DateType()).add(\"ts\", TimestampType())\n data = [\n (1, \"foo\", True, 3.0, date(1969, 1, 1), datetime(1969, 1, 1, 1, 1, 1)),\n (2, \"foo\", True, 5.0, None, None),\n (3, \"bar\", False, -1.0, date(2012, 3, 3), datetime(2012, 3, 3, 3, 3, 3)),\n (4, \"bar\", False, 6.0, date(2100, 4, 4), datetime(2100, 4, 4, 4, 4, 4)),\n ]\n df = self.spark.createDataFrame(data, schema)\n return df.toPandas()\n\n @unittest.skipIf(not _have_pandas, _pandas_requirement_message)\n def test_to_pandas(self):\n import numpy as np\n pdf = self._to_pandas()\n types = pdf.dtypes\n self.assertEquals(types[0], np.int32)\n self.assertEquals(types[1], np.object)\n self.assertEquals(types[2], np.bool)\n self.assertEquals(types[3], np.float32)\n self.assertEquals(types[4], np.object) # datetime.date\n self.assertEquals(types[5], 'datetime64[ns]')\n\n @unittest.skipIf(_have_pandas, \"Required Pandas was found.\")\n def test_to_pandas_required_pandas_not_found(self):\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(ImportError, 'Pandas >= .* must be installed'):\n self._to_pandas()\n\n @unittest.skipIf(not _have_pandas, _pandas_requirement_message)\n def test_to_pandas_avoid_astype(self):\n import numpy as np\n schema = StructType().add(\"a\", IntegerType()).add(\"b\", StringType())\\\n .add(\"c\", IntegerType())\n data = [(1, \"foo\", 16777220), (None, \"bar\", None)]\n df = self.spark.createDataFrame(data, schema)\n types = df.toPandas().dtypes\n self.assertEquals(types[0], np.float64) # doesn't convert to np.int32 due to NaN value.\n self.assertEquals(types[1], np.object)\n self.assertEquals(types[2], np.float64)\n\n def test_create_dataframe_from_array_of_long(self):\n import array\n data = [Row(longarray=array.array('l', [-9223372036854775808, 0, 9223372036854775807]))]\n df = self.spark.createDataFrame(data)\n self.assertEqual(df.first(), Row(longarray=[-9223372036854775808, 0, 9223372036854775807]))\n\n @unittest.skipIf(not _have_pandas, _pandas_requirement_message)\n def test_create_dataframe_from_pandas_with_timestamp(self):\n import pandas as pd\n from datetime import datetime\n pdf = pd.DataFrame({\"ts\": [datetime(2017, 10, 31, 1, 1, 1)],\n \"d\": [pd.Timestamp.now().date()]})\n # test types are inferred correctly without specifying schema\n df = self.spark.createDataFrame(pdf)\n self.assertTrue(isinstance(df.schema['ts'].dataType, TimestampType))\n self.assertTrue(isinstance(df.schema['d'].dataType, DateType))\n # test with schema will accept pdf as input\n df = self.spark.createDataFrame(pdf, schema=\"d date, ts timestamp\")\n self.assertTrue(isinstance(df.schema['ts'].dataType, TimestampType))\n self.assertTrue(isinstance(df.schema['d'].dataType, DateType))\n\n @unittest.skipIf(_have_pandas, \"Required Pandas was found.\")\n def test_create_dataframe_required_pandas_not_found(self):\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(\n ImportError,\n \"(Pandas >= .* must be installed|No module named '?pandas'?)\"):\n import pandas as pd\n from datetime import datetime\n pdf = pd.DataFrame({\"ts\": [datetime(2017, 10, 31, 1, 1, 1)],\n \"d\": [pd.Timestamp.now().date()]})\n self.spark.createDataFrame(pdf)\n\n # Regression test for SPARK-23360\n @unittest.skipIf(not _have_pandas, _pandas_requirement_message)\n def test_create_dateframe_from_pandas_with_dst(self):\n import pandas as pd\n from datetime import datetime\n\n pdf = pd.DataFrame({'time': [datetime(2015, 10, 31, 22, 30)]})\n\n df = self.spark.createDataFrame(pdf)\n self.assertPandasEqual(pdf, df.toPandas())\n\n orig_env_tz = os.environ.get('TZ', None)\n try:\n tz = 'America/Los_Angeles'\n os.environ['TZ'] = tz\n time.tzset()\n with self.sql_conf({'spark.sql.session.timeZone': tz}):\n df = self.spark.createDataFrame(pdf)\n self.assertPandasEqual(pdf, df.toPandas())\n finally:\n del os.environ['TZ']\n if orig_env_tz is not None:\n os.environ['TZ'] = orig_env_tz\n time.tzset()\n\n def test_sort_with_nulls_order(self):\n from pyspark.sql import functions\n\n df = self.spark.createDataFrame(\n [('Tom', 80), (None, 60), ('Alice', 50)], [\"name\", \"height\"])\n self.assertEquals(\n df.select(df.name).orderBy(functions.asc_nulls_first('name')).collect(),\n [Row(name=None), Row(name=u'Alice'), Row(name=u'Tom')])\n self.assertEquals(\n df.select(df.name).orderBy(functions.asc_nulls_last('name')).collect(),\n [Row(name=u'Alice'), Row(name=u'Tom'), Row(name=None)])\n self.assertEquals(\n df.select(df.name).orderBy(functions.desc_nulls_first('name')).collect(),\n [Row(name=None), Row(name=u'Tom'), Row(name=u'Alice')])\n self.assertEquals(\n df.select(df.name).orderBy(functions.desc_nulls_last('name')).collect(),\n [Row(name=u'Tom'), Row(name=u'Alice'), Row(name=None)])\n\n def test_json_sampling_ratio(self):\n rdd = self.spark.sparkContext.range(0, 100, 1, 1) \\\n .map(lambda x: '{\"a\":0.1}' if x == 1 else '{\"a\":%s}' % str(x))\n schema = self.spark.read.option('inferSchema', True) \\\n .option('samplingRatio', 0.5) \\\n .json(rdd).schema\n self.assertEquals(schema, StructType([StructField(\"a\", LongType(), True)]))\n\n def test_csv_sampling_ratio(self):\n rdd = self.spark.sparkContext.range(0, 100, 1, 1) \\\n .map(lambda x: '0.1' if x == 1 else str(x))\n schema = self.spark.read.option('inferSchema', True)\\\n .csv(rdd, samplingRatio=0.5).schema\n self.assertEquals(schema, StructType([StructField(\"_c0\", IntegerType(), True)]))\n\n def test_checking_csv_header(self):\n path = tempfile.mkdtemp()\n shutil.rmtree(path)\n try:\n self.spark.createDataFrame([[1, 1000], [2000, 2]])\\\n .toDF('f1', 'f2').write.option(\"header\", \"true\").csv(path)\n schema = StructType([\n StructField('f2', IntegerType(), nullable=True),\n StructField('f1', IntegerType(), nullable=True)])\n df = self.spark.read.option('header', 'true').schema(schema)\\\n .csv(path, enforceSchema=False)\n self.assertRaisesRegexp(\n Exception,\n \"CSV header does not conform to the schema\",\n lambda: df.collect())\n finally:\n shutil.rmtree(path)\n\n def test_ignore_column_of_all_nulls(self):\n path = tempfile.mkdtemp()\n shutil.rmtree(path)\n try:\n df = self.spark.createDataFrame([[\"\"\"{\"a\":null, \"b\":1, \"c\":3.0}\"\"\"],\n [\"\"\"{\"a\":null, \"b\":null, \"c\":\"string\"}\"\"\"],\n [\"\"\"{\"a\":null, \"b\":null, \"c\":null}\"\"\"]])\n df.write.text(path)\n schema = StructType([\n StructField('b', LongType(), nullable=True),\n StructField('c', StringType(), nullable=True)])\n readback = self.spark.read.json(path, dropFieldIfAllNull=True)\n self.assertEquals(readback.schema, schema)\n finally:\n shutil.rmtree(path)\n\n # SPARK-24721\n @unittest.skipIf(not _test_compiled, _test_not_compiled_message)\n def test_datasource_with_udf(self):\n from pyspark.sql.functions import udf, lit, col\n\n path = tempfile.mkdtemp()\n shutil.rmtree(path)\n\n try:\n self.spark.range(1).write.mode(\"overwrite\").format('csv').save(path)\n filesource_df = self.spark.read.option('inferSchema', True).csv(path).toDF('i')\n datasource_df = self.spark.read \\\n .format(\"org.apache.spark.sql.sources.SimpleScanSource\") \\\n .option('from', 0).option('to', 1).load().toDF('i')\n datasource_v2_df = self.spark.read \\\n .format(\"org.apache.spark.sql.sources.v2.SimpleDataSourceV2\") \\\n .load().toDF('i', 'j')\n\n c1 = udf(lambda x: x + 1, 'int')(lit(1))\n c2 = udf(lambda x: x + 1, 'int')(col('i'))\n\n f1 = udf(lambda x: False, 'boolean')(lit(1))\n f2 = udf(lambda x: False, 'boolean')(col('i'))\n\n for df in [filesource_df, datasource_df, datasource_v2_df]:\n result = df.withColumn('c', c1)\n expected = df.withColumn('c', lit(2))\n self.assertEquals(expected.collect(), result.collect())\n\n for df in [filesource_df, datasource_df, datasource_v2_df]:\n result = df.withColumn('c', c2)\n expected = df.withColumn('c', col('i') + 1)\n self.assertEquals(expected.collect(), result.collect())\n\n for df in [filesource_df, datasource_df, datasource_v2_df]:\n for f in [f1, f2]:\n result = df.filter(f)\n self.assertEquals(0, result.count())\n finally:\n shutil.rmtree(path)\n\n def test_repr_behaviors(self):\n import re\n pattern = re.compile(r'^ *\\|', re.MULTILINE)\n df = self.spark.createDataFrame([(1, \"1\"), (22222, \"22222\")], (\"key\", \"value\"))\n\n # test when eager evaluation is enabled and _repr_html_ will not be called\n with self.sql_conf({\"spark.sql.repl.eagerEval.enabled\": True}):\n expected1 = \"\"\"+-----+-----+\n || key|value|\n |+-----+-----+\n || 1| 1|\n ||22222|22222|\n |+-----+-----+\n |\"\"\"\n self.assertEquals(re.sub(pattern, '', expected1), df.__repr__())\n with self.sql_conf({\"spark.sql.repl.eagerEval.truncate\": 3}):\n expected2 = \"\"\"+---+-----+\n ||key|value|\n |+---+-----+\n || 1| 1|\n ||222| 222|\n |+---+-----+\n |\"\"\"\n self.assertEquals(re.sub(pattern, '', expected2), df.__repr__())\n with self.sql_conf({\"spark.sql.repl.eagerEval.maxNumRows\": 1}):\n expected3 = \"\"\"+---+-----+\n ||key|value|\n |+---+-----+\n || 1| 1|\n |+---+-----+\n |only showing top 1 row\n |\"\"\"\n self.assertEquals(re.sub(pattern, '', expected3), df.__repr__())\n\n # test when eager evaluation is enabled and _repr_html_ will be called\n with self.sql_conf({\"spark.sql.repl.eagerEval.enabled\": True}):\n expected1 = \"\"\"<table border='1'>\n |<tr><th>key</th><th>value</th></tr>\n |<tr><td>1</td><td>1</td></tr>\n |<tr><td>22222</td><td>22222</td></tr>\n |</table>\n |\"\"\"\n self.assertEquals(re.sub(pattern, '', expected1), df._repr_html_())\n with self.sql_conf({\"spark.sql.repl.eagerEval.truncate\": 3}):\n expected2 = \"\"\"<table border='1'>\n |<tr><th>key</th><th>value</th></tr>\n |<tr><td>1</td><td>1</td></tr>\n |<tr><td>222</td><td>222</td></tr>\n |</table>\n |\"\"\"\n self.assertEquals(re.sub(pattern, '', expected2), df._repr_html_())\n with self.sql_conf({\"spark.sql.repl.eagerEval.maxNumRows\": 1}):\n expected3 = \"\"\"<table border='1'>\n |<tr><th>key</th><th>value</th></tr>\n |<tr><td>1</td><td>1</td></tr>\n |</table>\n |only showing top 1 row\n |\"\"\"\n self.assertEquals(re.sub(pattern, '', expected3), df._repr_html_())\n\n # test when eager evaluation is disabled and _repr_html_ will be called\n with self.sql_conf({\"spark.sql.repl.eagerEval.enabled\": False}):\n expected = \"DataFrame[key: bigint, value: string]\"\n self.assertEquals(None, df._repr_html_())\n self.assertEquals(expected, df.__repr__())\n with self.sql_conf({\"spark.sql.repl.eagerEval.truncate\": 3}):\n self.assertEquals(None, df._repr_html_())\n self.assertEquals(expected, df.__repr__())\n with self.sql_conf({\"spark.sql.repl.eagerEval.maxNumRows\": 1}):\n self.assertEquals(None, df._repr_html_())\n self.assertEquals(expected, df.__repr__())\n\n\nclass HiveSparkSubmitTests(SparkSubmitTests):\n\n @classmethod\n def setUpClass(cls):\n # get a SparkContext to check for availability of Hive\n sc = SparkContext('local[4]', cls.__name__)\n cls.hive_available = True\n try:\n sc._jvm.org.apache.hadoop.hive.conf.HiveConf()\n except py4j.protocol.Py4JError:\n cls.hive_available = False\n except TypeError:\n cls.hive_available = False\n finally:\n # we don't need this SparkContext for the test\n sc.stop()\n\n def setUp(self):\n super(HiveSparkSubmitTests, self).setUp()\n if not self.hive_available:\n self.skipTest(\"Hive is not available.\")\n\n def test_hivecontext(self):\n # This test checks that HiveContext is using Hive metastore (SPARK-16224).\n # It sets a metastore url and checks if there is a derby dir created by\n # Hive metastore. If this derby dir exists, HiveContext is using\n # Hive metastore.\n metastore_path = os.path.join(tempfile.mkdtemp(), \"spark16224_metastore_db\")\n metastore_URL = \"jdbc:derby:;databaseName=\" + metastore_path + \";create=true\"\n hive_site_dir = os.path.join(self.programDir, \"conf\")\n hive_site_file = self.createTempFile(\"hive-site.xml\", (\"\"\"\n |<configuration>\n | <property>\n | <name>javax.jdo.option.ConnectionURL</name>\n | <value>%s</value>\n | </property>\n |</configuration>\n \"\"\" % metastore_URL).lstrip(), \"conf\")\n script = self.createTempFile(\"test.py\", \"\"\"\n |import os\n |\n |from pyspark.conf import SparkConf\n |from pyspark.context import SparkContext\n |from pyspark.sql import HiveContext\n |\n |conf = SparkConf()\n |sc = SparkContext(conf=conf)\n |hive_context = HiveContext(sc)\n |print(hive_context.sql(\"show databases\").collect())\n \"\"\")\n proc = subprocess.Popen(\n self.sparkSubmit + [\"--master\", \"local-cluster[1,1,1024]\",\n \"--driver-class-path\", hive_site_dir, script],\n stdout=subprocess.PIPE)\n out, err = proc.communicate()\n self.assertEqual(0, proc.returncode)\n self.assertIn(\"default\", out.decode('utf-8'))\n self.assertTrue(os.path.exists(metastore_path))\n\n\nclass SQLTests2(ReusedSQLTestCase):\n\n # We can't include this test into SQLTests because we will stop class's SparkContext and cause\n # other tests failed.\n def test_sparksession_with_stopped_sparkcontext(self):\n self.sc.stop()\n sc = SparkContext('local[4]', self.sc.appName)\n spark = SparkSession.builder.getOrCreate()\n try:\n df = spark.createDataFrame([(1, 2)], [\"c\", \"c\"])\n df.collect()\n finally:\n spark.stop()\n sc.stop()\n\n\nclass QueryExecutionListenerTests(unittest.TestCase, SQLTestUtils):\n # These tests are separate because it uses 'spark.sql.queryExecutionListeners' which is\n # static and immutable. This can't be set or unset, for example, via `spark.conf`.\n\n @classmethod\n def setUpClass(cls):\n import glob\n from pyspark.find_spark_home import _find_spark_home\n\n SPARK_HOME = _find_spark_home()\n filename_pattern = (\n \"sql/core/target/scala-*/test-classes/org/apache/spark/sql/\"\n \"TestQueryExecutionListener.class\")\n cls.has_listener = bool(glob.glob(os.path.join(SPARK_HOME, filename_pattern)))\n\n if cls.has_listener:\n # Note that 'spark.sql.queryExecutionListeners' is a static immutable configuration.\n cls.spark = SparkSession.builder \\\n .master(\"local[4]\") \\\n .appName(cls.__name__) \\\n .config(\n \"spark.sql.queryExecutionListeners\",\n \"org.apache.spark.sql.TestQueryExecutionListener\") \\\n .getOrCreate()\n\n def setUp(self):\n if not self.has_listener:\n raise self.skipTest(\n \"'org.apache.spark.sql.TestQueryExecutionListener' is not \"\n \"available. Will skip the related tests.\")\n\n @classmethod\n def tearDownClass(cls):\n if hasattr(cls, \"spark\"):\n cls.spark.stop()\n\n def tearDown(self):\n self.spark._jvm.OnSuccessCall.clear()\n\n def test_query_execution_listener_on_collect(self):\n self.assertFalse(\n self.spark._jvm.OnSuccessCall.isCalled(),\n \"The callback from the query execution listener should not be called before 'collect'\")\n self.spark.sql(\"SELECT * FROM range(1)\").collect()\n self.assertTrue(\n self.spark._jvm.OnSuccessCall.isCalled(),\n \"The callback from the query execution listener should be called after 'collect'\")\n\n @unittest.skipIf(\n not _have_pandas or not _have_pyarrow,\n _pandas_requirement_message or _pyarrow_requirement_message)\n def test_query_execution_listener_on_collect_with_arrow(self):\n with self.sql_conf({\"spark.sql.execution.arrow.enabled\": True}):\n self.assertFalse(\n self.spark._jvm.OnSuccessCall.isCalled(),\n \"The callback from the query execution listener should not be \"\n \"called before 'toPandas'\")\n self.spark.sql(\"SELECT * FROM range(1)\").toPandas()\n self.assertTrue(\n self.spark._jvm.OnSuccessCall.isCalled(),\n \"The callback from the query execution listener should be called after 'toPandas'\")\n\n\nclass SparkSessionTests(PySparkTestCase):\n\n # This test is separate because it's closely related with session's start and stop.\n # See SPARK-23228.\n def test_set_jvm_default_session(self):\n spark = SparkSession.builder.getOrCreate()\n try:\n self.assertTrue(spark._jvm.SparkSession.getDefaultSession().isDefined())\n finally:\n spark.stop()\n self.assertTrue(spark._jvm.SparkSession.getDefaultSession().isEmpty())\n\n def test_jvm_default_session_already_set(self):\n # Here, we assume there is the default session already set in JVM.\n jsession = self.sc._jvm.SparkSession(self.sc._jsc.sc())\n self.sc._jvm.SparkSession.setDefaultSession(jsession)\n\n spark = SparkSession.builder.getOrCreate()\n try:\n self.assertTrue(spark._jvm.SparkSession.getDefaultSession().isDefined())\n # The session should be the same with the exiting one.\n self.assertTrue(jsession.equals(spark._jvm.SparkSession.getDefaultSession().get()))\n finally:\n spark.stop()\n\n\nclass UDFInitializationTests(unittest.TestCase):\n def tearDown(self):\n if SparkSession._instantiatedSession is not None:\n SparkSession._instantiatedSession.stop()\n\n if SparkContext._active_spark_context is not None:\n SparkContext._active_spark_context.stop()\n\n def test_udf_init_shouldnt_initialize_context(self):\n from pyspark.sql.functions import UserDefinedFunction\n\n UserDefinedFunction(lambda x: x, StringType())\n\n self.assertIsNone(\n SparkContext._active_spark_context,\n \"SparkContext shouldn't be initialized when UserDefinedFunction is created.\"\n )\n self.assertIsNone(\n SparkSession._instantiatedSession,\n \"SparkSession shouldn't be initialized when UserDefinedFunction is created.\"\n )\n\n\nclass HiveContextSQLTests(ReusedPySparkTestCase):\n\n @classmethod\n def setUpClass(cls):\n ReusedPySparkTestCase.setUpClass()\n cls.tempdir = tempfile.NamedTemporaryFile(delete=False)\n cls.hive_available = True\n try:\n cls.sc._jvm.org.apache.hadoop.hive.conf.HiveConf()\n except py4j.protocol.Py4JError:\n cls.hive_available = False\n except TypeError:\n cls.hive_available = False\n os.unlink(cls.tempdir.name)\n if cls.hive_available:\n cls.spark = HiveContext._createForTesting(cls.sc)\n cls.testData = [Row(key=i, value=str(i)) for i in range(100)]\n cls.df = cls.sc.parallelize(cls.testData).toDF()\n\n def setUp(self):\n if not self.hive_available:\n self.skipTest(\"Hive is not available.\")\n\n @classmethod\n def tearDownClass(cls):\n ReusedPySparkTestCase.tearDownClass()\n shutil.rmtree(cls.tempdir.name, ignore_errors=True)\n\n def test_save_and_load_table(self):\n df = self.df\n tmpPath = tempfile.mkdtemp()\n shutil.rmtree(tmpPath)\n df.write.saveAsTable(\"savedJsonTable\", \"json\", \"append\", path=tmpPath)\n actual = self.spark.createExternalTable(\"externalJsonTable\", tmpPath, \"json\")\n self.assertEqual(sorted(df.collect()),\n sorted(self.spark.sql(\"SELECT * FROM savedJsonTable\").collect()))\n self.assertEqual(sorted(df.collect()),\n sorted(self.spark.sql(\"SELECT * FROM externalJsonTable\").collect()))\n self.assertEqual(sorted(df.collect()), sorted(actual.collect()))\n self.spark.sql(\"DROP TABLE externalJsonTable\")\n\n df.write.saveAsTable(\"savedJsonTable\", \"json\", \"overwrite\", path=tmpPath)\n schema = StructType([StructField(\"value\", StringType(), True)])\n actual = self.spark.createExternalTable(\"externalJsonTable\", source=\"json\",\n schema=schema, path=tmpPath,\n noUse=\"this options will not be used\")\n self.assertEqual(sorted(df.collect()),\n sorted(self.spark.sql(\"SELECT * FROM savedJsonTable\").collect()))\n self.assertEqual(sorted(df.select(\"value\").collect()),\n sorted(self.spark.sql(\"SELECT * FROM externalJsonTable\").collect()))\n self.assertEqual(sorted(df.select(\"value\").collect()), sorted(actual.collect()))\n self.spark.sql(\"DROP TABLE savedJsonTable\")\n self.spark.sql(\"DROP TABLE externalJsonTable\")\n\n defaultDataSourceName = self.spark.getConf(\"spark.sql.sources.default\",\n \"org.apache.spark.sql.parquet\")\n self.spark.sql(\"SET spark.sql.sources.default=org.apache.spark.sql.json\")\n df.write.saveAsTable(\"savedJsonTable\", path=tmpPath, mode=\"overwrite\")\n actual = self.spark.createExternalTable(\"externalJsonTable\", path=tmpPath)\n self.assertEqual(sorted(df.collect()),\n sorted(self.spark.sql(\"SELECT * FROM savedJsonTable\").collect()))\n self.assertEqual(sorted(df.collect()),\n sorted(self.spark.sql(\"SELECT * FROM externalJsonTable\").collect()))\n self.assertEqual(sorted(df.collect()), sorted(actual.collect()))\n self.spark.sql(\"DROP TABLE savedJsonTable\")\n self.spark.sql(\"DROP TABLE externalJsonTable\")\n self.spark.sql(\"SET spark.sql.sources.default=\" + defaultDataSourceName)\n\n shutil.rmtree(tmpPath)\n\n def test_window_functions(self):\n df = self.spark.createDataFrame([(1, \"1\"), (2, \"2\"), (1, \"2\"), (1, \"2\")], [\"key\", \"value\"])\n w = Window.partitionBy(\"value\").orderBy(\"key\")\n from pyspark.sql import functions as F\n sel = df.select(df.value, df.key,\n F.max(\"key\").over(w.rowsBetween(0, 1)),\n F.min(\"key\").over(w.rowsBetween(0, 1)),\n F.count(\"key\").over(w.rowsBetween(float('-inf'), float('inf'))),\n F.row_number().over(w),\n F.rank().over(w),\n F.dense_rank().over(w),\n F.ntile(2).over(w))\n rs = sorted(sel.collect())\n expected = [\n (\"1\", 1, 1, 1, 1, 1, 1, 1, 1),\n (\"2\", 1, 1, 1, 3, 1, 1, 1, 1),\n (\"2\", 1, 2, 1, 3, 2, 1, 1, 1),\n (\"2\", 2, 2, 2, 3, 3, 3, 2, 2)\n ]\n for r, ex in zip(rs, expected):\n self.assertEqual(tuple(r), ex[:len(r)])\n\n def test_window_functions_without_partitionBy(self):\n df = self.spark.createDataFrame([(1, \"1\"), (2, \"2\"), (1, \"2\"), (1, \"2\")], [\"key\", \"value\"])\n w = Window.orderBy(\"key\", df.value)\n from pyspark.sql import functions as F\n sel = df.select(df.value, df.key,\n F.max(\"key\").over(w.rowsBetween(0, 1)),\n F.min(\"key\").over(w.rowsBetween(0, 1)),\n F.count(\"key\").over(w.rowsBetween(float('-inf'), float('inf'))),\n F.row_number().over(w),\n F.rank().over(w),\n F.dense_rank().over(w),\n F.ntile(2).over(w))\n rs = sorted(sel.collect())\n expected = [\n (\"1\", 1, 1, 1, 4, 1, 1, 1, 1),\n (\"2\", 1, 1, 1, 4, 2, 2, 2, 1),\n (\"2\", 1, 2, 1, 4, 3, 2, 2, 2),\n (\"2\", 2, 2, 2, 4, 4, 4, 3, 2)\n ]\n for r, ex in zip(rs, expected):\n self.assertEqual(tuple(r), ex[:len(r)])\n\n def test_window_functions_cumulative_sum(self):\n df = self.spark.createDataFrame([(\"one\", 1), (\"two\", 2)], [\"key\", \"value\"])\n from pyspark.sql import functions as F\n\n # Test cumulative sum\n sel = df.select(\n df.key,\n F.sum(df.value).over(Window.rowsBetween(Window.unboundedPreceding, 0)))\n rs = sorted(sel.collect())\n expected = [(\"one\", 1), (\"two\", 3)]\n for r, ex in zip(rs, expected):\n self.assertEqual(tuple(r), ex[:len(r)])\n\n # Test boundary values less than JVM's Long.MinValue and make sure we don't overflow\n sel = df.select(\n df.key,\n F.sum(df.value).over(Window.rowsBetween(Window.unboundedPreceding - 1, 0)))\n rs = sorted(sel.collect())\n expected = [(\"one\", 1), (\"two\", 3)]\n for r, ex in zip(rs, expected):\n self.assertEqual(tuple(r), ex[:len(r)])\n\n # Test boundary values greater than JVM's Long.MaxValue and make sure we don't overflow\n frame_end = Window.unboundedFollowing + 1\n sel = df.select(\n df.key,\n F.sum(df.value).over(Window.rowsBetween(Window.currentRow, frame_end)))\n rs = sorted(sel.collect())\n expected = [(\"one\", 3), (\"two\", 2)]\n for r, ex in zip(rs, expected):\n self.assertEqual(tuple(r), ex[:len(r)])\n\n def test_collect_functions(self):\n df = self.spark.createDataFrame([(1, \"1\"), (2, \"2\"), (1, \"2\"), (1, \"2\")], [\"key\", \"value\"])\n from pyspark.sql import functions\n\n self.assertEqual(\n sorted(df.select(functions.collect_set(df.key).alias('r')).collect()[0].r),\n [1, 2])\n self.assertEqual(\n sorted(df.select(functions.collect_list(df.key).alias('r')).collect()[0].r),\n [1, 1, 1, 2])\n self.assertEqual(\n sorted(df.select(functions.collect_set(df.value).alias('r')).collect()[0].r),\n [\"1\", \"2\"])\n self.assertEqual(\n sorted(df.select(functions.collect_list(df.value).alias('r')).collect()[0].r),\n [\"1\", \"2\", \"2\", \"2\"])\n\n def test_limit_and_take(self):\n df = self.spark.range(1, 1000, numPartitions=10)\n\n def assert_runs_only_one_job_stage_and_task(job_group_name, f):\n tracker = self.sc.statusTracker()\n self.sc.setJobGroup(job_group_name, description=\"\")\n f()\n jobs = tracker.getJobIdsForGroup(job_group_name)\n self.assertEqual(1, len(jobs))\n stages = tracker.getJobInfo(jobs[0]).stageIds\n self.assertEqual(1, len(stages))\n self.assertEqual(1, tracker.getStageInfo(stages[0]).numTasks)\n\n # Regression test for SPARK-10731: take should delegate to Scala implementation\n assert_runs_only_one_job_stage_and_task(\"take\", lambda: df.take(1))\n # Regression test for SPARK-17514: limit(n).collect() should the perform same as take(n)\n assert_runs_only_one_job_stage_and_task(\"collect_limit\", lambda: df.limit(1).collect())\n\n def test_datetime_functions(self):\n from pyspark.sql import functions\n from datetime import date, datetime\n df = self.spark.range(1).selectExpr(\"'2017-01-22' as dateCol\")\n parse_result = df.select(functions.to_date(functions.col(\"dateCol\"))).first()\n self.assertEquals(date(2017, 1, 22), parse_result['to_date(`dateCol`)'])\n\n @unittest.skipIf(sys.version_info < (3, 3), \"Unittest < 3.3 doesn't support mocking\")\n def test_unbounded_frames(self):\n from unittest.mock import patch\n from pyspark.sql import functions as F\n from pyspark.sql import window\n import importlib\n\n df = self.spark.range(0, 3)\n\n def rows_frame_match():\n return \"ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING\" in df.select(\n F.count(\"*\").over(window.Window.rowsBetween(-sys.maxsize, sys.maxsize))\n ).columns[0]\n\n def range_frame_match():\n return \"RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING\" in df.select(\n F.count(\"*\").over(window.Window.rangeBetween(-sys.maxsize, sys.maxsize))\n ).columns[0]\n\n with patch(\"sys.maxsize\", 2 ** 31 - 1):\n importlib.reload(window)\n self.assertTrue(rows_frame_match())\n self.assertTrue(range_frame_match())\n\n with patch(\"sys.maxsize\", 2 ** 63 - 1):\n importlib.reload(window)\n self.assertTrue(rows_frame_match())\n self.assertTrue(range_frame_match())\n\n with patch(\"sys.maxsize\", 2 ** 127 - 1):\n importlib.reload(window)\n self.assertTrue(rows_frame_match())\n self.assertTrue(range_frame_match())\n\n importlib.reload(window)\n\n\nclass DataTypeVerificationTests(unittest.TestCase):\n\n def test_verify_type_exception_msg(self):\n self.assertRaisesRegexp(\n ValueError,\n \"test_name\",\n lambda: _make_type_verifier(StringType(), nullable=False, name=\"test_name\")(None))\n\n schema = StructType([StructField('a', StructType([StructField('b', IntegerType())]))])\n self.assertRaisesRegexp(\n TypeError,\n \"field b in field a\",\n lambda: _make_type_verifier(schema)([[\"data\"]]))\n\n def test_verify_type_ok_nullable(self):\n obj = None\n types = [IntegerType(), FloatType(), StringType(), StructType([])]\n for data_type in types:\n try:\n _make_type_verifier(data_type, nullable=True)(obj)\n except Exception:\n self.fail(\"verify_type(%s, %s, nullable=True)\" % (obj, data_type))\n\n def test_verify_type_not_nullable(self):\n import array\n import datetime\n import decimal\n\n schema = StructType([\n StructField('s', StringType(), nullable=False),\n StructField('i', IntegerType(), nullable=True)])\n\n class MyObj:\n def __init__(self, **kwargs):\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n # obj, data_type\n success_spec = [\n # String\n (\"\", StringType()),\n (u\"\", StringType()),\n (1, StringType()),\n (1.0, StringType()),\n ([], StringType()),\n ({}, StringType()),\n\n # UDT\n (ExamplePoint(1.0, 2.0), ExamplePointUDT()),\n\n # Boolean\n (True, BooleanType()),\n\n # Byte\n (-(2**7), ByteType()),\n (2**7 - 1, ByteType()),\n\n # Short\n (-(2**15), ShortType()),\n (2**15 - 1, ShortType()),\n\n # Integer\n (-(2**31), IntegerType()),\n (2**31 - 1, IntegerType()),\n\n # Long\n (2**64, LongType()),\n\n # Float & Double\n (1.0, FloatType()),\n (1.0, DoubleType()),\n\n # Decimal\n (decimal.Decimal(\"1.0\"), DecimalType()),\n\n # Binary\n (bytearray([1, 2]), BinaryType()),\n\n # Date/Timestamp\n (datetime.date(2000, 1, 2), DateType()),\n (datetime.datetime(2000, 1, 2, 3, 4), DateType()),\n (datetime.datetime(2000, 1, 2, 3, 4), TimestampType()),\n\n # Array\n ([], ArrayType(IntegerType())),\n ([\"1\", None], ArrayType(StringType(), containsNull=True)),\n ([1, 2], ArrayType(IntegerType())),\n ((1, 2), ArrayType(IntegerType())),\n (array.array('h', [1, 2]), ArrayType(IntegerType())),\n\n # Map\n ({}, MapType(StringType(), IntegerType())),\n ({\"a\": 1}, MapType(StringType(), IntegerType())),\n ({\"a\": None}, MapType(StringType(), IntegerType(), valueContainsNull=True)),\n\n # Struct\n ({\"s\": \"a\", \"i\": 1}, schema),\n ({\"s\": \"a\", \"i\": None}, schema),\n ({\"s\": \"a\"}, schema),\n ({\"s\": \"a\", \"f\": 1.0}, schema),\n (Row(s=\"a\", i=1), schema),\n (Row(s=\"a\", i=None), schema),\n (Row(s=\"a\", i=1, f=1.0), schema),\n ([\"a\", 1], schema),\n ([\"a\", None], schema),\n ((\"a\", 1), schema),\n (MyObj(s=\"a\", i=1), schema),\n (MyObj(s=\"a\", i=None), schema),\n (MyObj(s=\"a\"), schema),\n ]\n\n # obj, data_type, exception class\n failure_spec = [\n # String (match anything but None)\n (None, StringType(), ValueError),\n\n # UDT\n (ExamplePoint(1.0, 2.0), PythonOnlyUDT(), ValueError),\n\n # Boolean\n (1, BooleanType(), TypeError),\n (\"True\", BooleanType(), TypeError),\n ([1], BooleanType(), TypeError),\n\n # Byte\n (-(2**7) - 1, ByteType(), ValueError),\n (2**7, ByteType(), ValueError),\n (\"1\", ByteType(), TypeError),\n (1.0, ByteType(), TypeError),\n\n # Short\n (-(2**15) - 1, ShortType(), ValueError),\n (2**15, ShortType(), ValueError),\n\n # Integer\n (-(2**31) - 1, IntegerType(), ValueError),\n (2**31, IntegerType(), ValueError),\n\n # Float & Double\n (1, FloatType(), TypeError),\n (1, DoubleType(), TypeError),\n\n # Decimal\n (1.0, DecimalType(), TypeError),\n (1, DecimalType(), TypeError),\n (\"1.0\", DecimalType(), TypeError),\n\n # Binary\n (1, BinaryType(), TypeError),\n\n # Date/Timestamp\n (\"2000-01-02\", DateType(), TypeError),\n (946811040, TimestampType(), TypeError),\n\n # Array\n ([\"1\", None], ArrayType(StringType(), containsNull=False), ValueError),\n ([1, \"2\"], ArrayType(IntegerType()), TypeError),\n\n # Map\n ({\"a\": 1}, MapType(IntegerType(), IntegerType()), TypeError),\n ({\"a\": \"1\"}, MapType(StringType(), IntegerType()), TypeError),\n ({\"a\": None}, MapType(StringType(), IntegerType(), valueContainsNull=False),\n ValueError),\n\n # Struct\n ({\"s\": \"a\", \"i\": \"1\"}, schema, TypeError),\n (Row(s=\"a\"), schema, ValueError), # Row can't have missing field\n (Row(s=\"a\", i=\"1\"), schema, TypeError),\n ([\"a\"], schema, ValueError),\n ([\"a\", \"1\"], schema, TypeError),\n (MyObj(s=\"a\", i=\"1\"), schema, TypeError),\n (MyObj(s=None, i=\"1\"), schema, ValueError),\n ]\n\n # Check success cases\n for obj, data_type in success_spec:\n try:\n _make_type_verifier(data_type, nullable=False)(obj)\n except Exception:\n self.fail(\"verify_type(%s, %s, nullable=False)\" % (obj, data_type))\n\n # Check failure cases\n for obj, data_type, exp in failure_spec:\n msg = \"verify_type(%s, %s, nullable=False) == %s\" % (obj, data_type, exp)\n with self.assertRaises(exp, msg=msg):\n _make_type_verifier(data_type, nullable=False)(obj)\n\n\[email protected](\n not _have_pandas or not _have_pyarrow,\n _pandas_requirement_message or _pyarrow_requirement_message)\nclass ArrowTests(ReusedSQLTestCase):\n\n @classmethod\n def setUpClass(cls):\n from datetime import date, datetime\n from decimal import Decimal\n from distutils.version import LooseVersion\n import pyarrow as pa\n super(ArrowTests, cls).setUpClass()\n cls.warnings_lock = threading.Lock()\n\n # Synchronize default timezone between Python and Java\n cls.tz_prev = os.environ.get(\"TZ\", None) # save current tz if set\n tz = \"America/Los_Angeles\"\n os.environ[\"TZ\"] = tz\n time.tzset()\n\n cls.spark.conf.set(\"spark.sql.session.timeZone\", tz)\n cls.spark.conf.set(\"spark.sql.execution.arrow.enabled\", \"true\")\n # Disable fallback by default to easily detect the failures.\n cls.spark.conf.set(\"spark.sql.execution.arrow.fallback.enabled\", \"false\")\n cls.schema = StructType([\n StructField(\"1_str_t\", StringType(), True),\n StructField(\"2_int_t\", IntegerType(), True),\n StructField(\"3_long_t\", LongType(), True),\n StructField(\"4_float_t\", FloatType(), True),\n StructField(\"5_double_t\", DoubleType(), True),\n StructField(\"6_decimal_t\", DecimalType(38, 18), True),\n StructField(\"7_date_t\", DateType(), True),\n StructField(\"8_timestamp_t\", TimestampType(), True)])\n cls.data = [(u\"a\", 1, 10, 0.2, 2.0, Decimal(\"2.0\"),\n date(1969, 1, 1), datetime(1969, 1, 1, 1, 1, 1)),\n (u\"b\", 2, 20, 0.4, 4.0, Decimal(\"4.0\"),\n date(2012, 2, 2), datetime(2012, 2, 2, 2, 2, 2)),\n (u\"c\", 3, 30, 0.8, 6.0, Decimal(\"6.0\"),\n date(2100, 3, 3), datetime(2100, 3, 3, 3, 3, 3))]\n\n # TODO: remove version check once minimum pyarrow version is 0.10.0\n if LooseVersion(\"0.10.0\") <= LooseVersion(pa.__version__):\n cls.schema.add(StructField(\"9_binary_t\", BinaryType(), True))\n cls.data[0] = cls.data[0] + (bytearray(b\"a\"),)\n cls.data[1] = cls.data[1] + (bytearray(b\"bb\"),)\n cls.data[2] = cls.data[2] + (bytearray(b\"ccc\"),)\n\n @classmethod\n def tearDownClass(cls):\n del os.environ[\"TZ\"]\n if cls.tz_prev is not None:\n os.environ[\"TZ\"] = cls.tz_prev\n time.tzset()\n super(ArrowTests, cls).tearDownClass()\n\n def create_pandas_data_frame(self):\n import pandas as pd\n import numpy as np\n data_dict = {}\n for j, name in enumerate(self.schema.names):\n data_dict[name] = [self.data[i][j] for i in range(len(self.data))]\n # need to convert these to numpy types first\n data_dict[\"2_int_t\"] = np.int32(data_dict[\"2_int_t\"])\n data_dict[\"4_float_t\"] = np.float32(data_dict[\"4_float_t\"])\n return pd.DataFrame(data=data_dict)\n\n def test_toPandas_fallback_enabled(self):\n import pandas as pd\n\n with self.sql_conf({\"spark.sql.execution.arrow.fallback.enabled\": True}):\n schema = StructType([StructField(\"map\", MapType(StringType(), IntegerType()), True)])\n df = self.spark.createDataFrame([({u'a': 1},)], schema=schema)\n with QuietTest(self.sc):\n with self.warnings_lock:\n with warnings.catch_warnings(record=True) as warns:\n # we want the warnings to appear even if this test is run from a subclass\n warnings.simplefilter(\"always\")\n pdf = df.toPandas()\n # Catch and check the last UserWarning.\n user_warns = [\n warn.message for warn in warns if isinstance(warn.message, UserWarning)]\n self.assertTrue(len(user_warns) > 0)\n self.assertTrue(\n \"Attempting non-optimization\" in _exception_message(user_warns[-1]))\n self.assertPandasEqual(pdf, pd.DataFrame({u'map': [{u'a': 1}]}))\n\n def test_toPandas_fallback_disabled(self):\n from distutils.version import LooseVersion\n import pyarrow as pa\n\n schema = StructType([StructField(\"map\", MapType(StringType(), IntegerType()), True)])\n df = self.spark.createDataFrame([(None,)], schema=schema)\n with QuietTest(self.sc):\n with self.warnings_lock:\n with self.assertRaisesRegexp(Exception, 'Unsupported type'):\n df.toPandas()\n\n # TODO: remove BinaryType check once minimum pyarrow version is 0.10.0\n if LooseVersion(pa.__version__) < LooseVersion(\"0.10.0\"):\n schema = StructType([StructField(\"binary\", BinaryType(), True)])\n df = self.spark.createDataFrame([(None,)], schema=schema)\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(Exception, 'Unsupported type.*BinaryType'):\n df.toPandas()\n\n def test_null_conversion(self):\n df_null = self.spark.createDataFrame([tuple([None for _ in range(len(self.data[0]))])] +\n self.data)\n pdf = df_null.toPandas()\n null_counts = pdf.isnull().sum().tolist()\n self.assertTrue(all([c == 1 for c in null_counts]))\n\n def _toPandas_arrow_toggle(self, df):\n with self.sql_conf({\"spark.sql.execution.arrow.enabled\": False}):\n pdf = df.toPandas()\n\n pdf_arrow = df.toPandas()\n\n return pdf, pdf_arrow\n\n def test_toPandas_arrow_toggle(self):\n df = self.spark.createDataFrame(self.data, schema=self.schema)\n pdf, pdf_arrow = self._toPandas_arrow_toggle(df)\n expected = self.create_pandas_data_frame()\n self.assertPandasEqual(expected, pdf)\n self.assertPandasEqual(expected, pdf_arrow)\n\n def test_toPandas_respect_session_timezone(self):\n df = self.spark.createDataFrame(self.data, schema=self.schema)\n\n timezone = \"America/New_York\"\n with self.sql_conf({\n \"spark.sql.execution.pandas.respectSessionTimeZone\": False,\n \"spark.sql.session.timeZone\": timezone}):\n pdf_la, pdf_arrow_la = self._toPandas_arrow_toggle(df)\n self.assertPandasEqual(pdf_arrow_la, pdf_la)\n\n with self.sql_conf({\n \"spark.sql.execution.pandas.respectSessionTimeZone\": True,\n \"spark.sql.session.timeZone\": timezone}):\n pdf_ny, pdf_arrow_ny = self._toPandas_arrow_toggle(df)\n self.assertPandasEqual(pdf_arrow_ny, pdf_ny)\n\n self.assertFalse(pdf_ny.equals(pdf_la))\n\n from pyspark.sql.types import _check_series_convert_timestamps_local_tz\n pdf_la_corrected = pdf_la.copy()\n for field in self.schema:\n if isinstance(field.dataType, TimestampType):\n pdf_la_corrected[field.name] = _check_series_convert_timestamps_local_tz(\n pdf_la_corrected[field.name], timezone)\n self.assertPandasEqual(pdf_ny, pdf_la_corrected)\n\n def test_pandas_round_trip(self):\n pdf = self.create_pandas_data_frame()\n df = self.spark.createDataFrame(self.data, schema=self.schema)\n pdf_arrow = df.toPandas()\n self.assertPandasEqual(pdf_arrow, pdf)\n\n def test_filtered_frame(self):\n df = self.spark.range(3).toDF(\"i\")\n pdf = df.filter(\"i < 0\").toPandas()\n self.assertEqual(len(pdf.columns), 1)\n self.assertEqual(pdf.columns[0], \"i\")\n self.assertTrue(pdf.empty)\n\n def _createDataFrame_toggle(self, pdf, schema=None):\n with self.sql_conf({\"spark.sql.execution.arrow.enabled\": False}):\n df_no_arrow = self.spark.createDataFrame(pdf, schema=schema)\n\n df_arrow = self.spark.createDataFrame(pdf, schema=schema)\n\n return df_no_arrow, df_arrow\n\n def test_createDataFrame_toggle(self):\n pdf = self.create_pandas_data_frame()\n df_no_arrow, df_arrow = self._createDataFrame_toggle(pdf, schema=self.schema)\n self.assertEquals(df_no_arrow.collect(), df_arrow.collect())\n\n def test_createDataFrame_respect_session_timezone(self):\n from datetime import timedelta\n pdf = self.create_pandas_data_frame()\n timezone = \"America/New_York\"\n with self.sql_conf({\n \"spark.sql.execution.pandas.respectSessionTimeZone\": False,\n \"spark.sql.session.timeZone\": timezone}):\n df_no_arrow_la, df_arrow_la = self._createDataFrame_toggle(pdf, schema=self.schema)\n result_la = df_no_arrow_la.collect()\n result_arrow_la = df_arrow_la.collect()\n self.assertEqual(result_la, result_arrow_la)\n\n with self.sql_conf({\n \"spark.sql.execution.pandas.respectSessionTimeZone\": True,\n \"spark.sql.session.timeZone\": timezone}):\n df_no_arrow_ny, df_arrow_ny = self._createDataFrame_toggle(pdf, schema=self.schema)\n result_ny = df_no_arrow_ny.collect()\n result_arrow_ny = df_arrow_ny.collect()\n self.assertEqual(result_ny, result_arrow_ny)\n\n self.assertNotEqual(result_ny, result_la)\n\n # Correct result_la by adjusting 3 hours difference between Los Angeles and New York\n result_la_corrected = [Row(**{k: v - timedelta(hours=3) if k == '8_timestamp_t' else v\n for k, v in row.asDict().items()})\n for row in result_la]\n self.assertEqual(result_ny, result_la_corrected)\n\n def test_createDataFrame_with_schema(self):\n pdf = self.create_pandas_data_frame()\n df = self.spark.createDataFrame(pdf, schema=self.schema)\n self.assertEquals(self.schema, df.schema)\n pdf_arrow = df.toPandas()\n self.assertPandasEqual(pdf_arrow, pdf)\n\n def test_createDataFrame_with_incorrect_schema(self):\n pdf = self.create_pandas_data_frame()\n fields = list(self.schema)\n fields[0], fields[7] = fields[7], fields[0] # swap str with timestamp\n wrong_schema = StructType(fields)\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(Exception, \".*No cast.*string.*timestamp.*\"):\n self.spark.createDataFrame(pdf, schema=wrong_schema)\n\n def test_createDataFrame_with_names(self):\n pdf = self.create_pandas_data_frame()\n new_names = list(map(str, range(len(self.schema.fieldNames()))))\n # Test that schema as a list of column names gets applied\n df = self.spark.createDataFrame(pdf, schema=list(new_names))\n self.assertEquals(df.schema.fieldNames(), new_names)\n # Test that schema as tuple of column names gets applied\n df = self.spark.createDataFrame(pdf, schema=tuple(new_names))\n self.assertEquals(df.schema.fieldNames(), new_names)\n\n def test_createDataFrame_column_name_encoding(self):\n import pandas as pd\n pdf = pd.DataFrame({u'a': [1]})\n columns = self.spark.createDataFrame(pdf).columns\n self.assertTrue(isinstance(columns[0], str))\n self.assertEquals(columns[0], 'a')\n columns = self.spark.createDataFrame(pdf, [u'b']).columns\n self.assertTrue(isinstance(columns[0], str))\n self.assertEquals(columns[0], 'b')\n\n def test_createDataFrame_with_single_data_type(self):\n import pandas as pd\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(ValueError, \".*IntegerType.*not supported.*\"):\n self.spark.createDataFrame(pd.DataFrame({\"a\": [1]}), schema=\"int\")\n\n def test_createDataFrame_does_not_modify_input(self):\n import pandas as pd\n # Some series get converted for Spark to consume, this makes sure input is unchanged\n pdf = self.create_pandas_data_frame()\n # Use a nanosecond value to make sure it is not truncated\n pdf.ix[0, '8_timestamp_t'] = pd.Timestamp(1)\n # Integers with nulls will get NaNs filled with 0 and will be casted\n pdf.ix[1, '2_int_t'] = None\n pdf_copy = pdf.copy(deep=True)\n self.spark.createDataFrame(pdf, schema=self.schema)\n self.assertTrue(pdf.equals(pdf_copy))\n\n def test_schema_conversion_roundtrip(self):\n from pyspark.sql.types import from_arrow_schema, to_arrow_schema\n arrow_schema = to_arrow_schema(self.schema)\n schema_rt = from_arrow_schema(arrow_schema)\n self.assertEquals(self.schema, schema_rt)\n\n def test_createDataFrame_with_array_type(self):\n import pandas as pd\n pdf = pd.DataFrame({\"a\": [[1, 2], [3, 4]], \"b\": [[u\"x\", u\"y\"], [u\"y\", u\"z\"]]})\n df, df_arrow = self._createDataFrame_toggle(pdf)\n result = df.collect()\n result_arrow = df_arrow.collect()\n expected = [tuple(list(e) for e in rec) for rec in pdf.to_records(index=False)]\n for r in range(len(expected)):\n for e in range(len(expected[r])):\n self.assertTrue(expected[r][e] == result_arrow[r][e] and\n result[r][e] == result_arrow[r][e])\n\n def test_toPandas_with_array_type(self):\n expected = [([1, 2], [u\"x\", u\"y\"]), ([3, 4], [u\"y\", u\"z\"])]\n array_schema = StructType([StructField(\"a\", ArrayType(IntegerType())),\n StructField(\"b\", ArrayType(StringType()))])\n df = self.spark.createDataFrame(expected, schema=array_schema)\n pdf, pdf_arrow = self._toPandas_arrow_toggle(df)\n result = [tuple(list(e) for e in rec) for rec in pdf.to_records(index=False)]\n result_arrow = [tuple(list(e) for e in rec) for rec in pdf_arrow.to_records(index=False)]\n for r in range(len(expected)):\n for e in range(len(expected[r])):\n self.assertTrue(expected[r][e] == result_arrow[r][e] and\n result[r][e] == result_arrow[r][e])\n\n def test_createDataFrame_with_int_col_names(self):\n import numpy as np\n import pandas as pd\n pdf = pd.DataFrame(np.random.rand(4, 2))\n df, df_arrow = self._createDataFrame_toggle(pdf)\n pdf_col_names = [str(c) for c in pdf.columns]\n self.assertEqual(pdf_col_names, df.columns)\n self.assertEqual(pdf_col_names, df_arrow.columns)\n\n def test_createDataFrame_fallback_enabled(self):\n import pandas as pd\n\n with QuietTest(self.sc):\n with self.sql_conf({\"spark.sql.execution.arrow.fallback.enabled\": True}):\n with warnings.catch_warnings(record=True) as warns:\n # we want the warnings to appear even if this test is run from a subclass\n warnings.simplefilter(\"always\")\n df = self.spark.createDataFrame(\n pd.DataFrame([[{u'a': 1}]]), \"a: map<string, int>\")\n # Catch and check the last UserWarning.\n user_warns = [\n warn.message for warn in warns if isinstance(warn.message, UserWarning)]\n self.assertTrue(len(user_warns) > 0)\n self.assertTrue(\n \"Attempting non-optimization\" in _exception_message(user_warns[-1]))\n self.assertEqual(df.collect(), [Row(a={u'a': 1})])\n\n def test_createDataFrame_fallback_disabled(self):\n from distutils.version import LooseVersion\n import pandas as pd\n import pyarrow as pa\n\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(TypeError, 'Unsupported type'):\n self.spark.createDataFrame(\n pd.DataFrame([[{u'a': 1}]]), \"a: map<string, int>\")\n\n # TODO: remove BinaryType check once minimum pyarrow version is 0.10.0\n if LooseVersion(pa.__version__) < LooseVersion(\"0.10.0\"):\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(TypeError, 'Unsupported type.*BinaryType'):\n self.spark.createDataFrame(\n pd.DataFrame([[{'a': b'aaa'}]]), \"a: binary\")\n\n # Regression test for SPARK-23314\n def test_timestamp_dst(self):\n import pandas as pd\n # Daylight saving time for Los Angeles for 2015 is Sun, Nov 1 at 2:00 am\n dt = [datetime.datetime(2015, 11, 1, 0, 30),\n datetime.datetime(2015, 11, 1, 1, 30),\n datetime.datetime(2015, 11, 1, 2, 30)]\n pdf = pd.DataFrame({'time': dt})\n\n df_from_python = self.spark.createDataFrame(dt, 'timestamp').toDF('time')\n df_from_pandas = self.spark.createDataFrame(pdf)\n\n self.assertPandasEqual(pdf, df_from_python.toPandas())\n self.assertPandasEqual(pdf, df_from_pandas.toPandas())\n\n\nclass EncryptionArrowTests(ArrowTests):\n\n @classmethod\n def conf(cls):\n return super(EncryptionArrowTests, cls).conf().set(\"spark.io.encryption.enabled\", \"true\")\n\n\[email protected](\n not _have_pandas or not _have_pyarrow,\n _pandas_requirement_message or _pyarrow_requirement_message)\nclass PandasUDFTests(ReusedSQLTestCase):\n\n def test_pandas_udf_basic(self):\n from pyspark.rdd import PythonEvalType\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n udf = pandas_udf(lambda x: x, DoubleType())\n self.assertEqual(udf.returnType, DoubleType())\n self.assertEqual(udf.evalType, PythonEvalType.SQL_SCALAR_PANDAS_UDF)\n\n udf = pandas_udf(lambda x: x, DoubleType(), PandasUDFType.SCALAR)\n self.assertEqual(udf.returnType, DoubleType())\n self.assertEqual(udf.evalType, PythonEvalType.SQL_SCALAR_PANDAS_UDF)\n\n udf = pandas_udf(lambda x: x, 'double', PandasUDFType.SCALAR)\n self.assertEqual(udf.returnType, DoubleType())\n self.assertEqual(udf.evalType, PythonEvalType.SQL_SCALAR_PANDAS_UDF)\n\n udf = pandas_udf(lambda x: x, StructType([StructField(\"v\", DoubleType())]),\n PandasUDFType.GROUPED_MAP)\n self.assertEqual(udf.returnType, StructType([StructField(\"v\", DoubleType())]))\n self.assertEqual(udf.evalType, PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF)\n\n udf = pandas_udf(lambda x: x, 'v double', PandasUDFType.GROUPED_MAP)\n self.assertEqual(udf.returnType, StructType([StructField(\"v\", DoubleType())]))\n self.assertEqual(udf.evalType, PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF)\n\n udf = pandas_udf(lambda x: x, 'v double',\n functionType=PandasUDFType.GROUPED_MAP)\n self.assertEqual(udf.returnType, StructType([StructField(\"v\", DoubleType())]))\n self.assertEqual(udf.evalType, PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF)\n\n udf = pandas_udf(lambda x: x, returnType='v double',\n functionType=PandasUDFType.GROUPED_MAP)\n self.assertEqual(udf.returnType, StructType([StructField(\"v\", DoubleType())]))\n self.assertEqual(udf.evalType, PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF)\n\n def test_pandas_udf_decorator(self):\n from pyspark.rdd import PythonEvalType\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n from pyspark.sql.types import StructType, StructField, DoubleType\n\n @pandas_udf(DoubleType())\n def foo(x):\n return x\n self.assertEqual(foo.returnType, DoubleType())\n self.assertEqual(foo.evalType, PythonEvalType.SQL_SCALAR_PANDAS_UDF)\n\n @pandas_udf(returnType=DoubleType())\n def foo(x):\n return x\n self.assertEqual(foo.returnType, DoubleType())\n self.assertEqual(foo.evalType, PythonEvalType.SQL_SCALAR_PANDAS_UDF)\n\n schema = StructType([StructField(\"v\", DoubleType())])\n\n @pandas_udf(schema, PandasUDFType.GROUPED_MAP)\n def foo(x):\n return x\n self.assertEqual(foo.returnType, schema)\n self.assertEqual(foo.evalType, PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF)\n\n @pandas_udf('v double', PandasUDFType.GROUPED_MAP)\n def foo(x):\n return x\n self.assertEqual(foo.returnType, schema)\n self.assertEqual(foo.evalType, PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF)\n\n @pandas_udf(schema, functionType=PandasUDFType.GROUPED_MAP)\n def foo(x):\n return x\n self.assertEqual(foo.returnType, schema)\n self.assertEqual(foo.evalType, PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF)\n\n @pandas_udf(returnType='double', functionType=PandasUDFType.SCALAR)\n def foo(x):\n return x\n self.assertEqual(foo.returnType, DoubleType())\n self.assertEqual(foo.evalType, PythonEvalType.SQL_SCALAR_PANDAS_UDF)\n\n @pandas_udf(returnType=schema, functionType=PandasUDFType.GROUPED_MAP)\n def foo(x):\n return x\n self.assertEqual(foo.returnType, schema)\n self.assertEqual(foo.evalType, PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF)\n\n def test_udf_wrong_arg(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n with QuietTest(self.sc):\n with self.assertRaises(ParseException):\n @pandas_udf('blah')\n def foo(x):\n return x\n with self.assertRaisesRegexp(ValueError, 'Invalid returnType.*None'):\n @pandas_udf(functionType=PandasUDFType.SCALAR)\n def foo(x):\n return x\n with self.assertRaisesRegexp(ValueError, 'Invalid functionType'):\n @pandas_udf('double', 100)\n def foo(x):\n return x\n\n with self.assertRaisesRegexp(ValueError, '0-arg pandas_udfs.*not.*supported'):\n pandas_udf(lambda: 1, LongType(), PandasUDFType.SCALAR)\n with self.assertRaisesRegexp(ValueError, '0-arg pandas_udfs.*not.*supported'):\n @pandas_udf(LongType(), PandasUDFType.SCALAR)\n def zero_with_type():\n return 1\n\n with self.assertRaisesRegexp(TypeError, 'Invalid returnType'):\n @pandas_udf(returnType=PandasUDFType.GROUPED_MAP)\n def foo(df):\n return df\n with self.assertRaisesRegexp(TypeError, 'Invalid returnType'):\n @pandas_udf(returnType='double', functionType=PandasUDFType.GROUPED_MAP)\n def foo(df):\n return df\n with self.assertRaisesRegexp(ValueError, 'Invalid function'):\n @pandas_udf(returnType='k int, v double', functionType=PandasUDFType.GROUPED_MAP)\n def foo(k, v, w):\n return k\n\n def test_stopiteration_in_udf(self):\n from pyspark.sql.functions import udf, pandas_udf, PandasUDFType\n from py4j.protocol import Py4JJavaError\n\n def foo(x):\n raise StopIteration()\n\n def foofoo(x, y):\n raise StopIteration()\n\n exc_message = \"Caught StopIteration thrown from user's code; failing the task\"\n df = self.spark.range(0, 100)\n\n # plain udf (test for SPARK-23754)\n self.assertRaisesRegexp(\n Py4JJavaError,\n exc_message,\n df.withColumn('v', udf(foo)('id')).collect\n )\n\n # pandas scalar udf\n self.assertRaisesRegexp(\n Py4JJavaError,\n exc_message,\n df.withColumn(\n 'v', pandas_udf(foo, 'double', PandasUDFType.SCALAR)('id')\n ).collect\n )\n\n # pandas grouped map\n self.assertRaisesRegexp(\n Py4JJavaError,\n exc_message,\n df.groupBy('id').apply(\n pandas_udf(foo, df.schema, PandasUDFType.GROUPED_MAP)\n ).collect\n )\n\n self.assertRaisesRegexp(\n Py4JJavaError,\n exc_message,\n df.groupBy('id').apply(\n pandas_udf(foofoo, df.schema, PandasUDFType.GROUPED_MAP)\n ).collect\n )\n\n # pandas grouped agg\n self.assertRaisesRegexp(\n Py4JJavaError,\n exc_message,\n df.groupBy('id').agg(\n pandas_udf(foo, 'double', PandasUDFType.GROUPED_AGG)('id')\n ).collect\n )\n\n\[email protected](\n not _have_pandas or not _have_pyarrow,\n _pandas_requirement_message or _pyarrow_requirement_message)\nclass ScalarPandasUDFTests(ReusedSQLTestCase):\n\n @classmethod\n def setUpClass(cls):\n ReusedSQLTestCase.setUpClass()\n\n # Synchronize default timezone between Python and Java\n cls.tz_prev = os.environ.get(\"TZ\", None) # save current tz if set\n tz = \"America/Los_Angeles\"\n os.environ[\"TZ\"] = tz\n time.tzset()\n\n cls.sc.environment[\"TZ\"] = tz\n cls.spark.conf.set(\"spark.sql.session.timeZone\", tz)\n\n @classmethod\n def tearDownClass(cls):\n del os.environ[\"TZ\"]\n if cls.tz_prev is not None:\n os.environ[\"TZ\"] = cls.tz_prev\n time.tzset()\n ReusedSQLTestCase.tearDownClass()\n\n @property\n def nondeterministic_vectorized_udf(self):\n from pyspark.sql.functions import pandas_udf\n\n @pandas_udf('double')\n def random_udf(v):\n import pandas as pd\n import numpy as np\n return pd.Series(np.random.random(len(v)))\n random_udf = random_udf.asNondeterministic()\n return random_udf\n\n def test_pandas_udf_tokenize(self):\n from pyspark.sql.functions import pandas_udf\n tokenize = pandas_udf(lambda s: s.apply(lambda str: str.split(' ')),\n ArrayType(StringType()))\n self.assertEqual(tokenize.returnType, ArrayType(StringType()))\n df = self.spark.createDataFrame([(\"hi boo\",), (\"bye boo\",)], [\"vals\"])\n result = df.select(tokenize(\"vals\").alias(\"hi\"))\n self.assertEqual([Row(hi=[u'hi', u'boo']), Row(hi=[u'bye', u'boo'])], result.collect())\n\n def test_pandas_udf_nested_arrays(self):\n from pyspark.sql.functions import pandas_udf\n tokenize = pandas_udf(lambda s: s.apply(lambda str: [str.split(' ')]),\n ArrayType(ArrayType(StringType())))\n self.assertEqual(tokenize.returnType, ArrayType(ArrayType(StringType())))\n df = self.spark.createDataFrame([(\"hi boo\",), (\"bye boo\",)], [\"vals\"])\n result = df.select(tokenize(\"vals\").alias(\"hi\"))\n self.assertEqual([Row(hi=[[u'hi', u'boo']]), Row(hi=[[u'bye', u'boo']])], result.collect())\n\n def test_vectorized_udf_basic(self):\n from pyspark.sql.functions import pandas_udf, col, array\n df = self.spark.range(10).select(\n col('id').cast('string').alias('str'),\n col('id').cast('int').alias('int'),\n col('id').alias('long'),\n col('id').cast('float').alias('float'),\n col('id').cast('double').alias('double'),\n col('id').cast('decimal').alias('decimal'),\n col('id').cast('boolean').alias('bool'),\n array(col('id')).alias('array_long'))\n f = lambda x: x\n str_f = pandas_udf(f, StringType())\n int_f = pandas_udf(f, IntegerType())\n long_f = pandas_udf(f, LongType())\n float_f = pandas_udf(f, FloatType())\n double_f = pandas_udf(f, DoubleType())\n decimal_f = pandas_udf(f, DecimalType())\n bool_f = pandas_udf(f, BooleanType())\n array_long_f = pandas_udf(f, ArrayType(LongType()))\n res = df.select(str_f(col('str')), int_f(col('int')),\n long_f(col('long')), float_f(col('float')),\n double_f(col('double')), decimal_f('decimal'),\n bool_f(col('bool')), array_long_f('array_long'))\n self.assertEquals(df.collect(), res.collect())\n\n def test_register_nondeterministic_vectorized_udf_basic(self):\n from pyspark.sql.functions import pandas_udf\n from pyspark.rdd import PythonEvalType\n import random\n random_pandas_udf = pandas_udf(\n lambda x: random.randint(6, 6) + x, IntegerType()).asNondeterministic()\n self.assertEqual(random_pandas_udf.deterministic, False)\n self.assertEqual(random_pandas_udf.evalType, PythonEvalType.SQL_SCALAR_PANDAS_UDF)\n nondeterministic_pandas_udf = self.spark.catalog.registerFunction(\n \"randomPandasUDF\", random_pandas_udf)\n self.assertEqual(nondeterministic_pandas_udf.deterministic, False)\n self.assertEqual(nondeterministic_pandas_udf.evalType, PythonEvalType.SQL_SCALAR_PANDAS_UDF)\n [row] = self.spark.sql(\"SELECT randomPandasUDF(1)\").collect()\n self.assertEqual(row[0], 7)\n\n def test_vectorized_udf_null_boolean(self):\n from pyspark.sql.functions import pandas_udf, col\n data = [(True,), (True,), (None,), (False,)]\n schema = StructType().add(\"bool\", BooleanType())\n df = self.spark.createDataFrame(data, schema)\n bool_f = pandas_udf(lambda x: x, BooleanType())\n res = df.select(bool_f(col('bool')))\n self.assertEquals(df.collect(), res.collect())\n\n def test_vectorized_udf_null_byte(self):\n from pyspark.sql.functions import pandas_udf, col\n data = [(None,), (2,), (3,), (4,)]\n schema = StructType().add(\"byte\", ByteType())\n df = self.spark.createDataFrame(data, schema)\n byte_f = pandas_udf(lambda x: x, ByteType())\n res = df.select(byte_f(col('byte')))\n self.assertEquals(df.collect(), res.collect())\n\n def test_vectorized_udf_null_short(self):\n from pyspark.sql.functions import pandas_udf, col\n data = [(None,), (2,), (3,), (4,)]\n schema = StructType().add(\"short\", ShortType())\n df = self.spark.createDataFrame(data, schema)\n short_f = pandas_udf(lambda x: x, ShortType())\n res = df.select(short_f(col('short')))\n self.assertEquals(df.collect(), res.collect())\n\n def test_vectorized_udf_null_int(self):\n from pyspark.sql.functions import pandas_udf, col\n data = [(None,), (2,), (3,), (4,)]\n schema = StructType().add(\"int\", IntegerType())\n df = self.spark.createDataFrame(data, schema)\n int_f = pandas_udf(lambda x: x, IntegerType())\n res = df.select(int_f(col('int')))\n self.assertEquals(df.collect(), res.collect())\n\n def test_vectorized_udf_null_long(self):\n from pyspark.sql.functions import pandas_udf, col\n data = [(None,), (2,), (3,), (4,)]\n schema = StructType().add(\"long\", LongType())\n df = self.spark.createDataFrame(data, schema)\n long_f = pandas_udf(lambda x: x, LongType())\n res = df.select(long_f(col('long')))\n self.assertEquals(df.collect(), res.collect())\n\n def test_vectorized_udf_null_float(self):\n from pyspark.sql.functions import pandas_udf, col\n data = [(3.0,), (5.0,), (-1.0,), (None,)]\n schema = StructType().add(\"float\", FloatType())\n df = self.spark.createDataFrame(data, schema)\n float_f = pandas_udf(lambda x: x, FloatType())\n res = df.select(float_f(col('float')))\n self.assertEquals(df.collect(), res.collect())\n\n def test_vectorized_udf_null_double(self):\n from pyspark.sql.functions import pandas_udf, col\n data = [(3.0,), (5.0,), (-1.0,), (None,)]\n schema = StructType().add(\"double\", DoubleType())\n df = self.spark.createDataFrame(data, schema)\n double_f = pandas_udf(lambda x: x, DoubleType())\n res = df.select(double_f(col('double')))\n self.assertEquals(df.collect(), res.collect())\n\n def test_vectorized_udf_null_decimal(self):\n from decimal import Decimal\n from pyspark.sql.functions import pandas_udf, col\n data = [(Decimal(3.0),), (Decimal(5.0),), (Decimal(-1.0),), (None,)]\n schema = StructType().add(\"decimal\", DecimalType(38, 18))\n df = self.spark.createDataFrame(data, schema)\n decimal_f = pandas_udf(lambda x: x, DecimalType(38, 18))\n res = df.select(decimal_f(col('decimal')))\n self.assertEquals(df.collect(), res.collect())\n\n def test_vectorized_udf_null_string(self):\n from pyspark.sql.functions import pandas_udf, col\n data = [(\"foo\",), (None,), (\"bar\",), (\"bar\",)]\n schema = StructType().add(\"str\", StringType())\n df = self.spark.createDataFrame(data, schema)\n str_f = pandas_udf(lambda x: x, StringType())\n res = df.select(str_f(col('str')))\n self.assertEquals(df.collect(), res.collect())\n\n def test_vectorized_udf_string_in_udf(self):\n from pyspark.sql.functions import pandas_udf, col\n import pandas as pd\n df = self.spark.range(10)\n str_f = pandas_udf(lambda x: pd.Series(map(str, x)), StringType())\n actual = df.select(str_f(col('id')))\n expected = df.select(col('id').cast('string'))\n self.assertEquals(expected.collect(), actual.collect())\n\n def test_vectorized_udf_datatype_string(self):\n from pyspark.sql.functions import pandas_udf, col\n df = self.spark.range(10).select(\n col('id').cast('string').alias('str'),\n col('id').cast('int').alias('int'),\n col('id').alias('long'),\n col('id').cast('float').alias('float'),\n col('id').cast('double').alias('double'),\n col('id').cast('decimal').alias('decimal'),\n col('id').cast('boolean').alias('bool'))\n f = lambda x: x\n str_f = pandas_udf(f, 'string')\n int_f = pandas_udf(f, 'integer')\n long_f = pandas_udf(f, 'long')\n float_f = pandas_udf(f, 'float')\n double_f = pandas_udf(f, 'double')\n decimal_f = pandas_udf(f, 'decimal(38, 18)')\n bool_f = pandas_udf(f, 'boolean')\n res = df.select(str_f(col('str')), int_f(col('int')),\n long_f(col('long')), float_f(col('float')),\n double_f(col('double')), decimal_f('decimal'),\n bool_f(col('bool')))\n self.assertEquals(df.collect(), res.collect())\n\n def test_vectorized_udf_null_binary(self):\n from distutils.version import LooseVersion\n import pyarrow as pa\n from pyspark.sql.functions import pandas_udf, col\n if LooseVersion(pa.__version__) < LooseVersion(\"0.10.0\"):\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(\n NotImplementedError,\n 'Invalid returnType.*scalar Pandas UDF.*BinaryType'):\n pandas_udf(lambda x: x, BinaryType())\n else:\n data = [(bytearray(b\"a\"),), (None,), (bytearray(b\"bb\"),), (bytearray(b\"ccc\"),)]\n schema = StructType().add(\"binary\", BinaryType())\n df = self.spark.createDataFrame(data, schema)\n str_f = pandas_udf(lambda x: x, BinaryType())\n res = df.select(str_f(col('binary')))\n self.assertEquals(df.collect(), res.collect())\n\n def test_vectorized_udf_array_type(self):\n from pyspark.sql.functions import pandas_udf, col\n data = [([1, 2],), ([3, 4],)]\n array_schema = StructType([StructField(\"array\", ArrayType(IntegerType()))])\n df = self.spark.createDataFrame(data, schema=array_schema)\n array_f = pandas_udf(lambda x: x, ArrayType(IntegerType()))\n result = df.select(array_f(col('array')))\n self.assertEquals(df.collect(), result.collect())\n\n def test_vectorized_udf_null_array(self):\n from pyspark.sql.functions import pandas_udf, col\n data = [([1, 2],), (None,), (None,), ([3, 4],), (None,)]\n array_schema = StructType([StructField(\"array\", ArrayType(IntegerType()))])\n df = self.spark.createDataFrame(data, schema=array_schema)\n array_f = pandas_udf(lambda x: x, ArrayType(IntegerType()))\n result = df.select(array_f(col('array')))\n self.assertEquals(df.collect(), result.collect())\n\n def test_vectorized_udf_complex(self):\n from pyspark.sql.functions import pandas_udf, col, expr\n df = self.spark.range(10).select(\n col('id').cast('int').alias('a'),\n col('id').cast('int').alias('b'),\n col('id').cast('double').alias('c'))\n add = pandas_udf(lambda x, y: x + y, IntegerType())\n power2 = pandas_udf(lambda x: 2 ** x, IntegerType())\n mul = pandas_udf(lambda x, y: x * y, DoubleType())\n res = df.select(add(col('a'), col('b')), power2(col('a')), mul(col('b'), col('c')))\n expected = df.select(expr('a + b'), expr('power(2, a)'), expr('b * c'))\n self.assertEquals(expected.collect(), res.collect())\n\n def test_vectorized_udf_exception(self):\n from pyspark.sql.functions import pandas_udf, col\n df = self.spark.range(10)\n raise_exception = pandas_udf(lambda x: x * (1 / 0), LongType())\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(Exception, 'division( or modulo)? by zero'):\n df.select(raise_exception(col('id'))).collect()\n\n def test_vectorized_udf_invalid_length(self):\n from pyspark.sql.functions import pandas_udf, col\n import pandas as pd\n df = self.spark.range(10)\n raise_exception = pandas_udf(lambda _: pd.Series(1), LongType())\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(\n Exception,\n 'Result vector from pandas_udf was not the required length'):\n df.select(raise_exception(col('id'))).collect()\n\n def test_vectorized_udf_chained(self):\n from pyspark.sql.functions import pandas_udf, col\n df = self.spark.range(10)\n f = pandas_udf(lambda x: x + 1, LongType())\n g = pandas_udf(lambda x: x - 1, LongType())\n res = df.select(g(f(col('id'))))\n self.assertEquals(df.collect(), res.collect())\n\n def test_vectorized_udf_wrong_return_type(self):\n from pyspark.sql.functions import pandas_udf, col\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(\n NotImplementedError,\n 'Invalid returnType.*scalar Pandas UDF.*MapType'):\n pandas_udf(lambda x: x * 1.0, MapType(LongType(), LongType()))\n\n def test_vectorized_udf_return_scalar(self):\n from pyspark.sql.functions import pandas_udf, col\n df = self.spark.range(10)\n f = pandas_udf(lambda x: 1.0, DoubleType())\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(Exception, 'Return.*type.*Series'):\n df.select(f(col('id'))).collect()\n\n def test_vectorized_udf_decorator(self):\n from pyspark.sql.functions import pandas_udf, col\n df = self.spark.range(10)\n\n @pandas_udf(returnType=LongType())\n def identity(x):\n return x\n res = df.select(identity(col('id')))\n self.assertEquals(df.collect(), res.collect())\n\n def test_vectorized_udf_empty_partition(self):\n from pyspark.sql.functions import pandas_udf, col\n df = self.spark.createDataFrame(self.sc.parallelize([Row(id=1)], 2))\n f = pandas_udf(lambda x: x, LongType())\n res = df.select(f(col('id')))\n self.assertEquals(df.collect(), res.collect())\n\n def test_vectorized_udf_varargs(self):\n from pyspark.sql.functions import pandas_udf, col\n df = self.spark.createDataFrame(self.sc.parallelize([Row(id=1)], 2))\n f = pandas_udf(lambda *v: v[0], LongType())\n res = df.select(f(col('id')))\n self.assertEquals(df.collect(), res.collect())\n\n def test_vectorized_udf_unsupported_types(self):\n from pyspark.sql.functions import pandas_udf\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(\n NotImplementedError,\n 'Invalid returnType.*scalar Pandas UDF.*MapType'):\n pandas_udf(lambda x: x, MapType(StringType(), IntegerType()))\n\n def test_vectorized_udf_dates(self):\n from pyspark.sql.functions import pandas_udf, col\n from datetime import date\n schema = StructType().add(\"idx\", LongType()).add(\"date\", DateType())\n data = [(0, date(1969, 1, 1),),\n (1, date(2012, 2, 2),),\n (2, None,),\n (3, date(2100, 4, 4),)]\n df = self.spark.createDataFrame(data, schema=schema)\n\n date_copy = pandas_udf(lambda t: t, returnType=DateType())\n df = df.withColumn(\"date_copy\", date_copy(col(\"date\")))\n\n @pandas_udf(returnType=StringType())\n def check_data(idx, date, date_copy):\n import pandas as pd\n msgs = []\n is_equal = date.isnull()\n for i in range(len(idx)):\n if (is_equal[i] and data[idx[i]][1] is None) or \\\n date[i] == data[idx[i]][1]:\n msgs.append(None)\n else:\n msgs.append(\n \"date values are not equal (date='%s': data[%d][1]='%s')\"\n % (date[i], idx[i], data[idx[i]][1]))\n return pd.Series(msgs)\n\n result = df.withColumn(\"check_data\",\n check_data(col(\"idx\"), col(\"date\"), col(\"date_copy\"))).collect()\n\n self.assertEquals(len(data), len(result))\n for i in range(len(result)):\n self.assertEquals(data[i][1], result[i][1]) # \"date\" col\n self.assertEquals(data[i][1], result[i][2]) # \"date_copy\" col\n self.assertIsNone(result[i][3]) # \"check_data\" col\n\n def test_vectorized_udf_timestamps(self):\n from pyspark.sql.functions import pandas_udf, col\n from datetime import datetime\n schema = StructType([\n StructField(\"idx\", LongType(), True),\n StructField(\"timestamp\", TimestampType(), True)])\n data = [(0, datetime(1969, 1, 1, 1, 1, 1)),\n (1, datetime(2012, 2, 2, 2, 2, 2)),\n (2, None),\n (3, datetime(2100, 3, 3, 3, 3, 3))]\n\n df = self.spark.createDataFrame(data, schema=schema)\n\n # Check that a timestamp passed through a pandas_udf will not be altered by timezone calc\n f_timestamp_copy = pandas_udf(lambda t: t, returnType=TimestampType())\n df = df.withColumn(\"timestamp_copy\", f_timestamp_copy(col(\"timestamp\")))\n\n @pandas_udf(returnType=StringType())\n def check_data(idx, timestamp, timestamp_copy):\n import pandas as pd\n msgs = []\n is_equal = timestamp.isnull() # use this array to check values are equal\n for i in range(len(idx)):\n # Check that timestamps are as expected in the UDF\n if (is_equal[i] and data[idx[i]][1] is None) or \\\n timestamp[i].to_pydatetime() == data[idx[i]][1]:\n msgs.append(None)\n else:\n msgs.append(\n \"timestamp values are not equal (timestamp='%s': data[%d][1]='%s')\"\n % (timestamp[i], idx[i], data[idx[i]][1]))\n return pd.Series(msgs)\n\n result = df.withColumn(\"check_data\", check_data(col(\"idx\"), col(\"timestamp\"),\n col(\"timestamp_copy\"))).collect()\n # Check that collection values are correct\n self.assertEquals(len(data), len(result))\n for i in range(len(result)):\n self.assertEquals(data[i][1], result[i][1]) # \"timestamp\" col\n self.assertEquals(data[i][1], result[i][2]) # \"timestamp_copy\" col\n self.assertIsNone(result[i][3]) # \"check_data\" col\n\n def test_vectorized_udf_return_timestamp_tz(self):\n from pyspark.sql.functions import pandas_udf, col\n import pandas as pd\n df = self.spark.range(10)\n\n @pandas_udf(returnType=TimestampType())\n def gen_timestamps(id):\n ts = [pd.Timestamp(i, unit='D', tz='America/Los_Angeles') for i in id]\n return pd.Series(ts)\n\n result = df.withColumn(\"ts\", gen_timestamps(col(\"id\"))).collect()\n spark_ts_t = TimestampType()\n for r in result:\n i, ts = r\n ts_tz = pd.Timestamp(i, unit='D', tz='America/Los_Angeles').to_pydatetime()\n expected = spark_ts_t.fromInternal(spark_ts_t.toInternal(ts_tz))\n self.assertEquals(expected, ts)\n\n def test_vectorized_udf_check_config(self):\n from pyspark.sql.functions import pandas_udf, col\n import pandas as pd\n with self.sql_conf({\"spark.sql.execution.arrow.maxRecordsPerBatch\": 3}):\n df = self.spark.range(10, numPartitions=1)\n\n @pandas_udf(returnType=LongType())\n def check_records_per_batch(x):\n return pd.Series(x.size).repeat(x.size)\n\n result = df.select(check_records_per_batch(col(\"id\"))).collect()\n for (r,) in result:\n self.assertTrue(r <= 3)\n\n def test_vectorized_udf_timestamps_respect_session_timezone(self):\n from pyspark.sql.functions import pandas_udf, col\n from datetime import datetime\n import pandas as pd\n schema = StructType([\n StructField(\"idx\", LongType(), True),\n StructField(\"timestamp\", TimestampType(), True)])\n data = [(1, datetime(1969, 1, 1, 1, 1, 1)),\n (2, datetime(2012, 2, 2, 2, 2, 2)),\n (3, None),\n (4, datetime(2100, 3, 3, 3, 3, 3))]\n df = self.spark.createDataFrame(data, schema=schema)\n\n f_timestamp_copy = pandas_udf(lambda ts: ts, TimestampType())\n internal_value = pandas_udf(\n lambda ts: ts.apply(lambda ts: ts.value if ts is not pd.NaT else None), LongType())\n\n timezone = \"America/New_York\"\n with self.sql_conf({\n \"spark.sql.execution.pandas.respectSessionTimeZone\": False,\n \"spark.sql.session.timeZone\": timezone}):\n df_la = df.withColumn(\"tscopy\", f_timestamp_copy(col(\"timestamp\"))) \\\n .withColumn(\"internal_value\", internal_value(col(\"timestamp\")))\n result_la = df_la.select(col(\"idx\"), col(\"internal_value\")).collect()\n # Correct result_la by adjusting 3 hours difference between Los Angeles and New York\n diff = 3 * 60 * 60 * 1000 * 1000 * 1000\n result_la_corrected = \\\n df_la.select(col(\"idx\"), col(\"tscopy\"), col(\"internal_value\") + diff).collect()\n\n with self.sql_conf({\n \"spark.sql.execution.pandas.respectSessionTimeZone\": True,\n \"spark.sql.session.timeZone\": timezone}):\n df_ny = df.withColumn(\"tscopy\", f_timestamp_copy(col(\"timestamp\"))) \\\n .withColumn(\"internal_value\", internal_value(col(\"timestamp\")))\n result_ny = df_ny.select(col(\"idx\"), col(\"tscopy\"), col(\"internal_value\")).collect()\n\n self.assertNotEqual(result_ny, result_la)\n self.assertEqual(result_ny, result_la_corrected)\n\n def test_nondeterministic_vectorized_udf(self):\n # Test that nondeterministic UDFs are evaluated only once in chained UDF evaluations\n from pyspark.sql.functions import udf, pandas_udf, col\n\n @pandas_udf('double')\n def plus_ten(v):\n return v + 10\n random_udf = self.nondeterministic_vectorized_udf\n\n df = self.spark.range(10).withColumn('rand', random_udf(col('id')))\n result1 = df.withColumn('plus_ten(rand)', plus_ten(df['rand'])).toPandas()\n\n self.assertEqual(random_udf.deterministic, False)\n self.assertTrue(result1['plus_ten(rand)'].equals(result1['rand'] + 10))\n\n def test_nondeterministic_vectorized_udf_in_aggregate(self):\n from pyspark.sql.functions import pandas_udf, sum\n\n df = self.spark.range(10)\n random_udf = self.nondeterministic_vectorized_udf\n\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(AnalysisException, 'nondeterministic'):\n df.groupby(df.id).agg(sum(random_udf(df.id))).collect()\n with self.assertRaisesRegexp(AnalysisException, 'nondeterministic'):\n df.agg(sum(random_udf(df.id))).collect()\n\n def test_register_vectorized_udf_basic(self):\n from pyspark.rdd import PythonEvalType\n from pyspark.sql.functions import pandas_udf, col, expr\n df = self.spark.range(10).select(\n col('id').cast('int').alias('a'),\n col('id').cast('int').alias('b'))\n original_add = pandas_udf(lambda x, y: x + y, IntegerType())\n self.assertEqual(original_add.deterministic, True)\n self.assertEqual(original_add.evalType, PythonEvalType.SQL_SCALAR_PANDAS_UDF)\n new_add = self.spark.catalog.registerFunction(\"add1\", original_add)\n res1 = df.select(new_add(col('a'), col('b')))\n res2 = self.spark.sql(\n \"SELECT add1(t.a, t.b) FROM (SELECT id as a, id as b FROM range(10)) t\")\n expected = df.select(expr('a + b'))\n self.assertEquals(expected.collect(), res1.collect())\n self.assertEquals(expected.collect(), res2.collect())\n\n # Regression test for SPARK-23314\n def test_timestamp_dst(self):\n from pyspark.sql.functions import pandas_udf\n # Daylight saving time for Los Angeles for 2015 is Sun, Nov 1 at 2:00 am\n dt = [datetime.datetime(2015, 11, 1, 0, 30),\n datetime.datetime(2015, 11, 1, 1, 30),\n datetime.datetime(2015, 11, 1, 2, 30)]\n df = self.spark.createDataFrame(dt, 'timestamp').toDF('time')\n foo_udf = pandas_udf(lambda x: x, 'timestamp')\n result = df.withColumn('time', foo_udf(df.time))\n self.assertEquals(df.collect(), result.collect())\n\n @unittest.skipIf(sys.version_info[:2] < (3, 5), \"Type hints are supported from Python 3.5.\")\n def test_type_annotation(self):\n from pyspark.sql.functions import pandas_udf\n # Regression test to check if type hints can be used. See SPARK-23569.\n # Note that it throws an error during compilation in lower Python versions if 'exec'\n # is not used. Also, note that we explicitly use another dictionary to avoid modifications\n # in the current 'locals()'.\n #\n # Hyukjin: I think it's an ugly way to test issues about syntax specific in\n # higher versions of Python, which we shouldn't encourage. This was the last resort\n # I could come up with at that time.\n _locals = {}\n exec(\n \"import pandas as pd\\ndef noop(col: pd.Series) -> pd.Series: return col\",\n _locals)\n df = self.spark.range(1).select(pandas_udf(f=_locals['noop'], returnType='bigint')('id'))\n self.assertEqual(df.first()[0], 0)\n\n def test_mixed_udf(self):\n import pandas as pd\n from pyspark.sql.functions import col, udf, pandas_udf\n\n df = self.spark.range(0, 1).toDF('v')\n\n # Test mixture of multiple UDFs and Pandas UDFs.\n\n @udf('int')\n def f1(x):\n assert type(x) == int\n return x + 1\n\n @pandas_udf('int')\n def f2(x):\n assert type(x) == pd.Series\n return x + 10\n\n @udf('int')\n def f3(x):\n assert type(x) == int\n return x + 100\n\n @pandas_udf('int')\n def f4(x):\n assert type(x) == pd.Series\n return x + 1000\n\n # Test single expression with chained UDFs\n df_chained_1 = df.withColumn('f2_f1', f2(f1(df['v'])))\n df_chained_2 = df.withColumn('f3_f2_f1', f3(f2(f1(df['v']))))\n df_chained_3 = df.withColumn('f4_f3_f2_f1', f4(f3(f2(f1(df['v'])))))\n df_chained_4 = df.withColumn('f4_f2_f1', f4(f2(f1(df['v']))))\n df_chained_5 = df.withColumn('f4_f3_f1', f4(f3(f1(df['v']))))\n\n expected_chained_1 = df.withColumn('f2_f1', df['v'] + 11)\n expected_chained_2 = df.withColumn('f3_f2_f1', df['v'] + 111)\n expected_chained_3 = df.withColumn('f4_f3_f2_f1', df['v'] + 1111)\n expected_chained_4 = df.withColumn('f4_f2_f1', df['v'] + 1011)\n expected_chained_5 = df.withColumn('f4_f3_f1', df['v'] + 1101)\n\n self.assertEquals(expected_chained_1.collect(), df_chained_1.collect())\n self.assertEquals(expected_chained_2.collect(), df_chained_2.collect())\n self.assertEquals(expected_chained_3.collect(), df_chained_3.collect())\n self.assertEquals(expected_chained_4.collect(), df_chained_4.collect())\n self.assertEquals(expected_chained_5.collect(), df_chained_5.collect())\n\n # Test multiple mixed UDF expressions in a single projection\n df_multi_1 = df \\\n .withColumn('f1', f1(col('v'))) \\\n .withColumn('f2', f2(col('v'))) \\\n .withColumn('f3', f3(col('v'))) \\\n .withColumn('f4', f4(col('v'))) \\\n .withColumn('f2_f1', f2(col('f1'))) \\\n .withColumn('f3_f1', f3(col('f1'))) \\\n .withColumn('f4_f1', f4(col('f1'))) \\\n .withColumn('f3_f2', f3(col('f2'))) \\\n .withColumn('f4_f2', f4(col('f2'))) \\\n .withColumn('f4_f3', f4(col('f3'))) \\\n .withColumn('f3_f2_f1', f3(col('f2_f1'))) \\\n .withColumn('f4_f2_f1', f4(col('f2_f1'))) \\\n .withColumn('f4_f3_f1', f4(col('f3_f1'))) \\\n .withColumn('f4_f3_f2', f4(col('f3_f2'))) \\\n .withColumn('f4_f3_f2_f1', f4(col('f3_f2_f1')))\n\n # Test mixed udfs in a single expression\n df_multi_2 = df \\\n .withColumn('f1', f1(col('v'))) \\\n .withColumn('f2', f2(col('v'))) \\\n .withColumn('f3', f3(col('v'))) \\\n .withColumn('f4', f4(col('v'))) \\\n .withColumn('f2_f1', f2(f1(col('v')))) \\\n .withColumn('f3_f1', f3(f1(col('v')))) \\\n .withColumn('f4_f1', f4(f1(col('v')))) \\\n .withColumn('f3_f2', f3(f2(col('v')))) \\\n .withColumn('f4_f2', f4(f2(col('v')))) \\\n .withColumn('f4_f3', f4(f3(col('v')))) \\\n .withColumn('f3_f2_f1', f3(f2(f1(col('v'))))) \\\n .withColumn('f4_f2_f1', f4(f2(f1(col('v'))))) \\\n .withColumn('f4_f3_f1', f4(f3(f1(col('v'))))) \\\n .withColumn('f4_f3_f2', f4(f3(f2(col('v'))))) \\\n .withColumn('f4_f3_f2_f1', f4(f3(f2(f1(col('v'))))))\n\n expected = df \\\n .withColumn('f1', df['v'] + 1) \\\n .withColumn('f2', df['v'] + 10) \\\n .withColumn('f3', df['v'] + 100) \\\n .withColumn('f4', df['v'] + 1000) \\\n .withColumn('f2_f1', df['v'] + 11) \\\n .withColumn('f3_f1', df['v'] + 101) \\\n .withColumn('f4_f1', df['v'] + 1001) \\\n .withColumn('f3_f2', df['v'] + 110) \\\n .withColumn('f4_f2', df['v'] + 1010) \\\n .withColumn('f4_f3', df['v'] + 1100) \\\n .withColumn('f3_f2_f1', df['v'] + 111) \\\n .withColumn('f4_f2_f1', df['v'] + 1011) \\\n .withColumn('f4_f3_f1', df['v'] + 1101) \\\n .withColumn('f4_f3_f2', df['v'] + 1110) \\\n .withColumn('f4_f3_f2_f1', df['v'] + 1111)\n\n self.assertEquals(expected.collect(), df_multi_1.collect())\n self.assertEquals(expected.collect(), df_multi_2.collect())\n\n def test_mixed_udf_and_sql(self):\n import pandas as pd\n from pyspark.sql import Column\n from pyspark.sql.functions import udf, pandas_udf\n\n df = self.spark.range(0, 1).toDF('v')\n\n # Test mixture of UDFs, Pandas UDFs and SQL expression.\n\n @udf('int')\n def f1(x):\n assert type(x) == int\n return x + 1\n\n def f2(x):\n assert type(x) == Column\n return x + 10\n\n @pandas_udf('int')\n def f3(x):\n assert type(x) == pd.Series\n return x + 100\n\n df1 = df.withColumn('f1', f1(df['v'])) \\\n .withColumn('f2', f2(df['v'])) \\\n .withColumn('f3', f3(df['v'])) \\\n .withColumn('f1_f2', f1(f2(df['v']))) \\\n .withColumn('f1_f3', f1(f3(df['v']))) \\\n .withColumn('f2_f1', f2(f1(df['v']))) \\\n .withColumn('f2_f3', f2(f3(df['v']))) \\\n .withColumn('f3_f1', f3(f1(df['v']))) \\\n .withColumn('f3_f2', f3(f2(df['v']))) \\\n .withColumn('f1_f2_f3', f1(f2(f3(df['v'])))) \\\n .withColumn('f1_f3_f2', f1(f3(f2(df['v'])))) \\\n .withColumn('f2_f1_f3', f2(f1(f3(df['v'])))) \\\n .withColumn('f2_f3_f1', f2(f3(f1(df['v'])))) \\\n .withColumn('f3_f1_f2', f3(f1(f2(df['v'])))) \\\n .withColumn('f3_f2_f1', f3(f2(f1(df['v']))))\n\n expected = df.withColumn('f1', df['v'] + 1) \\\n .withColumn('f2', df['v'] + 10) \\\n .withColumn('f3', df['v'] + 100) \\\n .withColumn('f1_f2', df['v'] + 11) \\\n .withColumn('f1_f3', df['v'] + 101) \\\n .withColumn('f2_f1', df['v'] + 11) \\\n .withColumn('f2_f3', df['v'] + 110) \\\n .withColumn('f3_f1', df['v'] + 101) \\\n .withColumn('f3_f2', df['v'] + 110) \\\n .withColumn('f1_f2_f3', df['v'] + 111) \\\n .withColumn('f1_f3_f2', df['v'] + 111) \\\n .withColumn('f2_f1_f3', df['v'] + 111) \\\n .withColumn('f2_f3_f1', df['v'] + 111) \\\n .withColumn('f3_f1_f2', df['v'] + 111) \\\n .withColumn('f3_f2_f1', df['v'] + 111)\n\n self.assertEquals(expected.collect(), df1.collect())\n\n # SPARK-24721\n @unittest.skipIf(not _test_compiled, _test_not_compiled_message)\n def test_datasource_with_udf(self):\n # Same as SQLTests.test_datasource_with_udf, but with Pandas UDF\n # This needs to a separate test because Arrow dependency is optional\n import pandas as pd\n import numpy as np\n from pyspark.sql.functions import pandas_udf, lit, col\n\n path = tempfile.mkdtemp()\n shutil.rmtree(path)\n\n try:\n self.spark.range(1).write.mode(\"overwrite\").format('csv').save(path)\n filesource_df = self.spark.read.option('inferSchema', True).csv(path).toDF('i')\n datasource_df = self.spark.read \\\n .format(\"org.apache.spark.sql.sources.SimpleScanSource\") \\\n .option('from', 0).option('to', 1).load().toDF('i')\n datasource_v2_df = self.spark.read \\\n .format(\"org.apache.spark.sql.sources.v2.SimpleDataSourceV2\") \\\n .load().toDF('i', 'j')\n\n c1 = pandas_udf(lambda x: x + 1, 'int')(lit(1))\n c2 = pandas_udf(lambda x: x + 1, 'int')(col('i'))\n\n f1 = pandas_udf(lambda x: pd.Series(np.repeat(False, len(x))), 'boolean')(lit(1))\n f2 = pandas_udf(lambda x: pd.Series(np.repeat(False, len(x))), 'boolean')(col('i'))\n\n for df in [filesource_df, datasource_df, datasource_v2_df]:\n result = df.withColumn('c', c1)\n expected = df.withColumn('c', lit(2))\n self.assertEquals(expected.collect(), result.collect())\n\n for df in [filesource_df, datasource_df, datasource_v2_df]:\n result = df.withColumn('c', c2)\n expected = df.withColumn('c', col('i') + 1)\n self.assertEquals(expected.collect(), result.collect())\n\n for df in [filesource_df, datasource_df, datasource_v2_df]:\n for f in [f1, f2]:\n result = df.filter(f)\n self.assertEquals(0, result.count())\n finally:\n shutil.rmtree(path)\n\n\[email protected](\n not _have_pandas or not _have_pyarrow,\n _pandas_requirement_message or _pyarrow_requirement_message)\nclass GroupedMapPandasUDFTests(ReusedSQLTestCase):\n\n @property\n def data(self):\n from pyspark.sql.functions import array, explode, col, lit\n return self.spark.range(10).toDF('id') \\\n .withColumn(\"vs\", array([lit(i) for i in range(20, 30)])) \\\n .withColumn(\"v\", explode(col('vs'))).drop('vs')\n\n def test_supported_types(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType, array, col\n df = self.data.withColumn(\"arr\", array(col(\"id\")))\n\n # Different forms of group map pandas UDF, results of these are the same\n\n output_schema = StructType(\n [StructField('id', LongType()),\n StructField('v', IntegerType()),\n StructField('arr', ArrayType(LongType())),\n StructField('v1', DoubleType()),\n StructField('v2', LongType())])\n\n udf1 = pandas_udf(\n lambda pdf: pdf.assign(v1=pdf.v * pdf.id * 1.0, v2=pdf.v + pdf.id),\n output_schema,\n PandasUDFType.GROUPED_MAP\n )\n\n udf2 = pandas_udf(\n lambda _, pdf: pdf.assign(v1=pdf.v * pdf.id * 1.0, v2=pdf.v + pdf.id),\n output_schema,\n PandasUDFType.GROUPED_MAP\n )\n\n udf3 = pandas_udf(\n lambda key, pdf: pdf.assign(id=key[0], v1=pdf.v * pdf.id * 1.0, v2=pdf.v + pdf.id),\n output_schema,\n PandasUDFType.GROUPED_MAP\n )\n\n result1 = df.groupby('id').apply(udf1).sort('id').toPandas()\n expected1 = df.toPandas().groupby('id').apply(udf1.func).reset_index(drop=True)\n\n result2 = df.groupby('id').apply(udf2).sort('id').toPandas()\n expected2 = expected1\n\n result3 = df.groupby('id').apply(udf3).sort('id').toPandas()\n expected3 = expected1\n\n self.assertPandasEqual(expected1, result1)\n self.assertPandasEqual(expected2, result2)\n self.assertPandasEqual(expected3, result3)\n\n def test_array_type_correct(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType, array, col\n\n df = self.data.withColumn(\"arr\", array(col(\"id\"))).repartition(1, \"id\")\n\n output_schema = StructType(\n [StructField('id', LongType()),\n StructField('v', IntegerType()),\n StructField('arr', ArrayType(LongType()))])\n\n udf = pandas_udf(\n lambda pdf: pdf,\n output_schema,\n PandasUDFType.GROUPED_MAP\n )\n\n result = df.groupby('id').apply(udf).sort('id').toPandas()\n expected = df.toPandas().groupby('id').apply(udf.func).reset_index(drop=True)\n self.assertPandasEqual(expected, result)\n\n def test_register_grouped_map_udf(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n foo_udf = pandas_udf(lambda x: x, \"id long\", PandasUDFType.GROUPED_MAP)\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(ValueError, 'f must be either SQL_BATCHED_UDF or '\n 'SQL_SCALAR_PANDAS_UDF'):\n self.spark.catalog.registerFunction(\"foo_udf\", foo_udf)\n\n def test_decorator(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n df = self.data\n\n @pandas_udf(\n 'id long, v int, v1 double, v2 long',\n PandasUDFType.GROUPED_MAP\n )\n def foo(pdf):\n return pdf.assign(v1=pdf.v * pdf.id * 1.0, v2=pdf.v + pdf.id)\n\n result = df.groupby('id').apply(foo).sort('id').toPandas()\n expected = df.toPandas().groupby('id').apply(foo.func).reset_index(drop=True)\n self.assertPandasEqual(expected, result)\n\n def test_coerce(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n df = self.data\n\n foo = pandas_udf(\n lambda pdf: pdf,\n 'id long, v double',\n PandasUDFType.GROUPED_MAP\n )\n\n result = df.groupby('id').apply(foo).sort('id').toPandas()\n expected = df.toPandas().groupby('id').apply(foo.func).reset_index(drop=True)\n expected = expected.assign(v=expected.v.astype('float64'))\n self.assertPandasEqual(expected, result)\n\n def test_complex_groupby(self):\n from pyspark.sql.functions import pandas_udf, col, PandasUDFType\n df = self.data\n\n @pandas_udf(\n 'id long, v int, norm double',\n PandasUDFType.GROUPED_MAP\n )\n def normalize(pdf):\n v = pdf.v\n return pdf.assign(norm=(v - v.mean()) / v.std())\n\n result = df.groupby(col('id') % 2 == 0).apply(normalize).sort('id', 'v').toPandas()\n pdf = df.toPandas()\n expected = pdf.groupby(pdf['id'] % 2 == 0).apply(normalize.func)\n expected = expected.sort_values(['id', 'v']).reset_index(drop=True)\n expected = expected.assign(norm=expected.norm.astype('float64'))\n self.assertPandasEqual(expected, result)\n\n def test_empty_groupby(self):\n from pyspark.sql.functions import pandas_udf, col, PandasUDFType\n df = self.data\n\n @pandas_udf(\n 'id long, v int, norm double',\n PandasUDFType.GROUPED_MAP\n )\n def normalize(pdf):\n v = pdf.v\n return pdf.assign(norm=(v - v.mean()) / v.std())\n\n result = df.groupby().apply(normalize).sort('id', 'v').toPandas()\n pdf = df.toPandas()\n expected = normalize.func(pdf)\n expected = expected.sort_values(['id', 'v']).reset_index(drop=True)\n expected = expected.assign(norm=expected.norm.astype('float64'))\n self.assertPandasEqual(expected, result)\n\n def test_datatype_string(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n df = self.data\n\n foo_udf = pandas_udf(\n lambda pdf: pdf.assign(v1=pdf.v * pdf.id * 1.0, v2=pdf.v + pdf.id),\n 'id long, v int, v1 double, v2 long',\n PandasUDFType.GROUPED_MAP\n )\n\n result = df.groupby('id').apply(foo_udf).sort('id').toPandas()\n expected = df.toPandas().groupby('id').apply(foo_udf.func).reset_index(drop=True)\n self.assertPandasEqual(expected, result)\n\n def test_wrong_return_type(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(\n NotImplementedError,\n 'Invalid returnType.*grouped map Pandas UDF.*MapType'):\n pandas_udf(\n lambda pdf: pdf,\n 'id long, v map<int, int>',\n PandasUDFType.GROUPED_MAP)\n\n def test_wrong_args(self):\n from pyspark.sql.functions import udf, pandas_udf, sum, PandasUDFType\n df = self.data\n\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(ValueError, 'Invalid udf'):\n df.groupby('id').apply(lambda x: x)\n with self.assertRaisesRegexp(ValueError, 'Invalid udf'):\n df.groupby('id').apply(udf(lambda x: x, DoubleType()))\n with self.assertRaisesRegexp(ValueError, 'Invalid udf'):\n df.groupby('id').apply(sum(df.v))\n with self.assertRaisesRegexp(ValueError, 'Invalid udf'):\n df.groupby('id').apply(df.v + 1)\n with self.assertRaisesRegexp(ValueError, 'Invalid function'):\n df.groupby('id').apply(\n pandas_udf(lambda: 1, StructType([StructField(\"d\", DoubleType())])))\n with self.assertRaisesRegexp(ValueError, 'Invalid udf'):\n df.groupby('id').apply(pandas_udf(lambda x, y: x, DoubleType()))\n with self.assertRaisesRegexp(ValueError, 'Invalid udf.*GROUPED_MAP'):\n df.groupby('id').apply(\n pandas_udf(lambda x, y: x, DoubleType(), PandasUDFType.SCALAR))\n\n def test_unsupported_types(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n schema = StructType(\n [StructField(\"id\", LongType(), True),\n StructField(\"map\", MapType(StringType(), IntegerType()), True)])\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(\n NotImplementedError,\n 'Invalid returnType.*grouped map Pandas UDF.*MapType'):\n pandas_udf(lambda x: x, schema, PandasUDFType.GROUPED_MAP)\n\n schema = StructType(\n [StructField(\"id\", LongType(), True),\n StructField(\"arr_ts\", ArrayType(TimestampType()), True)])\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(\n NotImplementedError,\n 'Invalid returnType.*grouped map Pandas UDF.*ArrayType.*TimestampType'):\n pandas_udf(lambda x: x, schema, PandasUDFType.GROUPED_MAP)\n\n # Regression test for SPARK-23314\n def test_timestamp_dst(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n # Daylight saving time for Los Angeles for 2015 is Sun, Nov 1 at 2:00 am\n dt = [datetime.datetime(2015, 11, 1, 0, 30),\n datetime.datetime(2015, 11, 1, 1, 30),\n datetime.datetime(2015, 11, 1, 2, 30)]\n df = self.spark.createDataFrame(dt, 'timestamp').toDF('time')\n foo_udf = pandas_udf(lambda pdf: pdf, 'time timestamp', PandasUDFType.GROUPED_MAP)\n result = df.groupby('time').apply(foo_udf).sort('time')\n self.assertPandasEqual(df.toPandas(), result.toPandas())\n\n def test_udf_with_key(self):\n from pyspark.sql.functions import pandas_udf, col, PandasUDFType\n df = self.data\n pdf = df.toPandas()\n\n def foo1(key, pdf):\n import numpy as np\n assert type(key) == tuple\n assert type(key[0]) == np.int64\n\n return pdf.assign(v1=key[0],\n v2=pdf.v * key[0],\n v3=pdf.v * pdf.id,\n v4=pdf.v * pdf.id.mean())\n\n def foo2(key, pdf):\n import numpy as np\n assert type(key) == tuple\n assert type(key[0]) == np.int64\n assert type(key[1]) == np.int32\n\n return pdf.assign(v1=key[0],\n v2=key[1],\n v3=pdf.v * key[0],\n v4=pdf.v + key[1])\n\n def foo3(key, pdf):\n assert type(key) == tuple\n assert len(key) == 0\n return pdf.assign(v1=pdf.v * pdf.id)\n\n # v2 is int because numpy.int64 * pd.Series<int32> results in pd.Series<int32>\n # v3 is long because pd.Series<int64> * pd.Series<int32> results in pd.Series<int64>\n udf1 = pandas_udf(\n foo1,\n 'id long, v int, v1 long, v2 int, v3 long, v4 double',\n PandasUDFType.GROUPED_MAP)\n\n udf2 = pandas_udf(\n foo2,\n 'id long, v int, v1 long, v2 int, v3 int, v4 int',\n PandasUDFType.GROUPED_MAP)\n\n udf3 = pandas_udf(\n foo3,\n 'id long, v int, v1 long',\n PandasUDFType.GROUPED_MAP)\n\n # Test groupby column\n result1 = df.groupby('id').apply(udf1).sort('id', 'v').toPandas()\n expected1 = pdf.groupby('id')\\\n .apply(lambda x: udf1.func((x.id.iloc[0],), x))\\\n .sort_values(['id', 'v']).reset_index(drop=True)\n self.assertPandasEqual(expected1, result1)\n\n # Test groupby expression\n result2 = df.groupby(df.id % 2).apply(udf1).sort('id', 'v').toPandas()\n expected2 = pdf.groupby(pdf.id % 2)\\\n .apply(lambda x: udf1.func((x.id.iloc[0] % 2,), x))\\\n .sort_values(['id', 'v']).reset_index(drop=True)\n self.assertPandasEqual(expected2, result2)\n\n # Test complex groupby\n result3 = df.groupby(df.id, df.v % 2).apply(udf2).sort('id', 'v').toPandas()\n expected3 = pdf.groupby([pdf.id, pdf.v % 2])\\\n .apply(lambda x: udf2.func((x.id.iloc[0], (x.v % 2).iloc[0],), x))\\\n .sort_values(['id', 'v']).reset_index(drop=True)\n self.assertPandasEqual(expected3, result3)\n\n # Test empty groupby\n result4 = df.groupby().apply(udf3).sort('id', 'v').toPandas()\n expected4 = udf3.func((), pdf)\n self.assertPandasEqual(expected4, result4)\n\n def test_column_order(self):\n from collections import OrderedDict\n import pandas as pd\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n # Helper function to set column names from a list\n def rename_pdf(pdf, names):\n pdf.rename(columns={old: new for old, new in\n zip(pd_result.columns, names)}, inplace=True)\n\n df = self.data\n grouped_df = df.groupby('id')\n grouped_pdf = df.toPandas().groupby('id')\n\n # Function returns a pdf with required column names, but order could be arbitrary using dict\n def change_col_order(pdf):\n # Constructing a DataFrame from a dict should result in the same order,\n # but use from_items to ensure the pdf column order is different than schema\n return pd.DataFrame.from_items([\n ('id', pdf.id),\n ('u', pdf.v * 2),\n ('v', pdf.v)])\n\n ordered_udf = pandas_udf(\n change_col_order,\n 'id long, v int, u int',\n PandasUDFType.GROUPED_MAP\n )\n\n # The UDF result should assign columns by name from the pdf\n result = grouped_df.apply(ordered_udf).sort('id', 'v')\\\n .select('id', 'u', 'v').toPandas()\n pd_result = grouped_pdf.apply(change_col_order)\n expected = pd_result.sort_values(['id', 'v']).reset_index(drop=True)\n self.assertPandasEqual(expected, result)\n\n # Function returns a pdf with positional columns, indexed by range\n def range_col_order(pdf):\n # Create a DataFrame with positional columns, fix types to long\n return pd.DataFrame(list(zip(pdf.id, pdf.v * 3, pdf.v)), dtype='int64')\n\n range_udf = pandas_udf(\n range_col_order,\n 'id long, u long, v long',\n PandasUDFType.GROUPED_MAP\n )\n\n # The UDF result uses positional columns from the pdf\n result = grouped_df.apply(range_udf).sort('id', 'v') \\\n .select('id', 'u', 'v').toPandas()\n pd_result = grouped_pdf.apply(range_col_order)\n rename_pdf(pd_result, ['id', 'u', 'v'])\n expected = pd_result.sort_values(['id', 'v']).reset_index(drop=True)\n self.assertPandasEqual(expected, result)\n\n # Function returns a pdf with columns indexed with integers\n def int_index(pdf):\n return pd.DataFrame(OrderedDict([(0, pdf.id), (1, pdf.v * 4), (2, pdf.v)]))\n\n int_index_udf = pandas_udf(\n int_index,\n 'id long, u int, v int',\n PandasUDFType.GROUPED_MAP\n )\n\n # The UDF result should assign columns by position of integer index\n result = grouped_df.apply(int_index_udf).sort('id', 'v') \\\n .select('id', 'u', 'v').toPandas()\n pd_result = grouped_pdf.apply(int_index)\n rename_pdf(pd_result, ['id', 'u', 'v'])\n expected = pd_result.sort_values(['id', 'v']).reset_index(drop=True)\n self.assertPandasEqual(expected, result)\n\n @pandas_udf('id long, v int', PandasUDFType.GROUPED_MAP)\n def column_name_typo(pdf):\n return pd.DataFrame({'iid': pdf.id, 'v': pdf.v})\n\n @pandas_udf('id long, v int', PandasUDFType.GROUPED_MAP)\n def invalid_positional_types(pdf):\n return pd.DataFrame([(u'a', 1.2)])\n\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(Exception, \"KeyError: 'id'\"):\n grouped_df.apply(column_name_typo).collect()\n with self.assertRaisesRegexp(Exception, \"No cast implemented\"):\n grouped_df.apply(invalid_positional_types).collect()\n\n def test_positional_assignment_conf(self):\n import pandas as pd\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n with self.sql_conf({\"spark.sql.execution.pandas.groupedMap.assignColumnsByPosition\": True}):\n\n @pandas_udf(\"a string, b float\", PandasUDFType.GROUPED_MAP)\n def foo(_):\n return pd.DataFrame([('hi', 1)], columns=['x', 'y'])\n\n df = self.data\n result = df.groupBy('id').apply(foo).select('a', 'b').collect()\n for r in result:\n self.assertEqual(r.a, 'hi')\n self.assertEqual(r.b, 1)\n\n def test_self_join_with_pandas(self):\n import pyspark.sql.functions as F\n\n @F.pandas_udf('key long, col string', F.PandasUDFType.GROUPED_MAP)\n def dummy_pandas_udf(df):\n return df[['key', 'col']]\n\n df = self.spark.createDataFrame([Row(key=1, col='A'), Row(key=1, col='B'),\n Row(key=2, col='C')])\n df_with_pandas = df.groupBy('key').apply(dummy_pandas_udf)\n\n # this was throwing an AnalysisException before SPARK-24208\n res = df_with_pandas.alias('temp0').join(df_with_pandas.alias('temp1'),\n F.col('temp0.key') == F.col('temp1.key'))\n self.assertEquals(res.count(), 5)\n\n def test_mixed_scalar_udfs_followed_by_grouby_apply(self):\n import pandas as pd\n from pyspark.sql.functions import udf, pandas_udf, PandasUDFType\n\n df = self.spark.range(0, 10).toDF('v1')\n df = df.withColumn('v2', udf(lambda x: x + 1, 'int')(df['v1'])) \\\n .withColumn('v3', pandas_udf(lambda x: x + 2, 'int')(df['v1']))\n\n result = df.groupby() \\\n .apply(pandas_udf(lambda x: pd.DataFrame([x.sum().sum()]),\n 'sum int',\n PandasUDFType.GROUPED_MAP))\n\n self.assertEquals(result.collect()[0]['sum'], 165)\n\n\[email protected](\n not _have_pandas or not _have_pyarrow,\n _pandas_requirement_message or _pyarrow_requirement_message)\nclass GroupedAggPandasUDFTests(ReusedSQLTestCase):\n\n @property\n def data(self):\n from pyspark.sql.functions import array, explode, col, lit\n return self.spark.range(10).toDF('id') \\\n .withColumn(\"vs\", array([lit(i * 1.0) + col('id') for i in range(20, 30)])) \\\n .withColumn(\"v\", explode(col('vs'))) \\\n .drop('vs') \\\n .withColumn('w', lit(1.0))\n\n @property\n def python_plus_one(self):\n from pyspark.sql.functions import udf\n\n @udf('double')\n def plus_one(v):\n assert isinstance(v, (int, float))\n return v + 1\n return plus_one\n\n @property\n def pandas_scalar_plus_two(self):\n import pandas as pd\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n @pandas_udf('double', PandasUDFType.SCALAR)\n def plus_two(v):\n assert isinstance(v, pd.Series)\n return v + 2\n return plus_two\n\n @property\n def pandas_agg_mean_udf(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n @pandas_udf('double', PandasUDFType.GROUPED_AGG)\n def avg(v):\n return v.mean()\n return avg\n\n @property\n def pandas_agg_sum_udf(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n @pandas_udf('double', PandasUDFType.GROUPED_AGG)\n def sum(v):\n return v.sum()\n return sum\n\n @property\n def pandas_agg_weighted_mean_udf(self):\n import numpy as np\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n @pandas_udf('double', PandasUDFType.GROUPED_AGG)\n def weighted_mean(v, w):\n return np.average(v, weights=w)\n return weighted_mean\n\n def test_manual(self):\n from pyspark.sql.functions import pandas_udf, array\n\n df = self.data\n sum_udf = self.pandas_agg_sum_udf\n mean_udf = self.pandas_agg_mean_udf\n mean_arr_udf = pandas_udf(\n self.pandas_agg_mean_udf.func,\n ArrayType(self.pandas_agg_mean_udf.returnType),\n self.pandas_agg_mean_udf.evalType)\n\n result1 = df.groupby('id').agg(\n sum_udf(df.v),\n mean_udf(df.v),\n mean_arr_udf(array(df.v))).sort('id')\n expected1 = self.spark.createDataFrame(\n [[0, 245.0, 24.5, [24.5]],\n [1, 255.0, 25.5, [25.5]],\n [2, 265.0, 26.5, [26.5]],\n [3, 275.0, 27.5, [27.5]],\n [4, 285.0, 28.5, [28.5]],\n [5, 295.0, 29.5, [29.5]],\n [6, 305.0, 30.5, [30.5]],\n [7, 315.0, 31.5, [31.5]],\n [8, 325.0, 32.5, [32.5]],\n [9, 335.0, 33.5, [33.5]]],\n ['id', 'sum(v)', 'avg(v)', 'avg(array(v))'])\n\n self.assertPandasEqual(expected1.toPandas(), result1.toPandas())\n\n def test_basic(self):\n from pyspark.sql.functions import col, lit, sum, mean\n\n df = self.data\n weighted_mean_udf = self.pandas_agg_weighted_mean_udf\n\n # Groupby one column and aggregate one UDF with literal\n result1 = df.groupby('id').agg(weighted_mean_udf(df.v, lit(1.0))).sort('id')\n expected1 = df.groupby('id').agg(mean(df.v).alias('weighted_mean(v, 1.0)')).sort('id')\n self.assertPandasEqual(expected1.toPandas(), result1.toPandas())\n\n # Groupby one expression and aggregate one UDF with literal\n result2 = df.groupby((col('id') + 1)).agg(weighted_mean_udf(df.v, lit(1.0)))\\\n .sort(df.id + 1)\n expected2 = df.groupby((col('id') + 1))\\\n .agg(mean(df.v).alias('weighted_mean(v, 1.0)')).sort(df.id + 1)\n self.assertPandasEqual(expected2.toPandas(), result2.toPandas())\n\n # Groupby one column and aggregate one UDF without literal\n result3 = df.groupby('id').agg(weighted_mean_udf(df.v, df.w)).sort('id')\n expected3 = df.groupby('id').agg(mean(df.v).alias('weighted_mean(v, w)')).sort('id')\n self.assertPandasEqual(expected3.toPandas(), result3.toPandas())\n\n # Groupby one expression and aggregate one UDF without literal\n result4 = df.groupby((col('id') + 1).alias('id'))\\\n .agg(weighted_mean_udf(df.v, df.w))\\\n .sort('id')\n expected4 = df.groupby((col('id') + 1).alias('id'))\\\n .agg(mean(df.v).alias('weighted_mean(v, w)'))\\\n .sort('id')\n self.assertPandasEqual(expected4.toPandas(), result4.toPandas())\n\n def test_unsupported_types(self):\n from pyspark.sql.types import DoubleType, MapType\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(NotImplementedError, 'not supported'):\n pandas_udf(\n lambda x: x,\n ArrayType(ArrayType(TimestampType())),\n PandasUDFType.GROUPED_AGG)\n\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(NotImplementedError, 'not supported'):\n @pandas_udf('mean double, std double', PandasUDFType.GROUPED_AGG)\n def mean_and_std_udf(v):\n return v.mean(), v.std()\n\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(NotImplementedError, 'not supported'):\n @pandas_udf(MapType(DoubleType(), DoubleType()), PandasUDFType.GROUPED_AGG)\n def mean_and_std_udf(v):\n return {v.mean(): v.std()}\n\n def test_alias(self):\n from pyspark.sql.functions import mean\n\n df = self.data\n mean_udf = self.pandas_agg_mean_udf\n\n result1 = df.groupby('id').agg(mean_udf(df.v).alias('mean_alias'))\n expected1 = df.groupby('id').agg(mean(df.v).alias('mean_alias'))\n\n self.assertPandasEqual(expected1.toPandas(), result1.toPandas())\n\n def test_mixed_sql(self):\n \"\"\"\n Test mixing group aggregate pandas UDF with sql expression.\n \"\"\"\n from pyspark.sql.functions import sum, mean\n\n df = self.data\n sum_udf = self.pandas_agg_sum_udf\n\n # Mix group aggregate pandas UDF with sql expression\n result1 = (df.groupby('id')\n .agg(sum_udf(df.v) + 1)\n .sort('id'))\n expected1 = (df.groupby('id')\n .agg(sum(df.v) + 1)\n .sort('id'))\n\n # Mix group aggregate pandas UDF with sql expression (order swapped)\n result2 = (df.groupby('id')\n .agg(sum_udf(df.v + 1))\n .sort('id'))\n\n expected2 = (df.groupby('id')\n .agg(sum(df.v + 1))\n .sort('id'))\n\n # Wrap group aggregate pandas UDF with two sql expressions\n result3 = (df.groupby('id')\n .agg(sum_udf(df.v + 1) + 2)\n .sort('id'))\n expected3 = (df.groupby('id')\n .agg(sum(df.v + 1) + 2)\n .sort('id'))\n\n self.assertPandasEqual(expected1.toPandas(), result1.toPandas())\n self.assertPandasEqual(expected2.toPandas(), result2.toPandas())\n self.assertPandasEqual(expected3.toPandas(), result3.toPandas())\n\n def test_mixed_udfs(self):\n \"\"\"\n Test mixing group aggregate pandas UDF with python UDF and scalar pandas UDF.\n \"\"\"\n from pyspark.sql.functions import sum, mean\n\n df = self.data\n plus_one = self.python_plus_one\n plus_two = self.pandas_scalar_plus_two\n sum_udf = self.pandas_agg_sum_udf\n\n # Mix group aggregate pandas UDF and python UDF\n result1 = (df.groupby('id')\n .agg(plus_one(sum_udf(df.v)))\n .sort('id'))\n expected1 = (df.groupby('id')\n .agg(plus_one(sum(df.v)))\n .sort('id'))\n\n # Mix group aggregate pandas UDF and python UDF (order swapped)\n result2 = (df.groupby('id')\n .agg(sum_udf(plus_one(df.v)))\n .sort('id'))\n expected2 = (df.groupby('id')\n .agg(sum(plus_one(df.v)))\n .sort('id'))\n\n # Mix group aggregate pandas UDF and scalar pandas UDF\n result3 = (df.groupby('id')\n .agg(sum_udf(plus_two(df.v)))\n .sort('id'))\n expected3 = (df.groupby('id')\n .agg(sum(plus_two(df.v)))\n .sort('id'))\n\n # Mix group aggregate pandas UDF and scalar pandas UDF (order swapped)\n result4 = (df.groupby('id')\n .agg(plus_two(sum_udf(df.v)))\n .sort('id'))\n expected4 = (df.groupby('id')\n .agg(plus_two(sum(df.v)))\n .sort('id'))\n\n # Wrap group aggregate pandas UDF with two python UDFs and use python UDF in groupby\n result5 = (df.groupby(plus_one(df.id))\n .agg(plus_one(sum_udf(plus_one(df.v))))\n .sort('plus_one(id)'))\n expected5 = (df.groupby(plus_one(df.id))\n .agg(plus_one(sum(plus_one(df.v))))\n .sort('plus_one(id)'))\n\n # Wrap group aggregate pandas UDF with two scala pandas UDF and user scala pandas UDF in\n # groupby\n result6 = (df.groupby(plus_two(df.id))\n .agg(plus_two(sum_udf(plus_two(df.v))))\n .sort('plus_two(id)'))\n expected6 = (df.groupby(plus_two(df.id))\n .agg(plus_two(sum(plus_two(df.v))))\n .sort('plus_two(id)'))\n\n self.assertPandasEqual(expected1.toPandas(), result1.toPandas())\n self.assertPandasEqual(expected2.toPandas(), result2.toPandas())\n self.assertPandasEqual(expected3.toPandas(), result3.toPandas())\n self.assertPandasEqual(expected4.toPandas(), result4.toPandas())\n self.assertPandasEqual(expected5.toPandas(), result5.toPandas())\n self.assertPandasEqual(expected6.toPandas(), result6.toPandas())\n\n def test_multiple_udfs(self):\n \"\"\"\n Test multiple group aggregate pandas UDFs in one agg function.\n \"\"\"\n from pyspark.sql.functions import col, lit, sum, mean\n\n df = self.data\n mean_udf = self.pandas_agg_mean_udf\n sum_udf = self.pandas_agg_sum_udf\n weighted_mean_udf = self.pandas_agg_weighted_mean_udf\n\n result1 = (df.groupBy('id')\n .agg(mean_udf(df.v),\n sum_udf(df.v),\n weighted_mean_udf(df.v, df.w))\n .sort('id')\n .toPandas())\n expected1 = (df.groupBy('id')\n .agg(mean(df.v),\n sum(df.v),\n mean(df.v).alias('weighted_mean(v, w)'))\n .sort('id')\n .toPandas())\n\n self.assertPandasEqual(expected1, result1)\n\n def test_complex_groupby(self):\n from pyspark.sql.functions import lit, sum\n\n df = self.data\n sum_udf = self.pandas_agg_sum_udf\n plus_one = self.python_plus_one\n plus_two = self.pandas_scalar_plus_two\n\n # groupby one expression\n result1 = df.groupby(df.v % 2).agg(sum_udf(df.v))\n expected1 = df.groupby(df.v % 2).agg(sum(df.v))\n\n # empty groupby\n result2 = df.groupby().agg(sum_udf(df.v))\n expected2 = df.groupby().agg(sum(df.v))\n\n # groupby one column and one sql expression\n result3 = df.groupby(df.id, df.v % 2).agg(sum_udf(df.v)).orderBy(df.id, df.v % 2)\n expected3 = df.groupby(df.id, df.v % 2).agg(sum(df.v)).orderBy(df.id, df.v % 2)\n\n # groupby one python UDF\n result4 = df.groupby(plus_one(df.id)).agg(sum_udf(df.v))\n expected4 = df.groupby(plus_one(df.id)).agg(sum(df.v))\n\n # groupby one scalar pandas UDF\n result5 = df.groupby(plus_two(df.id)).agg(sum_udf(df.v))\n expected5 = df.groupby(plus_two(df.id)).agg(sum(df.v))\n\n # groupby one expression and one python UDF\n result6 = df.groupby(df.v % 2, plus_one(df.id)).agg(sum_udf(df.v))\n expected6 = df.groupby(df.v % 2, plus_one(df.id)).agg(sum(df.v))\n\n # groupby one expression and one scalar pandas UDF\n result7 = df.groupby(df.v % 2, plus_two(df.id)).agg(sum_udf(df.v)).sort('sum(v)')\n expected7 = df.groupby(df.v % 2, plus_two(df.id)).agg(sum(df.v)).sort('sum(v)')\n\n self.assertPandasEqual(expected1.toPandas(), result1.toPandas())\n self.assertPandasEqual(expected2.toPandas(), result2.toPandas())\n self.assertPandasEqual(expected3.toPandas(), result3.toPandas())\n self.assertPandasEqual(expected4.toPandas(), result4.toPandas())\n self.assertPandasEqual(expected5.toPandas(), result5.toPandas())\n self.assertPandasEqual(expected6.toPandas(), result6.toPandas())\n self.assertPandasEqual(expected7.toPandas(), result7.toPandas())\n\n def test_complex_expressions(self):\n from pyspark.sql.functions import col, sum\n\n df = self.data\n plus_one = self.python_plus_one\n plus_two = self.pandas_scalar_plus_two\n sum_udf = self.pandas_agg_sum_udf\n\n # Test complex expressions with sql expression, python UDF and\n # group aggregate pandas UDF\n result1 = (df.withColumn('v1', plus_one(df.v))\n .withColumn('v2', df.v + 2)\n .groupby(df.id, df.v % 2)\n .agg(sum_udf(col('v')),\n sum_udf(col('v1') + 3),\n sum_udf(col('v2')) + 5,\n plus_one(sum_udf(col('v1'))),\n sum_udf(plus_one(col('v2'))))\n .sort('id')\n .toPandas())\n\n expected1 = (df.withColumn('v1', df.v + 1)\n .withColumn('v2', df.v + 2)\n .groupby(df.id, df.v % 2)\n .agg(sum(col('v')),\n sum(col('v1') + 3),\n sum(col('v2')) + 5,\n plus_one(sum(col('v1'))),\n sum(plus_one(col('v2'))))\n .sort('id')\n .toPandas())\n\n # Test complex expressions with sql expression, scala pandas UDF and\n # group aggregate pandas UDF\n result2 = (df.withColumn('v1', plus_one(df.v))\n .withColumn('v2', df.v + 2)\n .groupby(df.id, df.v % 2)\n .agg(sum_udf(col('v')),\n sum_udf(col('v1') + 3),\n sum_udf(col('v2')) + 5,\n plus_two(sum_udf(col('v1'))),\n sum_udf(plus_two(col('v2'))))\n .sort('id')\n .toPandas())\n\n expected2 = (df.withColumn('v1', df.v + 1)\n .withColumn('v2', df.v + 2)\n .groupby(df.id, df.v % 2)\n .agg(sum(col('v')),\n sum(col('v1') + 3),\n sum(col('v2')) + 5,\n plus_two(sum(col('v1'))),\n sum(plus_two(col('v2'))))\n .sort('id')\n .toPandas())\n\n # Test sequential groupby aggregate\n result3 = (df.groupby('id')\n .agg(sum_udf(df.v).alias('v'))\n .groupby('id')\n .agg(sum_udf(col('v')))\n .sort('id')\n .toPandas())\n\n expected3 = (df.groupby('id')\n .agg(sum(df.v).alias('v'))\n .groupby('id')\n .agg(sum(col('v')))\n .sort('id')\n .toPandas())\n\n self.assertPandasEqual(expected1, result1)\n self.assertPandasEqual(expected2, result2)\n self.assertPandasEqual(expected3, result3)\n\n def test_retain_group_columns(self):\n from pyspark.sql.functions import sum, lit, col\n with self.sql_conf({\"spark.sql.retainGroupColumns\": False}):\n df = self.data\n sum_udf = self.pandas_agg_sum_udf\n\n result1 = df.groupby(df.id).agg(sum_udf(df.v))\n expected1 = df.groupby(df.id).agg(sum(df.v))\n self.assertPandasEqual(expected1.toPandas(), result1.toPandas())\n\n def test_array_type(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n df = self.data\n\n array_udf = pandas_udf(lambda x: [1.0, 2.0], 'array<double>', PandasUDFType.GROUPED_AGG)\n result1 = df.groupby('id').agg(array_udf(df['v']).alias('v2'))\n self.assertEquals(result1.first()['v2'], [1.0, 2.0])\n\n def test_invalid_args(self):\n from pyspark.sql.functions import mean\n\n df = self.data\n plus_one = self.python_plus_one\n mean_udf = self.pandas_agg_mean_udf\n\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(\n AnalysisException,\n 'nor.*aggregate function'):\n df.groupby(df.id).agg(plus_one(df.v)).collect()\n\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(\n AnalysisException,\n 'aggregate function.*argument.*aggregate function'):\n df.groupby(df.id).agg(mean_udf(mean_udf(df.v))).collect()\n\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(\n AnalysisException,\n 'mixture.*aggregate function.*group aggregate pandas UDF'):\n df.groupby(df.id).agg(mean_udf(df.v), mean(df.v)).collect()\n\n\[email protected](\n not _have_pandas or not _have_pyarrow,\n _pandas_requirement_message or _pyarrow_requirement_message)\nclass WindowPandasUDFTests(ReusedSQLTestCase):\n @property\n def data(self):\n from pyspark.sql.functions import array, explode, col, lit\n return self.spark.range(10).toDF('id') \\\n .withColumn(\"vs\", array([lit(i * 1.0) + col('id') for i in range(20, 30)])) \\\n .withColumn(\"v\", explode(col('vs'))) \\\n .drop('vs') \\\n .withColumn('w', lit(1.0))\n\n @property\n def python_plus_one(self):\n from pyspark.sql.functions import udf\n return udf(lambda v: v + 1, 'double')\n\n @property\n def pandas_scalar_time_two(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n return pandas_udf(lambda v: v * 2, 'double')\n\n @property\n def pandas_agg_mean_udf(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n @pandas_udf('double', PandasUDFType.GROUPED_AGG)\n def avg(v):\n return v.mean()\n return avg\n\n @property\n def pandas_agg_max_udf(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n @pandas_udf('double', PandasUDFType.GROUPED_AGG)\n def max(v):\n return v.max()\n return max\n\n @property\n def pandas_agg_min_udf(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n @pandas_udf('double', PandasUDFType.GROUPED_AGG)\n def min(v):\n return v.min()\n return min\n\n @property\n def unbounded_window(self):\n return Window.partitionBy('id') \\\n .rowsBetween(Window.unboundedPreceding, Window.unboundedFollowing)\n\n @property\n def ordered_window(self):\n return Window.partitionBy('id').orderBy('v')\n\n @property\n def unpartitioned_window(self):\n return Window.partitionBy()\n\n def test_simple(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType, percent_rank, mean, max\n\n df = self.data\n w = self.unbounded_window\n\n mean_udf = self.pandas_agg_mean_udf\n\n result1 = df.withColumn('mean_v', mean_udf(df['v']).over(w))\n expected1 = df.withColumn('mean_v', mean(df['v']).over(w))\n\n result2 = df.select(mean_udf(df['v']).over(w))\n expected2 = df.select(mean(df['v']).over(w))\n\n self.assertPandasEqual(expected1.toPandas(), result1.toPandas())\n self.assertPandasEqual(expected2.toPandas(), result2.toPandas())\n\n def test_multiple_udfs(self):\n from pyspark.sql.functions import max, min, mean\n\n df = self.data\n w = self.unbounded_window\n\n result1 = df.withColumn('mean_v', self.pandas_agg_mean_udf(df['v']).over(w)) \\\n .withColumn('max_v', self.pandas_agg_max_udf(df['v']).over(w)) \\\n .withColumn('min_w', self.pandas_agg_min_udf(df['w']).over(w))\n\n expected1 = df.withColumn('mean_v', mean(df['v']).over(w)) \\\n .withColumn('max_v', max(df['v']).over(w)) \\\n .withColumn('min_w', min(df['w']).over(w))\n\n self.assertPandasEqual(expected1.toPandas(), result1.toPandas())\n\n def test_replace_existing(self):\n from pyspark.sql.functions import mean\n\n df = self.data\n w = self.unbounded_window\n\n result1 = df.withColumn('v', self.pandas_agg_mean_udf(df['v']).over(w))\n expected1 = df.withColumn('v', mean(df['v']).over(w))\n\n self.assertPandasEqual(expected1.toPandas(), result1.toPandas())\n\n def test_mixed_sql(self):\n from pyspark.sql.functions import mean\n\n df = self.data\n w = self.unbounded_window\n mean_udf = self.pandas_agg_mean_udf\n\n result1 = df.withColumn('v', mean_udf(df['v'] * 2).over(w) + 1)\n expected1 = df.withColumn('v', mean(df['v'] * 2).over(w) + 1)\n\n self.assertPandasEqual(expected1.toPandas(), result1.toPandas())\n\n def test_mixed_udf(self):\n from pyspark.sql.functions import mean\n\n df = self.data\n w = self.unbounded_window\n\n plus_one = self.python_plus_one\n time_two = self.pandas_scalar_time_two\n mean_udf = self.pandas_agg_mean_udf\n\n result1 = df.withColumn(\n 'v2',\n plus_one(mean_udf(plus_one(df['v'])).over(w)))\n expected1 = df.withColumn(\n 'v2',\n plus_one(mean(plus_one(df['v'])).over(w)))\n\n result2 = df.withColumn(\n 'v2',\n time_two(mean_udf(time_two(df['v'])).over(w)))\n expected2 = df.withColumn(\n 'v2',\n time_two(mean(time_two(df['v'])).over(w)))\n\n self.assertPandasEqual(expected1.toPandas(), result1.toPandas())\n self.assertPandasEqual(expected2.toPandas(), result2.toPandas())\n\n def test_without_partitionBy(self):\n from pyspark.sql.functions import mean\n\n df = self.data\n w = self.unpartitioned_window\n mean_udf = self.pandas_agg_mean_udf\n\n result1 = df.withColumn('v2', mean_udf(df['v']).over(w))\n expected1 = df.withColumn('v2', mean(df['v']).over(w))\n\n result2 = df.select(mean_udf(df['v']).over(w))\n expected2 = df.select(mean(df['v']).over(w))\n\n self.assertPandasEqual(expected1.toPandas(), result1.toPandas())\n self.assertPandasEqual(expected2.toPandas(), result2.toPandas())\n\n def test_mixed_sql_and_udf(self):\n from pyspark.sql.functions import max, min, rank, col\n\n df = self.data\n w = self.unbounded_window\n ow = self.ordered_window\n max_udf = self.pandas_agg_max_udf\n min_udf = self.pandas_agg_min_udf\n\n result1 = df.withColumn('v_diff', max_udf(df['v']).over(w) - min_udf(df['v']).over(w))\n expected1 = df.withColumn('v_diff', max(df['v']).over(w) - min(df['v']).over(w))\n\n # Test mixing sql window function and window udf in the same expression\n result2 = df.withColumn('v_diff', max_udf(df['v']).over(w) - min(df['v']).over(w))\n expected2 = expected1\n\n # Test chaining sql aggregate function and udf\n result3 = df.withColumn('max_v', max_udf(df['v']).over(w)) \\\n .withColumn('min_v', min(df['v']).over(w)) \\\n .withColumn('v_diff', col('max_v') - col('min_v')) \\\n .drop('max_v', 'min_v')\n expected3 = expected1\n\n # Test mixing sql window function and udf\n result4 = df.withColumn('max_v', max_udf(df['v']).over(w)) \\\n .withColumn('rank', rank().over(ow))\n expected4 = df.withColumn('max_v', max(df['v']).over(w)) \\\n .withColumn('rank', rank().over(ow))\n\n self.assertPandasEqual(expected1.toPandas(), result1.toPandas())\n self.assertPandasEqual(expected2.toPandas(), result2.toPandas())\n self.assertPandasEqual(expected3.toPandas(), result3.toPandas())\n self.assertPandasEqual(expected4.toPandas(), result4.toPandas())\n\n def test_array_type(self):\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n df = self.data\n w = self.unbounded_window\n\n array_udf = pandas_udf(lambda x: [1.0, 2.0], 'array<double>', PandasUDFType.GROUPED_AGG)\n result1 = df.withColumn('v2', array_udf(df['v']).over(w))\n self.assertEquals(result1.first()['v2'], [1.0, 2.0])\n\n def test_invalid_args(self):\n from pyspark.sql.functions import mean, pandas_udf, PandasUDFType\n\n df = self.data\n w = self.unbounded_window\n ow = self.ordered_window\n mean_udf = self.pandas_agg_mean_udf\n\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(\n AnalysisException,\n '.*not supported within a window function'):\n foo_udf = pandas_udf(lambda x: x, 'v double', PandasUDFType.GROUPED_MAP)\n df.withColumn('v2', foo_udf(df['v']).over(w))\n\n with QuietTest(self.sc):\n with self.assertRaisesRegexp(\n AnalysisException,\n '.*Only unbounded window frame is supported.*'):\n df.withColumn('mean_v', mean_udf(df['v']).over(ow))\n\n\nif __name__ == \"__main__\":\n from pyspark.sql.tests import *\n if xmlrunner:\n unittest.main(testRunner=xmlrunner.XMLTestRunner(output='target/test-reports'), verbosity=2)\n else:\n unittest.main(verbosity=2)\n" ]
[ [ "pandas.DataFrame.from_items", "pandas.Series", "numpy.int32", "pandas.DataFrame", "pandas.Timestamp.now", "numpy.random.rand", "numpy.float32", "numpy.average", "pandas.Timestamp" ] ]
kshulgina/codetta
[ "4f5f31a33beed19bc3e10745154705ad002273df" ]
[ "helper_functions.py" ]
[ "import os\nimport sys\nfrom subprocess import call, Popen, PIPE\nimport re\nimport numpy as np\nfrom ftplib import FTP\nimport datetime\n\ndef translate(sequence, gct):\n \"\"\"\n For a DNA sequence, translate it into a sequence of one symbol per codon, following \n a specific translation table. For example, this could be translating DNA sequence into\n an amino acid sequence following some genetic code, or it could be mapping the DNA \n sequence to a sequence of symbols corresponding to each codon. Replaces values not in \n the translation dict with X's\n \n Args:\n sequence (string): DNA sequence of A, T, G, C characters\n gc (dict): translation table\n Returns:\n string: new sequence of symbols, 1/3 length of DNA sequence\n \n \"\"\"\n return ''.join([gct.get(sequence[3*i:3*i+3].upper(),'X') for i in range(len(sequence)//3)])\n\ndef replace_stop(sequence):\n \"\"\"\n For a string, replace all '_' characters with 'X's\n \n Args:\n sequence (string)\n Returns:\n string: '_' characters replaced with 'X's\n \n \"\"\"\n return sequence.replace('_', 'X')\n\nglobal dna_complements\ndna_complements = bytes.maketrans(b\"AaTtGgCcRrYySsWwKkMmBbVvDdHhNn\", b\"TtAaCcGgYyRrSsWwMmKkVvBbHhDdNn\")\n\ndef reverse_complement(sequence):\n \"\"\"\n For a string consisting of valid IUPAC DNA characters, return the reverse complement\n \"\"\"\n return sequence.translate(dna_complements)[::-1]\n\ndef validate_codon_line(line):\n '''\n Validates that line in hmmscan_summary file is valid\n '''\n # check line length (100 chosen somewhat arbitrarily)\n if len(line) > 100:\n return False\n \n # split into fields\n info = line.rstrip().split(',')\n \n try:\n dum = int(info[0]) # codon ind\n dum = float(info[1]) # coded position\n dum = int(info[3])\n dum = int(info[4])\n dum = int(info[5])\n dum = float(info[7])\n dum = int(info[8])\n except ValueError:\n return False\n \n if not info[2].isupper():\n return False\n \n return True\n\ndef validate_fasta(fasta_file_path):\n \"\"\"\n Checks that FASTA sequence file, either downloaded genome or provided file, are in \n correct FASTA format. Arg is file path. Returns True or False.\n \"\"\"\n # get number of lines that start with >\n p = Popen('grep \"^>\" %s | wc' % (fasta_file_path), shell=True, stdout=PIPE)\n n_header = int(p.communicate()[0].decode().split()[0])\n \n # get number of lines that don't start with >\n p = Popen('grep -v \"^>\" %s | wc' % (fasta_file_path), shell=True, stdout=PIPE)\n n_not_header = int(p.communicate()[0].decode().split()[0])\n \n if n_not_header < n_header:\n return False\n \n # check if any illegal characters present in non-header lines\n p = Popen('grep -v \"^>\" %s | grep -i [^acgturykmswbdhvn] | wc' % (fasta_file_path), shell=True, stdout=PIPE)\n n_illegal_chars = int(p.communicate()[0].decode().split()[0])\n if n_illegal_chars > 0:\n return False\n \n return True\n\ndef validate_hmm_output(hmm_output_files, hmm_file_name):\n \"\"\"\n Checks that the content of an hmmscan output are not corrupted. Arg is a list of \n line-by-line hmmscan outfile file contents. Returns True or False.\n \"\"\"\n if len(hmm_output_files) < 20: # somewhat arbitrary\n return False\n # check that this is the output for the right file\n if not (hmm_file_name in hmm_output_files[7]):\n return False\n # first line always is a comment with name of program\n if hmm_output_files[0] != '# hmmscan :: search sequence(s) against a profile database':\n return False\n # last line always says // (not [ok] because I split on that)\n if hmm_output_files[-1] != '//':\n return False\n \n return True\n\ndef extract_hmmscan_output(lines, eval_threshold):\n \"\"\"\n Reads a single hmmscan output and parses out relevant parts for genetic code inference.\n Filters domain hits based on E-value threshold.\n \n Args:\n lines (string): line-by-line contents of hmmscan output file\n eval_threshold (float): threshold for excluding domain hits based on e-value\n Returns:\n list of strings: a list of strings for each suitable domain found, with domain and \n conserved residue information encoded in a string\n \"\"\"\n # parse output from hmmscan and identify which conserved domains were found\n y = 0\n conserved_regions = list()\n cr_append = conserved_regions.append # define function locally to speed it up\n while y < len(lines):\n line = lines[y]\n domains = list()\n if line[0:2] == '>>':\n domain_name = line.split(' ')[1]\n y = y+3\n line = lines[y]\n if line[0:2] != '>>':\n while len(line)>0:\n # only analyze domains below e-value threshold\n splits = line.split()\n dom_eval = splits[5]\n if float(dom_eval) < eval_threshold:\n domains.append(splits[0]+\",\"+domain_name+\",\"+dom_eval+\",\"+splits[6]+\",\"+splits[7]+\",\"+splits[9]+\",\"+splits[10])\n y = y+1\n line = lines[y]\n y = y+2\n line = lines[y]\n while line[0:2] != '>>':\n splits2=line.split()\n if len(splits2) > 0 and splits2[0] == '==':\n for d, dom in enumerate(domains):\n dom_info = dom.split(\",\")\n if dom_info[0] == splits2[2]:\n try:\n hmm_ali = lines[y+1].split()[2]\n que_ali = lines[y+3].split()[2]\n post_ali = lines[y+4].split()[0]\n y = y + 1\n amt_add = 5\n except IndexError:\n try:\n hmm_ali = lines[y+2].split()[2]\n que_ali = lines[y+4].split()[2]\n post_ali = lines[y+5].split()[0]\n y = y + 2\n amt_add = 6\n except IndexError:\n hmm_ali = lines[y+3].split()[2]\n que_ali = lines[y+5].split()[2]\n post_ali = lines[y+6].split()[0]\n y = y + 3\n amt_add = 7\n line = lines[y]\n while int(line.split()[3]) < int(dom_info[4]):\n y = y + amt_add\n line = lines[y]\n hmm_ali = hmm_ali + line.split()[2]\n que_ali = que_ali + lines[y+2].split()[2]\n post_ali = post_ali + lines[y+3].split()[0]\n # turn into numpy arrays so can mask\n hmm_ali = np.frombuffer(hmm_ali.encode(), dtype='a1')\n que_ali = np.frombuffer(que_ali.encode(), dtype='a1')\n post_ali = np.frombuffer(post_ali.encode(), dtype='a1')\n # now transform this into pairs of hmm and query index that have no gaps and pass \n # alignment posterior quality filter\n mask1 = hmm_ali != b'.'\n mask2 = que_ali != b'-'\n mask3 = post_ali == b'*'\n mask = mask1 & mask2 & mask3\n \n hmm_inds = np.ones(len(hmm_ali), dtype=int)\n hmm_inds[~mask1] = 0\n que_inds = np.ones(len(que_ali), dtype=int)\n que_inds[~mask2] = 0\n \n hmms = np.cumsum(hmm_inds)-1+int(dom_info[3])\n hmms = hmms[mask]\n que = np.cumsum(que_inds)-1+int(dom_info[5])\n que = que[mask]\n \n if len(hmms) == 0:\n continue\n region = np.empty((hmms.size + que.size,), dtype=int)\n region[0::2] = hmms\n region[1::2] = que\n region = ','.join(region.astype(str))\n cr_append(\"%s,%s,%s,%s,%s\" % (dom_info[1], dom_info[2], dom_info[5], dom_info[6], region))\n \n y = y+1\n if y >= len(lines):\n break\n line = lines[y]\n else:\n y = y+1\n \n return conserved_regions\n\ndef genome_download(species_id, type_download, database_dir, download_output_file):\n \"\"\"\n For a given species ID, function will attempt to download a genome\n \n Args:\n species_id : species ID that will be matched to genomes in GenBank\n type_download ('a' or 'c'): specifying is ID is GenBank assembly or accession number\n Returns:\n Nothing\n \"\"\"\n # database files\n genbank_file = '%s/assembly_summary_genbank.txt' % database_dir\n \n # try to download from genbank \n genbank_res = download_genbank(species_id, genbank_file, type_download, download_output_file)\n return genbank_res\n\ndef update_genbank(genbank_file):\n '''\n Updates the assembly_summary file from GenBank, used to download assembly accessions\n '''\n # get modification time of local copy of GenBank database file (in UTC)\n UTC_OFFSET = datetime.datetime.utcnow() - datetime.datetime.now()\n if os.path.isfile(genbank_file):\n local_time = int((datetime.datetime.fromtimestamp(os.path.getmtime(genbank_file)) + \n UTC_OFFSET).strftime(\"%Y%m%d%H%M\"))\n else:\n local_time = 0\n \n # get modification time of database file on GenBank ftp server (in UTC)\n ftp = FTP('ftp.ncbi.nlm.nih.gov') \n ftp.login()\n ftp.cwd('./genomes/ASSEMBLY_REPORTS')\n genbank_time = ftp.sendcmd(\"MDTM assembly_summary_genbank.txt\")\n if genbank_time[:3] == \"213\":\n genbank_time = int(genbank_time[3:-2].strip())\n \n # if local version of file is younger than the GenBank version, download new version\n if local_time < genbank_time:\n print('Downloading updated version of GenBank assembly reference file')\n with open(os.devnull, \"w\") as f:\n dum = call('wget -O %s ftp.ncbi.nlm.nih.gov/genomes/ASSEMBLY_REPORTS/assembly_summary_genbank.txt' \n % (genbank_file), shell=True, stdout=f, stderr=f)\n\ndef download_genbank(species_id, genbank_file, type_download, download_output_file):\n '''\n Downloads nucleotide sequence from GenBank, either assembly accession or nucleotide \n accession. Returns either the ftp URL from which the file was downloaded OR a 1 if failed\n '''\n # deal with case where species id is a GenBank genome assembly ID\n if type_download == 'a':\n # see if newer versions of genome database file is available, if so download\n update_genbank(genbank_file)\n \n # get urls\n p = Popen(\"awk -F'\\t' -v OFS='\\t' '$1 == \\\"%s\\\" {print $20}' %s\" \n % (species_id, genbank_file), shell=True, stdout=PIPE)\n info = p.communicate()[0].decode().split('\\n')[:-1]\n \n # if species id does not exist in GenBank\n if len(info) == 0:\n return 1\n \n # if multiple entries exist, just pick the first one\n u = info[0]\n prefix = u.split('/')[-1]\n download_url = '%s/%s_genomic.fna.gz' % (u, prefix)\n \n # check if sequence is being downloaded into a directory that exists\n download_dir = os.path.dirname(download_output_file)\n if download_dir != '' and not os.path.isdir(download_dir):\n sys.exit('ERROR: the path leading up to prefix has not been created')\n\n # download the genome! \n genome_path = '%s.gz' % download_output_file\n with open(os.devnull, \"w\") as f:\n dum = call('wget -O %s %s' % (re.escape(genome_path), download_url), shell=True, stdout=f, stderr=f)\n \n # unzip\n os.system('gunzip -f %s' % (re.escape(genome_path)))\n \n return download_url\n \n # deal with case where species id is a GenBank accession number\n elif type_download == 'c':\n # check if sequence is being downloaded into a directory that exists\n download_dir = os.path.dirname(download_output_file)\n if download_dir != '' and not os.path.isdir(download_dir):\n sys.exit('ERROR: the path leading up to prefix has not been created')\n \n download_url = 'https://www.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nuccore&id=%s&rettype=fasta&retmode=text' % species_id\n wget_command = \"wget -q -O %s '%s'\" % (download_output_file, download_url)\n with open(os.devnull, \"w\") as f:\n dum = call(wget_command, shell=True, stdout=f, stderr=f)\n return download_url\n" ]
[ [ "numpy.cumsum", "numpy.empty" ] ]
cyzhao2013/detext
[ "23874fd3ae26c581bbd1806b7885f4c93f4b4d33" ]
[ "test/train/test_data_fn.py" ]
[ "import numpy as np\nimport os\nimport tensorflow as tf\n\nfrom detext.train import data_fn\nfrom detext.utils import vocab_utils\n\n\nclass TestData(tf.test.TestCase):\n \"\"\"Unit test for data_fn.\"\"\"\n PAD_ID = 3\n CLS_ID = 101\n\n def testInputFnBuilderTfrecord(self):\n \"\"\"Test function input_fn_builder() in eval mode\"\"\"\n res_dir = os.path.dirname(__file__) + '/../resources'\n\n # create a vocab table\n vocab_table = vocab_utils.read_tf_vocab(res_dir + '/vocab.txt', '[UNK]')\n\n # dataset dir\n data_dir = os.path.join(res_dir, 'train', 'dataset', 'tfrecord')\n\n # create a dataset.\n # Read schema\n # Parse and process data in dataset\n feature_names = (\n 'label', 'query', 'doc_completedQuery', 'usr_headline', 'usr_skills', 'usr_currTitles', 'usrId_currTitles',\n 'docId_completedQuery', 'wide_ftrs', 'weight')\n\n batch_size = 2\n dataset = data_fn.input_fn(input_pattern=data_dir,\n metadata_path=None,\n batch_size=batch_size,\n mode=tf.estimator.ModeKeys.EVAL,\n vocab_table=vocab_table,\n vocab_table_for_id_ftr=vocab_table,\n feature_names=feature_names,\n CLS='[CLS]',\n SEP='[SEP]',\n PAD='[PAD]',\n PAD_FOR_ID_FTR='[PAD]',\n max_len=16,\n cnn_filter_window_size=1)\n\n # Make iterator\n iterator = dataset.make_initializable_iterator()\n batch_data = iterator.get_next()\n\n with tf.Session() as sess:\n sess.run([tf.global_variables_initializer(), tf.tables_initializer()])\n sess.run([iterator.initializer])\n batch_data_val, = sess.run([batch_data])\n features, label = batch_data_val\n\n # First dimension of data should be batch_size\n for ftr_name in feature_names:\n if ftr_name != 'label':\n self.assertTrue(ftr_name in features)\n self.assertTrue(features[ftr_name].shape[0] == batch_size)\n\n self.assertTrue(label['label'].shape[0] == batch_size)\n\n doc_completedQuery = features['doc_completedQuery']\n docId_completedQuery = features['docId_completedQuery']\n usr_currTitles = features['usr_currTitles']\n usrId_currTitles = features['usrId_currTitles']\n\n # vocab[PAD] == PAD_ID\n self.assertTrue(doc_completedQuery[0, 0, -1] == self.PAD_ID)\n self.assertTrue(docId_completedQuery[0, 0, -1] == self.PAD_ID)\n\n # vocab[CLS] == CLS_ID\n self.assertTrue(np.all(doc_completedQuery[0, 0, 0] == self.CLS_ID))\n self.assertTrue(np.all(usr_currTitles[0, 0] == self.CLS_ID))\n\n # No CLS in id feature\n self.assertTrue(np.all(docId_completedQuery[:, :, 0] != self.CLS_ID))\n\n # In this TFRecord file, we populate docId_completeQuery using doc_completedQuery\n # doc id feature should be the same as doc text feature except CLS and SEP addition\n # Here we make sure this is correct for the first sample\n for text_arr, id_arr in zip(doc_completedQuery[0], docId_completedQuery[0]):\n self.assertAllEqual(text_arr[text_arr != self.PAD_ID][1:-1], id_arr[id_arr != self.PAD_ID])\n\n # In this TFRecord file, we populate usrId_currTitles using usr_currTitles\n # usr id feature should be the same as usr text feature except CLS and SEP addition\n for text_arr, id_arr in zip(usr_currTitles, usrId_currTitles):\n self.assertAllEqual(text_arr[text_arr != self.PAD_ID][1:-1], id_arr[id_arr != self.PAD_ID])\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n" ]
[ [ "tensorflow.test.main", "numpy.all", "tensorflow.global_variables_initializer", "tensorflow.Session", "tensorflow.tables_initializer" ] ]
DOsinga/art_critic
[ "90a8b100c391d4ed28c7208d481f85522323362f" ]
[ "art_server.py" ]
[ "#!/usr/bin/env python\nimport argparse\nimport pickle\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.platform import gfile\nimport os\nfrom flask import Flask, request, redirect, flash, jsonify\n\n\nBOTTLENECK_TENSOR_NAME = 'pool_3/_reshape:0'\nJPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0'\n\napp = Flask(__name__)\n\nnbrs = None\nimage_infos = None\nbottleneck_tensor = None\njpeg_data_tensor = None\n\[email protected]('/', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n # if user does not select file, browser also\n # submit a empty part without filename\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n\n if file:\n image_data = file.read()\n bottleneck_values = sess.run(bottleneck_tensor, {jpeg_data_tensor: image_data})\n bottleneck_values = np.squeeze(bottleneck_values)\n distances, indices = nbrs.kneighbors([bottleneck_values])\n res = [(image_infos[idx], dist) for idx, dist in zip(indices[0], distances[0])]\n return jsonify(results=res)\n\n\n return '''\n <!doctype html>\n <title>Upload new File</title>\n <h1>Upload new File</h1>\n <form action=\"\" method=post enctype=multipart/form-data>\n <p><input type=file name=file>\n <input type=submit value=Upload>\n </form>\n '''\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Index images using inception')\n parser.add_argument('--model_path', type=str, default='imagenet',\n help='Where the unpacked model dump is')\n parser.add_argument('--image_match_model', type=str, default='image_match_model.pickle',\n help='Where to save the resulting model')\n\n print('loading model')\n\n args = parser.parse_args()\n with open(args.image_match_model, 'rb') as fin:\n nbrs, image_infos = pickle.load(fin)\n\n sess = tf.Session()\n model_filename = os.path.join(args.model_path, 'classify_image_graph_def.pb')\n\n with gfile.FastGFile(model_filename, 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n bottleneck_tensor, jpeg_data_tensor = (\n tf.import_graph_def(graph_def, name='', return_elements=[\n BOTTLENECK_TENSOR_NAME, JPEG_DATA_TENSOR_NAME]))\n\n app.run()\n\n\n\n\n\n" ]
[ [ "tensorflow.import_graph_def", "numpy.squeeze", "tensorflow.Session", "tensorflow.python.platform.gfile.FastGFile", "tensorflow.GraphDef" ] ]
Maelstrom6/MachineLearning3
[ "cb9a327f998ed2d76d1b9cbcb96e970435a0f17d", "cb9a327f998ed2d76d1b9cbcb96e970435a0f17d" ]
[ "DeepLearning/ArtificialNeuralNetwork/Tst.py", "Classification/Naive Bayes/Naive Bayes.py" ]
[ "import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\nimport math\nimport keras\n\nfrom tensorflow.python.client import device_lib\nprint(device_lib.list_local_devices())\n", "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.model_selection import train_test_split\n\n\n# import the data set\ndataset = pd.read_csv(\"Social_Network_Ads.csv\")\n\n# make sure X is a matrix not a vector\nx = dataset.iloc[:, [2, 3]].values\ny = dataset.iloc[:, 4].values\n\n# split into training and test\nX_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=0)\n# Feature scaling\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.fit_transform(X_test)\n\n# Fitting logistic regression model\nfrom sklearn.naive_bayes import GaussianNB\n# classifier = SVC() # The gaussian kernel\n# 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or a callable\nclassifier = GaussianNB()\nclassifier.fit(X_train, y_train)\n\ny_pred = classifier.predict(X_test)\n\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\n\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = X_test, y_test\nX1, X2 = np.meshgrid(np.arange(start=X_set[:, 0].min() - 1, stop=X_set[:, 0].max() + 1, step=0.01),\n np.arange(start=X_set[:, 1].min() - 1, stop=X_set[:, 1].max() + 1, step=0.01))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha=0.75, cmap=ListedColormap((\"red\", \"green\")))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\n\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n cmap=ListedColormap((\"red\", \"green\")))\nplt.title(\"Naive Bayes\")\nplt.ylabel(\"Salary\")\nplt.xlabel(\"Age\")\nplt.legend()\nplt.show()\n\n" ]
[ [ "tensorflow.python.client.device_lib.list_local_devices" ], [ "matplotlib.pyplot.legend", "pandas.read_csv", "sklearn.naive_bayes.GaussianNB", "matplotlib.pyplot.title", "numpy.unique", "sklearn.metrics.confusion_matrix", "sklearn.model_selection.train_test_split", "matplotlib.colors.ListedColormap", "matplotlib.pyplot.xlabel", "sklearn.preprocessing.StandardScaler", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
paulhfu/unsup_pix_embed
[ "fcfc319f81942ba73ef54bd96e26225d52e8c054" ]
[ "unet3d/model.py" ]
[ "import importlib\n\nimport torch.nn as nn\nimport torch\n\nfrom unet3d.buildingblocks import Encoder, Decoder, DoubleConv, ExtResNetBlock\nfrom unet3d.utils import number_of_features_per_level\n\n\nclass Abstract3DUNet(nn.Module):\n \"\"\"\n Base class for standard and residual UNet.\n\n Args:\n in_channels (int): number of input channels\n out_channels (int): number of output segmentation masks;\n Note that that the of out_channels might correspond to either\n different semantic classes or to different binary segmentation mask.\n It's up to the user of the class to interpret the out_channels and\n use the proper loss criterion during training (i.e. CrossEntropyLoss (multi-class)\n or BCEWithLogitsLoss (two-class) respectively)\n f_maps (int, tuple): number of feature maps at each level of the encoder; if it's an integer the number\n of feature maps is given by the geometric progression: f_maps ^ k, k=1,2,3,4\n final_sigmoid (bool): if True apply element-wise nn.Sigmoid after the\n final 1x1 convolution, otherwise apply nn.Softmax. MUST be True if nn.BCELoss (two-class) is used\n to train the model. MUST be False if nn.CrossEntropyLoss (multi-class) is used to train the model.\n basic_module: basic model for the encoder/decoder (DoubleConv, ExtResNetBlock, ....)\n layer_order (string): determines the order of layers\n in `SingleConv` module. e.g. 'crg' stands for Conv3d+ReLU+GroupNorm3d.\n See `SingleConv` for more info\n f_maps (int, tuple): if int: number of feature maps in the first conv layer of the encoder (default: 64);\n if tuple: number of feature maps at each level\n num_groups (int): number of groups for the GroupNorm\n num_levels (int): number of levels in the encoder/decoder path (applied only if f_maps is an int)\n is_segmentation (bool): if True (semantic segmentation problem) Sigmoid/Softmax normalization is applied\n after the final convolution; if False (regression problem) the normalization layer is skipped at the end\n testing (bool): if True (testing mode) the `final_activation` (if present, i.e. `is_segmentation=true`)\n will be applied as the last operation during the forward pass; if False the model is in training mode\n and the `final_activation` (even if present) won't be applied; default: False\n conv_kernel_size (int or tuple): size of the convolving kernel in the basic_module\n pool_kernel_size (int or tuple): the size of the window\n conv_padding (int or tuple): add zero-padding added to all three sides of the input\n \"\"\"\n\n def __init__(self, in_channels, out_channels, final_sigmoid, basic_module, f_maps=64, layer_order='gcr',\n num_groups=8, num_levels=4, is_segmentation=True, testing=False,\n conv_kernel_size=3, pool_kernel_size=2, conv_padding=1, **kwargs):\n super(Abstract3DUNet, self).__init__()\n\n self.testing = testing\n\n if isinstance(f_maps, int):\n f_maps = number_of_features_per_level(f_maps, num_levels=num_levels)\n\n # create encoder path consisting of Encoder modules. Depth of the encoder is equal to `len(f_maps)`\n encoders = []\n for i, out_feature_num in enumerate(f_maps):\n if i == 0:\n encoder = Encoder(in_channels, out_feature_num,\n apply_pooling=False, # skip pooling in the firs encoder\n basic_module=basic_module,\n conv_layer_order=layer_order,\n conv_kernel_size=conv_kernel_size,\n num_groups=num_groups,\n padding=conv_padding)\n else:\n # TODO: adapt for anisotropy in the data, i.e. use proper pooling kernel to make the data isotropic after 1-2 pooling operations\n encoder = Encoder(f_maps[i - 1], out_feature_num,\n basic_module=basic_module,\n conv_layer_order=layer_order,\n conv_kernel_size=conv_kernel_size,\n num_groups=num_groups,\n pool_kernel_size=pool_kernel_size,\n padding=conv_padding)\n\n encoders.append(encoder)\n\n self.encoders = nn.ModuleList(encoders)\n\n # create decoder path consisting of the Decoder modules. The length of the decoder is equal to `len(f_maps) - 1`\n decoders = []\n reversed_f_maps = list(reversed(f_maps))\n for i in range(len(reversed_f_maps) - 1):\n if basic_module == DoubleConv:\n in_feature_num = reversed_f_maps[i] + reversed_f_maps[i + 1]\n else:\n in_feature_num = reversed_f_maps[i]\n\n out_feature_num = reversed_f_maps[i + 1]\n # TODO: if non-standard pooling was used, make sure to use correct striding for transpose conv\n # currently strides with a constant stride: (2, 2, 2)\n decoder = Decoder(in_feature_num, out_feature_num,\n basic_module=basic_module,\n conv_layer_order=layer_order,\n conv_kernel_size=conv_kernel_size,\n num_groups=num_groups,\n padding=conv_padding)\n decoders.append(decoder)\n\n self.decoders = nn.ModuleList(decoders)\n\n # in the last layer a 1×1 convolution reduces the number of output\n # channels to the number of labels\n self.final_conv = nn.Conv3d(f_maps[0], out_channels, 1)\n\n if is_segmentation:\n # semantic segmentation problem\n if final_sigmoid:\n self.final_activation = nn.Sigmoid()\n else:\n self.final_activation = nn.Softmax(dim=1)\n else:\n # regression problem\n self.final_activation = None\n\n def forward(self, x):\n # encoder part\n encoders_features = []\n for encoder in self.encoders:\n x = encoder(x)\n # reverse the encoder outputs to be aligned with the decoder\n encoders_features.insert(0, x)\n\n # remove the last encoder's output from the list\n # !!remember: it's the 1st in the list\n encoders_features = encoders_features[1:]\n\n # decoder part\n for decoder, encoder_features in zip(self.decoders, encoders_features):\n # pass the output from the corresponding encoder and the output\n # of the previous decoder\n x = decoder(encoder_features, x)\n\n x = self.final_conv(x)\n\n # apply final_activation (i.e. Sigmoid or Softmax) only during prediction. During training the network outputs\n # logits and it's up to the user to normalize it before visualising with tensorboard or computing validation metric\n if self.testing and self.final_activation is not None:\n x = self.final_activation(x)\n\n return x\n\n\nclass UNet3D(Abstract3DUNet):\n \"\"\"\n 3DUnet model from\n `\"3D U-Net: Learning Dense Volumetric Segmentation from Sparse Annotation\"\n <https://arxiv.org/pdf/1606.06650.pdf>`.\n\n Uses `DoubleConv` as a basic_module and nearest neighbor upsampling in the decoder\n \"\"\"\n\n def __init__(self, in_channels, out_channels, final_sigmoid=True, f_maps=64, layer_order='gcr',\n num_groups=8, num_levels=4, is_segmentation=True, conv_padding=1, **kwargs):\n super(UNet3D, self).__init__(in_channels=in_channels, out_channels=out_channels, final_sigmoid=final_sigmoid,\n basic_module=DoubleConv, f_maps=f_maps, layer_order=layer_order,\n num_groups=num_groups, num_levels=num_levels, is_segmentation=is_segmentation,\n conv_padding=conv_padding, **kwargs)\n\n\nclass ResidualUNet3D(Abstract3DUNet):\n \"\"\"\n Residual 3DUnet model implementation based on https://arxiv.org/pdf/1706.00120.pdf.\n Uses ExtResNetBlock as a basic building block, summation joining instead\n of concatenation joining and transposed convolutions for upsampling (watch out for block artifacts).\n Since the model effectively becomes a residual net, in theory it allows for deeper UNet.\n \"\"\"\n\n def __init__(self, in_channels, out_channels, final_sigmoid=True, f_maps=64, layer_order='gcr',\n num_groups=8, num_levels=5, is_segmentation=True, conv_padding=1, **kwargs):\n super(ResidualUNet3D, self).__init__(in_channels=in_channels, out_channels=out_channels,\n final_sigmoid=final_sigmoid,\n basic_module=ExtResNetBlock, f_maps=f_maps, layer_order=layer_order,\n num_groups=num_groups, num_levels=num_levels,\n is_segmentation=is_segmentation, conv_padding=conv_padding,\n **kwargs)\n\n\nclass UNet2D(Abstract3DUNet):\n \"\"\"\n Just a standard 2D Unet. Arises naturally by specifying conv_kernel_size=(1, 3, 3), pool_kernel_size=(1, 2, 2).\n \"\"\"\n\n def __init__(self, in_channels, out_channels, final_sigmoid=True, f_maps=64, layer_order='bcr',\n num_groups=8, num_levels=4, is_segmentation=True, conv_padding=1, **kwargs):\n if conv_padding == 1:\n conv_padding = (0, 1, 1)\n super(UNet2D, self).__init__(in_channels=in_channels,\n out_channels=out_channels,\n final_sigmoid=final_sigmoid,\n basic_module=DoubleConv,\n f_maps=f_maps,\n layer_order=layer_order,\n num_groups=num_groups,\n num_levels=num_levels,\n is_segmentation=is_segmentation,\n conv_kernel_size=(1, 3, 3),\n pool_kernel_size=(1, 2, 2),\n conv_padding=conv_padding,\n **kwargs)\n\n\ndef get_model(config):\n def _model_class(class_name):\n m = importlib.import_module('pytorch3dunet.unet3d.model')\n clazz = getattr(m, class_name)\n return clazz\n\n assert 'model' in config, 'Could not find model configuration'\n model_config = config['model']\n model_class = _model_class(model_config['name'])\n return model_class(**model_config)\n" ]
[ [ "torch.nn.Softmax", "torch.nn.ModuleList", "torch.nn.Conv3d", "torch.nn.Sigmoid" ] ]
MarcMeinhardt/2DTerrainGeneration
[ "396e035ee13f96da09eeb299cde6884ea3faabcd" ]
[ "Python/transform.py" ]
[ "\"\"\"\nPython Image Manipulation by Kylie Ying (modified from MIT 6.865)\n\nYouTube Kylie Ying: https://www.youtube.com/ycubed \nTwitch KylieYing: https://www.twitch.tv/kylieying \nTwitter @kylieyying: https://twitter.com/kylieyying \nInstagram @kylieyying: https://www.instagram.com/kylieyying/ \nWebsite: https://www.kylieying.com\nGithub: https://www.github.com/kying18 \nProgrammer Beast Mode Spotify playlist: https://open.spotify.com/playlist/4Akns5EUb3gzmlXIdsJkPs?si=qGc4ubKRRYmPHAJAIrCxVQ \n\"\"\"\n\nfrom image import Image\nimport numpy as np\n\n\ndef brighten(image, factor):\n # when we brighten, we just want to make each channel higher by some amount \n # factor is a value > 0, how much you want to brighten the image by (< 1 = darken, > 1 = brighten)\n x_pixels, y_pixels, num_channels = image.array.shape # represents x, y pixels of image, # channels (R, G, B)\n new_im = Image(x_pixels=x_pixels, y_pixels=y_pixels, num_channels=num_channels) # making a new array to copy values to!\n\n # # this is the non vectorized version\n # for x in range(x_pixels):\n # for y in range(y_pixels):\n # for c in range(num_channels):\n # new_im.array[x, y, c] = image.array[x, y, c] * factor\n\n # faster version that leverages numpy\n new_im.array = image.array * factor\n\n return new_im\n\ndef adjust_contrast(image, factor, mid):\n # adjust the contrast by increasing the difference from the user-defined midpoint by factor amount\n x_pixels, y_pixels, num_channels = image.array.shape # represents x, y pixels of image, # channels (R, G, B)\n new_im = Image(x_pixels=x_pixels, y_pixels=y_pixels, num_channels=num_channels) # making a new array to copy values to!\n for x in range(x_pixels):\n for y in range(y_pixels):\n for c in range(num_channels):\n new_im.array[x, y, c] = (image.array[x, y, c] - mid) * factor + mid\n\n return new_im\n\ndef blur(image, kernel_size):\n # kernel size is the number of pixels to take into account when applying the blur\n # (ie kernel_size = 3 would be neighbors to the left/right, top/bottom, and diagonals)\n # kernel size should always be an *odd* number\n x_pixels, y_pixels, num_channels = image.array.shape # represents x, y pixels of image, # channels (R, G, B)\n new_im = Image(x_pixels=x_pixels, y_pixels=y_pixels, num_channels=num_channels) # making a new array to copy values to!\n neighbor_range = kernel_size // 2 # this is a variable that tells us how many neighbors we actually look at (ie for a kernel of 3, this value should be 1)\n for x in range(x_pixels):\n for y in range(y_pixels):\n for c in range(num_channels):\n # we are going to use a naive implementation of iterating through each neighbor and summing\n # there are faster implementations where you can use memoization, but this is the most straightforward for a beginner to understand\n total = 0\n for x_i in range(max(0,x-neighbor_range), min(new_im.x_pixels-1, x+neighbor_range)+1):\n for y_i in range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1):\n total += image.array[x_i, y_i, c]\n new_im.array[x, y, c] = total / (kernel_size ** 2)\n return new_im\n\ndef apply_kernel(image, kernel):\n # the kernel should be a 2D array that represents the kernel we'll use!\n # for the sake of simiplicity of this implementation, let's assume that the kernel is SQUARE\n # for example the sobel x kernel (detecting horizontal edges) is as follows:\n # [1 0 -1]\n # [2 0 -2]\n # [1 0 -1]\n x_pixels, y_pixels, num_channels = image.array.shape # represents x, y pixels of image, # channels (R, G, B)\n new_im = Image(x_pixels=x_pixels, y_pixels=y_pixels, num_channels=num_channels) # making a new array to copy values to!\n neighbor_range = kernel.shape[0] // 2 # this is a variable that tells us how many neighbors we actually look at (ie for a 3x3 kernel, this value should be 1)\n for x in range(x_pixels):\n for y in range(y_pixels):\n for c in range(num_channels):\n total = 0\n for x_i in range(max(0,x-neighbor_range), min(new_im.x_pixels-1, x+neighbor_range)+1):\n for y_i in range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1):\n x_k = x_i + neighbor_range - x\n y_k = y_i + neighbor_range - y\n kernel_val = kernel[x_k, y_k]\n total += image.array[x_i, y_i, c] * kernel_val\n new_im.array[x, y, c] = total\n return new_im\n\ndef combine_images(image1, image2):\n # let's combine two images using the squared sum of squares: value = sqrt(value_1**2, value_2**2)\n # size of image1 and image2 MUST be the same\n x_pixels, y_pixels, num_channels = image1.array.shape # represents x, y pixels of image, # channels (R, G, B)\n new_im = Image(x_pixels=x_pixels, y_pixels=y_pixels, num_channels=num_channels) # making a new array to copy values to!\n for x in range(x_pixels):\n for y in range(y_pixels):\n for c in range(num_channels):\n new_im.array[x, y, c] = (image1.array[x, y, c]**2 + image2.array[x, y, c]**2)**0.5\n return new_im\n \nif __name__ == '__main__':\n chunk1 = Image(filename='chunk1.png')\n\n # brightening\n # brightened_im = brighten(lake, 1.7)\n # brightened_im.write_image('brightened.png')\n\n # # darkening\n # darkened_im = brighten(lake, 0.3)\n # darkened_im.write_image('darkened.png')\n\n # # increase contrast\n # incr_contrast = adjust_contrast(lake, 2, 0.5)\n # incr_contrast.write_image('increased_contrast.png')\n\n # # decrease contrast\n # decr_contrast = adjust_contrast(lake, 0.5, 0.5)\n # decr_contrast.write_image('decreased_contrast.png')\n\n # # blur using kernel 3\n # blur_3 = blur(city, 3)\n # blur_3.write_image('blur_k3.png')\n\n # # blur using kernel size of 15\n # blur_15 = blur(city, 15)\n # blur_15.write_image('blur_k15.png')\n\n # let's apply a sobel edge detection kernel on the x and y axis\n sobel_x = apply_kernel(city, np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]))\n # sobel_x.write_image('edge_x.png')\n sobel_y = apply_kernel(city, np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]]))\n # sobel_y.write_image('edge_y.png')\n\n # let's combine these and make an edge detector!\n sobel_xy = combine_images(sobel_x, sobel_y)\n sobel_xy.write_image('edge_xy.png')\n\n" ]
[ [ "numpy.array" ] ]
Arjung27/SFM-Learner
[ "8da43b4266dfeb23465d3caad0d23b0c8f457257" ]
[ "data_loader.py" ]
[ "from __future__ import division\nimport os\nimport random\nimport tensorflow as tf\nimport numpy as np\n\nclass DataLoader(object):\n def __init__(self, \n dataset_dir=None, \n batch_size=None, \n img_height=None, \n img_width=None, \n num_source=None, \n num_scales=None):\n self.dataset_dir = dataset_dir\n self.batch_size = batch_size\n self.img_height = img_height\n self.img_width = img_width\n self.num_source = num_source\n self.num_scales = num_scales\n\n def load_train_batch(self):\n \"\"\"Load a batch of training instances.\n \"\"\"\n seed = random.randint(0, 2**31 - 1)\n # Load the list of training files into queues\n file_list = self.format_file_list(self.dataset_dir, 'train')\n image_paths_queue = tf.train.string_input_producer(\n file_list['image_file_list'], \n seed=seed, \n shuffle=True)\n cam_paths_queue = tf.train.string_input_producer(\n file_list['cam_file_list'], \n seed=seed, \n shuffle=True)\n self.steps_per_epoch = int(\n len(file_list['image_file_list'])//self.batch_size)\n\n # Load images\n img_reader = tf.WholeFileReader()\n _, image_contents = img_reader.read(image_paths_queue)\n image_seq = tf.image.decode_jpeg(image_contents)\n tgt_image, src_image_stack = \\\n self.unpack_image_sequence(\n image_seq, self.img_height, self.img_width, self.num_source)\n\n # Load camera intrinsics\n cam_reader = tf.TextLineReader()\n _, raw_cam_contents = cam_reader.read(cam_paths_queue)\n rec_def = []\n for i in range(9):\n rec_def.append([1.])\n raw_cam_vec = tf.decode_csv(raw_cam_contents, \n record_defaults=rec_def)\n raw_cam_vec = tf.stack(raw_cam_vec)\n intrinsics = tf.reshape(raw_cam_vec, [3, 3])\n\n # Form training batches\n src_image_stack, tgt_image, intrinsics = \\\n tf.train.batch([src_image_stack, tgt_image, intrinsics], \n batch_size=self.batch_size)\n\n # Data augmentation\n image_all = tf.concat([tgt_image, src_image_stack], axis=3)\n # print(src_image_stack.get_shape().as_list())\n # print(tgt_image.get_shape().as_list())\n # exit(-1)\n image_all, intrinsics = self.data_augmentation(\n image_all, intrinsics, self.img_height, self.img_width)\n tgt_image = image_all[:, :, :, :3]\n src_image_stack = image_all[:, :, :, 3:]\n intrinsics = self.get_multi_scale_intrinsics(\n intrinsics, self.num_scales)\n return tgt_image, src_image_stack, intrinsics\n\n def make_intrinsics_matrix(self, fx, fy, cx, cy):\n # Assumes batch input\n batch_size = fx.get_shape().as_list()[0]\n zeros = tf.zeros_like(fx)\n r1 = tf.stack([fx, zeros, cx], axis=1)\n r2 = tf.stack([zeros, fy, cy], axis=1)\n r3 = tf.constant([0.,0.,1.], shape=[1, 3])\n r3 = tf.tile(r3, [batch_size, 1])\n intrinsics = tf.stack([r1, r2, r3], axis=1)\n return intrinsics\n\n def data_augmentation(self, im, intrinsics, out_h, out_w):\n # Random scaling\n def random_scaling(im, intrinsics):\n batch_size, in_h, in_w, _ = im.get_shape().as_list()\n scaling = tf.random_uniform([2], 1, 1.15)\n x_scaling = scaling[0]\n y_scaling = scaling[1]\n out_h = tf.cast(in_h * y_scaling, dtype=tf.int32)\n out_w = tf.cast(in_w * x_scaling, dtype=tf.int32)\n im = tf.image.resize_area(im, [out_h, out_w])\n fx = intrinsics[:,0,0] * x_scaling\n fy = intrinsics[:,1,1] * y_scaling\n cx = intrinsics[:,0,2] * x_scaling\n cy = intrinsics[:,1,2] * y_scaling\n intrinsics = self.make_intrinsics_matrix(fx, fy, cx, cy)\n return im, intrinsics\n\n # Random cropping\n def random_cropping(im, intrinsics, out_h, out_w):\n # batch_size, in_h, in_w, _ = im.get_shape().as_list()\n batch_size, in_h, in_w, _ = tf.unstack(tf.shape(im))\n offset_y = tf.random_uniform([1], 0, in_h - out_h + 1, dtype=tf.int32)[0]\n offset_x = tf.random_uniform([1], 0, in_w - out_w + 1, dtype=tf.int32)[0]\n im = tf.image.crop_to_bounding_box(\n im, offset_y, offset_x, out_h, out_w)\n fx = intrinsics[:,0,0]\n fy = intrinsics[:,1,1]\n cx = intrinsics[:,0,2] - tf.cast(offset_x, dtype=tf.float32)\n cy = intrinsics[:,1,2] - tf.cast(offset_y, dtype=tf.float32)\n intrinsics = self.make_intrinsics_matrix(fx, fy, cx, cy)\n return im, intrinsics\n\n def random_photometric(ims, *,\n noise_stddev=0.0, min_contrast=0.0, max_contrast=0.0,\n brightness_stddev=0.0, min_colour=1.0, max_colour=1.0,\n min_gamma=1.0, max_gamma=1.0):\n \"\"\"Applies photometric augmentations to a list of image batches.\n Each image in the list is augmented in the same way.\n For all elements, num_batch must be equal while height and width may differ.\n Args:\n ims: list of 3-channel image batches normalized to [0, 1].\n channel_mean: tensor of shape [3] which was used to normalize the pixel\n values ranging from 0 ... 255.\n Returns:\n Batch of normalized images with photometric augmentations. Has the same\n shape as the input batch.\n \"\"\"\n\n with tf.variable_scope('random_photometric'):\n num_batch = tf.shape(ims)[0]\n\n contrast = tf.random_uniform([num_batch, 1], min_contrast, max_contrast)\n gamma = tf.random_uniform([num_batch, 1], min_gamma, max_gamma)\n gamma_inv = 1.0 / gamma\n colour = tf.random_uniform([num_batch, 9], min_colour, max_colour)\n if noise_stddev > 0.0:\n noise = tf.random_normal([num_batch, 1], stddev=noise_stddev)\n else:\n noise = tf.zeros([num_batch, 1])\n if brightness_stddev > 0.0:\n brightness = tf.random_normal([num_batch, 1],\n stddev=brightness_stddev)\n else:\n brightness = tf.zeros([num_batch, 1])\n\n out = []\n # print(ims.get_shape().as_list())\n # exit(-1)\n # for i in range(4):\n # Transpose to [height, width, num_batch, channels]\n ims = ims/255.0\n im_re = tf.transpose(ims, [1, 2, 0, 3])\n im_re = im_re\n im_re = (im_re * (contrast + 1.0) + brightness) * colour\n im_re = tf.maximum(0.0, tf.minimum(1.0, im_re))\n im_re = tf.pow(im_re, gamma_inv)\n\n im_re = im_re + noise\n\n # Subtract the mean again after clamping\n im_re = im_re\n\n im = tf.transpose(im_re, [2, 0, 1, 3])\n im = im*255\n tim = tf.clip_by_value(im, clip_value_min=0, clip_value_max=255)\n im = tf.stop_gradient(im)\n # out.append(im)\n return im\n\n im, intrinsics = random_scaling(im, intrinsics)\n im, intrinsics = random_cropping(im, intrinsics, out_h, out_w)\n\n # im = tf.cond(tf.random_uniform(shape=[1])[0] < tf.constant(0.5), lambda: im, \\\n # lambda: random_photometric(im, noise_stddev=0.04, min_contrast=-0.3, max_contrast=0.3,\n # brightness_stddev=0.02, min_colour=0.9, max_colour=1.1,\n # min_gamma=0.7, max_gamma=1.5))\n im = tf.cast(im, dtype=tf.uint8)\n # print(im.get_shape().as_list())\n # exit(-1)\n return im, intrinsics\n\n def format_file_list(self, data_root, split):\n with open(data_root + '/%s.txt' % split, 'r') as f:\n frames = f.readlines()\n subfolders = [x.split(' ')[0] for x in frames]\n frame_ids = [x.split(' ')[1][:-1] for x in frames]\n image_file_list = [os.path.join(data_root, subfolders[i], \n frame_ids[i] + '.jpg') for i in range(len(frames))]\n cam_file_list = [os.path.join(data_root, subfolders[i], \n frame_ids[i] + '_cam.txt') for i in range(len(frames))]\n all_list = {}\n all_list['image_file_list'] = image_file_list\n all_list['cam_file_list'] = cam_file_list\n return all_list\n\n def unpack_image_sequence(self, image_seq, img_height, img_width, num_source):\n # Assuming the center image is the target frame\n tgt_start_idx = int(img_width * (num_source//2))\n tgt_image = tf.slice(image_seq, \n [0, tgt_start_idx, 0], \n [-1, img_width, -1])\n # Source frames before the target frame\n src_image_1 = tf.slice(image_seq, \n [0, 0, 0], \n [-1, int(img_width * (num_source//2)), -1])\n # Source frames after the target frame\n src_image_2 = tf.slice(image_seq, \n [0, int(tgt_start_idx + img_width), 0], \n [-1, int(img_width * (num_source//2)), -1])\n src_image_seq = tf.concat([src_image_1, src_image_2], axis=1)\n # Stack source frames along the color channels (i.e. [H, W, N*3])\n src_image_stack = tf.concat([tf.slice(src_image_seq, \n [0, i*img_width, 0], \n [-1, img_width, -1]) \n for i in range(num_source)], axis=2)\n src_image_stack.set_shape([img_height, \n img_width, \n num_source * 3])\n tgt_image.set_shape([img_height, img_width, 3])\n return tgt_image, src_image_stack\n\n def batch_unpack_image_sequence(self, image_seq, img_height, img_width, num_source):\n # Assuming the center image is the target frame\n tgt_start_idx = int(img_width * (num_source//2))\n tgt_image = tf.slice(image_seq, \n [0, 0, tgt_start_idx, 0], \n [-1, -1, img_width, -1])\n # Source frames before the target frame\n src_image_1 = tf.slice(image_seq, \n [0, 0, 0, 0], \n [-1, -1, int(img_width * (num_source//2)), -1])\n # Source frames after the target frame\n src_image_2 = tf.slice(image_seq, \n [0, 0, int(tgt_start_idx + img_width), 0], \n [-1, -1, int(img_width * (num_source//2)), -1])\n src_image_seq = tf.concat([src_image_1, src_image_2], axis=2)\n # Stack source frames along the color channels (i.e. [B, H, W, N*3])\n src_image_stack = tf.concat([tf.slice(src_image_seq, \n [0, 0, i*img_width, 0], \n [-1, -1, img_width, -1]) \n for i in range(num_source)], axis=3)\n return tgt_image, src_image_stack\n\n def get_multi_scale_intrinsics(self, intrinsics, num_scales):\n intrinsics_mscale = []\n # Scale the intrinsics accordingly for each scale\n for s in range(num_scales):\n fx = intrinsics[:,0,0]/(2 ** s)\n fy = intrinsics[:,1,1]/(2 ** s)\n cx = intrinsics[:,0,2]/(2 ** s)\n cy = intrinsics[:,1,2]/(2 ** s)\n intrinsics_mscale.append(\n self.make_intrinsics_matrix(fx, fy, cx, cy))\n intrinsics_mscale = tf.stack(intrinsics_mscale, axis=1)\n return intrinsics_mscale" ]
[ [ "tensorflow.TextLineReader", "tensorflow.concat", "tensorflow.zeros", "tensorflow.stack", "tensorflow.cast", "tensorflow.minimum", "tensorflow.train.batch", "tensorflow.image.resize_area", "tensorflow.decode_csv", "tensorflow.WholeFileReader", "tensorflow.stop_gradient", "tensorflow.tile", "tensorflow.image.decode_jpeg", "tensorflow.shape", "tensorflow.pow", "tensorflow.zeros_like", "tensorflow.train.string_input_producer", "tensorflow.clip_by_value", "tensorflow.constant", "tensorflow.transpose", "tensorflow.image.crop_to_bounding_box", "tensorflow.slice", "tensorflow.reshape", "tensorflow.variable_scope", "tensorflow.random_uniform", "tensorflow.random_normal" ] ]
guisoares9/opencv_studies
[ "4bccb0b7fa436e589a23529e52fcd14660639589" ]
[ "calibration/calibration.py" ]
[ "import numpy as np\nimport cv2 as cv\nimport time\n\ncriteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30, 0.001)\n\nsquare_size = 28\n# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\nobjp = np.zeros((6*9,3), np.float32)\n#print(objp)\nobjp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2)\nobjp = square_size * objp\n#print(objp)\n#exit(0)\n# Arrays to store object points and image points from all the images.\nobjpoints = [] # 3d point in real world space\nimgpoints = [] # 2d points in image plane.\n \nfor i in range(9,50):\n\n img = cv.imread(\"patternphotos/calib\" + str(i) + \".png\")\n\n #if img == None:\n # print(\"Error while geting image \\n\")\n # exit(0)\n\n cv.imshow(\"a\", img)\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n #Find the chess board corners\n ret, corners = cv.findChessboardCorners(gray, (9,6), None)\n\n # If found, add object points, image points (after refining them)\n if ret == True:\n objpoints.append(objp)\n\n corners2 = cv.cornerSubPix(gray,corners, (11,11), (-1,-1), criteria)\n imgpoints.append(corners)\n # Draw and display the corners\n\n cv.drawChessboardCorners(img, (9,6), corners2, ret)\n cv.imshow('img', img)\n cv.waitKey(100)\n\n time.sleep(0.001)\n\ncv.destroyAllWindows()\n\nprint(\"Inicializing calibration... \\n\")\nret, mtx, dist, rvecs, tvecs = cv.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)\nprint(\"Calibration finished... \\n\")\n\ncam_file_name = str(input(\"Insira o nome do arquivo destinado a matriz da camera: \"))\n\nprint(\"Saving camera matrix... \\n\")\n\ncamfile = open(cam_file_name,\"w\")\n\nfor i in range(3):\n for j in range(3):\n camfile.write(str(mtx[i][j]) + \" \")\n camfile.write(\"\\n\")\ncamfile.write(\"\\n\")\nfor i in range(5):\n camfile.write(str(dist[0][i]) + \" \")\n\ncamfile.close()\ncamfile = open(cam_file_name, \"r\")\nprint(camfile.read())\n\n\nprint(mtx)\nprint(dist)\n#print(rvecs)\n#print(tvecs)\n" ]
[ [ "numpy.zeros" ] ]
akterskii/rlkit
[ "dd5d753e0fb3fa9e94b0eb5e78a2101d95657e9f" ]
[ "rlkit/data_management/shared_obs_dict_replay_buffer.py" ]
[ "import numpy as np\n\nfrom rlkit.data_management.obs_dict_replay_buffer import ObsDictRelabelingBuffer\n\nimport torch.multiprocessing as mp\nimport ctypes\n\n\nclass SharedObsDictRelabelingBuffer(ObsDictRelabelingBuffer):\n \"\"\"\n Same as an ObsDictRelabelingBuffer but the obs and next_obs are backed\n by multiprocessing arrays. The replay buffer size is also shared. The\n intended use case is for if one wants obs/next_obs to be shared between\n processes. Accesses are synchronized internally by locks (mp takes care\n of that). Technically, putting such large arrays in shared memory/requiring\n synchronized access can be extremely slow, but it seems ok empirically.\n\n This code also breaks a lot of functionality for the subprocess. For example,\n random_batch is incorrect as actions and _idx_to_future_obs_idx are not\n shared. If the subprocess needs all of the functionality, a mp.Array\n must be used for all numpy arrays in the replay buffer.\n\n \"\"\"\n\n def __init__(\n self,\n *args,\n **kwargs\n ):\n self._shared_size = mp.Value(ctypes.c_long, 0)\n ObsDictRelabelingBuffer.__init__(self, *args, **kwargs)\n\n self._mp_array_info = {}\n self._shared_obs_info = {}\n self._shared_next_obs_info = {}\n\n for obs_key, obs_arr in self._obs.items():\n ctype = ctypes.c_double\n if obs_arr.dtype == np.uint8:\n ctype = ctypes.c_uint8\n\n self._shared_obs_info[obs_key] = (\n mp.Array(ctype, obs_arr.size),\n obs_arr.dtype,\n obs_arr.shape,\n )\n self._shared_next_obs_info[obs_key] = (\n mp.Array(ctype, obs_arr.size),\n obs_arr.dtype,\n obs_arr.shape,\n )\n\n self._obs[obs_key] = to_np(*self._shared_obs_info[obs_key])\n self._next_obs[obs_key] = to_np(\n *self._shared_next_obs_info[obs_key])\n self._register_mp_array(\"_actions\")\n self._register_mp_array(\"_terminals\")\n\n def _register_mp_array(self, arr_instance_var_name):\n \"\"\"\n Use this function to register an array to be shared. This will wipe arr.\n \"\"\"\n assert hasattr(self, arr_instance_var_name), arr_instance_var_name\n arr = getattr(self, arr_instance_var_name)\n\n ctype = ctypes.c_double\n if arr.dtype == np.uint8:\n ctype = ctypes.c_uint8\n\n self._mp_array_info[arr_instance_var_name] = (\n mp.Array(ctype, arr.size), arr.dtype, arr.shape,\n )\n setattr(\n self,\n arr_instance_var_name,\n to_np(*self._mp_array_info[arr_instance_var_name])\n )\n\n def init_from_mp_info(\n self,\n mp_info,\n ):\n \"\"\"\n The intended use is to have a subprocess serialize/copy a\n SharedObsDictRelabelingBuffer instance and call init_from on the\n instance's shared variables. This can't be done during serialization\n since multiprocessing shared objects can't be serialized and must be\n passed directly to the subprocess as an argument to the fork call.\n \"\"\"\n shared_obs_info, shared_next_obs_info, mp_array_info, shared_size = mp_info\n\n self._shared_obs_info = shared_obs_info\n self._shared_next_obs_info = shared_next_obs_info\n self._mp_array_info = mp_array_info\n for obs_key in self._shared_obs_info.keys():\n self._obs[obs_key] = to_np(*self._shared_obs_info[obs_key])\n self._next_obs[obs_key] = to_np(\n *self._shared_next_obs_info[obs_key])\n\n for arr_instance_var_name in self._mp_array_info.keys():\n setattr(\n self,\n arr_instance_var_name,\n to_np(*self._mp_array_info[arr_instance_var_name])\n )\n self._shared_size = shared_size\n\n def get_mp_info(self):\n return (\n self._shared_obs_info,\n self._shared_next_obs_info,\n self._mp_array_info,\n self._shared_size,\n )\n\n @property\n def _size(self):\n return self._shared_size.value\n\n @_size.setter\n def _size(self, size):\n self._shared_size.value = size\n\n\ndef to_np(shared_arr, np_dtype, shape):\n return np.frombuffer(shared_arr.get_obj(), dtype=np_dtype).reshape(shape)\n" ]
[ [ "torch.multiprocessing.Array", "torch.multiprocessing.Value" ] ]
Crivella/pymatgen
[ "dd3737011e76520da1347d5db75db3a3f87e520f" ]
[ "pymatgen/io/vasp/tests/test_outputs.py" ]
[ "# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\n\nimport gzip\nimport json\nimport os\nimport unittest\nimport warnings\nimport xml.etree.ElementTree as ET\nfrom pathlib import Path\nfrom shutil import copyfile, copyfileobj\n\nimport numpy as np\nimport pytest\nfrom monty.tempfile import ScratchDir\n\nfrom pymatgen.core.lattice import Lattice\nfrom pymatgen.electronic_structure.core import Orbital, Spin\nfrom pymatgen.core.structure import Structure\nfrom pymatgen.core import Element\nfrom pymatgen.electronic_structure.core import Magmom, OrbitalType\nfrom pymatgen.entries.compatibility import MaterialsProjectCompatibility\nfrom pymatgen.io.vasp.inputs import Kpoints, Poscar\nfrom pymatgen.io.vasp.outputs import (\n BSVasprun,\n Chgcar,\n Dynmat,\n Eigenval,\n Elfcar,\n Locpot,\n Oszicar,\n Outcar,\n Procar,\n UnconvergedVASPWarning,\n VaspParserError,\n Vasprun,\n Wavecar,\n Waveder,\n Xdatcar,\n)\nfrom pymatgen.io.wannier90 import Unk\nfrom pymatgen.util.testing import PymatgenTest\n\n\nclass VasprunTest(PymatgenTest):\n _multiprocess_shared_ = True\n\n def setUp(self):\n warnings.simplefilter(\"ignore\")\n\n def tearDown(self):\n warnings.simplefilter(\"default\")\n\n def test_multiple_dielectric(self):\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.GW0.xml\")\n self.assertEqual(len(v.other_dielectric), 3)\n\n def test_charge_charge_dielectric(self):\n \"\"\"\n VASP 5.4.4 writes out two dielectric functions to vasprun.xml\n These are the \"density-density\" and \"velocity-velocity\" linear response functions.\n See the comments in `linear_optics.F` for details.\n \"\"\"\n v = Vasprun(\n self.TEST_FILES_DIR / \"vasprun.xml.dielectric_5.4.4\",\n parse_potcar_file=False,\n )\n self.assertEqual(v.dielectric is not None, True)\n self.assertEqual(\"density\" in v.dielectric_data, True)\n self.assertEqual(\"velocity\" in v.dielectric_data, True)\n\n def test_optical_absorption_coeff(self):\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.BSE.xml.gz\")\n absorption_coeff = v.optical_absorption_coeff\n self.assertEqual(absorption_coeff[1], 24966408728.917931)\n\n def test_vasprun_with_more_than_two_unlabelled_dielectric_functions(self):\n with self.assertRaises(NotImplementedError):\n Vasprun(\n self.TEST_FILES_DIR / \"vasprun.xml.dielectric_bad\",\n parse_potcar_file=False,\n )\n\n def test_bad_vasprun(self):\n self.assertRaises(ET.ParseError, Vasprun, self.TEST_FILES_DIR / \"bad_vasprun.xml\")\n\n with warnings.catch_warnings(record=True) as w:\n # Cause all warnings to always be triggered.\n warnings.simplefilter(\"always\")\n # Trigger a warning.\n v = Vasprun(self.TEST_FILES_DIR / \"bad_vasprun.xml\", exception_on_bad_xml=False)\n # Verify some things\n self.assertEqual(len(v.ionic_steps), 1)\n self.assertAlmostEqual(v.final_energy, -269.00551374)\n self.assertTrue(issubclass(w[-1].category, UserWarning))\n\n def test_runtype(self):\n\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.GW0.xml\")\n self.assertIn(v.run_type, \"HF\")\n\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.pbesol_vdw\")\n self.assertIn(v.run_type, \"PBEsol+vdW-DFT-D3-BJ\")\n\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.hse06\")\n self.assertIn(v.run_type, \"HSE06\")\n\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.scan_rvv10\")\n self.assertIn(v.run_type, \"SCAN+rVV10\")\n\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.dfpt.ionic\")\n self.assertIn(v.run_type, \"GGA\")\n\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.dfpt\")\n self.assertIn(v.run_type, \"GGA+U\")\n\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.r2scan\")\n self.assertIn(v.run_type, \"R2SCAN\")\n\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.scan\")\n self.assertIn(v.run_type, \"SCAN\")\n\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.pbesol\")\n self.assertIn(v.run_type, \"PBEsol\")\n\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.rscan\")\n self.assertIn(v.run_type, \"RSCAN\")\n\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.random\")\n self.assertIn(v.run_type, \"RANDOMFUNCTIONAL\")\n\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.unknown\")\n with pytest.warns(UserWarning, match=\"Unknown run type!\"):\n self.assertIn(v.run_type, \"unknown\")\n\n def test_vdw(self):\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.vdw\")\n self.assertAlmostEqual(v.final_energy, -9.78310677)\n\n def test_nonlmn(self):\n\n filepath = self.TEST_FILES_DIR / \"vasprun.xml.nonlm\"\n vasprun = Vasprun(filepath, parse_potcar_file=False)\n orbs = list(vasprun.complete_dos.pdos[vasprun.final_structure[0]].keys())\n self.assertIn(OrbitalType.s, orbs)\n\n def test_standard(self):\n filepath = self.TEST_FILES_DIR / \"vasprun.xml\"\n vasprun = Vasprun(filepath, parse_potcar_file=False)\n\n # Test NELM parsing.\n self.assertEqual(vasprun.parameters[\"NELM\"], 60)\n # test pdos parsing\n\n pdos0 = vasprun.complete_dos.pdos[vasprun.final_structure[0]]\n self.assertAlmostEqual(pdos0[Orbital.s][Spin.up][16], 0.0026)\n self.assertAlmostEqual(pdos0[Orbital.pz][Spin.down][16], 0.0012)\n self.assertEqual(pdos0[Orbital.s][Spin.up].shape, (301,))\n\n filepath2 = self.TEST_FILES_DIR / \"lifepo4.xml\"\n vasprun_ggau = Vasprun(filepath2, parse_projected_eigen=True, parse_potcar_file=False)\n totalscsteps = sum(len(i[\"electronic_steps\"]) for i in vasprun.ionic_steps)\n self.assertEqual(29, len(vasprun.ionic_steps))\n self.assertEqual(len(vasprun.structures), len(vasprun.ionic_steps))\n\n trajectory = vasprun.get_trajectory()\n self.assertEqual(len(trajectory), len(vasprun.ionic_steps))\n self.assertIn(\"forces\", trajectory[0].site_properties)\n\n for i, step in enumerate(vasprun.ionic_steps):\n self.assertEqual(vasprun.structures[i], step[\"structure\"])\n\n self.assertTrue(\n all(vasprun.structures[i] == vasprun.ionic_steps[i][\"structure\"] for i in range(len(vasprun.ionic_steps)))\n )\n\n self.assertEqual(308, totalscsteps, \"Incorrect number of energies read from vasprun.xml\")\n\n self.assertEqual([\"Li\"] + 4 * [\"Fe\"] + 4 * [\"P\"] + 16 * [\"O\"], vasprun.atomic_symbols)\n self.assertEqual(vasprun.final_structure.composition.reduced_formula, \"LiFe4(PO4)4\")\n self.assertIsNotNone(vasprun.incar, \"Incar cannot be read\")\n self.assertIsNotNone(vasprun.kpoints, \"Kpoints cannot be read\")\n self.assertIsNotNone(vasprun.eigenvalues, \"Eigenvalues cannot be read\")\n self.assertAlmostEqual(vasprun.final_energy, -269.38319884, 7)\n self.assertAlmostEqual(vasprun.tdos.get_gap(), 2.0589, 4)\n expectedans = (2.539, 4.0906, 1.5516, False)\n (gap, cbm, vbm, direct) = vasprun.eigenvalue_band_properties\n self.assertAlmostEqual(gap, expectedans[0])\n self.assertAlmostEqual(cbm, expectedans[1])\n self.assertAlmostEqual(vbm, expectedans[2])\n self.assertEqual(direct, expectedans[3])\n self.assertFalse(vasprun.is_hubbard)\n self.assertEqual(\n vasprun.potcar_symbols,\n [\n \"PAW_PBE Li 17Jan2003\",\n \"PAW_PBE Fe 06Sep2000\",\n \"PAW_PBE Fe 06Sep2000\",\n \"PAW_PBE P 17Jan2003\",\n \"PAW_PBE O 08Apr2002\",\n ],\n )\n self.assertIsNotNone(vasprun.kpoints, \"Kpoints cannot be read\")\n self.assertIsNotNone(vasprun.actual_kpoints, \"Actual kpoints cannot be read\")\n self.assertIsNotNone(vasprun.actual_kpoints_weights, \"Actual kpoints weights cannot be read\")\n for atomdoses in vasprun.pdos:\n for orbitaldos in atomdoses:\n self.assertIsNotNone(orbitaldos, \"Partial Dos cannot be read\")\n\n # test skipping ionic steps.\n vasprun_skip = Vasprun(filepath, 3, parse_potcar_file=False)\n self.assertEqual(vasprun_skip.nionic_steps, 29)\n self.assertEqual(len(vasprun_skip.ionic_steps), int(vasprun.nionic_steps / 3) + 1)\n self.assertEqual(len(vasprun_skip.ionic_steps), len(vasprun_skip.structures))\n self.assertEqual(len(vasprun_skip.ionic_steps), int(vasprun.nionic_steps / 3) + 1)\n # Check that nionic_steps is preserved no matter what.\n self.assertEqual(vasprun_skip.nionic_steps, vasprun.nionic_steps)\n\n self.assertNotAlmostEqual(vasprun_skip.final_energy, vasprun.final_energy)\n\n # Test with ionic_step_offset\n vasprun_offset = Vasprun(filepath, 3, 6, parse_potcar_file=False)\n self.assertEqual(len(vasprun_offset.ionic_steps), int(len(vasprun.ionic_steps) / 3) - 1)\n self.assertEqual(vasprun_offset.structures[0], vasprun_skip.structures[2])\n\n self.assertTrue(vasprun_ggau.is_hubbard)\n self.assertEqual(vasprun_ggau.hubbards[\"Fe\"], 4.3)\n self.assertAlmostEqual(vasprun_ggau.projected_eigenvalues[Spin.up][0][0][96][0], 0.0032)\n d = vasprun_ggau.as_dict()\n self.assertEqual(d[\"elements\"], [\"Fe\", \"Li\", \"O\", \"P\"])\n self.assertEqual(d[\"nelements\"], 4)\n\n entry = vasprun.get_computed_entry(inc_structure=True)\n self.assertTrue(entry.entry_id.startswith(\"vasprun\"))\n self.assertEqual(entry.parameters[\"run_type\"], \"PBEO or other Hybrid Functional\")\n\n def test_unconverged(self):\n filepath = self.TEST_FILES_DIR / \"vasprun.xml.unconverged\"\n with warnings.catch_warnings(record=True) as w:\n # Cause all warnings to always be triggered.\n warnings.simplefilter(\"always\")\n # Trigger a warning.\n vasprun_unconverged = Vasprun(filepath, parse_potcar_file=False)\n # Verify some things\n self.assertEqual(len(w), 1)\n self.assertTrue(issubclass(w[-1].category, UnconvergedVASPWarning))\n\n self.assertTrue(vasprun_unconverged.converged_ionic)\n self.assertFalse(vasprun_unconverged.converged_electronic)\n self.assertFalse(vasprun_unconverged.converged)\n\n def test_dfpt(self):\n filepath = self.TEST_FILES_DIR / \"vasprun.xml.dfpt\"\n vasprun_dfpt = Vasprun(filepath, parse_potcar_file=False)\n self.assertAlmostEqual(vasprun_dfpt.epsilon_static[0][0], 3.26105533)\n self.assertAlmostEqual(vasprun_dfpt.epsilon_static[0][1], -0.00459066)\n self.assertAlmostEqual(vasprun_dfpt.epsilon_static[2][2], 3.24330517)\n self.assertAlmostEqual(vasprun_dfpt.epsilon_static_wolfe[0][0], 3.33402531)\n self.assertAlmostEqual(vasprun_dfpt.epsilon_static_wolfe[0][1], -0.00559998)\n self.assertAlmostEqual(vasprun_dfpt.epsilon_static_wolfe[2][2], 3.31237357)\n self.assertTrue(vasprun_dfpt.converged)\n\n entry = vasprun_dfpt.get_computed_entry()\n entry = MaterialsProjectCompatibility(check_potcar_hash=False).process_entry(entry)\n self.assertAlmostEqual(entry.uncorrected_energy + entry.correction, entry.energy)\n\n def test_dfpt_ionic(self):\n filepath = self.TEST_FILES_DIR / \"vasprun.xml.dfpt.ionic\"\n vasprun_dfpt_ionic = Vasprun(filepath, parse_potcar_file=False)\n self.assertAlmostEqual(vasprun_dfpt_ionic.epsilon_ionic[0][0], 515.73485838)\n self.assertAlmostEqual(vasprun_dfpt_ionic.epsilon_ionic[0][1], -0.00263523)\n self.assertAlmostEqual(vasprun_dfpt_ionic.epsilon_ionic[2][2], 19.02110169)\n\n def test_dfpt_unconverged(self):\n filepath = self.TEST_FILES_DIR / \"vasprun.xml.dfpt.unconverged\"\n vasprun_dfpt_unconv = Vasprun(filepath, parse_potcar_file=False)\n self.assertFalse(vasprun_dfpt_unconv.converged_electronic)\n self.assertTrue(vasprun_dfpt_unconv.converged_ionic)\n self.assertFalse(vasprun_dfpt_unconv.converged)\n\n def test_chi(self):\n filepath = self.TEST_FILES_DIR / \"vasprun.xml.chi.gz\"\n vasprun_chi = Vasprun(filepath, parse_potcar_file=False)\n self.assertTrue(vasprun_chi.incar.get(\"ALGO\", \"\"), \"CHI\")\n\n def test_uniform(self):\n vasprun_uniform = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.uniform\", parse_potcar_file=False)\n self.assertEqual(vasprun_uniform.kpoints.style, Kpoints.supported_modes.Reciprocal)\n\n def test_no_projected(self):\n vasprun_no_pdos = Vasprun(self.TEST_FILES_DIR / \"Li_no_projected.xml\", parse_potcar_file=False)\n self.assertIsNotNone(vasprun_no_pdos.complete_dos)\n self.assertFalse(vasprun_no_pdos.dos_has_errors)\n\n def test_dielectric(self):\n vasprun_diel = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.dielectric\", parse_potcar_file=False)\n self.assertAlmostEqual(0.4294, vasprun_diel.dielectric[0][10])\n self.assertAlmostEqual(19.941, vasprun_diel.dielectric[1][51][0])\n self.assertAlmostEqual(19.941, vasprun_diel.dielectric[1][51][1])\n self.assertAlmostEqual(19.941, vasprun_diel.dielectric[1][51][2])\n self.assertAlmostEqual(0.0, vasprun_diel.dielectric[1][51][3])\n self.assertAlmostEqual(34.186, vasprun_diel.dielectric[2][85][0])\n self.assertAlmostEqual(34.186, vasprun_diel.dielectric[2][85][1])\n self.assertAlmostEqual(34.186, vasprun_diel.dielectric[2][85][2])\n self.assertAlmostEqual(0.0, vasprun_diel.dielectric[2][85][3])\n\n def test_dielectric_vasp608(self):\n # test reading dielectric constant in vasp 6.0.8\n vasprun_diel = Vasprun(\n self.TEST_FILES_DIR / \"vasprun.xml.dielectric_6.0.8\",\n parse_potcar_file=False,\n )\n self.assertAlmostEqual(0.4338, vasprun_diel.dielectric[0][10])\n self.assertAlmostEqual(5.267, vasprun_diel.dielectric[1][51][0])\n self.assertAlmostEqual(0.4338, vasprun_diel.dielectric_data[\"density\"][0][10])\n self.assertAlmostEqual(5.267, vasprun_diel.dielectric_data[\"density\"][1][51][0])\n self.assertAlmostEqual(0.4338, vasprun_diel.dielectric_data[\"velocity\"][0][10])\n self.assertAlmostEqual(1.0741, vasprun_diel.dielectric_data[\"velocity\"][1][51][0])\n self.assertEqual(len(vasprun_diel.other_dielectric), 0)\n\n def test_indirect_vasprun(self):\n v = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.indirect.gz\")\n (gap, cbm, vbm, direct) = v.eigenvalue_band_properties\n self.assertFalse(direct)\n\n def test_optical_vasprun(self):\n vasprun_optical = Vasprun(\n self.TEST_FILES_DIR / \"vasprun.xml.opticaltransitions\",\n parse_potcar_file=False,\n )\n self.assertAlmostEqual(3.084, vasprun_optical.optical_transition[0][0])\n self.assertAlmostEqual(3.087, vasprun_optical.optical_transition[3][0])\n self.assertAlmostEqual(0.001, vasprun_optical.optical_transition[0][1])\n self.assertAlmostEqual(0.001, vasprun_optical.optical_transition[1][1])\n self.assertAlmostEqual(0.001, vasprun_optical.optical_transition[7][1])\n self.assertAlmostEqual(0.001, vasprun_optical.optical_transition[19][1])\n self.assertAlmostEqual(3.3799999999, vasprun_optical.optical_transition[54][0])\n self.assertAlmostEqual(3.381, vasprun_optical.optical_transition[55][0])\n self.assertAlmostEqual(3.381, vasprun_optical.optical_transition[56][0])\n self.assertAlmostEqual(10554.9860, vasprun_optical.optical_transition[54][1])\n self.assertAlmostEqual(0.0, vasprun_optical.optical_transition[55][1])\n self.assertAlmostEqual(0.001, vasprun_optical.optical_transition[56][1])\n\n def test_force_constants(self):\n vasprun_fc = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.dfpt.phonon\", parse_potcar_file=False)\n fc_ans = [\n [-0.00184451, -0.0, -0.0],\n [-0.0, -0.00933824, -0.03021279],\n [-0.0, -0.03021279, 0.01202547],\n ]\n nm_ans = [\n [0.0884346, -0.08837289, -0.24995639],\n [-0.0884346, 0.08837289, 0.24995639],\n [0.15306645, -0.05105771, -0.14441306],\n [-0.15306645, 0.05105771, 0.14441306],\n [-0.0884346, 0.08837289, 0.24995639],\n [0.0884346, -0.08837289, -0.24995639],\n [-0.15306645, 0.05105771, 0.14441306],\n [0.15306645, -0.05105771, -0.14441306],\n [-0.0884346, 0.08837289, 0.24995639],\n [0.0884346, -0.08837289, -0.24995639],\n [-0.15306645, 0.05105771, 0.14441306],\n [0.15306645, -0.05105771, -0.14441306],\n [0.0884346, -0.08837289, -0.24995639],\n [-0.0884346, 0.08837289, 0.24995639],\n [0.15306645, -0.05105771, -0.14441306],\n [-0.15306645, 0.05105771, 0.14441306],\n ]\n nm_eigenval_ans = [\n -0.59067079,\n -0.59067079,\n -0.59067003,\n -0.59067003,\n -0.59067003,\n -0.59067003,\n -0.585009,\n -0.585009,\n -0.58500895,\n -0.58500883,\n -0.5062956,\n -0.5062956,\n ]\n self.assertEqual(vasprun_fc.force_constants.shape, (16, 16, 3, 3))\n self.assertTrue(np.allclose(vasprun_fc.force_constants[8, 9], fc_ans))\n self.assertEqual(vasprun_fc.normalmode_eigenvals.size, 48)\n self.assertTrue(np.allclose(vasprun_fc.normalmode_eigenvals[17:29], nm_eigenval_ans))\n self.assertEqual(vasprun_fc.normalmode_eigenvecs.shape, (48, 16, 3))\n self.assertTrue(np.allclose(vasprun_fc.normalmode_eigenvecs[33], nm_ans))\n\n def test_Xe(self):\n vr = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.xe\", parse_potcar_file=False)\n self.assertEqual(vr.atomic_symbols, [\"Xe\"])\n\n def test_invalid_element(self):\n self.assertRaises(ValueError, Vasprun, self.TEST_FILES_DIR / \"vasprun.xml.wrong_sp\")\n\n def test_selective_dynamics(self):\n vsd = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.indirect.gz\")\n np.testing.assert_array_equal(\n vsd.final_structure.site_properties.get(\"selective_dynamics\"),\n [[True] * 3, [False] * 3],\n \"Selective dynamics parsing error\",\n )\n\n def test_as_dict(self):\n filepath = self.TEST_FILES_DIR / \"vasprun.xml\"\n vasprun = Vasprun(filepath, parse_potcar_file=False)\n # Test that as_dict() is json-serializable\n self.assertIsNotNone(json.dumps(vasprun.as_dict()))\n self.assertEqual(\n vasprun.as_dict()[\"input\"][\"potcar_type\"],\n [\"PAW_PBE\", \"PAW_PBE\", \"PAW_PBE\", \"PAW_PBE\", \"PAW_PBE\"],\n )\n self.assertEqual(vasprun.as_dict()[\"input\"][\"nkpoints\"], 24)\n\n def test_get_band_structure(self):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n filepath = self.TEST_FILES_DIR / \"vasprun_Si_bands.xml\"\n vasprun = Vasprun(filepath, parse_projected_eigen=True, parse_potcar_file=False)\n bs = vasprun.get_band_structure(kpoints_filename=self.TEST_FILES_DIR / \"KPOINTS_Si_bands\")\n cbm = bs.get_cbm()\n vbm = bs.get_vbm()\n self.assertEqual(cbm[\"kpoint_index\"], [13], \"wrong cbm kpoint index\")\n self.assertAlmostEqual(cbm[\"energy\"], 6.2301, \"wrong cbm energy\")\n self.assertEqual(cbm[\"band_index\"], {Spin.up: [4], Spin.down: [4]}, \"wrong cbm bands\")\n self.assertEqual(vbm[\"kpoint_index\"], [0, 63, 64])\n self.assertAlmostEqual(vbm[\"energy\"], 5.6158, \"wrong vbm energy\")\n self.assertEqual(\n vbm[\"band_index\"],\n {Spin.up: [1, 2, 3], Spin.down: [1, 2, 3]},\n \"wrong vbm bands\",\n )\n self.assertEqual(vbm[\"kpoint\"].label, \"\\\\Gamma\", \"wrong vbm label\")\n self.assertEqual(cbm[\"kpoint\"].label, None, \"wrong cbm label\")\n\n projected = bs.get_projection_on_elements()\n self.assertAlmostEqual(projected[Spin.up][0][0][\"Si\"], 0.4238)\n projected = bs.get_projections_on_elements_and_orbitals({\"Si\": [\"s\"]})\n self.assertAlmostEqual(projected[Spin.up][0][0][\"Si\"][\"s\"], 0.4238)\n\n # Test compressed files case 1: compressed KPOINTS in current dir\n with ScratchDir(\"./\"):\n copyfile(self.TEST_FILES_DIR / \"vasprun_Si_bands.xml\", \"vasprun.xml\")\n\n # Check for error if no KPOINTS file\n vasprun = Vasprun(\"vasprun.xml\", parse_projected_eigen=True, parse_potcar_file=False)\n with self.assertRaises(VaspParserError):\n _ = vasprun.get_band_structure(line_mode=True)\n\n # Check KPOINTS.gz succesfully inferred and used if present\n with open(self.TEST_FILES_DIR / \"KPOINTS_Si_bands\", \"rb\") as f_in:\n with gzip.open(\"KPOINTS.gz\", \"wb\") as f_out:\n copyfileobj(f_in, f_out)\n bs_kpts_gzip = vasprun.get_band_structure()\n self.assertEqual(bs.efermi, bs_kpts_gzip.efermi)\n self.assertEqual(bs.as_dict(), bs_kpts_gzip.as_dict())\n\n # Test compressed files case 2: compressed vasprun in another dir\n with ScratchDir(\"./\"):\n os.mkdir(\"deeper\")\n copyfile(self.TEST_FILES_DIR / \"KPOINTS_Si_bands\", Path(\"deeper\") / \"KPOINTS\")\n with open(self.TEST_FILES_DIR / \"vasprun_Si_bands.xml\", \"rb\") as f_in:\n with gzip.open(os.path.join(\"deeper\", \"vasprun.xml.gz\"), \"wb\") as f_out:\n copyfileobj(f_in, f_out)\n vasprun = Vasprun(\n os.path.join(\"deeper\", \"vasprun.xml.gz\"),\n parse_projected_eigen=True,\n parse_potcar_file=False,\n )\n bs_vasprun_gzip = vasprun.get_band_structure(line_mode=True)\n self.assertEqual(bs.efermi, bs_vasprun_gzip.efermi)\n self.assertEqual(bs.as_dict(), bs_vasprun_gzip.as_dict())\n\n # test hybrid band structures\n vasprun.actual_kpoints_weights[-1] = 0.0\n bs = vasprun.get_band_structure(kpoints_filename=self.TEST_FILES_DIR / \"KPOINTS_Si_bands\")\n cbm = bs.get_cbm()\n vbm = bs.get_vbm()\n self.assertEqual(cbm[\"kpoint_index\"], [0])\n self.assertAlmostEqual(cbm[\"energy\"], 6.3676)\n self.assertEqual(cbm[\"kpoint\"].label, None)\n self.assertEqual(vbm[\"kpoint_index\"], [0])\n self.assertAlmostEqual(vbm[\"energy\"], 2.8218)\n self.assertEqual(vbm[\"kpoint\"].label, None)\n\n # test self-consistent band structure calculation for non-hybrid functionals\n vasprun = Vasprun(\n self.TEST_FILES_DIR / \"vasprun.xml.forcehybridlikecalc\",\n parse_projected_eigen=True,\n parse_potcar_file=False,\n )\n bs = vasprun.get_band_structure(\n kpoints_filename=self.TEST_FILES_DIR / \"KPOINTS.forcehybridlikecalc\",\n force_hybrid_mode=True,\n line_mode=True,\n )\n\n dict_to_test = bs.get_band_gap()\n\n self.assertTrue(dict_to_test[\"direct\"])\n self.assertAlmostEqual(dict_to_test[\"energy\"], 6.007899999999999)\n self.assertEqual(dict_to_test[\"transition\"], \"\\\\Gamma-\\\\Gamma\")\n self.assertEqual(bs.get_branch(0)[0][\"start_index\"], 0)\n self.assertEqual(bs.get_branch(0)[0][\"end_index\"], 0)\n\n def test_projected_magnetisation(self):\n filepath = self.TEST_FILES_DIR / \"vasprun.lvel.Si2H.xml\"\n vasprun = Vasprun(filepath, parse_projected_eigen=True)\n self.assertTrue(vasprun.projected_magnetisation is not None)\n self.assertEqual(vasprun.projected_magnetisation.shape, (76, 240, 4, 9, 3))\n self.assertAlmostEqual(vasprun.projected_magnetisation[0, 0, 0, 0, 0], -0.0712)\n\n def test_smart_efermi(self):\n # branch 1 - E_fermi does not cross a band\n vrun = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.LiF\")\n smart_fermi = vrun.calculate_efermi()\n self.assertAlmostEqual(smart_fermi, vrun.efermi, places=4)\n eigen_gap = vrun.eigenvalue_band_properties[0]\n bs_gap = vrun.get_band_structure(efermi=smart_fermi).get_band_gap()[\"energy\"]\n self.assertAlmostEqual(bs_gap, eigen_gap, places=3)\n\n # branch 2 - E_fermi crosses a band but bandgap=0\n vrun = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.Al\")\n smart_fermi = vrun.calculate_efermi()\n self.assertAlmostEqual(smart_fermi, vrun.efermi, places=4)\n eigen_gap = vrun.eigenvalue_band_properties[0]\n bs_gap = vrun.get_band_structure(efermi=smart_fermi).get_band_gap()[\"energy\"]\n self.assertAlmostEqual(bs_gap, eigen_gap, places=3)\n\n # branch 3 - E_fermi crosses a band in an insulator\n vrun = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.LiH_bad_efermi\")\n smart_fermi = vrun.calculate_efermi()\n self.assertNotAlmostEqual(smart_fermi, vrun.efermi, places=4)\n eigen_gap = vrun.eigenvalue_band_properties[0]\n bs_gap = vrun.get_band_structure(efermi=\"smart\").get_band_gap()[\"energy\"]\n self.assertAlmostEqual(bs_gap, eigen_gap, places=3)\n self.assertNotAlmostEqual(vrun.get_band_structure(efermi=None).get_band_gap()[\"energy\"], eigen_gap, places=3)\n self.assertNotEqual(bs_gap, 0)\n\n # branch 4 - E_fermi incorrectly placed inside a band\n vrun = Vasprun(self.TEST_FILES_DIR / \"vasprun.xml.bad_fermi.gz\")\n smart_fermi = vrun.calculate_efermi()\n self.assertAlmostEqual(smart_fermi, 6.0165)\n\n def test_sc_step_overflow(self):\n filepath = self.TEST_FILES_DIR / \"vasprun.xml.sc_overflow\"\n # with warnings.catch_warnings(record=True) as w:\n # warnings.simplefilter(\"always\")\n # vasprun = Vasprun(filepath)\n # self.assertEqual(len(w), 3)\n vasprun = Vasprun(filepath)\n estep = vasprun.ionic_steps[0][\"electronic_steps\"][29]\n self.assertTrue(np.isnan(estep[\"e_wo_entrp\"]))\n\n def test_update_potcar(self):\n filepath = self.TEST_FILES_DIR / \"vasprun.xml\"\n potcar_path = self.TEST_FILES_DIR / \"POTCAR.LiFePO4.gz\"\n potcar_path2 = self.TEST_FILES_DIR / \"POTCAR2.LiFePO4.gz\"\n vasprun = Vasprun(filepath, parse_potcar_file=False)\n self.assertEqual(\n vasprun.potcar_spec,\n [\n {\"titel\": \"PAW_PBE Li 17Jan2003\", \"hash\": None},\n {\"titel\": \"PAW_PBE Fe 06Sep2000\", \"hash\": None},\n {\"titel\": \"PAW_PBE Fe 06Sep2000\", \"hash\": None},\n {\"titel\": \"PAW_PBE P 17Jan2003\", \"hash\": None},\n {\"titel\": \"PAW_PBE O 08Apr2002\", \"hash\": None},\n ],\n )\n\n vasprun.update_potcar_spec(potcar_path)\n self.assertEqual(\n vasprun.potcar_spec,\n [\n {\n \"titel\": \"PAW_PBE Li 17Jan2003\",\n \"hash\": \"65e83282d1707ec078c1012afbd05be8\",\n },\n {\n \"titel\": \"PAW_PBE Fe 06Sep2000\",\n \"hash\": \"9530da8244e4dac17580869b4adab115\",\n },\n {\n \"titel\": \"PAW_PBE Fe 06Sep2000\",\n \"hash\": \"9530da8244e4dac17580869b4adab115\",\n },\n {\n \"titel\": \"PAW_PBE P 17Jan2003\",\n \"hash\": \"7dc3393307131ae67785a0cdacb61d5f\",\n },\n {\n \"titel\": \"PAW_PBE O 08Apr2002\",\n \"hash\": \"7a25bc5b9a5393f46600a4939d357982\",\n },\n ],\n )\n\n vasprun2 = Vasprun(filepath, parse_potcar_file=False)\n self.assertRaises(ValueError, vasprun2.update_potcar_spec, potcar_path2)\n vasprun = Vasprun(filepath, parse_potcar_file=potcar_path)\n\n self.assertEqual(\n vasprun.potcar_spec,\n [\n {\n \"titel\": \"PAW_PBE Li 17Jan2003\",\n \"hash\": \"65e83282d1707ec078c1012afbd05be8\",\n },\n {\n \"titel\": \"PAW_PBE Fe 06Sep2000\",\n \"hash\": \"9530da8244e4dac17580869b4adab115\",\n },\n {\n \"titel\": \"PAW_PBE Fe 06Sep2000\",\n \"hash\": \"9530da8244e4dac17580869b4adab115\",\n },\n {\n \"titel\": \"PAW_PBE P 17Jan2003\",\n \"hash\": \"7dc3393307131ae67785a0cdacb61d5f\",\n },\n {\n \"titel\": \"PAW_PBE O 08Apr2002\",\n \"hash\": \"7a25bc5b9a5393f46600a4939d357982\",\n },\n ],\n )\n\n self.assertRaises(ValueError, Vasprun, filepath, parse_potcar_file=potcar_path2)\n\n def test_search_for_potcar(self):\n filepath = self.TEST_FILES_DIR / \"vasprun.xml\"\n vasprun = Vasprun(filepath, parse_potcar_file=True)\n self.assertEqual(\n vasprun.potcar_spec,\n [\n {\n \"titel\": \"PAW_PBE Li 17Jan2003\",\n \"hash\": \"65e83282d1707ec078c1012afbd05be8\",\n },\n {\n \"titel\": \"PAW_PBE Fe 06Sep2000\",\n \"hash\": \"9530da8244e4dac17580869b4adab115\",\n },\n {\n \"titel\": \"PAW_PBE Fe 06Sep2000\",\n \"hash\": \"9530da8244e4dac17580869b4adab115\",\n },\n {\n \"titel\": \"PAW_PBE P 17Jan2003\",\n \"hash\": \"7dc3393307131ae67785a0cdacb61d5f\",\n },\n {\n \"titel\": \"PAW_PBE O 08Apr2002\",\n \"hash\": \"7a25bc5b9a5393f46600a4939d357982\",\n },\n ],\n )\n\n def test_potcar_not_found(self):\n filepath = self.TEST_FILES_DIR / \"vasprun.xml\"\n # Ensure no potcar is found and nothing is updated\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n vasprun = Vasprun(filepath, parse_potcar_file=\".\")\n self.assertEqual(len(w), 2)\n self.assertEqual(\n vasprun.potcar_spec,\n [\n {\"titel\": \"PAW_PBE Li 17Jan2003\", \"hash\": None},\n {\"titel\": \"PAW_PBE Fe 06Sep2000\", \"hash\": None},\n {\"titel\": \"PAW_PBE Fe 06Sep2000\", \"hash\": None},\n {\"titel\": \"PAW_PBE P 17Jan2003\", \"hash\": None},\n {\"titel\": \"PAW_PBE O 08Apr2002\", \"hash\": None},\n ],\n )\n\n def test_parsing_chemical_shift_calculations(self):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n filepath = self.TEST_FILES_DIR / \"nmr\" / \"cs\" / \"basic\" / \"vasprun.xml.chemical_shift.scstep\"\n vasprun = Vasprun(filepath)\n nestep = len(vasprun.ionic_steps[-1][\"electronic_steps\"])\n self.assertEqual(nestep, 10)\n self.assertTrue(vasprun.converged)\n\n def test_parsing_efg_calcs(self):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n filepath = self.TEST_FILES_DIR / \"nmr\" / \"efg\" / \"AlPO4\" / \"vasprun.xml\"\n vasprun = Vasprun(filepath)\n nestep = len(vasprun.ionic_steps[-1][\"electronic_steps\"])\n self.assertEqual(nestep, 18)\n self.assertTrue(vasprun.converged)\n\n def test_charged_structure(self):\n vpath = self.TEST_FILES_DIR / \"vasprun.charged.xml\"\n potcar_path = self.TEST_FILES_DIR / \"POT_GGA_PAW_PBE\" / \"POTCAR.Si.gz\"\n vasprun = Vasprun(vpath, parse_potcar_file=False)\n vasprun.update_charge_from_potcar(potcar_path)\n self.assertEqual(vasprun.parameters.get(\"NELECT\", 8), 9)\n self.assertEqual(vasprun.structures[0].charge, 1)\n\n vpath = self.TEST_FILES_DIR / \"vasprun.split.charged.xml\"\n potcar_path = self.TEST_FILES_DIR / \"POTCAR.split.charged.gz\"\n vasprun = Vasprun(vpath, parse_potcar_file=False)\n vasprun.update_charge_from_potcar(potcar_path)\n self.assertEqual(vasprun.parameters.get(\"NELECT\", 0), 7)\n self.assertEqual(vasprun.structures[-1].charge, 1)\n\n def test_kpointset_electronvelocities(self):\n vpath = self.TEST_FILES_DIR / \"vasprun.lvel.Si2H.xml\"\n vasprun = Vasprun(vpath, parse_potcar_file=False)\n self.assertEqual(vasprun.eigenvalues[Spin.up].shape[0], len(vasprun.actual_kpoints))\n\n def test_eigenvalue_band_properties_separate_spins(self):\n eig = Vasprun(self.TEST_FILES_DIR / \"vasprun_eig_separate_spins.xml.gz\", separate_spins=True)\n props = eig.eigenvalue_band_properties\n eig2 = Vasprun(self.TEST_FILES_DIR / \"vasprun_eig_separate_spins.xml.gz\", separate_spins=False)\n props2 = eig2.eigenvalue_band_properties\n self.assertAlmostEqual(props[0][0], 2.8772, places=4)\n self.assertAlmostEqual(props[0][1], 1.2810, places=4)\n self.assertAlmostEqual(props[1][0], 3.6741, places=4)\n self.assertAlmostEqual(props[1][1], 1.6225, places=4)\n self.assertAlmostEqual(props[2][0], 0.7969, places=4)\n self.assertAlmostEqual(props[2][1], 0.3415, places=4)\n self.assertAlmostEqual(props2[0], np.min(props[1]) - np.max(props[2]), places=4)\n self.assertEqual(props[3][0], True)\n self.assertEqual(props[3][1], True)\n\n\nclass OutcarTest(PymatgenTest):\n _multiprocess_shared_ = True\n\n def test_init(self):\n for f in [\"OUTCAR\", \"OUTCAR.gz\"]:\n filepath = self.TEST_FILES_DIR / f\n outcar = Outcar(filepath)\n expected_mag = (\n {\"d\": 0.0, \"p\": 0.003, \"s\": 0.002, \"tot\": 0.005},\n {\"d\": 0.798, \"p\": 0.008, \"s\": 0.007, \"tot\": 0.813},\n {\"d\": 0.798, \"p\": 0.008, \"s\": 0.007, \"tot\": 0.813},\n {\"d\": 0.0, \"p\": -0.117, \"s\": 0.005, \"tot\": -0.112},\n {\"d\": 0.0, \"p\": -0.165, \"s\": 0.004, \"tot\": -0.162},\n {\"d\": 0.0, \"p\": -0.117, \"s\": 0.005, \"tot\": -0.112},\n {\"d\": 0.0, \"p\": -0.165, \"s\": 0.004, \"tot\": -0.162},\n )\n expected_chg = (\n {\"p\": 0.154, \"s\": 0.078, \"d\": 0.0, \"tot\": 0.232},\n {\"p\": 0.707, \"s\": 0.463, \"d\": 8.316, \"tot\": 9.486},\n {\"p\": 0.707, \"s\": 0.463, \"d\": 8.316, \"tot\": 9.486},\n {\"p\": 3.388, \"s\": 1.576, \"d\": 0.0, \"tot\": 4.964},\n {\"p\": 3.365, \"s\": 1.582, \"d\": 0.0, \"tot\": 4.947},\n {\"p\": 3.388, \"s\": 1.576, \"d\": 0.0, \"tot\": 4.964},\n {\"p\": 3.365, \"s\": 1.582, \"d\": 0.0, \"tot\": 4.947},\n )\n\n self.assertAlmostEqual(\n outcar.magnetization,\n expected_mag,\n 5,\n \"Wrong magnetization read from Outcar\",\n )\n self.assertAlmostEqual(outcar.charge, expected_chg, 5, \"Wrong charge read from Outcar\")\n self.assertFalse(outcar.is_stopped)\n self.assertEqual(\n outcar.run_stats,\n {\n \"System time (sec)\": 0.938,\n \"Total CPU time used (sec)\": 545.142,\n \"Elapsed time (sec)\": 546.709,\n \"Maximum memory used (kb)\": 0.0,\n \"Average memory used (kb)\": 0.0,\n \"User time (sec)\": 544.204,\n \"cores\": \"8\",\n },\n )\n self.assertAlmostEqual(outcar.efermi, 2.0112)\n self.assertAlmostEqual(outcar.nelect, 44.9999991)\n self.assertAlmostEqual(outcar.total_mag, 0.9999998)\n\n self.assertIsNotNone(outcar.as_dict())\n\n self.assertFalse(outcar.lepsilon)\n\n toten = 0\n for k in outcar.final_energy_contribs.keys():\n toten += outcar.final_energy_contribs[k]\n self.assertAlmostEqual(toten, outcar.final_energy, 6)\n\n def test_stopped_old(self):\n filepath = self.TEST_FILES_DIR / \"OUTCAR.stopped\"\n outcar = Outcar(filepath)\n self.assertTrue(outcar.is_stopped)\n for f in [\"OUTCAR.lepsilon_old_born\", \"OUTCAR.lepsilon_old_born.gz\"]:\n filepath = self.TEST_FILES_DIR / f\n outcar = Outcar(filepath)\n\n self.assertTrue(outcar.lepsilon)\n self.assertAlmostEqual(outcar.dielectric_tensor[0][0], 3.716432)\n self.assertAlmostEqual(outcar.dielectric_tensor[0][1], -0.20464)\n self.assertAlmostEqual(outcar.dielectric_tensor[1][2], -0.20464)\n self.assertAlmostEqual(outcar.dielectric_ionic_tensor[0][0], 0.001419)\n self.assertAlmostEqual(outcar.dielectric_ionic_tensor[0][2], 0.001419)\n self.assertAlmostEqual(outcar.dielectric_ionic_tensor[2][2], 0.001419)\n self.assertAlmostEqual(outcar.piezo_tensor[0][0], 0.52799)\n self.assertAlmostEqual(outcar.piezo_tensor[1][3], 0.35998)\n self.assertAlmostEqual(outcar.piezo_tensor[2][5], 0.35997)\n self.assertAlmostEqual(outcar.piezo_ionic_tensor[0][0], 0.05868)\n self.assertAlmostEqual(outcar.piezo_ionic_tensor[1][3], 0.06241)\n self.assertAlmostEqual(outcar.piezo_ionic_tensor[2][5], 0.06242)\n self.assertAlmostEqual(outcar.born[0][1][2], -0.385)\n self.assertAlmostEqual(outcar.born[1][2][0], 0.36465)\n self.assertAlmostEqual(outcar.internal_strain_tensor[0][0][0], -572.5437, places=4)\n self.assertAlmostEqual(outcar.internal_strain_tensor[0][1][0], 683.2985, places=4)\n self.assertAlmostEqual(outcar.internal_strain_tensor[0][1][3], 73.07059, places=4)\n self.assertAlmostEqual(outcar.internal_strain_tensor[1][0][0], 570.98927, places=4)\n self.assertAlmostEqual(outcar.internal_strain_tensor[1][1][0], -683.68519, places=4)\n self.assertAlmostEqual(outcar.internal_strain_tensor[1][2][2], 570.98927, places=4)\n\n def test_stopped(self):\n filepath = self.TEST_FILES_DIR / \"OUTCAR.stopped\"\n outcar = Outcar(filepath)\n self.assertTrue(outcar.is_stopped)\n for f in [\"OUTCAR.lepsilon\", \"OUTCAR.lepsilon.gz\"]:\n filepath = self.TEST_FILES_DIR / f\n outcar = Outcar(filepath)\n\n self.assertTrue(outcar.lepsilon)\n self.assertAlmostEqual(outcar.dielectric_tensor[0][0], 3.716432)\n self.assertAlmostEqual(outcar.dielectric_tensor[0][1], -0.20464)\n self.assertAlmostEqual(outcar.dielectric_tensor[1][2], -0.20464)\n self.assertAlmostEqual(outcar.dielectric_ionic_tensor[0][0], 0.001419)\n self.assertAlmostEqual(outcar.dielectric_ionic_tensor[0][2], 0.001419)\n self.assertAlmostEqual(outcar.dielectric_ionic_tensor[2][2], 0.001419)\n self.assertAlmostEqual(outcar.piezo_tensor[0][0], 0.52799)\n self.assertAlmostEqual(outcar.piezo_tensor[1][3], 0.35998)\n self.assertAlmostEqual(outcar.piezo_tensor[2][5], 0.35997)\n self.assertAlmostEqual(outcar.piezo_ionic_tensor[0][0], 0.05868)\n self.assertAlmostEqual(outcar.piezo_ionic_tensor[1][3], 0.06241)\n self.assertAlmostEqual(outcar.piezo_ionic_tensor[2][5], 0.06242)\n self.assertAlmostEqual(outcar.born[0][1][2], -0.385)\n self.assertAlmostEqual(outcar.born[1][2][0], 0.36465)\n self.assertAlmostEqual(outcar.internal_strain_tensor[0][0][0], -572.5437, places=4)\n self.assertAlmostEqual(outcar.internal_strain_tensor[0][1][0], 683.2985, places=4)\n self.assertAlmostEqual(outcar.internal_strain_tensor[0][1][3], 73.07059, places=4)\n self.assertAlmostEqual(outcar.internal_strain_tensor[1][0][0], 570.98927, places=4)\n self.assertAlmostEqual(outcar.internal_strain_tensor[1][1][0], -683.68519, places=4)\n self.assertAlmostEqual(outcar.internal_strain_tensor[1][2][2], 570.98927, places=4)\n\n def test_soc(self):\n filepath = self.TEST_FILES_DIR / \"OUTCAR.NiO_SOC.gz\"\n outcar = Outcar(filepath)\n expected_mag = (\n {\n \"s\": Magmom([0.0, 0.0, -0.001]),\n \"p\": Magmom([0.0, 0.0, -0.003]),\n \"d\": Magmom([0.0, 0.0, 1.674]),\n \"tot\": Magmom([0.0, 0.0, 1.671]),\n },\n {\n \"s\": Magmom([0.0, 0.0, 0.001]),\n \"p\": Magmom([0.0, 0.0, 0.003]),\n \"d\": Magmom([0.0, 0.0, -1.674]),\n \"tot\": Magmom([0.0, 0.0, -1.671]),\n },\n {\n \"s\": Magmom([0.0, 0.0, 0.0]),\n \"p\": Magmom([0.0, 0.0, 0.0]),\n \"d\": Magmom([0.0, 0.0, 0.0]),\n \"tot\": Magmom([0.0, 0.0, 0.0]),\n },\n {\n \"s\": Magmom([0.0, 0.0, 0.0]),\n \"p\": Magmom([0.0, 0.0, 0.0]),\n \"d\": Magmom([0.0, 0.0, 0.0]),\n \"tot\": Magmom([0.0, 0.0, 0.0]),\n },\n )\n # test note: Magmom class uses np.allclose() when testing for equality\n # so fine to use assertEqual here\n self.assertEqual(\n outcar.magnetization,\n expected_mag,\n \"Wrong vector magnetization read from Outcar for SOC calculation\",\n )\n\n def test_polarization(self):\n filepath = self.TEST_FILES_DIR / \"OUTCAR.BaTiO3.polar\"\n outcar = Outcar(filepath)\n self.assertEqual(outcar.spin, True)\n self.assertEqual(outcar.noncollinear, False)\n self.assertAlmostEqual(outcar.p_ion[0], 0.0)\n self.assertAlmostEqual(outcar.p_ion[1], 0.0)\n self.assertAlmostEqual(outcar.p_ion[2], -5.56684)\n self.assertAlmostEqual(outcar.p_sp1[0], 2.00068)\n self.assertAlmostEqual(outcar.p_sp2[0], -2.00044)\n self.assertAlmostEqual(outcar.p_elec[0], 0.00024)\n self.assertAlmostEqual(outcar.p_elec[1], 0.00019)\n self.assertAlmostEqual(outcar.p_elec[2], 3.61674)\n\n def test_pseudo_zval(self):\n filepath = self.TEST_FILES_DIR / \"OUTCAR.BaTiO3.polar\"\n outcar = Outcar(filepath)\n self.assertDictEqual({\"Ba\": 10.00, \"Ti\": 10.00, \"O\": 6.00}, outcar.zval_dict)\n\n filepath = self.TEST_FILES_DIR / \"OUTCAR.LaSnNO2.polar\"\n outcar = Outcar(filepath)\n self.assertDictEqual({\"La\": 11.0, \"N\": 5.0, \"O\": 6.0, \"Sn\": 14.0}, outcar.zval_dict)\n\n def test_dielectric(self):\n filepath = self.TEST_FILES_DIR / \"OUTCAR.dielectric\"\n outcar = Outcar(filepath)\n outcar.read_corrections()\n self.assertAlmostEqual(outcar.data[\"dipol_quadrupol_correction\"], 0.03565)\n self.assertAlmostEqual(outcar.final_energy, -797.46760559)\n\n def test_freq_dielectric(self):\n filepath = self.TEST_FILES_DIR / \"OUTCAR.LOPTICS\"\n outcar = Outcar(filepath)\n outcar.read_freq_dielectric()\n self.assertAlmostEqual(outcar.dielectric_energies[0], 0)\n self.assertAlmostEqual(outcar.dielectric_energies[-1], 39.826101)\n self.assertAlmostEqual(outcar.dielectric_tensor_function[0][0, 0], 8.96938800)\n self.assertAlmostEqual(\n outcar.dielectric_tensor_function[-1][0, 0],\n 7.36167000e-01 + 1.53800000e-03j,\n )\n self.assertEqual(len(outcar.dielectric_energies), len(outcar.dielectric_tensor_function))\n np.testing.assert_array_equal(\n outcar.dielectric_tensor_function[0],\n outcar.dielectric_tensor_function[0].transpose(),\n )\n\n plasma_freq = outcar.plasma_frequencies\n self.assertArrayAlmostEqual(plasma_freq[\"intraband\"], np.zeros((3, 3)))\n self.assertArrayAlmostEqual(\n plasma_freq[\"interband\"],\n [\n [367.49, 63.939, 11.976],\n [63.939, 381.155, -24.461],\n [11.976, -24.461, 297.844],\n ],\n )\n\n def test_freq_dielectric_vasp544(self):\n filepath = self.TEST_FILES_DIR / \"OUTCAR.LOPTICS.vasp544\"\n outcar = Outcar(filepath)\n outcar.read_freq_dielectric()\n self.assertAlmostEqual(outcar.dielectric_energies[0], 0)\n self.assertAlmostEqual(outcar.dielectric_energies[-1], 39.63964)\n self.assertAlmostEqual(outcar.dielectric_tensor_function[0][0, 0], 12.769435 + 0j)\n self.assertAlmostEqual(outcar.dielectric_tensor_function[-1][0, 0], 0.828615 + 0.016594j)\n self.assertEqual(len(outcar.dielectric_energies), len(outcar.dielectric_tensor_function))\n np.testing.assert_array_equal(\n outcar.dielectric_tensor_function[0],\n outcar.dielectric_tensor_function[0].transpose(),\n )\n\n def test_parse_sci_notation(self):\n invalid_pattern = \"23535.35 35235.34 325325.3\"\n valid_pattern1 = \" 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00\"\n valid_pattern2 = \" 0.62963E+00 0.15467E+02 0.15467E+02 0.15467E+02-0.30654E-16-0.91612E-16 0.52388E-16\"\n\n self.assertEqual(Outcar._parse_sci_notation(invalid_pattern), [])\n self.assertEqual(Outcar._parse_sci_notation(valid_pattern1), [0, 0, 0, 0, 0, 0, 0])\n self.assertEqual(\n Outcar._parse_sci_notation(valid_pattern2),\n [\n 0.62963,\n 0.15467e02,\n 0.15467e02,\n 0.15467e02,\n -0.30654e-16,\n -0.91612e-16,\n 0.52388e-16,\n ],\n )\n\n def test_read_elastic_tensor(self):\n filepath = self.TEST_FILES_DIR / \"OUTCAR.total_tensor.Li2O.gz\"\n outcar = Outcar(filepath)\n\n outcar.read_elastic_tensor()\n\n self.assertAlmostEqual(outcar.data[\"elastic_tensor\"][0][0], 1986.3391)\n self.assertAlmostEqual(outcar.data[\"elastic_tensor\"][0][1], 187.8324)\n self.assertAlmostEqual(outcar.data[\"elastic_tensor\"][3][3], 586.3034)\n\n def test_read_piezo_tensor(self):\n filepath = self.TEST_FILES_DIR / \"OUTCAR.lepsilon.gz\"\n outcar = Outcar(filepath)\n\n outcar.read_piezo_tensor()\n self.assertAlmostEqual(outcar.data[\"piezo_tensor\"][0][0], 0.52799)\n self.assertAlmostEqual(outcar.data[\"piezo_tensor\"][1][3], 0.35998)\n self.assertAlmostEqual(outcar.data[\"piezo_tensor\"][2][5], 0.35997)\n\n def test_core_state_eigen(self):\n filepath = self.TEST_FILES_DIR / \"OUTCAR.CL\"\n cl = Outcar(filepath).read_core_state_eigen()\n self.assertAlmostEqual(cl[6][\"2s\"][-1], -174.4779)\n filepath = self.TEST_FILES_DIR / \"OUTCAR.icorelevel\"\n outcar = Outcar(filepath)\n cl = outcar.read_core_state_eigen()\n self.assertAlmostEqual(cl[4][\"3d\"][-1], -31.4522)\n\n # test serialization\n outcar.as_dict()\n\n def test_avg_core_poten(self):\n filepath = self.TEST_FILES_DIR / \"OUTCAR.lepsilon\"\n cp = Outcar(filepath).read_avg_core_poten()\n self.assertAlmostEqual(cp[-1][1], -90.0487)\n\n filepath = self.TEST_FILES_DIR / \"OUTCAR\"\n cp = Outcar(filepath).read_avg_core_poten()\n self.assertAlmostEqual(cp[0][6], -73.1068)\n\n filepath = self.TEST_FILES_DIR / \"OUTCAR.bad_core_poten.gz\"\n cp = Outcar(filepath).read_avg_core_poten()\n self.assertAlmostEqual(cp[0][1], -101.5055)\n\n def test_single_atom(self):\n filepath = self.TEST_FILES_DIR / \"OUTCAR.Al\"\n outcar = Outcar(filepath)\n expected_mag = ({\"p\": 0.0, \"s\": 0.0, \"d\": 0.0, \"tot\": 0.0},)\n expected_chg = ({\"p\": 0.343, \"s\": 0.425, \"d\": 0.0, \"tot\": 0.768},)\n\n self.assertAlmostEqual(outcar.magnetization, expected_mag)\n self.assertAlmostEqual(outcar.charge, expected_chg)\n self.assertFalse(outcar.is_stopped)\n self.assertEqual(\n outcar.run_stats,\n {\n \"System time (sec)\": 0.592,\n \"Total CPU time used (sec)\": 50.194,\n \"Elapsed time (sec)\": 52.337,\n \"Maximum memory used (kb)\": 62900.0,\n \"Average memory used (kb)\": 0.0,\n \"User time (sec)\": 49.602,\n \"cores\": \"32\",\n },\n )\n self.assertAlmostEqual(outcar.efermi, 8.0942)\n self.assertAlmostEqual(outcar.nelect, 3)\n self.assertAlmostEqual(outcar.total_mag, 8.2e-06)\n\n self.assertIsNotNone(outcar.as_dict())\n\n def test_chemical_shielding(self):\n filename = self.TEST_FILES_DIR / \"nmr\" / \"cs\" / \"core.diff\" / \"hydromagnesite\" / \"OUTCAR\"\n outcar = Outcar(filename)\n expected_chemical_shielding = [\n [191.9974, 69.5232, 0.6342],\n [195.0808, 68.183, 0.833],\n [192.0389, 69.5762, 0.6329],\n [195.0844, 68.1756, 0.8336],\n [192.005, 69.5289, 0.6339],\n [195.0913, 68.1859, 0.833],\n [192.0237, 69.565, 0.6333],\n [195.0788, 68.1733, 0.8337],\n ]\n\n self.assertAlmostEqual(\n len(outcar.data[\"chemical_shielding\"][\"valence_only\"][20:28]),\n len(expected_chemical_shielding),\n )\n\n self.assertArrayAlmostEqual(\n outcar.data[\"chemical_shielding\"][\"valence_and_core\"][20:28],\n expected_chemical_shielding,\n decimal=5,\n )\n\n def test_chemical_shielding_with_different_core_contribution(self):\n filename = self.TEST_FILES_DIR / \"nmr\" / \"cs\" / \"core.diff\" / \"core.diff.chemical.shifts.OUTCAR\"\n outcar = Outcar(filename)\n c_vo = outcar.data[\"chemical_shielding\"][\"valence_only\"][7]\n for x1, x2 in zip(list(c_vo), [198.7009, 73.7484, 1.0000]):\n self.assertAlmostEqual(x1, x2)\n c_vc = outcar.data[\"chemical_shielding\"][\"valence_and_core\"][7]\n for x1, x2 in zip(list(c_vc), [-1.9406, 73.7484, 1.0000]):\n self.assertAlmostEqual(x1, x2)\n\n def test_cs_raw_tensors(self):\n filename = self.TEST_FILES_DIR / \"nmr\" / \"cs\" / \"core.diff\" / \"core.diff.chemical.shifts.OUTCAR\"\n outcar = Outcar(filename)\n unsym_tensors = outcar.data[\"unsym_cs_tensor\"]\n self.assertEqual(\n unsym_tensors[0],\n [\n [-145.814605, -4.263425, 0.000301],\n [4.263434, -145.812238, -8.7e-05],\n [0.000136, -0.000189, -142.794068],\n ],\n )\n self.assertEqual(\n unsym_tensors[29],\n [\n [287.789318, -53.799325, 30.900024],\n [-53.799571, 225.668117, -17.839598],\n [3.801103, -2.195218, 88.896756],\n ],\n )\n\n def test_cs_g0_contribution(self):\n filename = self.TEST_FILES_DIR / \"nmr\" / \"cs\" / \"core.diff\" / \"core.diff.chemical.shifts.OUTCAR\"\n outcar = Outcar(filename)\n g0_contrib = outcar.data[\"cs_g0_contribution\"]\n self.assertEqual(\n g0_contrib,\n [\n [-8.773535, 9e-06, 1e-06],\n [1.7e-05, -8.773536, -0.0792],\n [-6e-06, -0.008328, -9.320237],\n ],\n )\n\n def test_cs_core_contribution(self):\n filename = self.TEST_FILES_DIR / \"nmr\" / \"cs\" / \"core.diff\" / \"core.diff.chemical.shifts.OUTCAR\"\n outcar = Outcar(filename)\n core_contrib = outcar.data[\"cs_core_contribution\"]\n self.assertEqual(core_contrib, {\"Mg\": -412.8248405, \"C\": -200.5098812, \"O\": -271.0766979})\n\n def test_nmr_efg(self):\n filename = self.TEST_FILES_DIR / \"nmr\" / \"efg\" / \"AlPO4\" / \"OUTCAR\"\n outcar = Outcar(filename)\n expected_efg = [\n {\"eta\": 0.465, \"nuclear_quadrupole_moment\": 146.6, \"cq\": -5.573},\n {\"eta\": 0.465, \"nuclear_quadrupole_moment\": 146.6, \"cq\": -5.573},\n {\"eta\": 0.137, \"nuclear_quadrupole_moment\": 146.6, \"cq\": 6.327},\n {\"eta\": 0.137, \"nuclear_quadrupole_moment\": 146.6, \"cq\": 6.327},\n {\"eta\": 0.112, \"nuclear_quadrupole_moment\": 146.6, \"cq\": -7.453},\n {\"eta\": 0.112, \"nuclear_quadrupole_moment\": 146.6, \"cq\": -7.453},\n {\"eta\": 0.42, \"nuclear_quadrupole_moment\": 146.6, \"cq\": -5.58},\n {\"eta\": 0.42, \"nuclear_quadrupole_moment\": 146.6, \"cq\": -5.58},\n ]\n self.assertEqual(len(outcar.data[\"efg\"][2:10]), len(expected_efg))\n for e1, e2 in zip(outcar.data[\"efg\"][2:10], expected_efg):\n for k in e1.keys():\n self.assertAlmostEqual(e1[k], e2[k], places=5)\n\n exepected_tensors = [\n [[11.11, 1.371, 2.652], [1.371, 3.635, -3.572], [2.652, -3.572, -14.746]],\n [[11.11, -1.371, 2.652], [-1.371, 3.635, 3.572], [2.652, 3.572, -14.746]],\n [[-3.098, 6.511, 7.732], [6.511, 1.419, 11.445], [7.732, 11.445, 1.678]],\n [\n [-3.098, -6.511, 7.732],\n [-6.511, 1.419, -11.445],\n [7.732, -11.445, 1.678],\n ],\n [\n [2.344, -10.775, -7.006],\n [-10.775, -7.152, -11.309],\n [-7.006, -11.309, 4.808],\n ],\n [\n [2.344, 10.775, -7.006],\n [10.775, -7.152, 11.309],\n [-7.006, 11.309, 4.808],\n ],\n [[2.404, -0.588, -6.83], [-0.588, 10.435, 3.159], [-6.83, 3.159, -12.839]],\n [[2.404, 0.588, -6.83], [0.588, 10.435, -3.159], [-6.83, -3.159, -12.839]],\n ]\n\n self.assertEqual(len(outcar.data[\"unsym_efg_tensor\"][2:10]), len(exepected_tensors))\n for e1, e2 in zip(outcar.data[\"unsym_efg_tensor\"][2:10], exepected_tensors):\n self.assertArrayAlmostEqual(e1, e2)\n\n def test_read_fermi_contact_shift(self):\n filepath = self.TEST_FILES_DIR / \"OUTCAR_fc\"\n outcar = Outcar(filepath)\n outcar.read_fermi_contact_shift()\n self.assertAlmostEqual(outcar.data[\"fermi_contact_shift\"][\"fch\"][0][0], -0.002)\n self.assertAlmostEqual(outcar.data[\"fermi_contact_shift\"][\"th\"][0][0], -0.052)\n self.assertAlmostEqual(outcar.data[\"fermi_contact_shift\"][\"dh\"][0][0], 0.0)\n\n def test_drift(self):\n outcar = Outcar(self.TEST_FILES_DIR / \"OUTCAR\")\n self.assertEqual(len(outcar.drift), 5)\n self.assertAlmostEqual(np.sum(outcar.drift), 0)\n\n outcar = Outcar(self.TEST_FILES_DIR / \"OUTCAR.CL\")\n self.assertEqual(len(outcar.drift), 79)\n self.assertAlmostEqual(np.sum(outcar.drift), 0.448010)\n\n def test_electrostatic_potential(self):\n\n outcar = Outcar(self.TEST_FILES_DIR / \"OUTCAR\")\n self.assertEqual(outcar.ngf, [54, 30, 54])\n self.assertTrue(np.allclose(outcar.sampling_radii, [0.9748, 0.9791, 0.7215]))\n self.assertTrue(\n np.allclose(\n outcar.electrostatic_potential,\n [-26.0704, -45.5046, -45.5046, -72.9539, -73.0621, -72.9539, -73.0621],\n )\n )\n\n def test_mag_electrostatic_error(self):\n outcar = Outcar(self.TEST_FILES_DIR / \"OUTCAR.electrostaticerror.gz\")\n self.assertEqual(\n outcar.electrostatic_potential,\n [\n -21.1667,\n -19.6865,\n -22.3983,\n -22.3307,\n -20.5213,\n -20.9292,\n -21.5063,\n -21.3554,\n -21.74,\n -21.7018,\n -20.3422,\n -20.6128,\n -21.4405,\n -21.0022,\n -21.975,\n -21.915,\n -21.0156,\n -21.9027,\n -22.3712,\n -21.5816,\n -21.8535,\n -20.5061,\n -22.2474,\n -22.1904,\n -22.2203,\n -20.1727,\n -21.1068,\n -20.1669,\n -22.1272,\n -21.3446,\n -82.4717,\n -83.035,\n -81.8289,\n -82.5957,\n -81.7813,\n -82.5011,\n -82.6098,\n -82.2885,\n -81.606,\n -99.1621,\n -99.3146,\n -99.1742,\n -99.4728,\n -100.2139,\n -99.852,\n -99.3575,\n -99.4135,\n -98.9092,\n -99.8867,\n -99.3707,\n -99.0794,\n -98.8376,\n -99.3656,\n -98.6474,\n -99.3264,\n -98.844,\n -99.074,\n -98.9354,\n -99.1643,\n -99.2412,\n -68.7667,\n -68.2528,\n -66.7326,\n -67.7113,\n -69.2228,\n -67.014,\n -69.1456,\n -67.3151,\n -68.2625,\n -67.6156,\n -69.8112,\n -68.9266,\n -67.8286,\n -69.3289,\n -68.7017,\n -67.2834,\n -68.4665,\n -68.0188,\n -67.7083,\n -69.7195,\n -67.4078,\n -67.9646,\n -68.584,\n -69.2387,\n -69.7822,\n -67.0701,\n -67.8236,\n -68.2468,\n -68.6533,\n -68.3218,\n -67.5923,\n -69.1266,\n -68.4615,\n -68.302,\n -67.999,\n -68.6709,\n -68.9973,\n -67.4147,\n -68.4463,\n -68.0899,\n -67.665,\n -69.6705,\n -68.6433,\n -68.4288,\n -66.9027,\n -67.3211,\n -68.604,\n -69.1299,\n -67.5565,\n -69.0845,\n -67.4289,\n -66.6864,\n -67.6484,\n -67.9783,\n -67.7661,\n -66.9797,\n -67.8007,\n -68.3194,\n -69.3671,\n -67.2708,\n ],\n )\n\n def test_onsite_density_matrix(self):\n outcar = Outcar(self.TEST_FILES_DIR / \"OUTCAR.LinearResponseU.gz\")\n matrices = outcar.data[\"onsite_density_matrices\"]\n self.assertEqual(matrices[0][Spin.up][0][0], 1.0227)\n self.assertEqual(len(matrices[0][Spin.up]), 5)\n self.assertEqual(len(matrices[0][Spin.up][0]), 5)\n self.assertTrue(\"onsite_density_matrices\" in outcar.as_dict())\n outcar = Outcar(self.TEST_FILES_DIR / \"OUTCAR_merged_numbers\")\n matrices = outcar.data[\"onsite_density_matrices\"]\n self.assertEqual(matrices[0][Spin.up][0][-1], 0.0)\n self.assertEqual(len(matrices[0][Spin.up]), 7)\n self.assertEqual(len(matrices[0][Spin.up][0]), 7)\n self.assertTrue(\"onsite_density_matrices\" in outcar.as_dict())\n outcar = Outcar(self.TEST_FILES_DIR / \"OUTCAR_merged_numbers2\")\n self.assertTrue(\"onsite_density_matrices\" in outcar.as_dict())\n\n def test_nplwvs(self):\n outcar = Outcar(self.TEST_FILES_DIR / \"OUTCAR\")\n self.assertEqual(outcar.data[\"nplwv\"], [[34560]])\n self.assertEqual(\n outcar.data[\"nplwvs_at_kpoints\"],\n [\n 1719,\n 1714,\n 1722,\n 1728,\n 1722,\n 1726,\n 1722,\n 1720,\n 1717,\n 1724,\n 1715,\n 1724,\n 1726,\n 1724,\n 1728,\n 1715,\n 1722,\n 1715,\n 1726,\n 1730,\n 1730,\n 1715,\n 1716,\n 1729,\n 1727,\n 1723,\n 1721,\n 1712,\n 1723,\n 1719,\n 1717,\n 1717,\n 1724,\n 1719,\n 1719,\n 1727,\n 1726,\n 1730,\n 1719,\n 1720,\n 1718,\n 1717,\n 1722,\n 1719,\n 1709,\n 1714,\n 1724,\n 1726,\n 1718,\n 1713,\n 1720,\n 1713,\n 1711,\n 1713,\n 1715,\n 1717,\n 1728,\n 1726,\n 1712,\n 1722,\n 1714,\n 1713,\n 1717,\n 1714,\n 1714,\n 1717,\n 1712,\n 1710,\n 1721,\n 1722,\n 1724,\n 1720,\n 1726,\n 1719,\n 1722,\n 1714,\n ],\n )\n outcar = Outcar(self.TEST_FILES_DIR / \"OUTCAR.CL\")\n self.assertEqual(outcar.data[\"nplwv\"], [[None]])\n self.assertEqual(outcar.data[\"nplwvs_at_kpoints\"], [85687])\n\n def test_vasp620_format(self):\n filepath = self.TEST_FILES_DIR / \"OUTCAR.vasp.6.2.0\"\n outcar = Outcar(filepath)\n self.assertEqual(outcar.run_stats[\"Average memory used (kb)\"], None)\n\n\nclass BSVasprunTest(PymatgenTest):\n _multiprocess_shared_ = True\n\n def test_get_band_structure(self):\n filepath = self.TEST_FILES_DIR / \"vasprun_Si_bands.xml\"\n vasprun = BSVasprun(filepath, parse_potcar_file=False)\n bs = vasprun.get_band_structure(kpoints_filename=self.TEST_FILES_DIR / \"KPOINTS_Si_bands\")\n cbm = bs.get_cbm()\n vbm = bs.get_vbm()\n self.assertEqual(cbm[\"kpoint_index\"], [13], \"wrong cbm kpoint index\")\n self.assertAlmostEqual(cbm[\"energy\"], 6.2301, \"wrong cbm energy\")\n self.assertEqual(cbm[\"band_index\"], {Spin.up: [4], Spin.down: [4]}, \"wrong cbm bands\")\n self.assertEqual(vbm[\"kpoint_index\"], [0, 63, 64])\n self.assertAlmostEqual(vbm[\"energy\"], 5.6158, \"wrong vbm energy\")\n self.assertEqual(\n vbm[\"band_index\"],\n {Spin.up: [1, 2, 3], Spin.down: [1, 2, 3]},\n \"wrong vbm bands\",\n )\n self.assertEqual(vbm[\"kpoint\"].label, \"\\\\Gamma\", \"wrong vbm label\")\n self.assertEqual(cbm[\"kpoint\"].label, None, \"wrong cbm label\")\n d = vasprun.as_dict()\n self.assertIn(\"eigenvalues\", d[\"output\"])\n\n\nclass OszicarTest(PymatgenTest):\n def test_init(self):\n filepath = self.TEST_FILES_DIR / \"OSZICAR\"\n oszicar = Oszicar(filepath)\n self.assertEqual(len(oszicar.electronic_steps), len(oszicar.ionic_steps))\n self.assertEqual(len(oszicar.all_energies), 60)\n self.assertAlmostEqual(oszicar.final_energy, -526.63928)\n\n\nclass LocpotTest(PymatgenTest):\n def test_init(self):\n filepath = self.TEST_FILES_DIR / \"LOCPOT\"\n locpot = Locpot.from_file(filepath)\n self.assertAlmostEqual(-217.05226954, sum(locpot.get_average_along_axis(0)))\n self.assertAlmostEqual(locpot.get_axis_grid(0)[-1], 2.87629, 2)\n self.assertAlmostEqual(locpot.get_axis_grid(1)[-1], 2.87629, 2)\n self.assertAlmostEqual(locpot.get_axis_grid(2)[-1], 2.87629, 2)\n\n\nclass ChgcarTest(PymatgenTest):\n @classmethod\n def setUpClass(cls):\n filepath = cls.TEST_FILES_DIR / \"CHGCAR.nospin\"\n cls.chgcar_no_spin = Chgcar.from_file(filepath)\n\n filepath = cls.TEST_FILES_DIR / \"CHGCAR.spin\"\n cls.chgcar_spin = Chgcar.from_file(filepath)\n\n filepath = cls.TEST_FILES_DIR / \"CHGCAR.Fe3O4\"\n cls.chgcar_fe3o4 = Chgcar.from_file(filepath)\n\n filepath = cls.TEST_FILES_DIR / \"CHGCAR.NiO_SOC.gz\"\n cls.chgcar_NiO_SOC = Chgcar.from_file(filepath)\n\n def test_init(self):\n self.assertAlmostEqual(self.chgcar_no_spin.get_integrated_diff(0, 2)[0, 1], 0)\n self.assertAlmostEqual(self.chgcar_spin.get_integrated_diff(0, 1)[0, 1], -0.0043896932237534022)\n # test sum\n chgcar = self.chgcar_spin + self.chgcar_spin\n self.assertAlmostEqual(chgcar.get_integrated_diff(0, 1)[0, 1], -0.0043896932237534022 * 2)\n\n chgcar = self.chgcar_spin - self.chgcar_spin\n self.assertAlmostEqual(chgcar.get_integrated_diff(0, 1)[0, 1], 0)\n\n ans = [1.56472768, 3.25985108, 3.49205728, 3.66275028, 3.8045896, 5.10813352]\n myans = self.chgcar_fe3o4.get_integrated_diff(0, 3, 6)\n self.assertTrue(np.allclose(myans[:, 1], ans))\n\n def test_write(self):\n self.chgcar_spin.write_file(\"CHGCAR_pmg\")\n with open(\"CHGCAR_pmg\") as f:\n for i, line in enumerate(f):\n if i == 22130:\n self.assertEqual(\"augmentation occupancies 1 15\\n\", line)\n if i == 44255:\n self.assertEqual(\"augmentation occupancies 1 15\\n\", line)\n os.remove(\"CHGCAR_pmg\")\n\n def test_soc_chgcar(self):\n self.assertEqual(\n set(self.chgcar_NiO_SOC.data.keys()),\n {\"total\", \"diff_x\", \"diff_y\", \"diff_z\", \"diff\"},\n )\n self.assertTrue(self.chgcar_NiO_SOC.is_soc)\n self.assertEqual(\n self.chgcar_NiO_SOC.data[\"diff\"].shape,\n self.chgcar_NiO_SOC.data[\"diff_y\"].shape,\n )\n\n # check our construction of chg.data['diff'] makes sense\n # this has been checked visually too and seems reasonable\n self.assertEqual(\n abs(self.chgcar_NiO_SOC.data[\"diff\"][0][0][0]),\n np.linalg.norm(\n [\n self.chgcar_NiO_SOC.data[\"diff_x\"][0][0][0],\n self.chgcar_NiO_SOC.data[\"diff_y\"][0][0][0],\n self.chgcar_NiO_SOC.data[\"diff_z\"][0][0][0],\n ]\n ),\n )\n\n # and that the net magnetization is about zero\n # note: we get ~ 0.08 here, seems a little high compared to\n # vasp output, but might be due to chgcar limitations?\n self.assertAlmostEqual(self.chgcar_NiO_SOC.net_magnetization, 0.0, places=0)\n\n self.chgcar_NiO_SOC.write_file(\"CHGCAR_pmg_soc\")\n chg_from_file = Chgcar.from_file(\"CHGCAR_pmg_soc\")\n self.assertTrue(chg_from_file.is_soc)\n os.remove(\"CHGCAR_pmg_soc\")\n\n def test_hdf5(self):\n chgcar = Chgcar.from_file(self.TEST_FILES_DIR / \"CHGCAR.NiO_SOC.gz\")\n chgcar.to_hdf5(\"chgcar_test.hdf5\")\n import h5py\n\n with h5py.File(\"chgcar_test.hdf5\", \"r\") as f:\n self.assertArrayAlmostEqual(np.array(f[\"vdata\"][\"total\"]), chgcar.data[\"total\"])\n self.assertArrayAlmostEqual(np.array(f[\"vdata\"][\"diff\"]), chgcar.data[\"diff\"])\n self.assertArrayAlmostEqual(np.array(f[\"lattice\"]), chgcar.structure.lattice.matrix)\n self.assertArrayAlmostEqual(np.array(f[\"fcoords\"]), chgcar.structure.frac_coords)\n for z in f[\"Z\"]:\n self.assertIn(z, [Element.Ni.Z, Element.O.Z])\n\n for sp in f[\"species\"]:\n self.assertIn(sp, [\"Ni\", \"O\"])\n\n chgcar2 = Chgcar.from_hdf5(\"chgcar_test.hdf5\")\n self.assertArrayAlmostEqual(chgcar2.data[\"total\"], chgcar.data[\"total\"])\n os.remove(\"chgcar_test.hdf5\")\n\n def test_spin_data(self):\n d = self.chgcar_spin.spin_data\n for k, v in d.items():\n self.assertEqual(v.shape, (48, 48, 48))\n\n def test_add(self):\n chgcar_sum = self.chgcar_spin + self.chgcar_spin\n self.assertArrayAlmostEqual(chgcar_sum.data[\"total\"], self.chgcar_spin.data[\"total\"] * 2)\n chgcar_copy = self.chgcar_spin.copy()\n chgcar_copy.structure = self.get_structure(\"Li2O\")\n with warnings.catch_warnings(record=True) as w:\n # Cause all warnings to always be triggered.\n warnings.simplefilter(\"always\")\n # Trigger a warning.\n chgcar_sum = chgcar_copy + self.chgcar_spin\n # Verify some things\n assert len(w) == 1\n assert \"Structures are different. Make sure you know what you are doing...\" in str(w[-1].message)\n self.assertRaises(ValueError, self.chgcar_spin.__add__, self.chgcar_fe3o4)\n self.assertRaises(ValueError, self.chgcar_spin.__add__, self.chgcar_no_spin)\n\n def test_as_dict_and_from_dict(self):\n d = self.chgcar_NiO_SOC.as_dict()\n chgcar_from_dict = Chgcar.from_dict(d)\n self.assertArrayAlmostEqual(self.chgcar_NiO_SOC.data[\"total\"], chgcar_from_dict.data[\"total\"])\n self.assertArrayAlmostEqual(\n self.chgcar_NiO_SOC.structure.lattice.matrix,\n chgcar_from_dict.structure.lattice.matrix,\n )\n\n\nclass ElfcarTest(PymatgenTest):\n def test_init(self):\n elfcar = Elfcar.from_file(self.TEST_FILES_DIR / \"ELFCAR.gz\")\n self.assertAlmostEqual(0.19076207645194002, np.mean(elfcar.data[\"total\"]))\n self.assertAlmostEqual(0.19076046677910055, np.mean(elfcar.data[\"diff\"]))\n reconstituted = Elfcar.from_dict(elfcar.as_dict())\n self.assertEqual(elfcar.data, reconstituted.data)\n self.assertEqual(elfcar.poscar.structure, reconstituted.poscar.structure)\n\n def test_alpha(self):\n elfcar = Elfcar.from_file(self.TEST_FILES_DIR / \"ELFCAR.gz\")\n alpha = elfcar.get_alpha()\n self.assertAlmostEqual(2.936678808979031, np.median(alpha.data[\"total\"]))\n\n def test_interpolation(self):\n elfcar = Elfcar.from_file(self.TEST_FILES_DIR / \"ELFCAR.gz\")\n self.assertAlmostEqual(0.0918471, elfcar.value_at(0.4, 0.5, 0.6))\n self.assertEqual(100, len(elfcar.linear_slice([0.0, 0.0, 0.0], [1.0, 1.0, 1.0])))\n\n\nclass ProcarTest(PymatgenTest):\n _multiprocess_shared_ = True\n\n def test_init(self):\n filepath = self.TEST_FILES_DIR / \"PROCAR.simple\"\n p = Procar(filepath)\n self.assertAlmostEqual(p.get_occupation(0, \"d\")[Spin.up], 0)\n self.assertAlmostEqual(p.get_occupation(0, \"s\")[Spin.up], 0.35381249999999997)\n self.assertAlmostEqual(p.get_occupation(0, \"p\")[Spin.up], 1.19540625)\n self.assertRaises(ValueError, p.get_occupation, 1, \"m\")\n self.assertEqual(p.nbands, 10)\n self.assertEqual(p.nkpoints, 10)\n self.assertEqual(p.nions, 3)\n lat = Lattice.cubic(3.0)\n s = Structure(\n lat,\n [\"Li\", \"Na\", \"K\"],\n [[0.0, 0.0, 0.0], [0.25, 0.25, 0.25], [0.75, 0.75, 0.75]],\n )\n d = p.get_projection_on_elements(s)\n self.assertAlmostEqual(d[Spin.up][2][2], {\"Na\": 0.042, \"K\": 0.646, \"Li\": 0.042})\n filepath = self.TEST_FILES_DIR / \"PROCAR\"\n p = Procar(filepath)\n self.assertAlmostEqual(p.get_occupation(0, \"dxy\")[Spin.up], 0.96214813853000025)\n self.assertAlmostEqual(p.get_occupation(0, \"dxy\")[Spin.down], 0.85796295426000124)\n\n def test_phase_factors(self):\n filepath = self.TEST_FILES_DIR / \"PROCAR.phase\"\n p = Procar(filepath)\n self.assertAlmostEqual(p.phase_factors[Spin.up][0, 0, 0, 0], -0.746 + 0.099j)\n self.assertAlmostEqual(p.phase_factors[Spin.down][0, 0, 0, 0], 0.372 - 0.654j)\n\n # Two Li should have same phase factor.\n self.assertAlmostEqual(p.phase_factors[Spin.up][0, 0, 0, 0], p.phase_factors[Spin.up][0, 0, 1, 0])\n self.assertAlmostEqual(p.phase_factors[Spin.up][0, 0, 2, 0], -0.053 + 0.007j)\n self.assertAlmostEqual(p.phase_factors[Spin.down][0, 0, 2, 0], 0.027 - 0.047j)\n\n # new style phase factors (VASP 5.4.4+)\n filepath = self.TEST_FILES_DIR / \"PROCAR.new_format_5.4.4\"\n p = Procar(filepath)\n self.assertAlmostEqual(p.phase_factors[Spin.up][0, 0, 0, 0], -0.13 + 0.199j)\n\n\nclass XdatcarTest(PymatgenTest):\n def test_init(self):\n filepath = self.TEST_FILES_DIR / \"XDATCAR_4\"\n x = Xdatcar(filepath)\n structures = x.structures\n self.assertEqual(len(structures), 4)\n for s in structures:\n self.assertEqual(s.formula, \"Li2 O1\")\n\n filepath = self.TEST_FILES_DIR / \"XDATCAR_5\"\n x = Xdatcar(filepath)\n structures = x.structures\n self.assertEqual(len(structures), 4)\n for s in structures:\n self.assertEqual(s.formula, \"Li2 O1\")\n\n x.concatenate(self.TEST_FILES_DIR / \"XDATCAR_4\")\n self.assertEqual(len(x.structures), 8)\n self.assertIsNotNone(x.get_string())\n\n filepath = self.TEST_FILES_DIR / \"XDATCAR_6\"\n x = Xdatcar(filepath)\n structures = x.structures\n\n self.assertNotEqual(structures[0].lattice, structures[-1].lattice)\n\n\nclass DynmatTest(PymatgenTest):\n def test_init(self):\n # nosetests pymatgen/io/vasp/tests/test_outputs.py:DynmatTest.test_init\n filepath = self.TEST_FILES_DIR / \"DYNMAT\"\n d = Dynmat(filepath)\n self.assertEqual(d.nspecs, 2)\n self.assertEqual(d.natoms, 6)\n self.assertEqual(d.ndisps, 3)\n self.assertTrue(np.allclose(d.masses, [63.546, 196.966]))\n self.assertTrue(4 in d.data)\n self.assertTrue(2 in d.data[4])\n self.assertTrue(np.allclose(d.data[4][2][\"dispvec\"], [0.0, 0.05, 0.0]))\n self.assertTrue(np.allclose(d.data[4][2][\"dynmat\"][3], [0.055046, -0.298080, 0.0]))\n # TODO: test get_phonon_frequencies once cross-checked\n\n\nclass WavecarTest(PymatgenTest):\n _multiprocess_shared_ = True\n\n def setUp(self):\n a = np.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]])\n self.vol = np.dot(a[0, :], np.cross(a[1, :], a[2, :]))\n b = np.array(\n [\n np.cross(a[1, :], a[2, :]),\n np.cross(a[2, :], a[0, :]),\n np.cross(a[0, :], a[1, :]),\n ]\n )\n self.b = 2 * np.pi * b / self.vol\n self.a = a\n self.w = Wavecar(self.TEST_FILES_DIR / \"WAVECAR.N2\")\n self.wH2 = Wavecar(self.TEST_FILES_DIR / \"WAVECAR.H2_low_symm\")\n self.wH2_gamma = Wavecar(self.TEST_FILES_DIR / \"WAVECAR.H2_low_symm.gamma\")\n self.w_ncl = Wavecar(self.TEST_FILES_DIR / \"WAVECAR.H2.ncl\")\n\n def test_standard(self):\n w = self.w\n a = np.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]])\n vol = np.dot(a[0, :], np.cross(a[1, :], a[2, :]))\n b = np.array(\n [\n np.cross(a[1, :], a[2, :]),\n np.cross(a[2, :], a[0, :]),\n np.cross(a[0, :], a[1, :]),\n ]\n )\n b = 2 * np.pi * b / vol\n\n self.assertEqual(w.filename, self.TEST_FILES_DIR / \"WAVECAR.N2\")\n self.assertAlmostEqual(w.efermi, -5.7232, places=4)\n self.assertEqual(w.encut, 25)\n self.assertEqual(w.nb, 9)\n self.assertEqual(w.nk, 1)\n self.assertTrue(np.allclose(w.a, a))\n self.assertTrue(np.allclose(w.b, b))\n self.assertAlmostEqual(w.vol, vol)\n self.assertEqual(len(w.kpoints), w.nk)\n self.assertEqual(len(w.coeffs), w.nk)\n self.assertEqual(len(w.coeffs[0]), w.nb)\n self.assertEqual(len(w.band_energy), w.nk)\n self.assertEqual(w.band_energy[0].shape, (w.nb, 3))\n self.assertLessEqual(len(w.Gpoints[0]), 257)\n for k in range(w.nk):\n for b in range(w.nb):\n self.assertEqual(len(w.coeffs[k][b]), len(w.Gpoints[k]))\n\n with self.assertRaises(ValueError):\n Wavecar(self.TEST_FILES_DIR / \"WAVECAR.N2.malformed\")\n\n with self.assertRaises(ValueError):\n Wavecar(self.TEST_FILES_DIR / \"WAVECAR.N2\", vasp_type=\"poop\")\n\n with self.assertRaises(ValueError):\n Wavecar(self.TEST_FILES_DIR / \"WAVECAR.N2\", vasp_type=\"g\")\n\n with self.assertRaises(ValueError):\n Wavecar(self.TEST_FILES_DIR / \"WAVECAR.N2\", vasp_type=\"n\")\n\n import sys\n from io import StringIO\n\n saved_stdout = sys.stdout\n try:\n out = StringIO()\n sys.stdout = out\n Wavecar(self.TEST_FILES_DIR / \"WAVECAR.N2\", verbose=True)\n self.assertNotEqual(out.getvalue().strip(), \"\")\n finally:\n sys.stdout = saved_stdout\n\n def test_n2_45210(self):\n w = Wavecar(self.TEST_FILES_DIR / \"WAVECAR.N2.45210\")\n self.assertEqual(w.filename, self.TEST_FILES_DIR / \"WAVECAR.N2.45210\")\n self.assertAlmostEqual(w.efermi, -5.7232, places=4)\n self.assertEqual(w.encut, 25)\n self.assertEqual(w.nb, 9)\n self.assertEqual(w.nk, 1)\n self.assertTrue(np.allclose(w.a, self.a))\n self.assertTrue(np.allclose(w.b, self.b))\n self.assertAlmostEqual(w.vol, self.vol)\n self.assertEqual(len(w.kpoints), w.nk)\n self.assertEqual(len(w.coeffs), w.nk)\n self.assertEqual(len(w.coeffs[0]), w.nb)\n self.assertEqual(len(w.band_energy), w.nk)\n self.assertEqual(w.band_energy[0].shape, (w.nb, 3))\n self.assertLessEqual(len(w.Gpoints[0]), 257)\n\n def test_n2_spin(self):\n w = Wavecar(self.TEST_FILES_DIR / \"WAVECAR.N2.spin\")\n self.assertEqual(len(w.coeffs), 2)\n self.assertEqual(len(w.band_energy), 2)\n self.assertEqual(len(w.kpoints), w.nk)\n self.assertEqual(len(w.Gpoints), w.nk)\n self.assertEqual(len(w.coeffs[0][0]), w.nb)\n self.assertEqual(len(w.band_energy[0]), w.nk)\n\n temp_ggp = Wavecar._generate_G_points\n try:\n Wavecar._generate_G_points = lambda x, y, gamma: []\n with self.assertRaises(ValueError):\n Wavecar(self.TEST_FILES_DIR / \"WAVECAR.N2\")\n finally:\n Wavecar._generate_G_points = temp_ggp\n\n def test__generate_nbmax(self):\n self.w._generate_nbmax()\n self.assertEqual(self.w._nbmax.tolist(), [5, 5, 5])\n\n def test__generate_G_points(self):\n for k in range(self.w.nk):\n kp = self.w.kpoints[k]\n self.assertLessEqual(len(self.w._generate_G_points(kp)), 257)\n\n def test_evaluate_wavefunc(self):\n self.w.Gpoints.append(np.array([0, 0, 0]))\n self.w.kpoints.append(np.array([0, 0, 0]))\n self.w.coeffs.append([[1 + 1j]])\n self.assertAlmostEqual(\n self.w.evaluate_wavefunc(-1, -1, [0, 0, 0]),\n (1 + 1j) / np.sqrt(self.vol),\n places=4,\n )\n self.assertAlmostEqual(\n self.w.evaluate_wavefunc(0, 0, [0, 0, 0]),\n np.sum(self.w.coeffs[0][0]) / np.sqrt(self.vol),\n places=4,\n )\n w = Wavecar(self.TEST_FILES_DIR / \"WAVECAR.N2.spin\")\n w.Gpoints.append(np.array([0, 0, 0]))\n w.kpoints.append(np.array([0, 0, 0]))\n w.coeffs[0].append([[1 + 1j]])\n self.assertAlmostEqual(\n w.evaluate_wavefunc(-1, -1, [0, 0, 0]),\n (1 + 1j) / np.sqrt(self.vol),\n places=4,\n )\n\n def test_fft_mesh_basic(self):\n mesh = self.w.fft_mesh(0, 5)\n ind = np.argmax(np.abs(mesh))\n self.assertEqual(np.unravel_index(ind, mesh.shape), (14, 1, 1))\n self.assertEqual(mesh[tuple((self.w.ng / 2).astype(np.int_))], 0j)\n mesh = self.w.fft_mesh(0, 5, shift=False)\n ind = np.argmax(np.abs(mesh))\n self.assertEqual(np.unravel_index(ind, mesh.shape), (6, 8, 8))\n self.assertEqual(mesh[0, 0, 0], 0j)\n\n def test_fft_mesh_advanced(self):\n ik = 0\n ib = 0\n mesh = self.wH2.fft_mesh(ik, ib)\n mesh_gamma = self.wH2_gamma.fft_mesh(ik, ib)\n mesh_ncl = self.w_ncl.fft_mesh(ik, ib)\n\n # check equality of plane-wave coefficients\n ind_max = np.unravel_index(np.argmax(np.abs(mesh)), mesh.shape)\n phase = mesh[ind_max] / mesh_gamma[ind_max]\n self.assertLessEqual(np.max(np.abs(mesh - phase * mesh_gamma)), 1.0e-6)\n\n # transform to real space for further checking\n mesh = np.fft.ifftn(mesh)\n mesh_gamma = np.fft.ifftn(mesh_gamma)\n mesh_ncl = np.fft.ifftn(mesh_ncl)\n\n # check equality in real space for regular vs. gamma only\n ind_max = np.unravel_index(np.argmax(np.abs(mesh)), mesh.shape)\n phase = mesh[ind_max] / mesh_gamma[ind_max]\n self.assertLessEqual(np.max(np.abs(mesh - phase * mesh_gamma)), 1.0e-6)\n\n # spot check some points in real space\n p1 = (\n int(mesh.shape[0] / 2),\n int(mesh.shape[1] / 2) - 1,\n int(mesh.shape[2] / 2) - 2,\n )\n p2 = (p1[0] + 1, p1[1], p1[2])\n c = np.array([[5, 0, 0], [0, 4, 0], [0, 0, 6]]) # this needs to match POSCAR, which we don't have\n r1 = np.dot(np.array(p1) / mesh.shape, c)\n r2 = np.dot(np.array(p2) / mesh.shape, c)\n\n # check equality of FFT and slow FT for regular mesh (ratio, to account for normalization)\n v1 = self.wH2.evaluate_wavefunc(ik, ib, r1)\n v2 = self.wH2.evaluate_wavefunc(ik, ib, r2)\n self.assertAlmostEqual(np.abs(mesh[p1]) / np.abs(mesh[p2]), np.abs(v1) / np.abs(v2), places=6)\n\n # spot check one value that we happen to know from reference run\n self.assertAlmostEqual(v1, -0.01947068011502887 + 0.23340228099620275j, places=8)\n\n # check equality of FFT and slow FT for gamma-only mesh (ratio again)\n v1_gamma = self.wH2_gamma.evaluate_wavefunc(ik, ib, r1)\n v2_gamma = self.wH2_gamma.evaluate_wavefunc(ik, ib, r2)\n self.assertAlmostEqual(\n np.abs(mesh_gamma[p1]) / np.abs(mesh_gamma[p2]),\n np.abs(v1_gamma) / np.abs(v2_gamma),\n places=6,\n )\n\n # check equality of FFT and slow FT for ncl mesh (ratio again)\n v1_ncl = self.w_ncl.evaluate_wavefunc(ik, ib, r1)\n v2_ncl = self.w_ncl.evaluate_wavefunc(ik, ib, r2)\n self.assertAlmostEqual(\n np.abs(mesh_ncl[p1]) / np.abs(mesh_ncl[p2]),\n np.abs(v1_ncl) / np.abs(v2_ncl),\n places=6,\n )\n\n def test_get_parchg(self):\n poscar = Poscar.from_file(self.TEST_FILES_DIR / \"POSCAR\")\n\n w = self.w\n c = w.get_parchg(poscar, 0, 0, spin=0, phase=False)\n self.assertTrue(\"total\" in c.data)\n self.assertTrue(\"diff\" not in c.data)\n self.assertEqual(np.prod(c.data[\"total\"].shape), np.prod(w.ng * 2))\n self.assertTrue(np.all(c.data[\"total\"] > 0.0))\n\n c = w.get_parchg(poscar, 0, 0, spin=0, phase=True)\n self.assertTrue(\"total\" in c.data)\n self.assertTrue(\"diff\" not in c.data)\n self.assertEqual(np.prod(c.data[\"total\"].shape), np.prod(w.ng * 2))\n self.assertFalse(np.all(c.data[\"total\"] > 0.0))\n\n w = Wavecar(self.TEST_FILES_DIR / \"WAVECAR.N2.spin\")\n c = w.get_parchg(poscar, 0, 0, phase=False, scale=1)\n self.assertTrue(\"total\" in c.data)\n self.assertTrue(\"diff\" in c.data)\n self.assertEqual(np.prod(c.data[\"total\"].shape), np.prod(w.ng))\n self.assertTrue(np.all(c.data[\"total\"] > 0.0))\n self.assertFalse(np.all(c.data[\"diff\"] > 0.0))\n\n c = w.get_parchg(poscar, 0, 0, spin=0, phase=False)\n self.assertTrue(\"total\" in c.data)\n self.assertTrue(\"diff\" not in c.data)\n self.assertEqual(np.prod(c.data[\"total\"].shape), np.prod(w.ng * 2))\n self.assertTrue(np.all(c.data[\"total\"] > 0.0))\n\n c = w.get_parchg(poscar, 0, 0, spin=0, phase=True)\n self.assertTrue(\"total\" in c.data)\n self.assertTrue(\"diff\" not in c.data)\n self.assertEqual(np.prod(c.data[\"total\"].shape), np.prod(w.ng * 2))\n self.assertFalse(np.all(c.data[\"total\"] > 0.0))\n\n w = self.w_ncl\n w.coeffs.append([np.ones((2, 100))])\n c = w.get_parchg(poscar, -1, 0, phase=False, spinor=None)\n self.assertTrue(\"total\" in c.data)\n self.assertTrue(\"diff\" not in c.data)\n self.assertEqual(np.prod(c.data[\"total\"].shape), np.prod(w.ng * 2))\n self.assertFalse(np.all(c.data[\"total\"] > 0.0))\n\n c = w.get_parchg(poscar, -1, 0, phase=True, spinor=0)\n self.assertTrue(\"total\" in c.data)\n self.assertTrue(\"diff\" not in c.data)\n self.assertEqual(np.prod(c.data[\"total\"].shape), np.prod(w.ng * 2))\n self.assertFalse(np.all(c.data[\"total\"] > 0.0))\n\n w.coeffs[-1] = [np.zeros((2, 100))]\n c = w.get_parchg(poscar, -1, 0, phase=False, spinor=1)\n self.assertTrue(\"total\" in c.data)\n self.assertTrue(\"diff\" not in c.data)\n self.assertEqual(np.prod(c.data[\"total\"].shape), np.prod(w.ng * 2))\n self.assertTrue(np.allclose(c.data[\"total\"], 0.0))\n\n def test_write_unks(self):\n unk_std = Unk.from_file(self.TEST_FILES_DIR / \"UNK.N2.std\")\n unk_ncl = Unk.from_file(self.TEST_FILES_DIR / \"UNK.H2.ncl\")\n\n with self.assertRaises(ValueError):\n self.w.write_unks(self.TEST_FILES_DIR / \"UNK.N2.std\")\n\n # different grids\n with ScratchDir(\".\"):\n self.w.write_unks(\"./unk_dir\")\n self.assertEqual(len(list(Path(\"./unk_dir\").glob(\"UNK*\"))), 1)\n unk = Unk.from_file(\"./unk_dir/UNK00001.1\")\n self.assertNotEqual(unk, unk_std)\n\n # correct grid\n self.w.ng = np.array([12, 12, 12])\n with ScratchDir(\".\"):\n self.w.write_unks(\".\")\n unk = Unk.from_file(\"UNK00001.1\")\n self.assertEqual(unk, unk_std)\n\n # ncl test\n with ScratchDir(\".\"):\n self.w_ncl.write_unks(\".\")\n unk = Unk.from_file(\"UNK00001.NC\")\n self.assertEqual(unk, unk_ncl)\n\n\nclass EigenvalTest(PymatgenTest):\n _multiprocess_shared_ = True\n\n def test_init(self):\n eig = Eigenval(self.TEST_FILES_DIR / \"EIGENVAL.gz\")\n self.assertEqual(eig.ispin, 1)\n self.assertEqual(eig.nkpt, len(eig.kpoints))\n self.assertEqual(eig.nkpt, len(eig.kpoints_weights))\n self.assertEqual(eig.nkpt, eig.eigenvalues[Spin.up].shape[0])\n self.assertEqual(eig.nelect, 16)\n self.assertEqual(eig.nbands, eig.eigenvalues[Spin.up].shape[1])\n self.assertTrue(np.max(eig.eigenvalues[Spin.up]) > 0)\n self.assertTrue(np.min(eig.eigenvalues[Spin.up]) < 0)\n\n def test_ispin2(self):\n eig = Eigenval(self.TEST_FILES_DIR / \"EIGENVAL.ispin2.gz\")\n self.assertEqual(eig.ispin, 2)\n self.assertEqual(eig.nkpt, eig.eigenvalues[Spin.up].shape[0])\n self.assertEqual(eig.nbands, eig.eigenvalues[Spin.up].shape[1])\n self.assertEqual(eig.nkpt, eig.eigenvalues[Spin.down].shape[0])\n self.assertEqual(eig.nbands, eig.eigenvalues[Spin.down].shape[1])\n\n def test_eigenvalue_band_properties(self):\n eig = Eigenval(self.TEST_FILES_DIR / \"EIGENVAL.gz\")\n props = eig.eigenvalue_band_properties\n self.assertAlmostEqual(props[0], 6.4153, places=4)\n self.assertAlmostEqual(props[1], 7.5587, places=4)\n self.assertAlmostEqual(props[2], 1.1434, places=4)\n self.assertEqual(props[3], False)\n\n def test_eigenvalue_band_properties_separate_spins(self):\n eig = Eigenval(self.TEST_FILES_DIR / \"EIGENVAL_separate_spins.gz\", separate_spins=True)\n props = eig.eigenvalue_band_properties\n eig2 = Eigenval(self.TEST_FILES_DIR / \"EIGENVAL_separate_spins.gz\", separate_spins=False)\n props2 = eig2.eigenvalue_band_properties\n self.assertAlmostEqual(props[0][0], 2.8772, places=4)\n self.assertAlmostEqual(props[0][1], 1.2810, places=4)\n self.assertAlmostEqual(props[1][0], 3.6741, places=4)\n self.assertAlmostEqual(props[1][1], 1.6225, places=4)\n self.assertAlmostEqual(props[2][0], 0.7969, places=4)\n self.assertAlmostEqual(props[2][1], 0.3415, places=4)\n self.assertAlmostEqual(props2[0], np.min(props[1]) - np.max(props[2]), places=4)\n self.assertEqual(props[3][0], True)\n self.assertEqual(props[3][1], True)\n\n\nclass WavederTest(PymatgenTest):\n _multiprocess_shared_ = True\n\n def setUp(self):\n wder = Waveder(self.TEST_FILES_DIR / \"WAVEDER\", gamma_only=True)\n self.assertEqual(wder.nbands, 36)\n self.assertEqual(wder.nkpoints, 56)\n self.assertEqual(wder.nelect, 8)\n band_i = 0\n band_j = 0\n kp_index = 0\n spin_index = 0\n cart_dir_index = 0\n cder = wder.get_orbital_derivative_between_states(band_i, band_j, kp_index, spin_index, cart_dir_index)\n self.assertAlmostEqual(cder, -1.33639226092e-103, places=114)\n\n def test_consistency(self):\n wder = Waveder(self.TEST_FILES_DIR / \"WAVEDER.Si\")\n wderf = np.loadtxt(self.TEST_FILES_DIR / \"WAVEDERF.Si\", skiprows=1)\n with open(self.TEST_FILES_DIR / \"WAVEDERF.Si\") as f:\n first_line = [int(a) for a in f.readline().split()]\n self.assertEqual(wder.nkpoints, first_line[1])\n self.assertEqual(wder.nbands, first_line[2])\n for i in range(10):\n self.assertAlmostEqual(\n first=wder.get_orbital_derivative_between_states(0, i, 0, 0, 0).real,\n second=wderf[i, 6],\n places=10,\n )\n self.assertAlmostEqual(wder.cder_data[0, i, 0, 0, 0].real, wderf[i, 6], places=10)\n self.assertAlmostEqual(wder.cder_data[0, i, 0, 0, 0].imag, wderf[i, 7], places=10)\n self.assertAlmostEqual(wder.cder_data[0, i, 0, 0, 1].real, wderf[i, 8], places=10)\n self.assertAlmostEqual(wder.cder_data[0, i, 0, 0, 1].imag, wderf[i, 9], places=10)\n self.assertAlmostEqual(wder.cder_data[0, i, 0, 0, 2].real, wderf[i, 10], places=10)\n self.assertAlmostEqual(wder.cder_data[0, i, 0, 0, 2].imag, wderf[i, 11], places=10)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.sqrt", "numpy.all", "numpy.max", "numpy.mean", "numpy.cross", "numpy.allclose", "numpy.fft.ifftn", "numpy.unravel_index", "numpy.zeros", "numpy.min", "numpy.isnan", "numpy.median", "numpy.array", "numpy.sum", "numpy.abs", "numpy.linalg.norm", "numpy.ones", "numpy.prod", "numpy.loadtxt" ] ]
P2333/Reverse-Cross-Entropy
[ "2514af4a7fbd52423e4cac0da3ea58ac92b841c0" ]
[ "test_adv.py" ]
[ "from __future__ import division\r\nfrom __future__ import absolute_import\r\n\r\nimport six\r\nimport cifar_input\r\nimport mnist_input\r\nimport resnet_model_cifar\r\nimport resnet_model_mnist\r\nimport t_sne\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport attacks\r\nimport sys\r\nsys.path.append('..')\r\nsys.path.append('./../attacks')\r\nimport time\r\nimport copy\r\nfrom scipy.io import loadmat\r\nfrom scipy.misc import imsave\r\n\r\nFLAGS = tf.app.flags.FLAGS\r\ntf.app.flags.DEFINE_string('dataset', '', 'cifar10 or cifar100.')\r\ntf.app.flags.DEFINE_string('mode', 'train', 'train or eval.')\r\ntf.app.flags.DEFINE_string('train_data_path', '',\r\n 'Filepattern for training data.')\r\ntf.app.flags.DEFINE_string('eval_data_path', '',\r\n 'Filepattern for eval data')\r\ntf.app.flags.DEFINE_string('train_dir', '',\r\n 'Directory to keep training outputs.')\r\ntf.app.flags.DEFINE_string('eval_dir', '',\r\n 'Directory to keep eval outputs.')\r\ntf.app.flags.DEFINE_integer('eval_batch_count', 10,\r\n 'Number of batches to eval.')\r\ntf.app.flags.DEFINE_bool('eval_once', False,\r\n 'Whether evaluate the model only once.')\r\ntf.app.flags.DEFINE_string('log_root', '',\r\n 'Directory to keep the checkpoints. Should be a '\r\n 'parent directory of FLAGS.train_dir/eval_dir.')\r\ntf.app.flags.DEFINE_integer('num_gpus', 0,\r\n 'Number of gpus used for training. (0 or 1)')\r\ntf.app.flags.DEFINE_integer('num_residual_units', 5,\r\n 'num of residual units')\r\ntf.app.flags.DEFINE_string('Optimizer', 'mom',\r\n 'The optimizer used to train the model.')\r\ntf.app.flags.DEFINE_bool('RCE_train', False,\r\n 'Whether use RCE to train the model.')\r\ntf.app.flags.DEFINE_string('attack_method', 'fgsm',\r\n 'The attacking method used')\r\ntf.app.flags.DEFINE_float('eps', 0.01,\r\n 'The eps in attacking methods.')\r\ntf.app.flags.DEFINE_string('save_pwd', None,\r\n '')\r\n\r\nepoch_jsma = 100\r\n\r\n\r\nnum_classes = 10\r\nif FLAGS.dataset == 'cifar10':\r\n image_size = 32\r\n num_channel = 3\r\n model_name = resnet_model_cifar\r\n input_name = cifar_input\r\n\r\nelif FLAGS.dataset == 'mnist':\r\n image_size = 28\r\n num_channel = 1\r\n model_name = resnet_model_mnist\r\n input_name = mnist_input\r\n\r\nelse:\r\n print('Unrecognized dataset')\r\n image_size = None\r\n num_channel = None\r\n model_name = None\r\n input_name = None\r\n\r\nif FLAGS.RCE_train == True:\r\n sigma2 = 0.1 / 0.26\r\n f1 = 'RCE'\r\nelse:\r\n sigma2 = 1.0 / 0.26\r\n f1 = 'CE'\r\n\r\n\r\ndef models(hps, images, RCE_train, logits=False, tsne_logits=False):\r\n model = model_name.ResNet(hps, images, FLAGS.mode, Reuse=True)\r\n model.build_graph()\r\n op = model.predictions.op\r\n logit, = op.inputs\r\n if RCE_train==True:\r\n logit = -logit\r\n if tsne_logits==True:\r\n return tf.nn.softmax(logit), model.t_SNE_logits\r\n if logits==True:\r\n return tf.nn.softmax(logit), logit\r\n return tf.nn.softmax(logit)\r\n\r\nclass models_carlini:\r\n def __init__(self,hps):\r\n self.image_size = image_size\r\n self.num_channels = num_channel############MNIST and CIFAR10 are different ar here\r\n self.num_labels = num_classes\r\n self.hps = hps\r\n\r\n def predict(self,images,tsne_logits=False):\r\n model = model_name.ResNet(self.hps, images, FLAGS.mode, Reuse=True)\r\n model.build_graph()\r\n op = model.predictions.op\r\n logit, = op.inputs\r\n if FLAGS.RCE_train==True:\r\n logit = -logit\r\n if tsne_logits==True:\r\n return logit,model.t_SNE_logits\r\n return logit\r\n\r\ndef adv_craft_func(hps, images, method, eps=0.01,RCE_train=False, target_labels=None):\r\n if method=='fgsm':\r\n print('Attacking method is fgsm')\r\n adversarial_sample = attacks.fgsm.fgsm(models, images, hps, RCE_train,\r\n eps=eps, epochs=1, clip_min=-0.5, clip_max=0.5)\r\n elif method=='random':\r\n print('Attacking method is random')\r\n adversarial_sample = tf.clip_by_value(images + tf.random_uniform((hps.batch_size,image_size,image_size,num_channel),\r\n minval=-eps, maxval=eps), clip_value_min=-0.5, clip_value_max=0.5)\r\n elif method=='bim':\r\n print('Attacking method is bim')\r\n adversarial_sample = attacks.fgsm.fgsm(models, images, hps, RCE_train,\r\n eps=eps/10, epochs=10, clip_min=-0.5, clip_max=0.5)\r\n elif method=='tgsm':\r\n print('Attacking method is tgsm')\r\n adversarial_sample = attacks.tgsm.tgsm(models, images, hps, RCE_train, y=None,\r\n eps=eps/10, epochs=10, clip_min=-0.5, clip_max=0.5)\r\n\r\n elif method=='jsma':\r\n print('Attacking method is jsma')\r\n if target_labels==None:\r\n print('Target label is the argmin label')\r\n model_target_y = models(hps, images, FLAGS.RCE_train, logits=False)\r\n target_y64 = tf.argmin(model_target_y,axis=1)\r\n else:\r\n target_y64=target_labels\r\n target_y = tf.cast(target_y64, tf.int32)\r\n adversarial_sample = attacks.jsma.jsma(models, images, hps, RCE_train, target_y,epochs=epoch_jsma, eps=eps,\r\n clip_min=-0.5, clip_max=0.5, pair=False, min_proba=0.0)\r\n\r\n elif method=='smda':\r\n print('Attacking method is smda')\r\n if target_labels==None:\r\n print('Target label is the argmin label')\r\n model_target_y = models(hps, images, FLAGS.RCE_train, logits=False)\r\n target_y64 = tf.argmin(model_target_y,axis=1)\r\n else:\r\n target_y64=target_labels\r\n target_y = tf.cast(target_y64, tf.int32)\r\n adversarial_sample = attacks.smda.smda(models, images, hps, RCE_train, target_y, epochs=epoch_jsma, eps=eps,\r\n clip_min=-0.5, clip_max=0.5, min_proba=0.0)\r\n\r\n else:\r\n print('Not recognized method')\r\n adversarial_sample = None\r\n return adversarial_sample\r\n\r\ndef tSNE_visual(hps,num_batch):\r\n # Construct graph\r\n images, labels = input_name.build_input(\r\n FLAGS.dataset, FLAGS.eval_data_path, hps.batch_size, FLAGS.mode) # FLAGS.mode='attack', batch_size=200\r\n Res = model_name.ResNet(hps, images, FLAGS.mode, Reuse=False)\r\n Res.build_graph()\r\n saver = tf.train.Saver()\r\n adv_images = adv_craft_func(hps, images, FLAGS.attack_method, eps=FLAGS.eps, RCE_train=FLAGS.RCE_train)\r\n model_nor = model_name.ResNet(hps, images, FLAGS.mode, Reuse=True)\r\n model_nor.build_graph()\r\n model_adv = model_name.ResNet(hps, adv_images, FLAGS.mode, Reuse=True)\r\n model_adv.build_graph()\r\n\r\n # Open session and restore checkpoint\r\n sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))\r\n tf.train.start_queue_runners(sess)\r\n sess.run(tf.global_variables_initializer())\r\n\r\n ckpt_state = tf.train.get_checkpoint_state(FLAGS.log_root) # Choose dir according to rt\r\n tf.logging.info('Loading checkpoint %s', ckpt_state.model_checkpoint_path)\r\n saver.restore(sess, ckpt_state.model_checkpoint_path)\r\n\r\n logits_nor = model_nor.t_SNE_logits\r\n logits_adv = model_adv.t_SNE_logits\r\n\r\n dim_logits = logits_nor.shape[1]\r\n if hps.batch_size!=logits_nor.shape[0]:\r\n print('Error!!!!!')\r\n return\r\n logits_all = np.reshape(np.array([]),(0,dim_logits))\r\n labels_all = np.array([])\r\n is_adv_all = np.array([])\r\n\r\n\r\n #make the num of adv the same as per class\r\n if FLAGS.attack_method == 'fgsm' or FLAGS.attack_method == 'tgsm':\r\n num_adv = int(hps.batch_size/10)\r\n print('num_adv is %d'%(num_adv))\r\n else:\r\n num_adv = hps.batch_size\r\n\r\n for i in six.moves.range(num_batch):\r\n print(i)\r\n (logits_part_nor, logits_part_adv, labels_part) = sess.run([logits_nor, logits_adv, tf.argmax(labels, 1)])\r\n logits_all = np.concatenate((logits_all, logits_part_nor), axis=0)\r\n labels_all = np.concatenate((labels_all, labels_part), axis=0)\r\n is_adv_all = np.concatenate((is_adv_all, np.zeros(hps.batch_size)), axis=0)\r\n logits_all = np.concatenate((logits_all, logits_part_adv[:num_adv]), axis=0)\r\n labels_all = np.concatenate((labels_all, labels_part[:num_adv]), axis=0)\r\n is_adv_all = np.concatenate((is_adv_all, np.ones(num_adv)), axis=0)\r\n\r\n tsne_return = t_sne.tsne(logits_all, no_dims=2, initial_dims=60, perplexity=30.0)\r\n\r\n # Save results\r\n if FLAGS.RCE_train == True:\r\n f1 = 'RCE'\r\n else:\r\n f1 = 'CE'\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/tSNE/tSNE_' + f1, tsne_return)\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/tSNE/tSNElabels_' + f1, labels_all)\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/tSNE/tSNEisadv_' + f1, is_adv_all)\r\n return None\r\n\r\ndef tSNE_visual_carliniLi(hps, num_batch):\r\n # Construct graph\r\n images, labels = input_name.build_input(\r\n FLAGS.dataset, FLAGS.eval_data_path, hps.batch_size, FLAGS.mode) # FLAGS.mode='attack', batch_size=200\r\n Res = model_name.ResNet(hps, images, FLAGS.mode, Reuse=False)\r\n Res.build_graph()\r\n saver = tf.train.Saver()\r\n # Open session and restore checkpoint\r\n sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))\r\n tf.train.start_queue_runners(sess)\r\n sess.run(tf.global_variables_initializer())\r\n\r\n ckpt_state = tf.train.get_checkpoint_state(FLAGS.log_root) # Choose dir according to rt\r\n tf.logging.info('Loading checkpoint %s', ckpt_state.model_checkpoint_path)\r\n saver.restore(sess, ckpt_state.model_checkpoint_path)\r\n\r\n model_carlini = models_carlini(hps)\r\n if FLAGS.attack_method == 'carliniLi':\r\n attack_carlini = attacks.carliniLi.CarliniLi(sess, model_carlini, largest_const=10 ** -3)\r\n elif FLAGS.attack_method == 'carliniL2':\r\n attack_carlini = attacks.carliniL2.CarliniL2(sess, model_carlini, batch_size=10, max_iterations=1000, confidence=0,binary_search_steps=3)\r\n adv_image = tf.placeholder(tf.float32, shape=[hps.batch_size, image_size, image_size, num_channel])\r\n\r\n _, logits_nor = model_carlini.predict(images, tsne_logits=True)\r\n _, logits_adv = model_carlini.predict(adv_image, tsne_logits=True)\r\n\r\n dim_logits = logits_nor.shape[1]\r\n if hps.batch_size != logits_nor.shape[0]:\r\n print('Error!!!!!')\r\n return\r\n logits_all = np.reshape(np.array([]), (0, dim_logits))\r\n labels_all = np.array([])\r\n is_adv_all = np.array([])\r\n\r\n # make the num of adv the same as per class\r\n # if FLAGS.attack_method == 'fgsm' or FLAGS.attack_method == 'tgsm':\r\n # num_adv = int(hps.batch_size/10)\r\n # print('num_adv is %d'%(num_adv))\r\n # else:\r\n # num_adv = hps.batch_size\r\n\r\n num_adv = hps.batch_size\r\n\r\n for i in six.moves.range(num_batch):\r\n print(i)\r\n input_data = sess.run(images)\r\n target_label = sess.run(labels)\r\n adv = attack_carlini.attack(input_data, target_label)\r\n\r\n (logits_part_nor, logits_part_adv, labels_part) = sess.run([logits_nor, logits_adv, tf.argmax(labels, 1)],\r\n feed_dict={adv_image: adv})\r\n logits_all = np.concatenate((logits_all, logits_part_nor), axis=0)\r\n labels_all = np.concatenate((labels_all, labels_part), axis=0)\r\n is_adv_all = np.concatenate((is_adv_all, np.zeros(hps.batch_size)), axis=0)\r\n logits_all = np.concatenate((logits_all, logits_part_adv[:num_adv]), axis=0)\r\n labels_all = np.concatenate((labels_all, labels_part[:num_adv]), axis=0)\r\n is_adv_all = np.concatenate((is_adv_all, np.ones(num_adv)), axis=0)\r\n\r\n tsne_return = t_sne.tsne(logits_all, no_dims=2, initial_dims=60, perplexity=30.0)\r\n\r\n # Save results\r\n if FLAGS.RCE_train == True:\r\n f1 = 'RCE'\r\n else:\r\n f1 = 'CE'\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/tSNE/tSNE_' + f1, tsne_return)\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/tSNE/tSNElabels_' + f1, labels_all)\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/tSNE/tSNEisadv_' + f1, is_adv_all)\r\n return None\r\n\r\ndef apply_attack_carlini(hps):\r\n # Construct graph\r\n images, labels = input_name.build_input(\r\n FLAGS.dataset, FLAGS.eval_data_path, hps.batch_size, FLAGS.mode) # FLAGS.mode='attack', batch_size=200\r\n Res = model_name.ResNet(hps, images, FLAGS.mode, Reuse=False)\r\n Res.build_graph()\r\n saver = tf.train.Saver()\r\n\r\n # Open session and restore checkpoint\r\n sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))\r\n tf.train.start_queue_runners(sess)\r\n sess.run(tf.global_variables_initializer())\r\n\r\n ckpt_state = tf.train.get_checkpoint_state(FLAGS.log_root) # Choose dir according to rt\r\n tf.logging.info('Loading checkpoint %s', ckpt_state.model_checkpoint_path)\r\n saver.restore(sess, ckpt_state.model_checkpoint_path)\r\n\r\n num_sample = hps.batch_size * FLAGS.eval_batch_count\r\n\r\n # Initialize results to save\r\n entropy_test_adv_all = np.array([])\r\n confidence_test_adv_all = np.array([])\r\n entropy_test_nor_all = np.array([])\r\n confidence_test_nor_all = np.array([])\r\n logits_adv_all = np.reshape(np.array([]), (0, 64))\r\n logits_nor_all = np.reshape(np.array([]), (0, 64))\r\n labels_adv_all = np.array([])\r\n labels_true_all = np.array([])\r\n labels_nor_all = np.array([])\r\n L2_distance = np.array([])\r\n nor_img_all = np.reshape(np.array([]), (0, image_size,image_size,num_channel))\r\n adv_img_all = np.reshape(np.array([]), (0, image_size,image_size,num_channel))\r\n\r\n print('Num of sample per eps is %d' % (num_sample))\r\n\r\n #Construct carlini adversarial samples\r\n model_carlini_adv = models_carlini(hps)\r\n\r\n #Construct predictions\r\n image = tf.placeholder(tf.float32,shape=[hps.batch_size, image_size, image_size,\r\n num_channel])############MNIST and CIFAR10 are different ar here\r\n adv_image = tf.placeholder(tf.float32,shape=[hps.batch_size, image_size, image_size,\r\n num_channel])############MNIST and CIFAR10 are different ar here\r\n predict = tf.placeholder(tf.float32,shape=[hps.batch_size, 10])\r\n logit_nor,tsne_logit_nor = model_carlini_adv.predict(image,tsne_logits=True)\r\n logit_adv,tsne_logit_adv = model_carlini_adv.predict(adv_image,tsne_logits=True)\r\n predict_nor = tf.nn.softmax(logit_nor)\r\n predict_adv = tf.nn.softmax(logit_adv)\r\n\r\n # Calculate entropy\r\n argmax_y_onehot = tf.one_hot(tf.argmax(predict, 1), 10, on_value=0.0, off_value=1.0, axis=-1)\r\n normalized_y_nonmaximal = tf.reduce_sum(predict * argmax_y_onehot, 1)\r\n entropy = tf.reduce_sum(-tf.log(predict) * predict * argmax_y_onehot,1) / normalized_y_nonmaximal + tf.log(normalized_y_nonmaximal)\r\n\r\n for k in range(1):\r\n result_dict = loadmat('kernel_para_'+FLAGS.dataset+'/kernel1000_for_attack_' + f1 + '.mat')\r\n result_dict_median = loadmat('kernel_para_'+FLAGS.dataset+'/kernel1000_median_for_attack_' + f1 + '.mat')\r\n # e_mean = result_dict['mean_logits_' + f1] # 10X64\r\n # e_invcovar = result_dict['inv_covar_' + f1] # 64X64X10\r\n e_kernel_train = result_dict['kernel_'+f1+'_for_attack'] #100X64X10\r\n e_median = result_dict_median['median_out'] # 10X1\r\n\r\n if FLAGS.attack_method == 'carliniL2':\r\n attack1 = attacks.carliniL2.CarliniL2(sess, model_carlini_adv, batch_size=10, max_iterations=10,targeted=True,\r\n confidence=0, initial_const=1.0,binary_search_steps=9)\r\n attack2 = None\r\n\r\n elif FLAGS.attack_method == 'carliniL2_highcon':\r\n attack1 = attacks.carliniL2.CarliniL2(sess, model_carlini_adv, batch_size=10, max_iterations=10000,targeted=True,\r\n confidence=10, initial_const=1.0,binary_search_steps=9)\r\n attack2 = None\r\n\r\n elif FLAGS.attack_method == 'carliniL2_highden':\r\n attack1 = attacks.carliniL2.CarliniL2(sess, model_carlini_adv, batch_size=1,\r\n max_iterations=5000,\r\n targeted=True,\r\n initial_const=1.0,\r\n confidence=0, binary_search_steps=3)\r\n attack2 = attacks.carliniL2_specific.CarliniL2_specific(sess, model_carlini_adv, batch_size=1,\r\n max_iterations=10000,\r\n targeted=True,\r\n initial_const=1.0,\r\n confidence=0, binary_search_steps=8,\r\n extra_loss=True\r\n , e_kernel_train=e_kernel_train,\r\n e_median=e_median,\r\n sigma2=sigma2)\r\n\r\n elif FLAGS.attack_method == 'carliniL2_specific':\r\n attack1 = attacks.carliniL2.CarliniL2(sess, model_carlini_adv, batch_size=1,\r\n max_iterations=5000,\r\n targeted=True,\r\n initial_const=10.0,\r\n confidence=5, binary_search_steps=3)\r\n attack2 = attacks.carliniL2_specific.CarliniL2_specific(sess, model_carlini_adv, batch_size=1,\r\n max_iterations=10000,\r\n targeted=True,\r\n initial_const=100.0,\r\n confidence=5, binary_search_steps=9, extra_loss=True\r\n , e_kernel_train=e_kernel_train ,\r\n e_median = e_median,\r\n sigma2 = sigma2)\r\n else:\r\n print('Error!!!!')\r\n attack1 = None\r\n attack2 = None\r\n\r\n success = 0\r\n efficient = 0\r\n L2_distance_print = 0\r\n\r\n for i in six.moves.range(FLAGS.eval_batch_count):\r\n time_start = time.time()\r\n (nor_img,true_label) = sess.run([images,labels])\r\n\r\n #Crafting target labels\r\n target_lab = np.zeros((hps.batch_size, 10))\r\n for j in range(hps.batch_size):\r\n r = np.random.random_integers(0, 9)\r\n while r == np.argmax(true_label[j]):\r\n r = np.random.random_integers(0, 9)\r\n target_lab[j, r] = 1\r\n\r\n (predict_NOR, logits_part_nor) = sess.run(\r\n [predict_nor, tsne_logit_nor],\r\n feed_dict={image: nor_img}\r\n )\r\n #Attack1, craft adversarial samples in oblivious attack\r\n adv_img,succ = attack1.attack(nor_img, target_lab,predict_NOR)\r\n\r\n\r\n #Attack, craft adversarial samples in white-box attack\r\n if FLAGS.attack_method == 'carliniL2_specific' or FLAGS.attack_method == 'carliniL2_highden':\r\n if succ[0] == 1:\r\n is_succ = 'Success'\r\n else:\r\n is_succ = 'Fail'\r\n print('Finish attack 1. The %d batch in total %d(%f sec) %s' % (\r\n i, FLAGS.eval_batch_count, time.time() - time_start,is_succ))\r\n time_start = time.time()\r\n adv_img, succ, log_density_ratio = attack2.attack(nor_img, adv_img, target_lab,predict_NOR)\r\n if succ[0] == 1:\r\n is_succ = 'Success'\r\n else:\r\n is_succ = 'Fail'\r\n print('Finish attack 2. The %d batch in total %d(%f sec) %s' % (\r\n i, FLAGS.eval_batch_count, time.time() - time_start, is_succ))\r\n else:\r\n print('The %d batch in total %d, the eps = %f (%f sec)' % (\r\n i, FLAGS.eval_batch_count, 0.05 * k, time.time() - time_start))\r\n\r\n #Local logits\r\n (predict_ADV,logits_part_adv) = sess.run(\r\n [predict_adv, tsne_logit_adv],feed_dict={adv_image:adv_img}\r\n )\r\n\r\n #Local entropy and confidence for nor_img\r\n (entropy_test_nor_help,labels_nor_help,confidence_test_nor_help) = sess.run(\r\n [entropy,tf.argmax(predict,axis=1),tf.reduce_max(predict, axis=1)],feed_dict={predict:predict_NOR}\r\n )\r\n\r\n # Local entropy and confidence for adv_img\r\n (entropy_test_adv_help, labels_adv_help, confidence_test_adv_help) = sess.run(\r\n [entropy, tf.argmax(predict, axis=1), tf.reduce_max(predict, axis=1)], feed_dict={predict: predict_ADV}\r\n )\r\n\r\n if FLAGS.attack_method == 'carliniL2_specific' or FLAGS.attack_method == 'carliniL2_highden':\r\n print('Log-density-ratio in attacking function of nor/adv is %f'%np.sum(log_density_ratio))\r\n m_tsne_logits_adv = (copy.copy(logits_part_adv)).reshape((1, 64))\r\n m_tsne_logits_adv = np.repeat(m_tsne_logits_adv,100,axis=0)\r\n kernel_train = (copy.copy(e_kernel_train[:,:,np.argmax(target_lab)])).reshape((100,64))\r\n log_density_ratio2 = -np.log(1e-30+np.mean(np.exp(-np.sum(np.square(m_tsne_logits_adv\r\n - kernel_train), axis=1) / sigma2),\r\n axis=0)) + np.log(e_median[np.argmax(target_lab)])\r\n # m_tsne_logits_adv = (copy.copy(logits_part_adv-e_mean[np.argmax(target_lab)])).reshape((64,1))\r\n # inter_mat_adv = np.matmul(e_invcovar[:,:,np.argmax(target_lab)].reshape((64,64)), m_tsne_logits_adv)\r\n # m_tsne_logits_nor = (copy.copy(logits_part_nor-e_mean[labels_nor_help])).reshape((64,1))\r\n # inter_mat_nor = np.matmul(e_invcovar[:,:,labels_nor_help].reshape((64,64)), m_tsne_logits_nor)\r\n # log_density_ratio2 = np.matmul(m_tsne_logits_adv.reshape((1,64)), inter_mat_adv) \\\r\n # - np.matmul(m_tsne_logits_nor.reshape((1,64)), inter_mat_nor)\r\n #log_density_ratio2 = np.matmul(m_tsne_logits_adv.reshape((1, 64)), inter_mat_adv)+e_median[np.argmax(target_lab)]\r\n print('Log-density-ratio in saving results of nor/adv is %f'%np.sum(log_density_ratio2))\r\n\r\n entropy_test_adv_all = np.concatenate((entropy_test_adv_all,entropy_test_adv_help),axis=0)\r\n confidence_test_adv_all = np.concatenate((confidence_test_adv_all,confidence_test_adv_help),axis=0)\r\n entropy_test_nor_all = np.concatenate((entropy_test_nor_all, entropy_test_nor_help), axis=0)\r\n confidence_test_nor_all = np.concatenate((confidence_test_nor_all, confidence_test_nor_help), axis=0)\r\n logits_nor_all = np.concatenate((logits_nor_all, logits_part_nor), axis=0)\r\n labels_nor_all = np.concatenate((labels_nor_all, labels_nor_help), axis=0)\r\n logits_adv_all = np.concatenate((logits_adv_all,logits_part_adv),axis=0)\r\n labels_adv_all = np.concatenate((labels_adv_all, labels_adv_help), axis=0)\r\n labels_true_all = np.concatenate((labels_true_all, np.argmax(true_label,axis=1)), axis=0)\r\n L2_distance = np.concatenate((L2_distance,np.sqrt(np.mean(np.square(nor_img-adv_img),axis=(1,2,3)))), axis=0)\r\n nor_img_all = np.concatenate((nor_img_all,nor_img),axis=0)\r\n adv_img_all = np.concatenate((adv_img_all,adv_img),axis=0)\r\n\r\n #Efficient index refers to the indexes that are correctly classified and misclassified as adversarial samples\r\n efficient_index = succ*np.equal(np.argmax(true_label, axis=1),labels_nor_help)\r\n if FLAGS.attack_method != 'carliniL2_specific'or FLAGS.attack_method == 'carliniL2_highden':\r\n print('Num of attacking success is %d'%(np.sum(succ)))\r\n efficient += np.sum(efficient_index)\r\n L2_distance_print += np.sum(efficient_index*np.sqrt(np.mean(np.square(nor_img - adv_img), axis=(1, 2, 3))), axis=0)\r\n\r\n L2_distance_print = L2_distance_print/efficient\r\n k_index_begin = k*num_sample\r\n k_index_end = (k+1)*num_sample\r\n\r\n # Show local results\r\n precision_nor = np.mean(np.equal(labels_nor_all[k_index_begin:k_index_end],labels_true_all[k_index_begin:k_index_end]))\r\n precision_adv = np.mean(np.equal(labels_adv_all[k_index_begin:k_index_end],labels_true_all[k_index_begin:k_index_end]))\r\n mean_confidence_nor = np.mean(confidence_test_nor_all[k_index_begin:k_index_end])\r\n mean_confidence_adv = np.mean(confidence_test_adv_all[k_index_begin:k_index_end])\r\n mean_entropy_nor = np.mean(entropy_test_nor_all[k_index_begin:k_index_end])\r\n mean_entropy_adv = np.mean(entropy_test_adv_all[k_index_begin:k_index_end])\r\n\r\n print('Precision on nor images is %f, on adv images is %f' % (precision_nor, precision_adv))\r\n print('Confidence on nor images is %f, on adv images is %f' % (mean_confidence_nor, mean_confidence_adv))\r\n print('non-ME on nor images is %f, on adv images is %f' % (mean_entropy_nor, mean_entropy_adv))\r\n print('Average L2-distance between nor and adv imgs is %f'%(L2_distance_print))\r\n print('Total success num of attack 1 is %d'%(success))\r\n print('Total efficient num of attack 1 is %d' % (efficient))\r\n\r\n # # Save results\r\n # np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/'+f1+'/entropy_nor', entropy_test_nor_all)\r\n # np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/'+f1+ '/confidence_nor', confidence_test_nor_all)\r\n # np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/'+f1+'/entropy_adv', entropy_test_adv_all)\r\n # np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/'+f1+ '/confidence_adv', confidence_test_adv_all)\r\n # np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/'+f1+ '/logits_nor', logits_nor_all)\r\n # np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/'+f1+ '/logits_adv', logits_adv_all)\r\n # np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/'+f1+'/labels_nor', labels_nor_all)\r\n # np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/'+f1+'/labels_adv', labels_adv_all)\r\n # np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/'+f1+'/labels_true', labels_true_all)\r\n # np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/L2_distance', L2_distance)\r\n # np.save(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/nor_img.npy', nor_img_all)\r\n # np.save(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/adv_img.npy', adv_img_all)\r\n\r\n # #Save img\r\n # nor_img_all = nor_img_all + 0.5\r\n # adv_img_all = adv_img_all + 0.5\r\n # noise_img_all = 0.5 * (adv_img_all - nor_img_all + 1.0)\r\n\r\n # if FLAGS.dataset=='cifar10':\r\n # for i in range(nor_img_all.shape[0]):\r\n # imsave(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/nor_img/nor_img_' + str(i) + '.png', nor_img_all[i])\r\n # imsave(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/adv_img/adv_img_' + str(i) + '.png', adv_img_all[i])\r\n # imsave(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/noise_img/noise_img_' + str(i) + '.png', noise_img_all[i])\r\n # elif FLAGS.dataset=='mnist':\r\n # for i in range(nor_img_all.shape[0]):\r\n # imsave(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/nor_img/nor_img_' + str(i) + '.png', nor_img_all[i,:,:,0])\r\n # imsave(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/adv_img/adv_img_' + str(i) + '.png', adv_img_all[i,:,:,0])\r\n # imsave(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/noise_img/noise_img_' + str(i) + '.png', noise_img_all[i, :, :, 0])\r\n return None\r\n\r\ndef apply_attack_loop(hps):\r\n #Construct graph\r\n images, labels = input_name.build_input(\r\n FLAGS.dataset, FLAGS.eval_data_path, hps.batch_size, FLAGS.mode)#FLAGS.mode='attack', batch_size=200\r\n Res = model_name.ResNet(hps, images, FLAGS.mode, Reuse=False)\r\n Res.build_graph()\r\n saver = tf.train.Saver()\r\n\r\n #Open session and restore checkpoint\r\n sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))\r\n tf.train.start_queue_runners(sess)\r\n\r\n ckpt_state = tf.train.get_checkpoint_state(FLAGS.log_root) # Choose dir according to rt\r\n tf.logging.info('Loading checkpoint %s', ckpt_state.model_checkpoint_path)\r\n\r\n num_sample = hps.batch_size*FLAGS.eval_batch_count\r\n\r\n # Initialize results to save\r\n entropy_test_adv_all = np.array([])\r\n confidence_test_adv_all = np.array([])\r\n entropy_test_nor_all = np.array([])\r\n confidence_test_nor_all = np.array([])\r\n logits_adv_all = np.reshape(np.array([]), (0, 64))\r\n logits_nor_all = np.reshape(np.array([]), (0, 64))\r\n labels_adv_all = np.array([])\r\n labels_true_all = np.array([])\r\n labels_nor_all = np.array([])\r\n L2_distance = np.array([])\r\n nor_img_all = np.reshape(np.array([]), (0, image_size, image_size, num_channel))\r\n adv_img_all = np.reshape(np.array([]), (0, image_size, image_size, num_channel))\r\n print('Num of sample per eps is %d' % (num_sample))\r\n\r\n # Construct predictions\r\n image = tf.placeholder(tf.float32, shape=[hps.batch_size, image_size, image_size,\r\n num_channel]) ############MNIST and CIFAR10 are different ar here\r\n adv_image = tf.placeholder(tf.float32, shape=[hps.batch_size, image_size, image_size,\r\n num_channel]) ############MNIST and CIFAR10 are different ar here\r\n predict = tf.placeholder(tf.float32, shape=[hps.batch_size, 10])\r\n predict_nor, tsne_logit_nor = models(hps, image, FLAGS.RCE_train, logits=False, tsne_logits=True)\r\n predict_adv, tsne_logit_adv = models(hps, adv_image, FLAGS.RCE_train, logits=False, tsne_logits=True)\r\n\r\n # Calculate entropy\r\n argmax_y_onehot = tf.one_hot(tf.argmax(predict, 1), 10, on_value=0.0, off_value=1.0, axis=-1)\r\n normalized_y_nonmaximal = tf.reduce_sum(predict * argmax_y_onehot, 1)\r\n entropy = tf.reduce_sum(-tf.log(predict) * predict * argmax_y_onehot, 1) / normalized_y_nonmaximal + tf.log(\r\n normalized_y_nonmaximal)\r\n\r\n for k in range(10):\r\n adv_image_craft = adv_craft_func(hps, image, FLAGS.attack_method, eps=0.02 * k + 0.02, RCE_train=FLAGS.RCE_train)\r\n #adv_image_craft = adv_craft_func(hps, image, FLAGS.attack_method, eps=0.04,RCE_train=FLAGS.RCE_train)\r\n sess.run(tf.global_variables_initializer())\r\n saver.restore(sess, ckpt_state.model_checkpoint_path)\r\n\r\n for i in six.moves.range(FLAGS.eval_batch_count):\r\n time_start = time.time()\r\n (nor_img,true_label) = sess.run([images,labels])\r\n adv_img = sess.run(adv_image_craft,feed_dict={image:nor_img})\r\n\r\n # Local logits\r\n (predict_NOR, predict_ADV, logits_part_nor, logits_part_adv) = sess.run(\r\n [predict_nor, predict_adv, tsne_logit_nor, tsne_logit_adv],\r\n feed_dict={image: nor_img, adv_image: adv_img}\r\n )\r\n\r\n # Local entropy and confidence for nor_img\r\n (entropy_test_nor_help, labels_nor_help, confidence_test_nor_help) = sess.run(\r\n [entropy, tf.argmax(predict, axis=1), tf.reduce_max(predict, axis=1)], feed_dict={predict: predict_NOR}\r\n )\r\n\r\n # Local entropy and confidence for adv_img\r\n (entropy_test_adv_help, labels_adv_help, confidence_test_adv_help) = sess.run(\r\n [entropy, tf.argmax(predict, axis=1), tf.reduce_max(predict, axis=1)], feed_dict={predict: predict_ADV}\r\n )\r\n\r\n entropy_test_adv_all = np.concatenate((entropy_test_adv_all, entropy_test_adv_help), axis=0)\r\n confidence_test_adv_all = np.concatenate((confidence_test_adv_all, confidence_test_adv_help), axis=0)\r\n entropy_test_nor_all = np.concatenate((entropy_test_nor_all, entropy_test_nor_help), axis=0)\r\n confidence_test_nor_all = np.concatenate((confidence_test_nor_all, confidence_test_nor_help), axis=0)\r\n logits_nor_all = np.concatenate((logits_nor_all, logits_part_nor), axis=0)\r\n labels_nor_all = np.concatenate((labels_nor_all, labels_nor_help), axis=0)\r\n logits_adv_all = np.concatenate((logits_adv_all, logits_part_adv), axis=0)\r\n labels_adv_all = np.concatenate((labels_adv_all, labels_adv_help), axis=0)\r\n labels_true_all = np.concatenate((labels_true_all, np.argmax(true_label, axis=1)), axis=0)\r\n L2_distance = np.concatenate((L2_distance,np.sqrt(np.mean(np.square(nor_img-adv_img),axis=(1,2,3)))), axis=0)\r\n nor_img_all = np.concatenate((nor_img_all, nor_img), axis=0)\r\n adv_img_all = np.concatenate((adv_img_all, adv_img), axis=0)\r\n print('The %d batch in total %d, the eps = %f (%f sec)' % (\r\n i, FLAGS.eval_batch_count, 0.02 * k + 0.02, time.time() - time_start))\r\n k_index_begin = k * num_sample\r\n k_index_end = (k + 1) * num_sample\r\n\r\n # Show local results\r\n precision_nor = np.mean(\r\n np.equal(labels_nor_all[k_index_begin:k_index_end], labels_true_all[k_index_begin:k_index_end]))\r\n precision_adv = np.mean(\r\n np.equal(labels_adv_all[k_index_begin:k_index_end], labels_true_all[k_index_begin:k_index_end]))\r\n mean_confidence_nor = np.mean(confidence_test_nor_all[k_index_begin:k_index_end])\r\n mean_confidence_adv = np.mean(confidence_test_adv_all[k_index_begin:k_index_end])\r\n mean_entropy_nor = np.mean(entropy_test_nor_all[k_index_begin:k_index_end])\r\n mean_entropy_adv = np.mean(entropy_test_adv_all[k_index_begin:k_index_end])\r\n\r\n print('Precision on nor images is %f, on adv images is %f' % (precision_nor, precision_adv))\r\n print('Confidence on nor images is %f, on adv images is %f' % (mean_confidence_nor, mean_confidence_adv))\r\n print('non-ME on nor images is %f, on adv images is %f' % (mean_entropy_nor, mean_entropy_adv))\r\n print('Average L2-distance between nor and adv imgs is %f'%(np.mean(L2_distance)))\r\n\r\n # Save results\r\n if FLAGS.save_pwd ==None:\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/entropy_nor', entropy_test_nor_all)\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/confidence_nor', confidence_test_nor_all)\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/entropy_adv', entropy_test_adv_all)\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/confidence_adv', confidence_test_adv_all)\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/logits_nor', logits_nor_all)\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/logits_adv', logits_adv_all)\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/labels_nor', labels_nor_all)\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/labels_adv', labels_adv_all)\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/labels_true', labels_true_all)\r\n np.savetxt(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/L2_distance', L2_distance)\r\n np.save(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/nor_img.npy', nor_img_all)\r\n np.save(FLAGS.attack_method + '_' + FLAGS.dataset + '/' + f1 + '/adv_img.npy', adv_img_all)\r\n else:\r\n np.savetxt(FLAGS.save_pwd + '/entropy_nor', entropy_test_nor_all)\r\n np.savetxt(FLAGS.save_pwd + '/confidence_nor', confidence_test_nor_all)\r\n np.savetxt(FLAGS.save_pwd + '/entropy_adv', entropy_test_adv_all)\r\n np.savetxt(FLAGS.save_pwd + '/confidence_adv', confidence_test_adv_all)\r\n np.savetxt(FLAGS.save_pwd + '/logits_nor', logits_nor_all)\r\n np.savetxt(FLAGS.save_pwd + '/logits_adv', logits_adv_all)\r\n np.savetxt(FLAGS.save_pwd + '/labels_nor', labels_nor_all)\r\n np.savetxt(FLAGS.save_pwd + '/labels_adv', labels_adv_all)\r\n np.savetxt(FLAGS.save_pwd + '/labels_true', labels_true_all)\r\n np.savetxt(FLAGS.save_pwd + '/L2_distance', L2_distance)\r\n np.save(FLAGS.save_pwd + '/nor_img.npy', nor_img_all)\r\n np.save(FLAGS.save_pwd + '/adv_img.npy', adv_img_all)\r\n\r\n return None\r\n\r\ndef main(_):\r\n print('attacking method is %s' % (FLAGS.attack_method))\r\n print('mode is %s'%(FLAGS.mode))\r\n\r\n if FLAGS.attack_method == 'carliniL2' or FLAGS.attack_method == 'carliniL2_highcon' \\\r\n or FLAGS.attack_method == 'carliniL2_specific' or FLAGS.attack_method == 'carliniL2_highden':\r\n is_carliniL2 = True\r\n else:\r\n is_carliniL2 = False\r\n\r\n if FLAGS.attack_method == 'jsma' or FLAGS.attack_method == 'smda'\\\r\n or FLAGS.attack_method == 'carliniL2_specific' or FLAGS.attack_method == 'carliniL2_highden':\r\n batch_size = 1\r\n num_batch = 1000\r\n elif FLAGS.attack_method == 'fgsm' or FLAGS.attack_method == 'tgsm' or FLAGS.attack_method == 'bim' or FLAGS.attack_method == 'random':\r\n batch_size = 200\r\n num_batch = 5\r\n elif FLAGS.attack_method == 'carliniL2'or FLAGS.attack_method == 'carliniL2_highcon':\r\n batch_size = 10\r\n num_batch = 100\r\n else:\r\n print('Undefined attacking method')\r\n batch_size = None\r\n num_batch = None\r\n\r\n hps = model_name.HParams(batch_size=batch_size,\r\n num_classes=num_classes,\r\n min_lrn_rate=0.0001,\r\n lrn_rate=0.1,\r\n num_residual_units=FLAGS.num_residual_units,\r\n use_bottleneck=False,\r\n weight_decay_rate=0.0002,\r\n relu_leakiness=0.1,\r\n optimizer=FLAGS.Optimizer,\r\n RCE_train=FLAGS.RCE_train)\r\n\r\n if FLAGS.mode == 'attack':\r\n if is_carliniL2 == True:\r\n apply_attack_carlini(hps)\r\n else:\r\n apply_attack_loop(hps)\r\n\r\n elif FLAGS.mode == 'tSNE_logits':\r\n if is_carliniL2 == True:\r\n tSNE_visual_carliniLi(hps,num_batch)\r\n else:\r\n tSNE_visual(hps,num_batch)\r\n\r\n\r\nif __name__ == '__main__':\r\n tf.logging.set_verbosity(tf.logging.INFO)\r\n tf.app.run()" ]
[ [ "tensorflow.reduce_sum", "tensorflow.cast", "numpy.concatenate", "tensorflow.app.flags.DEFINE_string", "numpy.mean", "tensorflow.argmin", "numpy.square", "scipy.io.loadmat", "tensorflow.app.flags.DEFINE_integer", "numpy.save", "tensorflow.ConfigProto", "numpy.argmax", "tensorflow.logging.set_verbosity", "tensorflow.train.Saver", "tensorflow.argmax", "numpy.repeat", "numpy.zeros", "tensorflow.app.run", "tensorflow.app.flags.DEFINE_bool", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.logging.info", "numpy.equal", "numpy.random.random_integers", "numpy.savetxt", "numpy.array", "numpy.sum", "tensorflow.train.get_checkpoint_state", "tensorflow.reduce_max", "tensorflow.nn.softmax", "tensorflow.train.start_queue_runners", "numpy.ones", "tensorflow.log", "tensorflow.app.flags.DEFINE_float", "tensorflow.random_uniform" ] ]
kthyng/cmocean-paraview
[ "6251fc9b0fba9004caa4a4f23d6fecad519322e4" ]
[ "make_xml.py" ]
[ "'''\nConversion from rgb files to Paraview colormap files.\n\nThis reads in the colormap rgb from github directly, and it is stored\nlocally by np.genfromtxt.\n\nAdapted code from Phillip Wolfram (https://gist.github.com/1c042b2a1382eca5415d3139cf591379).\n'''\n\nimport os\nimport numpy as np\nimport cmocean\n\n\n# number of levels for colormap\nN = 256\nx = np.linspace(0, 1, N)\n\n# location of local rgb files\nloc = 'https://raw.githubusercontent.com/matplotlib/cmocean/master/cmocean/rgb/'\n\n# file list\nFiles = [loc + name + '-rgb.txt' for name in cmocean.cm.cmapnames]\n\nif not os.path.exists('xml'):\n os.makedirs('xml')\n\n# make indexed file\nfall = open('xml/cmocean_all.xml', 'w')\nfall.write('<ColorMaps>\\n')\n\n# Loop through rgb files and make xml file\nfor File, name in zip(Files, cmocean.cm.cmapnames):\n\n # read in rgb values\n rgb = np.genfromtxt(File)\n\n # convert to colormap\n cmap = cmocean.tools.cmap(rgb, N=N)\n\n # back to rgb, now correct number of levels\n rgb = cmocean.tools.print_colormaps([cmap], N=N)[0]\n\n # file name\n fname = File.split('/')[-1].split('-')[0]\n findv = open('xml/' + fname + '.xml', 'w')\n\n # write the first line of syntax for individual file\n findv.write('<ColorMaps>\\n')\n\n for af in [findv, fall]:\n af.write('<ColorMap name=\"cmocean_' + name + '\" space=\"RGB\">\\n')\n\n # loop through rgb to write to file\n for j in range(rgb.shape[0]):\n for af in [findv, fall]:\n af.write('<Point x=\"%f\" o=\"1\" r=\"%f\" g=\"%f\" b=\"%f\"/>\\n' % (x[j], rgb[j, 0], rgb[j, 1], rgb[j, 2]))\n\n # final line\n for af in [findv, fall]:\n af.write('</ColorMap>\\n')\n\n findv.write('</ColorMaps>')\n findv.close()\n\nfall.write('</ColorMaps>')\nfall.close()\n" ]
[ [ "numpy.linspace", "numpy.genfromtxt" ] ]
gabrielsluz/DCL-Release
[ "80d6b97371322fc560e04a365febacd6c7c34406" ]
[ "scripts/script_gen_tube_proposals.py" ]
[ "from opt import parse_opt\nimport pdb\nimport os\nimport json\nimport sys\nsys.path.append('/home/gabrielsluz/Jacinle/jaclearn/vision/coco')\nfrom pycocotools.coco import COCO\nimport pycocotools.mask as mask\nimport numpy as np\nimport copy\nimport cv2\nimport shutil\nimport subprocess\nimport math\nimport pickle\nfrom scipy.optimize import linear_sum_assignment\nfrom filterpy.kalman import KalmanFilter\n\nCOLORS = ['gray', 'red', 'blue', 'green', 'brown', 'yellow', 'cyan', 'purple']\nMATERIALS = ['metal', 'rubber']\nSHAPES = ['sphere', 'cylinder', 'cube']\n\nEPS = 1e-10\n\ndef convert_bbox_to_z(bbox):\n \"\"\"\n Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form\n [x,y,s,r] where x,y is the centre of the box and s is the scale/area and r is\n the aspect ratio\n \"\"\"\n w = bbox[2] - bbox[0]\n h = bbox[3] - bbox[1]\n x = bbox[0] + w/2.\n y = bbox[1] + h/2.\n s = w * h # scale is just area\n r = w / float(h)\n return np.array([x, y, s, r]).reshape((4, 1))\n\n\ndef convert_x_to_bbox(x, score=None):\n \"\"\"\n Takes a bounding box in the centre form [x,y,s,r] and returns it in the form\n [x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right\n \"\"\"\n w = np.sqrt(x[2] * x[3])\n h = x[2] / w\n if(score == None):\n return np.array([x[0]-w/2., x[1]-h/2., x[0]+w/2., x[1]+h/2.]).reshape((1, 4))\n else:\n return np.array([x[0]-w/2., x[1]-h/2., x[0]+w/2., x[1]+h/2., score]).reshape((1, 5))\n\nclass KalmanBoxTracker(object):\n \"\"\"\n This class represents the internal state of individual tracked objects observed as bbox.\n \"\"\"\n count = 0\n\n def __init__(self, bbox):\n \"\"\"\n Initialises a tracker using initial bounding box.\n \"\"\"\n # define constant velocity model\n self.kf = KalmanFilter(dim_x=7, dim_z=4)\n self.kf.F = np.array([[1, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0], [0, 0, 1, 0, 0, 0, 1], [\n 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1]])\n self.kf.H = np.array([[1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [\n 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0]])\n\n self.kf.R[2:, 2:] *= 10.\n self.kf.P[4:, 4:] *= 1000. # give high uncertainty to the unobservable initial velocities\n self.kf.P *= 10.\n self.kf.Q[-1, -1] *= 0.01\n self.kf.Q[4:, 4:] *= 0.01\n\n self.kf.x[:4] = convert_bbox_to_z(bbox)\n self.time_since_update = 0\n self.id = KalmanBoxTracker.count\n KalmanBoxTracker.count += 1\n self.history = []\n self.hits = 0\n self.hit_streak = 0\n self.age = 0\n\n def update(self, bbox):\n \"\"\"\n Updates the state vector with observed bbox.\n \"\"\"\n self.time_since_update = 0\n self.history = []\n self.hits += 1\n self.hit_streak += 1\n self.kf.update(convert_bbox_to_z(bbox))\n\n def predict(self):\n \"\"\"\n Advances the state vector and returns the predicted bounding box estimate.\n \"\"\"\n if((self.kf.x[6]+self.kf.x[2]) <= 0):\n self.kf.x[6] *= 0.0\n self.kf.predict()\n self.age += 1\n if(self.time_since_update > 0):\n self.hit_streak = 0\n self.time_since_update += 1\n self.history.append(convert_x_to_bbox(self.kf.x))\n return self.history[-1]\n\n def get_state(self):\n \"\"\"\n Returns the current bounding box estimate.\n \"\"\"\n return convert_x_to_bbox(self.kf.x)\n\n\ndef compute_IoU_v2(bbox1, bbox2):\n bbox1_area = float((bbox1[2] - bbox1[0] + EPS) * (bbox1[3] - bbox1[1] + EPS))\n bbox2_area = float((bbox2[2] - bbox2[0] + EPS) * (bbox2[3] - bbox2[1] + EPS))\n w = max(0.0, min(bbox1[2], bbox2[2]) - max(bbox1[0], bbox2[0]) + EPS)\n h = max(0.0, min(bbox1[3], bbox2[3]) - max(bbox1[1], bbox2[1]) + EPS)\n inter = float(w * h)\n ovr = inter / (bbox1_area + bbox2_area - inter)\n return ovr\n\ndef compute_LS(traj, gt_traj):\n # see http://jvgemert.github.io/pub/jain-tubelets-cvpr2014.pdf\n IoU_list = []\n frm_num = 0\n for frame_ind, gt_box in enumerate(gt_traj):\n box = traj[frame_ind]\n if not (box==[0, 0, 1, 1] and gt_box==[0, 0, 1, 1]):\n frm_num +=1\n if box==[0, 0, 1, 1] or gt_box==[0, 0, 1, 1]:\n continue\n IoU_list.append(compute_IoU_v2(box, gt_box))\n return sum(IoU_list) / frm_num\n\ndef pickleload(path):\n f = open(path, 'rb')\n this_ans = pickle.load(f)\n f.close()\n return this_ans\n\ndef pickledump(path, this_dic):\n f = open(path, 'wb')\n this_ans = pickle.dump(this_dic, f)\n f.close()\n\ndef jsonload(path):\n f = open(path)\n this_ans = json.load(f)\n f.close()\n return this_ans\n\ndef jsondump(path, this_dic):\n f = open(path, 'w')\n this_ans = json.dump(this_dic, f)\n f.close()\n\ndef set_debugger():\n from IPython.core import ultratb\n sys.excepthook = ultratb.FormattedTB(call_pdb=True)\n\nset_debugger()\n\ndef imread_if_str(img):\n if isinstance(img, str):\n img = cv2.imread(img)\n return img\n\ndef draw_rectangle(img, bbox, color=(0,0,255), thickness=3, use_dashed_line=False):\n img = imread_if_str(img)\n if isinstance(bbox, dict):\n bbox = [\n bbox['x1'],\n bbox['y1'],\n bbox['x2'],\n bbox['y2'],\n ]\n bbox[0] = max(bbox[0], 0)\n bbox[1] = max(bbox[1], 0)\n bbox[0] = min(bbox[0], img.shape[1])\n bbox[1] = min(bbox[1], img.shape[0])\n bbox[2] = max(bbox[2], 0)\n bbox[3] = max(bbox[3], 0)\n bbox[2] = min(bbox[2], img.shape[1])\n bbox[3] = min(bbox[3], img.shape[0])\n assert bbox[2] >= bbox[0]\n assert bbox[3] >= bbox[1]\n assert bbox[0] >= 0\n assert bbox[1] >= 0\n assert bbox[2] <= img.shape[1]\n assert bbox[3] <= img.shape[0]\n cur_img = copy.deepcopy(img)\n if use_dashed_line:\n drawrect(\n cur_img,\n (int(bbox[0]), int(bbox[1])),\n (int(bbox[2]), int(bbox[3])),\n color,\n thickness,\n 'dotted'\n )\n else:\n cv2.rectangle(\n cur_img,\n (int(bbox[0]), int(bbox[1])),\n (int(bbox[2]), int(bbox[3])),\n color,\n thickness)\n return cur_img\n\ndef images2video(image_list, frame_rate, video_path, max_edge=None):\n TMP_DIR = '.tmp'\n FFMPEG = 'ffmpeg'\n SAVE_VIDEO = FFMPEG + ' -y -r %d -i %s/%s.jpg %s'\n \n if os.path.exists(TMP_DIR):\n shutil.rmtree(TMP_DIR)\n os.mkdir(TMP_DIR)\n img_size = None\n for cur_num, cur_img in enumerate(image_list):\n cur_fname = os.path.join(TMP_DIR, '%08d.jpg' % cur_num)\n if max_edge is not None:\n cur_img = imread_if_str(cur_img)\n if isinstance(cur_img, str):\n shutil.copyfile(cur_img, cur_fname)\n elif isinstance(cur_img, np.ndarray):\n max_len = max(cur_img.shape[:2])\n if max_edge is not None and max_len > max_edge and img_size is None and max_edge is not None:\n magnif = float(max_edge) / float(max_len)\n img_size = (int(cur_img.shape[1] * magnif), int(cur_img.shape[0] * magnif))\n cur_img = cv2.resize(cur_img, img_size)\n elif max_edge is not None:\n if img_size is None:\n magnif = float(max_edge) / float(max_len)\n img_size = (int(cur_img.shape[1] * magnif), int(cur_img.shape[0] * magnif))\n cur_img = cv2.resize(cur_img, img_size)\n cv2.imwrite(cur_fname, cur_img)\n else:\n NotImplementedError()\n print(subprocess.getoutput(SAVE_VIDEO % (frame_rate, TMP_DIR, '%08d', video_path)))\n shutil.rmtree(TMP_DIR)\n\ndef visTube_from_image(frmList, tube, outName):\n image_list = list()\n for i, bbx in enumerate(tube):\n imName = frmList[i]\n img = draw_rectangle(imName, bbx)\n image_list.append(img)\n images2video(image_list, 10, outName)\n\ndef visual_tube_proposals(results, f_dict, prp_num, opt):\n sub_idx = int(f_dict['video_index']/1000)\n\n jpg_folder = os.path.join(opt['img_folder_path'], 'image_%s000-%s000'%(str(sub_idx).zfill(2), \\\n str(sub_idx+1).zfill(2)), 'video_%s'%(str(f_dict['video_index']).zfill(5)))\n frmImNameList = [os.path.join(jpg_folder, str(frm_info['frame_index']+1) + '.png') for frm_info in f_dict['frames']]\n frmImList = list()\n for fId, imPath in enumerate(frmImNameList):\n img = cv2.imread(imPath)\n frmImList.append(img)\n #vis_frame_num = len(frmImList)\n vis_frame_num = 32\n visIner = int(len(frmImList) /vis_frame_num)\n for ii in range(len(results[0])):\n print('visualizing tube %d\\n'%(ii))\n tube = results[0][ii]\n frmImList_vis = [frmImList[iii] for iii in range(0, len(frmImList), visIner)]\n tube_vis = [tube[iii] for iii in range(0, len(frmImList), visIner)]\n #tube_vis_resize = resize_tube_bbx(tube_vis, frmImList_vis)\n vd_name_raw = 'video_%d'%(f_dict['video_index'])\n #out_sub_path = 'sample/'+vd_name_raw + '_' + str(opt['connect_w'])+'_'+str(opt['score_w'])\n out_sub_path = opt['vis_path'] + vd_name_raw + '_' + str(opt['connect_w'])+'_'+str(opt['score_w']) + '_'+ str(opt['attr_w'])\n if not os.path.isdir(out_sub_path):\n os.makedirs(out_sub_path)\n out_full_path = os.path.join(out_sub_path, str(prp_num)+'_' + str(ii)+'.gif')\n visTube_from_image(copy.deepcopy(frmImList_vis), tube_vis, out_full_path) \n\ndef compute_IoU(box1, box2):\n KEYS = ['x1', 'y1', 'x2', 'y2']\n if isinstance(box1, list):\n box1 = {key: val for key, val in zip(KEYS, box1)}\n if isinstance(box2, list):\n box2 = {key: val for key, val in zip(KEYS, box2)}\n width = max(min(box1['x2'], box2['x2']) - max(box1['x1'], box2['x1']), 0)\n height = max(min(box1['y2'], box2['y2']) - max(box1['y1'], box2['y1']), 0)\n intersection = width * height\n box1_area = (box1['x2'] - box1['x1']) * (box1['y2'] - box1['y1'])\n box2_area = (box2['x2'] - box2['x1']) * (box2['y2'] - box2['y1'])\n union = box1_area + box2_area - intersection\n return float(intersection) / (float(union) +0.000001) # avoid overthow\n\ndef get_sub_folder_list(folder_name):\n folder_list = []\n for file_name in os.listdir(folder_name):\n full_sub_path = os.path.join(folder_name, file_name)\n if os.path.isdir(full_sub_path):\n folder_list.append(full_sub_path)\n return folder_list\n\ndef decode_mp4_to_jpg(opt):\n video_folder_path = opt['video_folder_path']\n sub_folder_list = get_sub_folder_list(video_folder_path)\n #pdb.set_trace()\n for sub_idx, full_sub_folder in enumerate(sub_folder_list):\n if 'video' not in full_sub_folder:\n continue\n img_sub_path = os.path.basename(full_sub_folder).replace('video', 'image')\n full_img_sub_path = os.path.join(opt['img_folder_path'], img_sub_path)\n\n for fn_idx, file_name in enumerate(os.listdir(full_sub_folder)):\n if 'mp4' not in file_name:\n continue\n full_sub_video_name = os.path.join(full_sub_folder, file_name)\n full_sub_img_out_path = os.path.join(full_img_sub_path, \\\n file_name.replace('.mp4', ''))\n \n if not os.path.isdir(full_sub_img_out_path):\n os.makedirs(full_sub_img_out_path)\n\n cmd = 'ffmpeg -i %s -vf fps=25 %s/' %(full_sub_video_name, full_sub_img_out_path) + '%d.png' \n os.system(cmd)\n\n print('finish!\\n')\n\n\ndef extract_tube_per_video(f_dict, opt):\n connect_w = opt['connect_w']\n score_w = opt['score_w']\n bbx_sc_list = []\n\n # get object number of a video\n max_obj_num = 0\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n tmp_obj_num = len(frm_info['objects']) \n if max_obj_num<tmp_obj_num:\n max_obj_num = tmp_obj_num \n\n\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n bbx_mat = []\n sc_mat = []\n color_list = []\n material_list = []\n shape_list = []\n attr_list = []\n tmp_obj_num = len(frm_info['objects']) \n for obj_idx, obj_info in enumerate(frm_info['objects']):\n bbx_xywh = mask.toBbox(obj_info['mask'])\n bbx_xyxy = copy.deepcopy(bbx_xywh)\n bbx_xyxy[2] = bbx_xyxy[2] + bbx_xyxy[0]\n bbx_xyxy[3] = bbx_xyxy[3] + bbx_xyxy[1]\n bbx_mat.append(bbx_xyxy)\n sc_mat.append(obj_info['score']*score_w)\n \n if opt['use_attr_flag']:\n attr_list.append([obj_info['color'], obj_info['material'], obj_info['shape']])\n\n frm_size = frm_info['objects'][0]['mask']['size']\n for tmp_idx in range(tmp_obj_num, max_obj_num):\n tmp_box = np.array([0, 0, 1, 1])\n bbx_mat.append(tmp_box)\n sc_mat.append(-100)\n \n if opt['use_attr_flag']:\n attr_list.append(['', '', ''])\n\n bbx_mat = np.stack(bbx_mat, axis=0)\n sc_mat = np.array(sc_mat)\n sc_mat = np.expand_dims(sc_mat, axis=1 )\n\n #pdb.set_trace()\n\n if not opt['use_attr_flag']:\n bbx_sc_list.append([sc_mat, bbx_mat])\n else:\n bbx_sc_list.append([sc_mat, bbx_mat, attr_list])\n\n tube_list, score_list = get_tubes(bbx_sc_list, connect_w, opt['use_attr_flag'])\n return tube_list, score_list, bbx_sc_list \n\n\ndef compare_attr_score(attr_list1, attr_list2):\n attr_score = 0\n for att_idx, att1 in enumerate(attr_list1):\n att2 = attr_list2[att_idx]\n if att1==att2 and att1 !='':\n attr_score +=1\n return attr_score \n\ndef get_tubes(det_list_org, alpha, use_attr_flag=False, attr_w=1.0):\n \"\"\"\n det_list_org: [score_list, bbx_list]\n alpha: connection weight\n \"\"\"\n det_list = copy.deepcopy(det_list_org)\n tubes = []\n continue_flg = True\n tube_scores = []\n\n while continue_flg:\n timestep = 0\n obj_num = det_list[timestep][0].shape[0]\n \n if use_attr_flag:\n acc_time_list = []\n acc_attr_list = []\n for obj_id in range(obj_num):\n tmp_obj_dict = {}\n for attr_id, attr_concept in enumerate(['colors', 'materials', 'shapes']):\n attr_upper = attr_concept.upper()\n tmp_obj_num = 0\n concept_dict = {}\n for concept in globals()[attr_upper]:\n concept_dict[concept] = 0.0\n obj_concept = det_list[timestep][2][obj_id][attr_id]\n concept_dict[obj_concept] = 1.0\n tmp_obj_dict[attr_upper] = concept_dict \n acc_attr_list.append(tmp_obj_dict) \n acc_time_list.append(acc_attr_list)\n\n for t_id in range(1, len(det_list)):\n acc_time_list.append([])\n for obj_id in range(obj_num):\n acc_time_list[t_id].append({})\n\n score_list = []\n score_list.append(np.zeros(det_list[timestep][0].shape[0]))\n prevind_list = []\n prevind_list.append([-1] * det_list[timestep][0].shape[0])\n timestep += 1\n\n\n while timestep < len(det_list):\n n_curbox = det_list[timestep][0].shape[0]\n n_prevbox = score_list[-1].shape[0]\n cur_scores = np.zeros(n_curbox) - np.inf\n prev_inds = [-1] * n_curbox\n for i_prevbox in range(n_prevbox):\n prevbox_coods = det_list[timestep-1][1][i_prevbox, :]\n prevbox_score = det_list[timestep-1][0][i_prevbox, 0]\n\n for i_curbox in range(n_curbox):\n curbox_coods = det_list[timestep][1][i_curbox, :]\n curbox_score = det_list[timestep][0][i_curbox, 0]\n #try:\n if True:\n e_score = compute_IoU(prevbox_coods.tolist(), curbox_coods.tolist())\n link_score = prevbox_score + curbox_score + alpha * (e_score)\n \n if use_attr_flag:\n #prevbox_attr = det_list[timestep-1][2][i_prevbox]\n det_list\n prevbox_attr = acc_time_list[timestep-1][i_prevbox]\n curbox_attr = det_list[timestep][2][i_curbox]\n #attr_score = compare_attr_score(prevbox_attr, curbox_attr)\n attr_score = 0.0\n for attr_id, attr_concept in enumerate(['colors', 'materials', 'shapes']):\n attr_upper = attr_concept.upper()\n concept = curbox_attr[attr_id] \n if concept!='':\n attr_score += prevbox_attr[attr_upper][concept] \n attr_score /= timestep \n link_score += attr_score * attr_w\n #if e_score<=0:\n # link_score = 0.0\n # pdb.set_trace()\n \n cur_score = score_list[-1][i_prevbox] + link_score\n if cur_score > cur_scores[i_curbox]:\n cur_scores[i_curbox] = cur_score\n prev_inds[i_curbox] = i_prevbox\n if use_attr_flag:\n acc_time_list[timestep][i_curbox] = copy.deepcopy(acc_time_list[timestep-1][i_prevbox])\n curbox_attr = det_list[timestep][2][i_curbox]\n for attr_id, attr_concept in enumerate(['colors', 'materials', 'shapes']):\n attr_upper = attr_concept.upper()\n concept = curbox_attr[attr_id] \n if concept!='':\n acc_time_list[timestep][i_curbox][attr_upper][concept] +=1 \n\n score_list.append(cur_scores)\n prevind_list.append(prev_inds)\n timestep += 1\n\n # get path and remove used boxes\n cur_tube = [None] * len(det_list)\n tube_score = np.max(score_list[-1]) / len(det_list)\n prev_ind = np.argmax(score_list[-1])\n timestep = len(det_list) - 1\n while timestep >= 0:\n cur_tube[timestep] = det_list[timestep][1][prev_ind, :].tolist()\n det_list[timestep][0] = np.delete(det_list[timestep][0], prev_ind, axis=0)\n det_list[timestep][1] = np.delete(det_list[timestep][1], prev_ind, axis=0)\n if use_attr_flag:\n det_list[timestep][2].pop(prev_ind)\n prev_ind = prevind_list[timestep][prev_ind]\n if det_list[timestep][1].shape[0] == 0:\n continue_flg = False\n timestep -= 1\n assert prev_ind < 0\n tubes.append(cur_tube)\n tube_scores.append(tube_score)\n return tubes, tube_scores\n\ndef extract_tube_v0(opt):\n sample_folder_path= '/datasets/dcl_clevrer/proposals'\n file_list = get_sub_file_list(sample_folder_path, '.json')\n file_list.sort()\n out_path = os.path.join(opt['tube_folder_path'] , str(opt['connect_w'])+'_'+str(opt['score_w'])+'_'+str(opt['attr_w']))\n if not os.path.isdir(out_path):\n os.makedirs(out_path)\n for file_idx, sample_file in enumerate(file_list):\n \n #if file_idx<10000:\n # continue \n\n out_fn_path = os.path.join(out_path, os.path.basename(sample_file.replace('json', 'pk')))\n if os.path.isfile(out_fn_path):\n continue \n #pass \n\n fh = open(sample_file, 'r')\n f_dict = json.load(fh)\n max_obj_num = 0\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n tmp_obj_num = len(frm_info['objects']) \n if max_obj_num<tmp_obj_num:\n max_obj_num = tmp_obj_num \n\n if opt['use_attr_flag']:\n attr_dict_path = os.path.join(opt['extract_att_path'], 'attribute_' + str(file_idx).zfill(5) +'.json')\n if not os.path.isfile(attr_dict_path):\n continue \n attr_dict_list = jsonload(attr_dict_path) \n tube_list, score_list, bbx_sc_list = extract_tube_per_video_attribute(f_dict, opt, attr_dict_list) \n else:\n tube_list, score_list, bbx_sc_list = extract_tube_per_video_attribute(f_dict, opt) \n out_dict = {'tubes': tube_list, 'scores': score_list, 'bbx_list': bbx_sc_list }\n pickledump(out_fn_path, out_dict)\n pdb.set_trace()\n if file_idx%100==0:\n print('finish processing %d/%d videos' %(file_idx, len(file_list)))\n #if file_idx<=10100 and 0:\n #visual_tube_proposals([tube_list, score_list], f_dict, max_obj_num, opt)\n\ndef visual_specific_tube(opt):\n sample_folder_path= '/datasets/dcl_clevrer/proposals'\n file_list = get_sub_file_list(sample_folder_path, '.json')\n file_list.sort()\n #out_path = os.path.join(opt['tube_folder_path'] , str(opt['connect_w'])+'_'+str(opt['score_w']))\n out_path = os.path.join('../clevrer/tubeProposalsGt')\n\n if not os.path.isdir(out_path):\n os.makedirs(out_path)\n \n for file_idx, sample_file in enumerate(file_list):\n #if file_idx not in [10000, 10001]:\n #if file_idx not in [10002, 10003, 10004]:\n if file_idx not in list(range(10000, 10011)):\n continue \n #pdb.set_trace()\n out_fn_path = os.path.join(out_path, os.path.basename(sample_file.replace('json', 'pk').replace('proposal', 'annotation')))\n\n fh = open(sample_file, 'r')\n f_dict = json.load(fh)\n max_obj_num = 0\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n tmp_obj_num = len(frm_info['objects']) \n if max_obj_num<tmp_obj_num:\n max_obj_num = tmp_obj_num \n\n out_dict = pickleload(out_fn_path)\n tube_list = out_dict['tubes']\n #score_list = out_dict['scores']\n #bbx_sc_list = out_dict['bbx_list']\n if file_idx%100==0:\n print('finish processing %d/%d videos' %(file_idx, len(file_list)))\n visual_tube_proposals([tube_list, None], f_dict, max_obj_num, opt)\n\n\n\ndef get_sub_file_list(folder_name, file_type=None):\n file_list = []\n for file_name in os.listdir(folder_name):\n full_sub_path = os.path.join(folder_name, file_name)\n if file_type is None:\n file_list.append(full_sub_path)\n elif file_type in full_sub_path:\n file_list.append(full_sub_path)\n return file_list\n\n\ndef extract_tube_attribute(opt):\n sample_folder_path= '/datasets/dcl_clevrer/proposals'\n file_list = get_sub_file_list(sample_folder_path, '.json')\n file_list.sort()\n out_path = os.path.join(opt['tube_folder_new_path'] , str(opt['connect_w'])+'_'+str(opt['score_w']))\n if not os.path.isdir(out_path):\n os.makedirs(out_path)\n for file_idx, sample_file in enumerate(file_list):\n\n if file_idx!=0:\n continue \n #if file_idx>=100:\n # break \n out_fn_path = os.path.join(out_path, os.path.basename(sample_file.replace('json', 'pk')))\n #if os.path.isfile(out_fn_path):\n # continue \n\n fh = open(sample_file, 'r')\n f_dict = json.load(fh)\n max_obj_num = 0\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n tmp_obj_num = len(frm_info['objects']) \n if max_obj_num<tmp_obj_num:\n max_obj_num = tmp_obj_num \n\n tube_list, score_list, bbx_sc_list = extract_tube_per_video(f_dict, opt) \n out_dict = {'tubes': tube_list, 'scores': score_list, 'bbx_list': bbx_sc_list }\n visual_tube_proposals([tube_list, score_list], f_dict, max_obj_num, opt)\n pdb.set_trace()\n pickledump(out_fn_path, out_dict)\n if file_idx%100==0:\n print('finish processing %d/%d videos' %(file_idx, len(file_list)))\n\ndef decode_box(obj_info):\n bbx_xywh = mask.toBbox(obj_info)\n bbx_xyxy = copy.deepcopy(bbx_xywh)\n bbx_xyxy[2] = bbx_xyxy[2] + bbx_xyxy[0]\n bbx_xyxy[3] = bbx_xyxy[3] + bbx_xyxy[1]\n return bbx_xyxy \n\ndef parse_tube_gt(obj_dict_gt, obj_dict_prp, opt):\n\n tube_num = len(obj_dict_gt['object_property'])\n tube_dict = [ [] for idx in range(tube_num)]\n for frm_idx, motion_info in enumerate(obj_dict_gt['motion_trajectory']):\n if frm_idx>=len(obj_dict_prp['frames']):\n print('Warning proposal frame num: %d, parse frame num: %d\\n' %(len(obj_dict_prp['frames']), len(obj_dict_gt['motion_trajectory'])))\n continue \n frm_prp_info = obj_dict_prp['frames'][frm_idx]\n for obj_idx, obj_info in enumerate(motion_info['objects']):\n \n if not obj_info['inside_camera_view']:\n tube_dict[obj_idx].append([0, 0, 1, 1])\n continue \n\n obj_attr_info = obj_dict_gt['object_property'][obj_idx] \n\n obj_attr = [obj_attr_info['color'], obj_attr_info['material'], obj_attr_info['shape']] \n \n max_score = 0\n max_bbx = [0, 0, 1, 1]\n\n for prp_idx, prp_info in enumerate(frm_prp_info['objects']):\n prp_xyxy = decode_box(prp_info['mask']).tolist()\n\n prp_attr = [prp_info['color'], prp_info['material'], prp_info['shape'] ]\n attr_score = compare_attr_score(obj_attr, prp_attr)\n conf_score = prp_info['score']\n if len(tube_dict[obj_idx])==0:\n iou_score = 0\n else:\n iou_score = compute_IoU(tube_dict[obj_idx][-1], prp_xyxy)\n match_score = attr_score + conf_score*opt['conf_w'] + iou_score*opt['iou_w']\n if match_score>max_score:\n max_score = match_score\n max_bbx = prp_xyxy\n \n tube_dict[obj_idx].append(max_bbx)\n\n return tube_dict \n\n\ndef parse_object_track(opt):\n #pdb.set_trace()\n sub_folder_list = get_sub_folder_list(opt['ann_path'])\n ann_file_list = []\n for sub_folder in sub_folder_list:\n if 'annotation' not in sub_folder:\n continue \n sub_file_list = get_sub_file_list(sub_folder, 'json')\n ann_file_list += sub_file_list\n ann_file_list.sort()\n pdb.set_trace()\n out_path = os.path.join(opt['tube_folder_new_path'])\n if not os.path.isdir(out_path):\n os.makedirs(out_path)\n\n for ann_idx, ann_file in enumerate(ann_file_list):\n\n out_fn_path = os.path.join(out_path, os.path.basename(ann_file.replace('json', 'pk')))\n if os.path.isfile(out_fn_path):\n continue \n if ann_idx <10000:\n continue \n ann_dict = jsonload(ann_file)\n prp_file_path = os.path.join(opt['prp_path'], 'proposal_'+str(ann_dict['scene_index']).zfill(5)+'.json')\n prp_dict = jsonload(prp_file_path)\n \n tube_list = parse_tube_gt(ann_dict, prp_dict, opt)\n #visual_tube_proposals([tube_list], prp_dict, len(tube_list), opt)\n\n out_dict = {'tubes': tube_list}\n pickledump(out_fn_path, out_dict)\n if ann_idx%100==0:\n print('finish processing %d/%d videos' %(ann_idx, len(ann_file_list)))\n #visual_tube_proposals([tube_list, score_list], f_dict, max_obj_num, opt)\n\ndef processing_tube_list(opt):\n tube_prp_path = os.path.join(opt['tube_folder_path'] , str(opt['connect_w'])+'_'+str(opt['score_w']))\n pk_fn_list = get_sub_file_list(tube_prp_path, 'pk')\n pk_fn_list.sort()\n minimum_len = 10\n for f_id, prp_fn in enumerate(pk_fn_list):\n prp_tube_dict = pickleload(prp_fn)\n remove_tube_ids= []\n for prp_id, prp_info in enumerate(prp_tube_dict['tubes']):\n new_tube_list = []\n new_st_id_list = []\n new_flag=True \n for box_id, box_info in enumerate(prp_info): \n if box_info==[0, 0, 1, 1]:\n if len(new_st_id_list)!=0 and len(new_st_id_list[-1])==1:\n new_st_id_list[-1].append(box_id)\n new_flag=True\n continue\n if new_flag:\n new_st_id_list.append([box_id])\n new_flag=False\n if len(new_st_id_list[-1])==1:\n new_st_id_list[-1].append(len(prp_info))\n\n new_list_len = len(new_st_id_list)\n remove_ids = []\n if new_list_len>1:\n for new_id in range(new_list_len):\n if new_st_id_list[new_id][1]-new_st_id_list[new_id][0]<minimum_len:\n remove_ids.append(new_id)\n if (len(new_st_id_list) - len(remove_ids))>1:\n remove_tube_ids.append(prp_id)\n for new_id, tube_bound in enumerate(new_st_id_list):\n if new_id in remove_ids:\n continue \n st_id, end_id = tube_bound\n new_list = []\n for frm_id, box_info in enumerate(prp_info):\n if frm_id <st_id or frm_id>=end_id:\n new_list.append([0, 0, 1, 1])\n else:\n new_list.append(box_info)\n new_tube_list.append(new_list)\n\n new_prp_list= []\n for prp_idx, prp_info in enumerate(prp_tube_dict['tubes']):\n if prp_idx in remove_tube_ids:\n continue \n new_prp_list.append(prp_info)\n new_prp_list+=new_tube_list\n\n if len(new_tube_list)>0:\n file_idx = prp_fn.split('_')[-1].split('.')[0]\n prp_file_path = os.path.join(opt['prp_path'], 'proposal_'+file_idx +'.json')\n f_dict = jsonload(prp_file_path)\n visual_tube_proposals([new_prp_list], f_dict, len(new_prp_list), opt)\n #pdb.set_trace()\n\n\ndef compute_recall_and_precision(opt):\n \n iou_thre_list = [0.5, 0.6, 0.7, 0.8, 0.9]\n precision_list = [0 for i in range(len(iou_thre_list))]\n recall_list = [0 for i in range(len(iou_thre_list))]\n prp_num = 0\n gt_num = 0\n\n #pdb.set_trace()\n\n if opt['use_attr_flag'] or opt['version']==2 or opt['version']==1 or opt['version']==3:\n #tube_prp_path = os.path.join(opt['tube_folder_path'] , str(opt['connect_w'])+'_'+str(opt['score_w']) + '_' +str(opt['attr_w']))\n tube_prp_path = os.path.join(opt['tube_folder_path'] , str(opt['connect_w'])+'_'+str(opt['score_w']) + '_' +str(opt['attr_w'])+ '_'+str(opt['match_thre']))\n else:\n tube_prp_path = os.path.join(opt['tube_folder_path'] , str(opt['connect_w'])+'_'+str(opt['score_w']))\n out_gt_path = os.path.join(opt['tube_folder_new_path'])\n\n pk_fn_list = get_sub_file_list(out_gt_path, 'pk')\n pk_fn_list.sort()\n for f_id, pk_fn in enumerate(pk_fn_list):\n gt_tube_dict = pickleload(pk_fn)\n id_str = pk_fn.split('_')[-1].split('.')[0]\n tube_prp_pk_fn = os.path.join(tube_prp_path, 'proposal_'+id_str+'.pk')\n if not os.path.isfile(tube_prp_pk_fn):\n continue\n if f_id < opt['start_index'] or f_id>=opt['end_index']:\n continue\n prp_tube_dict = pickleload(tube_prp_pk_fn)\n\n #iou_mat = np.zeros([len(prp_tube_dict['tubes']), len(gt_tube_dict['tubes'])])\n tmp_correct_num = 0\n tmp_iou_list = []\n \n for prp_idx, prp in enumerate(prp_tube_dict['tubes']):\n tmp_max_iou = 0\n for gt_idx, gt in enumerate(gt_tube_dict['tubes']):\n iou = compute_LS(prp, gt)\n #iou_mat[prp_idx, gt_idx] = iou\n\n for thre_idx, iou_thre in enumerate(iou_thre_list):\n if iou>=iou_thre:\n precision_list[thre_idx]+=1\n recall_list[thre_idx]+=1\n\n if iou>=iou_thre_list[-1]:\n tmp_correct_num +=1\n if iou>tmp_max_iou:\n tmp_max_iou = iou\n tmp_iou_list.append(tmp_max_iou)\n\n tmp_prp_num = len(prp_tube_dict['tubes'])\n tmp_gt_num = len(gt_tube_dict['tubes'])\n\n tmp_recall = tmp_correct_num *1.0 / tmp_gt_num \n tmp_precision = tmp_correct_num *1.0 / tmp_prp_num \n if (tmp_recall <1 or tmp_precision <1) and opt['visualize_flag']==1:\n sample_folder_path= '/datasets/dcl_clevrer/proposals'\n sample_file = os.path.join(sample_folder_path, 'proposal_'+str(f_id)+'.json')\n fh = open(sample_file, 'r')\n f_dict = json.load(fh)\n visual_tube_proposals([prp_tube_dict['tubes'], prp_tube_dict['scores']], f_dict, tmp_prp_num, opt)\n print(tmp_iou_list)\n print(tmp_recall)\n print(tmp_precision)\n print(f_id)\n pdb.set_trace()\n\n prp_num +=len(prp_tube_dict['tubes'])\n gt_num +=len(gt_tube_dict['tubes'])\n\n #if f_id % 500==0 or f_id==(len(pk_fn_list)-1) or f_id==99:\n if f_id==(len(pk_fn_list)-1) or f_id==opt['end_index']-1:\n #or f_id==99:\n print('processing %d/%d videos.\\n' %(f_id, len(pk_fn_list)))\n for thre_idx, iou_thre in enumerate(iou_thre_list):\n #if thre_idx!=len(iou_thre_list)-1:\n # continue \n print('precision@%3f is %3f\\n' %(iou_thre, precision_list[thre_idx]*1.0/prp_num))\n for thre_idx, iou_thre in enumerate(iou_thre_list):\n #if thre_idx!=len(iou_thre_list)-1:\n # continue \n print('recall@%3f is %3f\\n' %(iou_thre, recall_list[thre_idx]*1.0/gt_num))\n print('\\n')\n\ndef extract_tube_per_video_attribute(f_dict, opt, attr_dict_list):\n connect_w = opt['connect_w']\n score_w = opt['score_w']\n bbx_sc_list = []\n\n assert len(f_dict['frames'])==len(attr_dict_list)\n\n # get object number of a video\n max_obj_num = 0\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n tmp_obj_num = len(frm_info['objects']) \n if max_obj_num<tmp_obj_num:\n max_obj_num = tmp_obj_num \n\n\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n bbx_mat = []\n sc_mat = []\n color_list = []\n material_list = []\n shape_list = []\n attr_list = []\n tmp_obj_num = len(frm_info['objects']) \n\n attr_frm_dict = attr_dict_list[frm_idx]\n assert len(frm_info['objects']) == len(attr_frm_dict['color'])\n for obj_idx, obj_info in enumerate(frm_info['objects']):\n bbx_xywh = mask.toBbox(obj_info['mask'])\n bbx_xyxy = copy.deepcopy(bbx_xywh)\n bbx_xyxy[2] = bbx_xyxy[2] + bbx_xyxy[0]\n bbx_xyxy[3] = bbx_xyxy[3] + bbx_xyxy[1]\n bbx_mat.append(bbx_xyxy)\n sc_mat.append(obj_info['score']*score_w)\n \n if opt['use_attr_flag']:\n tmp_color = COLORS[attr_frm_dict['color'][obj_idx]]\n tmp_material = MATERIALS[attr_frm_dict['material'][obj_idx]]\n tmp_shape = SHAPES[attr_frm_dict['shape'][obj_idx]]\n attr_list.append([tmp_color, tmp_material, tmp_shape])\n #pdb.set_trace()\n\n\n frm_size = frm_info['objects'][0]['mask']['size']\n for tmp_idx in range(tmp_obj_num, max_obj_num):\n tmp_box = np.array([0, 0, 1, 1])\n bbx_mat.append(tmp_box)\n sc_mat.append(-100)\n \n if opt['use_attr_flag']:\n attr_list.append(['', '', ''])\n\n bbx_mat = np.stack(bbx_mat, axis=0)\n sc_mat = np.array(sc_mat)\n sc_mat = np.expand_dims(sc_mat, axis=1 )\n\n #pdb.set_trace()\n\n if not opt['use_attr_flag']:\n bbx_sc_list.append([sc_mat, bbx_mat])\n\n else:\n bbx_sc_list.append([sc_mat, bbx_mat, attr_list])\n\n tube_list, score_list = get_tubes(bbx_sc_list, connect_w, opt['use_attr_flag'], opt['attr_w'])\n return tube_list, score_list, bbx_sc_list \n\ndef extract_tube_v1(opt):\n sample_folder_path= '/datasets/dcl_clevrer/proposals'\n file_list = get_sub_file_list(sample_folder_path, '.json')\n file_list.sort()\n #out_path = os.path.join(opt['tube_folder_path'] , str(opt['connect_w'])+'_'+str(opt['score_w'])+'_'+str(opt['attr_w'])+'_v1')\n out_path = os.path.join(opt['tube_folder_path'] , str(opt['connect_w'])+'_'+str(opt['score_w'])+'_'+str(opt['attr_w'])+'_'+str(opt['match_thre']))\n if not os.path.isdir(out_path):\n os.makedirs(out_path)\n for file_idx, sample_file in enumerate(file_list):\n\n out_fn_path = os.path.join(out_path, os.path.basename(sample_file.replace('json', 'pk')))\n if file_idx < opt['start_index'] or file_idx>=opt['end_index']:\n continue\n\n if os.path.isfile(out_fn_path):\n continue\n\n fh = open(sample_file, 'r')\n f_dict = json.load(fh)\n max_obj_num = 0\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n tmp_obj_num = len(frm_info['objects']) \n if max_obj_num<tmp_obj_num:\n max_obj_num = tmp_obj_num \n \n if opt['use_attr_flag']:\n attr_dict_path = os.path.join(opt['extract_att_path'], 'attribute_' + str(file_idx).zfill(5) +'.json')\n if not os.path.isfile(attr_dict_path):\n continue \n attr_dict_list = jsonload(attr_dict_path) \n tube_list, score_list, bbx_sc_list = extract_tube_per_video_attribute_v1(f_dict, opt, attr_dict_list) \n else:\n tube_list, score_list, bbx_sc_list = extract_tube_per_video_attribute_v1(f_dict, opt) \n if opt['refine_tube_flag']:\n tube_list, score_list = refine_tube_list(tube_list, score_list, bbx_sc_list, opt)\n out_dict = {'tubes': tube_list, 'scores': score_list, 'bbx_list': bbx_sc_list }\n pickledump(out_fn_path, out_dict)\n if file_idx%1000==0 or file_idx==100:\n print('finish processing %d/%d videos' %(file_idx, len(file_list)))\n\ndef extract_tube_per_video_attribute_v1(f_dict, opt, attr_dict_list=None):\n connect_w = opt['connect_w']\n score_w = opt['score_w']\n bbx_sc_list = []\n\n if attr_dict_list is not None:\n assert len(f_dict['frames'])==len(attr_dict_list)\n\n # get object number of a video\n max_obj_num = 0\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n tmp_obj_num = len(frm_info['objects']) \n if max_obj_num<tmp_obj_num:\n max_obj_num = tmp_obj_num \n\n\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n bbx_mat = []\n sc_mat = []\n color_list = []\n material_list = []\n shape_list = []\n attr_list = []\n tmp_obj_num = len(frm_info['objects']) \n\n if opt['use_attr_flag']:\n attr_frm_dict = attr_dict_list[frm_idx]\n assert len(frm_info['objects']) == len(attr_frm_dict['color'])\n for obj_idx, obj_info in enumerate(frm_info['objects']):\n bbx_xywh = mask.toBbox(obj_info['mask'])\n bbx_xyxy = copy.deepcopy(bbx_xywh)\n bbx_xyxy[2] = bbx_xyxy[2] + bbx_xyxy[0]\n bbx_xyxy[3] = bbx_xyxy[3] + bbx_xyxy[1]\n bbx_mat.append(bbx_xyxy)\n sc_mat.append(obj_info['score']*score_w)\n \n if opt['use_attr_flag']:\n tmp_color = COLORS[attr_frm_dict['color'][obj_idx]]\n tmp_material = MATERIALS[attr_frm_dict['material'][obj_idx]]\n tmp_shape = SHAPES[attr_frm_dict['shape'][obj_idx]]\n attr_list.append([tmp_color, tmp_material, tmp_shape])\n #pdb.set_trace()\n\n\n frm_size = frm_info['objects'][0]['mask']['size']\n for tmp_idx in range(tmp_obj_num, max_obj_num):\n tmp_box = np.array([0, 0, 1, 1])\n bbx_mat.append(tmp_box)\n sc_mat.append(0)\n \n if opt['use_attr_flag']:\n attr_list.append(['', '', ''])\n\n bbx_mat = np.stack(bbx_mat, axis=0)\n sc_mat = np.array(sc_mat)\n sc_mat = np.expand_dims(sc_mat, axis=1 )\n\n #pdb.set_trace()\n\n if not opt['use_attr_flag']:\n bbx_sc_list.append([sc_mat, bbx_mat])\n\n else:\n bbx_sc_list.append([sc_mat, bbx_mat, attr_list])\n\n tube_list, score_list = get_tubes_v1(bbx_sc_list, connect_w, opt['use_attr_flag'], opt['attr_w'])\n return tube_list, score_list, bbx_sc_list \n\ndef get_tubes_v1(det_list_org, alpha, use_attr_flag=False, attr_w=1.0):\n \"\"\"\n det_list_org: [score_list, bbx_list]\n alpha: connection weight\n \"\"\"\n det_list = copy.deepcopy(det_list_org)\n tubes = []\n continue_flg = True\n tube_scores = []\n\n while continue_flg:\n timestep = 0\n obj_num = det_list[timestep][0].shape[0]\n \n if use_attr_flag:\n acc_time_list = []\n acc_attr_list = []\n for obj_id in range(obj_num):\n tmp_obj_dict = {}\n for attr_id, attr_concept in enumerate(['colors', 'materials', 'shapes']):\n attr_upper = attr_concept.upper()\n tmp_obj_num = 0\n concept_dict = {}\n for concept in globals()[attr_upper]:\n concept_dict[concept] = 0.0\n obj_concept = det_list[timestep][2][obj_id][attr_id]\n concept_dict[obj_concept] = 1.0\n tmp_obj_dict[attr_upper] = concept_dict \n acc_attr_list.append(tmp_obj_dict) \n acc_time_list.append(acc_attr_list)\n\n for t_id in range(1, len(det_list)):\n acc_time_list.append([])\n for obj_id in range(obj_num):\n acc_time_list[t_id].append({})\n\n score_list = []\n score_list.append(np.zeros(det_list[timestep][0].shape[0]))\n prevind_list = []\n prevind_list.append([-1] * det_list[timestep][0].shape[0])\n timestep += 1\n\n while timestep < len(det_list):\n n_curbox = det_list[timestep][0].shape[0]\n n_prevbox = score_list[-1].shape[0]\n cur_scores = np.zeros(n_curbox) - np.inf\n prev_inds = [-1] * n_curbox\n for i_prevbox in range(n_prevbox):\n prevbox_coods = det_list[timestep-1][1][i_prevbox, :]\n prevbox_score = det_list[timestep-1][0][i_prevbox, 0]\n\n for i_curbox in range(n_curbox):\n curbox_coods = det_list[timestep][1][i_curbox, :]\n curbox_score = det_list[timestep][0][i_curbox, 0]\n #try:\n if True:\n e_score = compute_IoU(prevbox_coods.tolist(), curbox_coods.tolist())\n link_score = prevbox_score + curbox_score + alpha * (e_score)\n \n if use_attr_flag:\n #prevbox_attr = det_list[timestep-1][2][i_prevbox]\n det_list\n prevbox_attr = acc_time_list[timestep-1][i_prevbox]\n curbox_attr = det_list[timestep][2][i_curbox]\n #attr_score = compare_attr_score(prevbox_attr, curbox_attr)\n attr_score = 0.0\n for attr_id, attr_concept in enumerate(['colors', 'materials', 'shapes']):\n attr_upper = attr_concept.upper()\n concept = curbox_attr[attr_id] \n if concept!='':\n attr_score += prevbox_attr[attr_upper][concept] \n attr_score /= timestep \n link_score += attr_score * attr_w\n #if e_score<=0:\n # link_score = 0.0\n \n cur_score = score_list[-1][i_prevbox] + link_score\n if cur_score > cur_scores[i_curbox]:\n cur_scores[i_curbox] = cur_score\n prev_inds[i_curbox] = i_prevbox\n if use_attr_flag:\n acc_time_list[timestep][i_curbox] = copy.deepcopy(acc_time_list[timestep-1][i_prevbox])\n curbox_attr = det_list[timestep][2][i_curbox]\n for attr_id, attr_concept in enumerate(['colors', 'materials', 'shapes']):\n attr_upper = attr_concept.upper()\n concept = curbox_attr[attr_id] \n if concept!='':\n acc_time_list[timestep][i_curbox][attr_upper][concept] +=1 \n\n score_list.append(cur_scores)\n prevind_list.append(prev_inds)\n timestep += 1\n\n # get path and remove used boxes\n cur_tube = [None] * len(det_list)\n tube_score = np.max(score_list[-1]) / len(det_list)\n prev_ind = np.argmax(score_list[-1])\n timestep = len(det_list) - 1\n while timestep >= 0:\n cur_tube[timestep] = det_list[timestep][1][prev_ind, :].tolist()\n det_list[timestep][0] = np.delete(det_list[timestep][0], prev_ind, axis=0)\n det_list[timestep][1] = np.delete(det_list[timestep][1], prev_ind, axis=0)\n if use_attr_flag:\n det_list[timestep][2].pop(prev_ind)\n prev_ind = prevind_list[timestep][prev_ind]\n if det_list[timestep][1].shape[0] == 0:\n continue_flg = False\n timestep -= 1\n assert prev_ind < 0\n tubes.append(cur_tube)\n tube_scores.append(tube_score)\n return tubes, tube_scores\n\n\ndef refine_tube_list(tube_list, score_list, bbx_sc_list, opt=None):\n #pdb.set_trace()\n bbx_bin_dict = {frm_id:[] for frm_id in range(len(tube_list[0]))}\n valid_frm_num_list = [0 for i in range(len(tube_list))]\n for tube_id, tmp_list in enumerate(tube_list):\n for frm_id, tmp_box in enumerate(tmp_list):\n if tmp_box!=[0, 0, 1, 1]:\n valid_frm_num_list[tube_id] +=1\n\n for tube_id, tmp_list in enumerate(tube_list):\n if valid_frm_num_list[tube_id]>opt['valid_frm_thre_hold']:\n continue\n for frm_id, tmp_box in enumerate(tmp_list):\n if tmp_box!=[0, 0, 1, 1]:\n bbx_bin_dict[frm_id].append(copy.deepcopy(tmp_box))\n\n \"\"\"\n delete small connected regions that are not connected\n \"\"\"\n def delete_small_connected_regions(tube_list, valid_frm_num_list, bbx_bin_dict, opt):\n max_seg_list = []\n time_step = len(tube_list[0]) \n for tube_id, tmp_list in enumerate(tube_list):\n if valid_frm_num_list[tube_id]<=opt['valid_frm_thre_hold']:\n max_seg_list.append([0, time_step])\n continue\n box_iou = compute_batch_IoU(np.array(tmp_list[0:time_step-1]), np.array(tmp_list[1:time_step]))\n st_id = 0\n tmp_seg_list = []\n tmp_seg_length = []\n for frm_id in range(time_step-1):\n if box_iou[frm_id]<=0 or frm_id==time_step-2:\n if tmp_list[st_id+1] == [0, 0, 1, 1]: # remove padding boxes\n continue \n if frm_id == time_step-2:\n frm_id = time_step \n tmp_seg_list.append([st_id, frm_id])\n tmp_seg_length.append(frm_id - st_id)\n st_id = frm_id\n if len(tmp_seg_length)>0:\n max_length = max(tmp_seg_length)\n max_idx = tmp_seg_length.index(max_length)\n max_seg_list.append(tmp_seg_list[max_idx])\n for frm_id, tmp_box in enumerate(tmp_list):\n if frm_id < tmp_seg_list[max_idx][0] or frm_id > tmp_seg_list[max_idx][1]:\n if tmp_box !=[0, 0, 1, 1]:\n bbx_bin_dict[frm_id].append(copy.deepcopy(tmp_box))\n tube_list[tube_id][frm_id] = [0, 0, 1, 1]\n else:\n max_seg_list.append([0, time_step])\n #pdb.set_trace()\n return tube_list, bbx_bin_dict, max_seg_list \n\n \"\"\"\n re-assign boxes into tubes\n \"\"\"\n def find_best_match_boxes(box_seq, frm_id, prp_box_list, bbx_sc_list, attr_dict, max_seg, opt):\n best_box = [0, 0, 1, 1]\n box_idx = -1\n if len(prp_box_list)==0:\n return best_box, box_idx\n match_score_list = []\n bbx_prp_mat = bbx_sc_list[frm_id][1]\n for idx, tmp_box in enumerate(prp_box_list): \n if tmp_box == [0, 0, 1, 1]:\n match_score_list.append(0)\n continue \n # attribute match score\n sim_mat = compute_batch_IoU(np.tile(np.array(tmp_box).reshape(1, 4), (len(bbx_prp_mat), 1)), bbx_prp_mat)\n box_id = np.argmax(sim_mat) \n max_score = sim_mat[box_id]\n assert max_score>0.99\n if opt['use_attr_flag']:\n tmp_attr_list = bbx_sc_list[frm_id][2][box_id]\n tmp_attr_score_list= []\n for attr_id, attr_concept in enumerate(['colors', 'materials', 'shapes']):\n tmp_attr_score_list.append(attr_dict[attr_concept][tmp_attr_list[attr_id]])\n match_score_list.append(sum(tmp_attr_score_list)/len(tmp_attr_score_list))\n else:\n match_score_list.append(0.0)\n # iou score before and after\n if frm_id>0:\n iou_before = compute_IoU_v2(tmp_box, box_seq[frm_id-1])\n match_score_list[idx] +=iou_before\n max_score = max(match_score_list) \n match_idx = match_score_list.index(max_score)\n if max_score> opt['match_thre']:\n best_box = prp_box_list[match_idx]\n box_idx = match_idx\n return best_box, box_idx \n\n def reassign_boxes(tube_list, valid_frm_num_list, bbx_bin_dict, opt, max_seg_list=None):\n for tube_id, tmp_list in enumerate(tube_list):\n if valid_frm_num_list[tube_id]<=opt['valid_frm_thre_hold']:\n continue\n def get_bbx_attr_info(tmp_list, bbx_sc_list, max_seg_list, tube_id):\n attr_dict = {}\n for attr_id, attr_concept in enumerate(['colors', 'materials', 'shapes']):\n concept_dict = {} \n attr_upper = attr_concept.upper()\n for concept in globals()[attr_upper]:\n concept_dict[concept] = 0.0\n attr_dict[attr_concept] = concept_dict \n\n if max_seg_list is None:\n st_id = 0\n ed_id = len(bbx_sc_list)\n else:\n st_id, ed_id = max_seg_list[tube_id]\n valid_num = 0\n for tmp_id in range(st_id, ed_id):\n tmp_box = tmp_list[tmp_id]\n if tmp_box==[0, 0, 1, 1]:\n continue\n valid_num +=1\n bbx_prp_mat = bbx_sc_list[tmp_id][1]\n sim_mat = compute_batch_IoU(np.tile(np.array(tmp_box).reshape(1, 4), (len(bbx_prp_mat), 1)), bbx_prp_mat)\n box_id = np.argmax(sim_mat) \n max_score = sim_mat[box_id]\n assert max_score>0.99\n attr_list = bbx_sc_list[tmp_id][2][box_id]\n for attr_id, attr_concept in enumerate(['colors', 'materials', 'shapes']):\n tmp_concept = attr_list[attr_id]\n attr_dict[attr_concept][tmp_concept] +=1 \n for attr_concept, concept_dict in attr_dict.items():\n for concept, concept_val in concept_dict.items():\n attr_dict[attr_concept][concept] = concept_val/(valid_num+0.000001)\n return attr_dict \n\n if opt['use_attr_flag']:\n attr_dict = get_bbx_attr_info(tmp_list, bbx_sc_list, max_seg_list, tube_id)\n else:\n attr_dict = None\n if max_seg_list is not None:\n max_seg = max_seg_list[tube_id]\n else:\n max_seg = None\n\n for frm_id, tmp_box in enumerate(tmp_list):\n if tmp_box==[0, 0, 1, 1]:\n #bbx_bin_dict[frm_id].append(copy.deepcopy(tmp_box))\n best_match_box, box_idx = find_best_match_boxes(tmp_list, frm_id, bbx_bin_dict[frm_id], bbx_sc_list, attr_dict, max_seg, opt)\n tube_list[tube_id][frm_id] = best_match_box\n if box_idx>=0:\n del bbx_bin_dict[frm_id][box_idx]\n return tube_list, bbx_bin_dict \n \n # making new tubes based on the cached proposals\n def make_new_tubes(bbx_bin_dict, bbx_sc_list, opt, tube_list, score_list):\n bbx_sc_list_new = []\n max_box_num = 0\n for frm_id, frm_list in bbx_bin_dict.items():\n if len(frm_list) > max_box_num:\n max_box_num = len(frm_list)\n if max_box_num<=0:\n return tube_list, score_list \n\n for frm_id, frm_list in bbx_bin_dict.items():\n while len(frm_list)<max_box_num:\n frm_list.append([0, 0, 1, 1])\n bbx_mat = np.stack(frm_list, axis=0)\n bbx_prp_mat = bbx_sc_list[frm_id][1]\n attr_list = []\n sc_score_list = []\n for box_id, tmp_box in enumerate(frm_list):\n if tmp_box==[0, 0, 1, 1]:\n attr_list.append(['', '', ''])\n sc_score_list.append(0.0)\n continue \n sim_mat = compute_batch_IoU(np.tile(np.array(tmp_box).reshape(1, 4), (len(bbx_prp_mat), 1)), bbx_prp_mat)\n box_id = np.argmax(sim_mat) \n max_score = sim_mat[box_id]\n assert max_score>0.99\n sc_score = float(bbx_sc_list[frm_id][0][box_id])\n sc_score_list.append(sc_score)\n if opt['use_attr_flag']:\n attr_list.append(bbx_sc_list[frm_id][2][box_id])\n \n sc_mat = np.array(sc_score_list).reshape(max_box_num, 1)\n if not opt['use_attr_flag']:\n bbx_sc_list_new.append([sc_mat, bbx_mat])\n else:\n bbx_sc_list_new.append([sc_mat, bbx_mat, attr_list])\n \n if opt['version']==0:\n tube_list_new, score_list_new = get_tubes_v0(bbx_sc_list_new, opt['connect_w'], opt['use_attr_flag'], opt['attr_w'])\n elif opt['version']==1:\n tube_list_new, score_list_new = get_tubes_v1(bbx_sc_list_new, opt['connect_w'], opt['use_attr_flag'], opt['attr_w'])\n elif opt['version']==2:\n tube_list_new, score_list_new = get_tubes_v2(bbx_sc_list_new, opt['connect_w'], opt['use_attr_flag'], opt['attr_w'])\n elif opt['version']==3:\n tube_list_new, score_list_new = get_tubes_v2(bbx_sc_list_new, opt['connect_w'], opt['use_attr_flag'], opt['attr_w'])\n \n # merge tube list\n new_valid_frm_num_list = [] \n new_valid_frm_num_list = [0 for i in range(len(tube_list_new))]\n for tube_id, tmp_list in enumerate(tube_list_new):\n for frm_id, tmp_box in enumerate(tmp_list):\n if tmp_box!=[0, 0, 1, 1]:\n new_valid_frm_num_list[tube_id] +=1\n for tube_id, tmp_list in enumerate(tube_list_new):\n if new_valid_frm_num_list[tube_id]<=opt['valid_frm_thre_hold']:\n continue\n tube_list.append(tmp_list)\n score_list.append(score_list_new[tube_id])\n \n # remove invalid tubes\n valid_frm_num_list = [0 for i in range(len(tube_list))]\n for tube_id, tmp_list in enumerate(tube_list):\n for frm_id, tmp_box in enumerate(tmp_list):\n if tmp_box!=[0, 0, 1, 1]:\n valid_frm_num_list[tube_id] +=1\n \"\"\"\n delete invalid tubes\n \"\"\"\n tube_num_ori = len(tube_list)\n for tube_id in range(tube_num_ori-1, -1, -1): \n if valid_frm_num_list[tube_id]>opt['valid_frm_thre_hold']:\n continue\n del tube_list[tube_id]\n del score_list[tube_id]\n \n return tube_list, score_list\n tube_list, bbx_bin_dict = reassign_boxes(tube_list, valid_frm_num_list, bbx_bin_dict, opt)\n tube_list, bbx_bin_dict, max_seg_list = delete_small_connected_regions(tube_list, valid_frm_num_list, bbx_bin_dict, opt)\n tube_list, bbx_bin_dict = reassign_boxes(tube_list, valid_frm_num_list, bbx_bin_dict, opt, max_seg_list)\n tube_list, score_list = make_new_tubes(bbx_bin_dict, bbx_sc_list, opt, tube_list, score_list)\n padding_valid_list = [128 for ii in range(len(tube_list))] \n #pdb.set_trace()\n tube_list, bbx_bin_dict, max_seg_list = delete_small_connected_regions(tube_list, padding_valid_list, bbx_bin_dict, opt)\n return tube_list, score_list \n\ndef compute_batch_IoU(bbox1_xyxy, bbox2_xyxy):\n bbox1_x1 = bbox1_xyxy[:, 0]\n bbox1_x2 = bbox1_xyxy[:, 2]\n bbox1_y1 = bbox1_xyxy[:, 1]\n bbox1_y2 = bbox1_xyxy[:, 3]\n\n bbox2_x1 = bbox2_xyxy[:, 0]\n bbox2_x2 = bbox2_xyxy[:, 2]\n bbox2_y1 = bbox2_xyxy[:, 1]\n bbox2_y2 = bbox2_xyxy[:, 3]\n\n w = np.clip(np.minimum(bbox1_x2, bbox2_x2) - np.maximum(bbox1_x1, bbox2_x1), 0, 10000)\n h = np.clip(np.minimum(bbox1_y2, bbox2_y2) - np.maximum(bbox1_y1, bbox2_y1), 0, 10000)\n inter = w * h\n bbox1_area = np.clip((bbox1_x2 - bbox1_x1), 0, 10000) * np.clip((bbox1_y2 - bbox1_y1), 0, 10000)\n bbox2_area = np.clip((bbox2_x2 - bbox2_x1), 0, 10000) * np.clip((bbox2_y2 - bbox2_y1), 0, 10000)\n ovr = inter / (bbox1_area + bbox2_area - inter+EPS)\n return ovr\n\ndef extract_tube_v2(opt):\n sample_folder_path= '/datasets/dcl_clevrer/proposals'\n file_list = get_sub_file_list(sample_folder_path, '.json')\n file_list.sort()\n #out_path = os.path.join(opt['tube_folder_path'] , str(opt['connect_w'])+'_'+str(opt['score_w'])+'_'+str(opt['attr_w'])+'_v1')\n out_path = os.path.join(opt['tube_folder_path'] , str(opt['connect_w'])+'_'+str(opt['score_w'])+'_'+str(opt['attr_w'])+'_'+str(opt['match_thre']))\n if not os.path.isdir(out_path):\n os.makedirs(out_path)\n for file_idx, sample_file in enumerate(file_list):\n\n out_fn_path = os.path.join(out_path, os.path.basename(sample_file.replace('json', 'pk')))\n if file_idx < opt['start_index'] or file_idx>=opt['end_index']:\n continue\n\n if os.path.isfile(out_fn_path):\n continue\n #pdb.set_trace()\n fh = open(sample_file, 'r')\n f_dict = json.load(fh)\n max_obj_num = 0\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n tmp_obj_num = len(frm_info['objects']) \n if max_obj_num<tmp_obj_num:\n max_obj_num = tmp_obj_num \n \n if opt['use_attr_flag'] and opt['attr_w']>0:\n attr_dict_path = os.path.join(opt['extract_att_path'], 'attribute_' + str(file_idx).zfill(5) +'.json')\n if not os.path.isfile(attr_dict_path):\n continue \n attr_dict_list = jsonload(attr_dict_path) \n else:\n attr_dict_list = None\n tube_list, score_list, bbx_sc_list = extract_tube_per_video_attribute_v2(f_dict, opt, attr_dict_list) \n if opt['refine_tube_flag']:\n tube_list, score_list = refine_tube_list(tube_list, score_list, bbx_sc_list, opt)\n out_dict = {'tubes': tube_list, 'scores': score_list, 'bbx_list': bbx_sc_list }\n pickledump(out_fn_path, out_dict)\n if file_idx%1000==0 or file_idx==10100:\n print('finish processing %d/%d videos' %(file_idx, len(file_list)))\n \n if opt['visualize_flag']==1:\n visual_tube_proposals([tube_list, score_list], f_dict, max_obj_num, opt)\n out_gt_path = os.path.join(opt['tube_folder_new_path'], 'annotation_'+str(file_idx)+'.pk')\n gt_tube_dict = pickleload(out_gt_path)\n iou_thre = 0.9\n tmp_correct_num = 0\n for prp_idx, prp in enumerate(out_dict['tubes']):\n tmp_max_iou = 0\n for gt_idx, gt in enumerate(gt_tube_dict['tubes']):\n iou = compute_LS(prp, gt)\n if iou>=iou_thre:\n tmp_correct_num +=1\n tmp_recall = tmp_correct_num * 1.0 / len(gt_tube_dict['tubes'])\n tmp_precision = tmp_correct_num * 1.0 / len(out_dict['tubes'])\n print('precision: %f, recall: %f\\n' %(tmp_precision, tmp_recall))\n pdb.set_trace()\n\n\ndef extract_tube_per_video_attribute_v2(f_dict, opt, attr_dict_list=None):\n connect_w = opt['connect_w']\n score_w = opt['score_w']\n bbx_sc_list = []\n\n if attr_dict_list is not None:\n assert len(f_dict['frames'])==len(attr_dict_list)\n\n # get object number of a video\n max_obj_num = 0\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n tmp_obj_num = len(frm_info['objects']) \n if max_obj_num<tmp_obj_num:\n max_obj_num = tmp_obj_num \n\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n bbx_mat = []\n sc_mat = []\n color_list = []\n material_list = []\n shape_list = []\n attr_list = []\n tmp_obj_num = len(frm_info['objects']) \n\n if opt['use_attr_flag'] and opt['attr_w']>0:\n attr_frm_dict = attr_dict_list[frm_idx]\n assert len(frm_info['objects']) == len(attr_frm_dict['color'])\n for obj_idx, obj_info in enumerate(frm_info['objects']):\n bbx_xywh = mask.toBbox(obj_info['mask'])\n bbx_xyxy = copy.deepcopy(bbx_xywh)\n bbx_xyxy[2] = bbx_xyxy[2] + bbx_xyxy[0]\n bbx_xyxy[3] = bbx_xyxy[3] + bbx_xyxy[1]\n bbx_mat.append(bbx_xyxy)\n sc_mat.append(obj_info['score']*score_w)\n \n if opt['use_attr_flag'] and opt['attr_w']>0:\n tmp_color = COLORS[attr_frm_dict['color'][obj_idx]]\n tmp_material = MATERIALS[attr_frm_dict['material'][obj_idx]]\n tmp_shape = SHAPES[attr_frm_dict['shape'][obj_idx]]\n attr_list.append([tmp_color, tmp_material, tmp_shape])\n #pdb.set_trace()\n\n frm_size = frm_info['objects'][0]['mask']['size']\n for tmp_idx in range(tmp_obj_num, max_obj_num):\n tmp_box = np.array([0, 0, 1, 1])\n bbx_mat.append(tmp_box)\n sc_mat.append(0)\n \n if opt['use_attr_flag'] and opt['attr_w']>0:\n attr_list.append(['', '', ''])\n\n bbx_mat = np.stack(bbx_mat, axis=0)\n sc_mat = np.array(sc_mat)\n sc_mat = np.expand_dims(sc_mat, axis=1 )\n\n #pdb.set_trace()\n\n if (not opt['use_attr_flag']) or opt['attr_w']<=0:\n bbx_sc_list.append([sc_mat, bbx_mat])\n else:\n bbx_sc_list.append([sc_mat, bbx_mat, attr_list])\n\n tube_list, score_list = get_tubes_v2(bbx_sc_list, connect_w, opt['use_attr_flag'], opt['attr_w'])\n return tube_list, score_list, bbx_sc_list \n\ndef get_tubes_v2(det_list_org, alpha, use_attr_flag=False, attr_w=1.0):\n \"\"\"\n det_list_org: [score_list, bbx_list]\n alpha: connection weight\n \"\"\"\n det_list = copy.deepcopy(det_list_org)\n tubes = []\n continue_flg = True\n tube_scores = []\n\n while continue_flg:\n timestep = 0\n obj_num = det_list[timestep][0].shape[0]\n \n if use_attr_flag:\n acc_time_list = []\n acc_attr_list = []\n for obj_id in range(obj_num):\n tmp_obj_dict = {}\n for attr_id, attr_concept in enumerate(['colors', 'materials', 'shapes']):\n attr_upper = attr_concept.upper()\n tmp_obj_num = 0\n concept_dict = {}\n for concept in globals()[attr_upper]:\n concept_dict[concept] = 0.0\n obj_concept = det_list[timestep][2][obj_id][attr_id]\n concept_dict[obj_concept] = 1.0\n tmp_obj_dict[attr_upper] = concept_dict \n acc_attr_list.append(tmp_obj_dict) \n acc_time_list.append(acc_attr_list)\n\n for t_id in range(1, len(det_list)):\n acc_time_list.append([])\n for obj_id in range(obj_num):\n acc_time_list[t_id].append({})\n\n score_list = []\n score_list.append(np.zeros(det_list[timestep][0].shape[0]))\n prevind_list = []\n prevind_list.append([-1] * det_list[timestep][0].shape[0])\n timestep += 1\n\n while timestep < len(det_list):\n n_curbox = det_list[timestep][0].shape[0]\n n_prevbox = score_list[-1].shape[0]\n cur_scores = np.zeros(n_curbox) - np.inf\n prev_inds = [-1] * n_curbox\n \n tmp_enery_score_mat = np.zeros((n_curbox, n_curbox)) - np.inf\n\n for i_prevbox in range(n_prevbox):\n prevbox_coods = det_list[timestep-1][1][i_prevbox, :]\n prevbox_score = det_list[timestep-1][0][i_prevbox, 0]\n\n for i_curbox in range(n_curbox):\n curbox_coods = det_list[timestep][1][i_curbox, :]\n curbox_score = det_list[timestep][0][i_curbox, 0]\n #try:\n if True:\n e_score = compute_IoU(prevbox_coods.tolist(), curbox_coods.tolist())\n link_score = prevbox_score + curbox_score + alpha * (e_score)\n \n if use_attr_flag:\n #prevbox_attr = det_list[timestep-1][2][i_prevbox]\n det_list\n prevbox_attr = acc_time_list[timestep-1][i_prevbox]\n curbox_attr = det_list[timestep][2][i_curbox]\n #attr_score = compare_attr_score(prevbox_attr, curbox_attr)\n attr_score = 0.0\n for attr_id, attr_concept in enumerate(['colors', 'materials', 'shapes']):\n attr_upper = attr_concept.upper()\n concept = curbox_attr[attr_id] \n if concept!='':\n attr_score += prevbox_attr[attr_upper][concept] \n attr_score /= timestep \n link_score += attr_score * attr_w\n #if e_score<=0:\n # link_score = 0.0\n \n cur_score = score_list[-1][i_prevbox] + link_score\n tmp_enery_score_mat[i_prevbox, i_curbox] = cur_score \n \n row_ind, col_ind = linear_sum_assignment(tmp_enery_score_mat, maximize=True)\n for i_curbox in range(n_curbox):\n cur_box_idx = col_ind[i_curbox]\n pred_box_idx = row_ind[i_curbox]\n # update assign boxes \n cur_scores[cur_box_idx] = tmp_enery_score_mat[pred_box_idx, cur_box_idx]\n prev_inds[cur_box_idx] = pred_box_idx \n if use_attr_flag:\n acc_time_list[timestep][cur_box_idx] = copy.deepcopy(acc_time_list[timestep-1][pred_box_idx])\n curbox_attr = det_list[timestep][2][cur_box_idx]\n for attr_id, attr_concept in enumerate(['colors', 'materials', 'shapes']):\n attr_upper = attr_concept.upper()\n concept = curbox_attr[attr_id] \n if concept!='':\n acc_time_list[timestep][cur_box_idx][attr_upper][concept] +=1 \n\n score_list.append(cur_scores)\n prevind_list.append(prev_inds)\n timestep += 1\n\n # get path and remove used boxes\n cur_tube = [None] * len(det_list)\n tube_score = np.max(score_list[-1]) / len(det_list)\n prev_ind = np.argmax(score_list[-1])\n timestep = len(det_list) - 1\n while timestep >= 0:\n cur_tube[timestep] = det_list[timestep][1][prev_ind, :].tolist()\n det_list[timestep][0] = np.delete(det_list[timestep][0], prev_ind, axis=0)\n det_list[timestep][1] = np.delete(det_list[timestep][1], prev_ind, axis=0)\n if use_attr_flag:\n det_list[timestep][2].pop(prev_ind)\n prev_ind = prevind_list[timestep][prev_ind]\n if det_list[timestep][1].shape[0] == 0:\n continue_flg = False\n timestep -= 1\n assert prev_ind < 0\n tubes.append(cur_tube)\n tube_scores.append(tube_score)\n return tubes, tube_scores\n\ndef extract_tube_v3(opt):\n sample_folder_path= '/datasets/dcl_clevrer/proposals'\n file_list = get_sub_file_list(sample_folder_path, '.json')\n file_list.sort()\n #out_path = os.path.join(opt['tube_folder_path'] , str(opt['connect_w'])+'_'+str(opt['score_w'])+'_'+str(opt['attr_w'])+'_v1')\n out_path = os.path.join(opt['tube_folder_path'] , str(opt['connect_w'])+'_'+str(opt['score_w'])+'_'+str(opt['attr_w'])+'_'+str(opt['match_thre']))\n if not os.path.isdir(out_path):\n os.makedirs(out_path)\n for file_idx, sample_file in enumerate(file_list):\n\n out_fn_path = os.path.join(out_path, os.path.basename(sample_file.replace('json', 'pk')))\n if file_idx < opt['start_index'] or file_idx>=opt['end_index']:\n continue\n\n if os.path.isfile(out_fn_path):\n continue\n #pdb.set_trace()\n fh = open(sample_file, 'r')\n f_dict = json.load(fh)\n max_obj_num = 0\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n tmp_obj_num = len(frm_info['objects']) \n if max_obj_num<tmp_obj_num:\n max_obj_num = tmp_obj_num \n \n if opt['use_attr_flag'] and opt['attr_w']>0:\n attr_dict_path = os.path.join(opt['extract_att_path'], 'attribute_' + str(file_idx).zfill(5) +'.json')\n if not os.path.isfile(attr_dict_path):\n continue \n attr_dict_list = jsonload(attr_dict_path) \n else:\n attr_dict_list = None\n #pdb.set_trace()\n tube_list, score_list, bbx_sc_list = extract_tube_per_video_attribute_v3(f_dict, opt, attr_dict_list) \n if opt['refine_tube_flag']:\n tube_list, score_list = refine_tube_list(tube_list, score_list, bbx_sc_list, opt)\n out_dict = {'tubes': tube_list, 'scores': score_list, 'bbx_list': bbx_sc_list }\n pickledump(out_fn_path, out_dict)\n if file_idx%1000==0 or file_idx==10100:\n print('finish processing %d/%d videos' %(file_idx, len(file_list)))\n \n if opt['visualize_flag']==1:\n visual_tube_proposals([tube_list, score_list], f_dict, max_obj_num, opt)\n out_gt_path = os.path.join(opt['tube_folder_new_path'], 'annotation_'+str(file_idx)+'.pk')\n gt_tube_dict = pickleload(out_gt_path)\n iou_thre = 0.9\n tmp_correct_num = 0\n for prp_idx, prp in enumerate(out_dict['tubes']):\n tmp_max_iou = 0\n for gt_idx, gt in enumerate(gt_tube_dict['tubes']):\n iou = compute_LS(prp, gt)\n if iou>=iou_thre:\n tmp_correct_num +=1\n tmp_recall = tmp_correct_num * 1.0 / len(gt_tube_dict['tubes'])\n tmp_precision = tmp_correct_num * 1.0 / len(out_dict['tubes'])\n print('precision: %f, recall: %f\\n' %(tmp_precision, tmp_recall))\n pdb.set_trace()\n\ndef extract_tube_per_video_attribute_v3(f_dict, opt, attr_dict_list=None):\n connect_w = opt['connect_w']\n score_w = opt['score_w']\n bbx_sc_list = []\n\n if attr_dict_list is not None:\n assert len(f_dict['frames'])==len(attr_dict_list)\n\n # get object number of a video\n max_obj_num = 0\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n tmp_obj_num = len(frm_info['objects']) \n if max_obj_num<tmp_obj_num:\n max_obj_num = tmp_obj_num \n\n for frm_idx, frm_info in enumerate(f_dict['frames']):\n bbx_mat = []\n sc_mat = []\n color_list = []\n material_list = []\n shape_list = []\n attr_list = []\n tmp_obj_num = len(frm_info['objects']) \n\n if opt['use_attr_flag'] and opt['attr_w']>0:\n attr_frm_dict = attr_dict_list[frm_idx]\n assert len(frm_info['objects']) == len(attr_frm_dict['color'])\n for obj_idx, obj_info in enumerate(frm_info['objects']):\n bbx_xywh = mask.toBbox(obj_info['mask'])\n bbx_xyxy = copy.deepcopy(bbx_xywh)\n bbx_xyxy[2] = bbx_xyxy[2] + bbx_xyxy[0]\n bbx_xyxy[3] = bbx_xyxy[3] + bbx_xyxy[1]\n bbx_mat.append(bbx_xyxy)\n sc_mat.append(obj_info['score']*score_w)\n \n if opt['use_attr_flag'] and opt['attr_w']>0:\n tmp_color = COLORS[attr_frm_dict['color'][obj_idx]]\n tmp_material = MATERIALS[attr_frm_dict['material'][obj_idx]]\n tmp_shape = SHAPES[attr_frm_dict['shape'][obj_idx]]\n attr_list.append([tmp_color, tmp_material, tmp_shape])\n #pdb.set_trace()\n\n frm_size = frm_info['objects'][0]['mask']['size']\n for tmp_idx in range(tmp_obj_num, max_obj_num):\n tmp_box = np.array([0, 0, 1, 1])\n bbx_mat.append(tmp_box)\n sc_mat.append(0)\n \n if opt['use_attr_flag'] and opt['attr_w']>0:\n attr_list.append(['', '', ''])\n\n bbx_mat = np.stack(bbx_mat, axis=0)\n sc_mat = np.array(sc_mat)\n sc_mat = np.expand_dims(sc_mat, axis=1 )\n\n #pdb.set_trace()\n\n if (not opt['use_attr_flag']) or opt['attr_w']<=0:\n bbx_sc_list.append([sc_mat, bbx_mat])\n else:\n bbx_sc_list.append([sc_mat, bbx_mat, attr_list])\n\n tube_list, score_list = get_tubes_v3(bbx_sc_list, connect_w, opt['use_attr_flag'], opt['attr_w'])\n return tube_list, score_list, bbx_sc_list \n\ndef get_tubes_v3(det_list_org, alpha, use_attr_flag=False, attr_w=1.0):\n \"\"\"\n det_list_org: [score_list, bbx_list]\n alpha: connection weight\n \"\"\"\n det_list = copy.deepcopy(det_list_org)\n tubes = []\n continue_flg = True\n tube_scores = []\n\n\n while continue_flg:\n timestep = 0\n obj_num = det_list[timestep][0].shape[0]\n \n if use_attr_flag:\n acc_time_list = []\n acc_attr_list = []\n for obj_id in range(obj_num):\n tmp_obj_dict = {}\n for attr_id, attr_concept in enumerate(['colors', 'materials', 'shapes']):\n attr_upper = attr_concept.upper()\n tmp_obj_num = 0\n concept_dict = {}\n for concept in globals()[attr_upper]:\n concept_dict[concept] = 0.0\n obj_concept = det_list[timestep][2][obj_id][attr_id]\n concept_dict[obj_concept] = 1.0\n tmp_obj_dict[attr_upper] = concept_dict \n acc_attr_list.append(tmp_obj_dict) \n acc_time_list.append(acc_attr_list)\n\n for t_id in range(1, len(det_list)):\n acc_time_list.append([])\n for obj_id in range(obj_num):\n acc_time_list[t_id].append({})\n\n\n score_list = []\n score_list.append(np.zeros(det_list[timestep][0].shape[0]))\n prevind_list = []\n prevind_list.append([-1] * det_list[timestep][0].shape[0])\n timestep += 1\n\n pre_id_to_tracker = {}\n for obj_id in range(obj_num):\n tmp_box = det_list[0][1][obj_id, :]\n pre_id_to_tracker[obj_id] = KalmanBoxTracker(tmp_box) \n\n\n while timestep < len(det_list):\n n_curbox = det_list[timestep][0].shape[0]\n n_prevbox = score_list[-1].shape[0]\n cur_scores = np.zeros(n_curbox) - np.inf\n prev_inds = [-1] * n_curbox\n \n tmp_enery_score_mat = np.zeros((n_curbox, n_curbox)) - np.inf\n\n for i_prevbox in range(n_prevbox):\n prevbox_coods = det_list[timestep-1][1][i_prevbox, :]\n prevbox_score = det_list[timestep-1][0][i_prevbox, 0]\n\n for i_curbox in range(n_curbox):\n curbox_coods = det_list[timestep][1][i_curbox, :]\n curbox_score = det_list[timestep][0][i_curbox, 0]\n #try:\n if True:\n if len(pre_id_to_tracker)>0:\n prevbox_coods_predicted = pre_id_to_tracker[i_prevbox].predict()[0] \n e_score = compute_IoU(prevbox_coods_predicted.tolist(), curbox_coods.tolist())\n else:\n e_score = compute_IoU(prevbox_coods.tolist(), curbox_coods.tolist())\n link_score = prevbox_score + curbox_score + alpha * (e_score)\n \n if use_attr_flag:\n #prevbox_attr = det_list[timestep-1][2][i_prevbox]\n prevbox_attr = acc_time_list[timestep-1][i_prevbox]\n curbox_attr = det_list[timestep][2][i_curbox]\n #attr_score = compare_attr_score(prevbox_attr, curbox_attr)\n attr_score = 0.0\n for attr_id, attr_concept in enumerate(['colors', 'materials', 'shapes']):\n attr_upper = attr_concept.upper()\n concept = curbox_attr[attr_id] \n if concept!='':\n attr_score += prevbox_attr[attr_upper][concept] \n attr_score /= timestep \n link_score += attr_score * attr_w\n #if e_score<=0:\n # link_score = 0.0\n \n cur_score = score_list[-1][i_prevbox] + link_score\n tmp_enery_score_mat[i_prevbox, i_curbox] = cur_score \n \n row_ind, col_ind = linear_sum_assignment(tmp_enery_score_mat, maximize=True)\n \n new_pre_id_to_tracker = {}\n for i_curbox in range(n_curbox):\n cur_box_idx = col_ind[i_curbox]\n pred_box_idx = row_ind[i_curbox]\n # update assign boxes \n cur_scores[cur_box_idx] = tmp_enery_score_mat[pred_box_idx, cur_box_idx]\n prev_inds[cur_box_idx] = pred_box_idx \n if use_attr_flag:\n acc_time_list[timestep][cur_box_idx] = copy.deepcopy(acc_time_list[timestep-1][pred_box_idx])\n curbox_attr = det_list[timestep][2][cur_box_idx]\n for attr_id, attr_concept in enumerate(['colors', 'materials', 'shapes']):\n attr_upper = attr_concept.upper()\n concept = curbox_attr[attr_id] \n if concept!='':\n acc_time_list[timestep][cur_box_idx][attr_upper][concept] +=1 \n \n # update trackers\n tmp_box = det_list[timestep][1][cur_box_idx, :]\n if cur_box_idx not in pre_id_to_tracker:\n new_pre_id_to_tracker[cur_box_idx] = KalmanBoxTracker(tmp_box) \n else:\n tmp_state = pre_id_to_tracker[pred_box_idx].get_state()[0]\n if np.array_equal(tmp_state, np.array([0, 0, 1, 1])):\n new_pre_id_to_tracker[cur_box_idx] = KalmanBoxTracker(tmp_box) \n elif not np.array_equal(tmp_box, np.array([0, 0, 1, 1])):\n pre_id_to_tracker[pred_box_idx].update(tmp_box) \n new_pre_id_to_tracker[cur_box_idx] = pre_id_to_tracker[pred_box_idx]\n else:\n new_pre_id_to_tracker[cur_box_idx] = pre_id_to_tracker[pred_box_idx] \n pre_id_to_tracker = new_pre_id_to_tracker \n score_list.append(cur_scores)\n prevind_list.append(prev_inds)\n timestep += 1\n\n # get path and remove used boxes\n cur_tube = [None] * len(det_list)\n tube_score = np.max(score_list[-1]) / len(det_list)\n prev_ind = np.argmax(score_list[-1])\n timestep = len(det_list) - 1\n while timestep >= 0:\n cur_tube[timestep] = det_list[timestep][1][prev_ind, :].tolist()\n det_list[timestep][0] = np.delete(det_list[timestep][0], prev_ind, axis=0)\n det_list[timestep][1] = np.delete(det_list[timestep][1], prev_ind, axis=0)\n if use_attr_flag:\n det_list[timestep][2].pop(prev_ind)\n prev_ind = prevind_list[timestep][prev_ind]\n if det_list[timestep][1].shape[0] == 0:\n continue_flg = False\n timestep -= 1\n assert prev_ind < 0\n tubes.append(cur_tube)\n tube_scores.append(tube_score)\n\n return tubes, tube_scores\n\n\nif __name__=='__main__':\n parms, opt = parse_opt()\n # 0 for IoU only, 1 for greedy attribute and 2 for NN match attribute\n if opt['version']==0:\n extract_tube_v0(opt)\n elif opt['version']==1:\n extract_tube_v1(opt)\n elif opt['version']==2:\n #compute_recall_and_precision(opt)\n #pdb.set_trace()\n extract_tube_v2(opt)\n elif opt['version']==3:\n extract_tube_v3(opt)\n compute_recall_and_precision(opt)\n #evaluate_tube_performance(opt)\n" ]
[ [ "numpy.expand_dims", "numpy.minimum", "numpy.sqrt", "numpy.maximum", "numpy.clip", "numpy.stack", "numpy.max", "numpy.delete", "numpy.argmax", "scipy.optimize.linear_sum_assignment", "numpy.array", "numpy.zeros" ] ]
redNixon/eland
[ "1b9cb1db6d30f0662fe3679c7bb31e2c0865f0c3" ]
[ "eland/tests/dataframe/test_nunique_pytest.py" ]
[ "# Copyright 2019 Elasticsearch BV\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# File called _pytest for PyCharm compatability\n\nfrom pandas.util.testing import assert_series_equal\n\nfrom eland.tests.common import TestData\n\n\nclass TestDataFrameNUnique(TestData):\n def test_flights_nunique(self):\n # Note pandas.nunique fails for dict columns (e.g. DestLocation)\n columns = [\n \"AvgTicketPrice\",\n \"Cancelled\",\n \"Carrier\",\n \"Dest\",\n \"DestAirportID\",\n \"DestCityName\",\n ]\n pd_flights = self.pd_flights()[columns]\n ed_flights = self.ed_flights()[columns]\n\n pd_flights.nunique()\n ed_flights.nunique()\n\n # TODO - ES is approximate counts so these aren't equal...\n # E[left]: [13059, 2, 4, 156, 156, 143]\n # E[right]: [13132, 2, 4, 156, 156, 143]\n # assert_series_equal(pd_nunique, ed_nunique)\n\n def test_ecommerce_nunique(self):\n columns = [\"customer_first_name\", \"customer_last_name\", \"day_of_week_i\"]\n pd_ecommerce = self.pd_ecommerce()[columns]\n ed_ecommerce = self.ed_ecommerce()[columns]\n\n pd_nunique = pd_ecommerce.nunique()\n ed_nunique = ed_ecommerce.nunique()\n\n assert_series_equal(pd_nunique, ed_nunique)\n" ]
[ [ "pandas.util.testing.assert_series_equal" ] ]
nrichards17/diabetes-pytorch
[ "80ba7e366e5850657cdd29dd8f81adf81408c56f" ]
[ "model/net.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass FCUnit(nn.Module):\n def __init__(self, input_size, output_size, dropout_rate):\n super(FCUnit, self).__init__()\n\n self.linear = nn.Linear(input_size, output_size)\n self.batchnorm = nn.BatchNorm1d(output_size)\n self.dropout = nn.Dropout(dropout_rate)\n\n def forward(self, x):\n x = self.linear(x)\n x = F.leaky_relu(x)\n x = self.batchnorm(x)\n x = self.dropout(x)\n\n return x\n\n\nclass Network(nn.Module):\n def __init__(self, params):\n\n super(Network, self).__init__()\n\n embedding_sizes = params['embedding_sizes']\n n_continous = len(params['continuous'])\n n_embedding = sum([y for _, y in embedding_sizes])\n # n_embedding = 0\n size_fc = params['model']['size_fc']\n size_final = params['model']['size_final']\n dropout_emb = params['model']['dropout_emb']\n dropout_fc = params['model']['dropout_fc']\n\n # prepend combined cont/cat input vector size\n # append final linear layer size\n layer_sizes = [n_continous + n_embedding] + size_fc + [size_final]\n # get pairs of input/output size\n fc_dims = [(x, y) for x, y in zip(layer_sizes, layer_sizes[1:])]\n\n # ----- Categorical Inputs -----\n # create categorical embeddings\n self.embeddings = nn.ModuleList(\n [nn.Embedding(x, y) for x, y in embedding_sizes]\n )\n # create dropout for embeddings\n self.dropout_emb = nn.Dropout(dropout_emb)\n\n # ----- Continuous Inputs -----\n # batchnorm for continuous\n self.bn_continuous = nn.BatchNorm1d(n_continous)\n\n # ----- Fully Connected (FC) -----\n self.fc_layers = nn.ModuleList(\n [FCUnit(in_size, out_size, dropout_fc) for in_size, out_size in fc_dims]\n )\n\n self.output_linear = nn.Linear(size_final, 1)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x_cont, x_cat):\n # apply batchnorm to continuous input\n x_cont = self.bn_continuous(x_cont)\n\n # apply embeddings to each categorical variable, store in list\n x_cat = [embedding(x_cat[:, i]) for i, embedding in enumerate(self.embeddings)]\n # concatenate embeddings across categorical variables\n x_cat = torch.cat(x_cat, 1)\n # apply dropout for embeddings\n x_cat = self.dropout_emb(x_cat)\n\n # concatenate continuous and categorical input\n x = torch.cat([x_cont, x_cat], 1)\n\n # apply each fc layer\n for fc_layer in self.fc_layers:\n x = fc_layer(x)\n # apply output linear layer\n x = self.output_linear(x)\n # apply sigmoid to output, squash (0,1)\n x = self.sigmoid(x)\n\n return x\n" ]
[ [ "torch.nn.BatchNorm1d", "torch.nn.Dropout", "torch.cat", "torch.nn.Embedding", "torch.nn.Sigmoid", "torch.nn.Linear", "torch.nn.functional.leaky_relu" ] ]
ZachT1711/tensor2robot
[ "7a58c5f6b6f2857d7ee730013da512f42b70cb58", "3ab8aa56ebe86464c8074a3a2f7282ebea74c1aa", "7a58c5f6b6f2857d7ee730013da512f42b70cb58" ]
[ "utils/subsample.py", "utils/cross_entropy.py", "hooks/async_export_hook_builder_tpu_test.py" ]
[ "# coding=utf-8\n# Copyright 2020 The Tensor2Robot Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Generates random subsampling indices.\"\"\"\n\n\n\nimport numpy as np\nimport tensorflow.compat.v1 as tf\n\n\ndef get_subsample_indices(sequence_lengths,\n min_length):\n \"\"\"Generates random indices for sequence subsampling.\n\n Args:\n sequence_lengths: An int tensor of shape [B], for the length of each\n sequence. Since the provided tensors are padded to the length of the\n longest sequence in the batch, sequence_lengths is needed to avoid\n sampling from the padding.\n min_length: The min_length to subsample. The sampling always includes the\n first and last frame. If the sequence is long enough, timesteps are\n sampled without replacement. Otherwise, they are sampled with\n replacement. If min_length = 1, the example is picked randomly from\n the entire sequence.\n\n Returns:\n An int tensor of shape [B, min_length], for how to index into the seuqence.\n \"\"\"\n def get_indices(sequence_length):\n \"\"\"Generates indices for single sequence.\"\"\"\n def without_replacement():\n # sample integers from [1, seq_len-1)\n indices = tf.random.shuffle(tf.range(1, sequence_length-1))\n middle = indices[:min_length - 2]\n return tf.sort(tf.concat([[0], middle, [sequence_length-1]], axis=0))\n\n def with_replacement():\n # sample integers from [0, seq_len)\n indices = (\n tf.random.uniform(shape=[min_length - 2]) *\n tf.cast(sequence_length, float))\n middle = tf.cast(tf.math.floor(indices), tf.int64)\n return tf.sort(tf.concat([[0], middle, [sequence_length-1]], axis=0))\n\n def random_frame():\n # Used when min_length == 1.\n indices = (\n tf.random.uniform(shape=[min_length]) *\n tf.cast(sequence_length, float))\n middle = tf.cast(tf.math.floor(indices), tf.int64)\n return tf.sort(middle)\n\n # pylint: disable=g-long-lambda\n samples = tf.cond(\n tf.equal(min_length, 1),\n random_frame,\n lambda: tf.cond(\n sequence_length >= min_length,\n without_replacement,\n with_replacement))\n # pylint: enable=g-long-lambda\n return samples\n\n indices = tf.map_fn(get_indices, sequence_lengths)\n batch_size = sequence_lengths.shape[0]\n indices.set_shape((batch_size, min_length))\n return indices\n\n\ndef get_subsample_indices_randomized_boundary(sequence_lengths,\n min_length,\n min_delta_t,\n max_delta_t):\n \"\"\"Generates random indices for sequence subsampling with random boundaries.\n\n Args:\n sequence_lengths: An int tensor of shape [B], for the length of each\n sequence. Since the provided tensors are padded to the length of the\n longest sequence in the batch, sequence_lengths is needed to avoid\n sampling from the padding.\n min_length: The min_length to subsample. The sampling always includes the\n first and last frame. If the sequence is long enough, timesteps are\n sampled without replacement. Otherwise, they are sampled with\n replacement. If min_length = 1, the example is picked randomly from\n the entire sequence.\n min_delta_t: smallest range of time-steps that can be sampled,\n if sampled length smaller sequence_length,\n then we use sequence_length instead\n max_delta_t: largest range of time-steps that can be sampled\n\n Returns:\n An int tensor of shape [B, min_length], for how to index into the seuqence.\n \"\"\"\n\n def get_indices(sequence_length):\n \"\"\"Generates indices for single sequence.\"\"\"\n episode_delta_t = tf.random.uniform(shape=[], minval=min_delta_t,\n maxval=max_delta_t + 1,\n dtype=tf.dtypes.int64)\n episode_delta_t = tf.math.reduce_min(tf.concat([sequence_length[None],\n episode_delta_t[None]],\n axis=0))\n episode_start = tf.random.uniform(shape=[], minval=0,\n maxval=(sequence_length -\n episode_delta_t + 1),\n dtype=tf.dtypes.int64)\n episode_end = episode_start + episode_delta_t - 1\n\n def without_replacement():\n # sample integers from [episode_start, episode_end)\n indices = tf.random.shuffle(tf.range(episode_start + 1,\n episode_end))\n middle = indices[:min_length - 2]\n middle = tf.reshape(middle, [min_length - 2])\n return tf.sort(tf.concat([[episode_start],\n middle, [episode_end]], axis=0))\n\n def with_replacement():\n # sample integers from [episode_start, episode_end)\n indices = tf.random.uniform(shape=[min_length - 2]) * \\\n tf.cast(episode_delta_t, float)\n middle = episode_start + tf.cast(tf.math.floor(indices), tf.int64)\n return tf.sort(tf.concat([[episode_start], middle,\n [episode_end]], axis=0))\n\n def random_frame():\n # Used when min_length == 1.\n return tf.random.uniform([1], minval=episode_start,\n maxval=episode_end, dtype=tf.dtypes.int64)\n\n # pylint: disable=g-long-lambda\n samples = tf.cond(\n tf.equal(min_length, 1),\n random_frame,\n lambda: tf.cond(\n episode_delta_t >= min_length,\n without_replacement,\n with_replacement))\n # pylint: enable=g-long-lambda\n return samples\n\n indices = tf.map_fn(get_indices, sequence_lengths)\n batch_size = sequence_lengths.shape[0]\n indices.set_shape((batch_size, min_length))\n return indices\n\n\ndef get_np_subsample_indices(sequence_lengths,\n min_length):\n \"\"\"Same behavior as get_subsample_indices, but in numpy format.\"\"\"\n def get_indices(sequence_length):\n \"\"\"Generates indices for single sequence.\"\"\"\n if min_length == 1:\n return np.random.randint(0, sequence_length, size=(1,))\n elif sequence_length >= min_length:\n # without replacement.\n arr = np.arange(1, sequence_length - 1)\n np.random.shuffle(arr)\n middle = arr[:min_length - 2]\n return np.sort(\n np.concatenate([[0], middle, [sequence_length-1]], axis=0))\n else:\n # with replacement.\n middle = np.random.randint(0, sequence_length, size=[min_length - 2])\n return np.sort(\n np.concatenate([[0], middle, [sequence_length-1]], axis=0))\n\n # Should do better than for loop at a later time....\n batch_size = sequence_lengths.shape[0]\n indices = np.zeros((batch_size, min_length), dtype=np.int64)\n for i in range(batch_size):\n indices[i] = get_indices(sequence_lengths[i])\n return indices\n", "# coding=utf-8\n# Copyright 2020 The Tensor2Robot Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python2, python3\n\"\"\"Cross-entropy method for continuous optimization.\n\nGiven some parametric family of sampling densities, the cross-entropy method\nwill adaptively select a set of parameters that minimizes the KL divergence\n(cross-entropy) between the sampling distribution and points with high objective\nfunction value.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport operator\nimport numpy as np\nfrom six.moves import range\nfrom six.moves import zip\n\n\ndef CrossEntropyMethod(sample_fn,\n objective_fn,\n update_fn,\n initial_params,\n num_elites,\n num_iterations=1,\n threshold_to_terminate=None):\n \"\"\"Uses the cross-entropy method (CEM) to maximize an objective function.\n\n Definition of 'sample batches':\n This function operates on 'sample batches' returned by sample_fn and received\n by objective_fn and update_fn. Sample batches can be either represented as\n lists `[x0, ..., xn]` of n samples or as dicts that map `str` keys to sample\n lists.\n\n Args:\n sample_fn: A sampling function that produces samples from some\n distribution. Inputs are arbitrary parameters `**params` to the sampling\n function; output is a sample batch as specified above.\n objective_fn: An objective function to evaluate the sampled points. Input is\n a sample batch as specified above; output is a list of scalars\n `[v0, ..., vn]` representing the objective function evaluated at the\n sampled points.\n update_fn: An update function that chooses new parameters to the sampling\n function. Inputs are a dictionary `params` representing the current\n parameters to the sampling function and a (elite) sample batch as\n specified above`; outputs is a dictionary `updated_params` representing\n the updated parameters to the sampling function.\n initial_params: A dictionary of initial parameters to the sampling function.\n num_elites: The number of elite samples to pass on to the update function.\n num_iterations: The number of iterations to perform.\n threshold_to_terminate: When provided, the function may terminate earlier\n than specified num_iterations if the best inference value is greater\n than threshold_to_terminate.\n\n Returns:\n final_samples: The final list of sampled points `[x0, ..., xn]`.\n final_values: The final list of scalars `[v0, ..., vn]` representing the\n objective function evaluated at the sampled points.\n final_params: A dictionary of final parameters to the sampling function.\n \"\"\"\n updated_params = initial_params\n\n for _ in range(num_iterations):\n # Draw samples from the sampling function.\n samples = sample_fn(**updated_params)\n\n # Evaluate the samples with the objective function.\n values = objective_fn(samples)\n\n if isinstance(samples, dict):\n # Sort the samples in ascending order.\n sample_order = [\n i for i, _ in sorted(enumerate(values), key=operator.itemgetter(1))\n ]\n sorted_samples = {\n k: [v[i] for i in sample_order] for k, v in samples.items()\n }\n\n # Identify the elite samples.\n elite_samples = {k: v[-num_elites:] for k, v in sorted_samples.items()}\n else:\n # Sort the samples in ascending order.\n sorted_samples = [\n s for s, _ in sorted(zip(samples, values), key=operator.itemgetter(1))\n ]\n\n # Identify the elite samples.\n elite_samples = sorted_samples[-num_elites:]\n\n # Update the parameters of the sampling distribution.\n updated_params = update_fn(updated_params, elite_samples)\n\n if ((threshold_to_terminate is not None) and\n (max(values) > threshold_to_terminate)):\n break\n\n return samples, values, updated_params\n\n\ndef NormalCrossEntropyMethod(objective_fn,\n mean,\n stddev,\n num_samples,\n num_elites,\n num_iterations=1):\n \"\"\"Uses CEM with a normal distribution as the sampling function.\n\n Args:\n objective_fn: An objective function to evaluate the sampled points. Input is\n a list of sampled points `[x0, ..., xn]`, output is a list of scalars\n `[v0, ..., vn]` representing the objective function evaluated at the\n sampled points.\n mean: A scalar or list of scalars representing the initial means.\n stddev: A scalar or list of scalars representing the initial stddevs.\n num_samples: The number of samples at each iteration.\n num_elites: The number of elite samples at each iteration.\n num_iterations: The number of iterations to perform.\n\n Returns:\n mean: A list of scalars representing the final means.\n stddev: A list of scalars representing the final stddevs.\n \"\"\"\n size = np.broadcast(mean, stddev).size\n\n def _SampleFn(mean, stddev):\n return mean + stddev * np.random.randn(num_samples, size)\n\n def _UpdateFn(params, elite_samples):\n del params\n return {\n 'mean': np.mean(elite_samples, axis=0),\n 'stddev': np.std(elite_samples, axis=0, ddof=1), # Bessel's correction\n }\n\n initial_params = {'mean': mean, 'stddev': stddev}\n _, _, final_params = CrossEntropyMethod(\n _SampleFn,\n objective_fn,\n _UpdateFn,\n initial_params,\n num_elites,\n num_iterations=num_iterations)\n\n return final_params['mean'], final_params['stddev']\n", "# coding=utf-8\n# Copyright 2020 The Tensor2Robot Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for TD3 Hooks.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport gin\nfrom tensor2robot.hooks import async_export_hook_builder\nfrom tensor2robot.predictors import exported_savedmodel_predictor\nfrom tensor2robot.preprocessors import noop_preprocessor\nfrom tensor2robot.utils import mocks\nfrom tensor2robot.utils import train_eval\nimport tensorflow.compat.v1 as tf # tf\n\n_EXPORT_DIR = 'export_dir'\n_BATCH_SIZES_FOR_EXPORT = [128]\n_MAX_STEPS = 4\n_BATCH_SIZE = 4\n\n\nclass AsyncExportHookBuilderTest(tf.test.TestCase):\n\n def test_with_mock_training(self):\n model_dir = self.create_tempdir().full_path\n mock_t2r_model = mocks.MockT2RModel(\n preprocessor_cls=noop_preprocessor.NoOpPreprocessor,\n device_type='tpu',\n use_avg_model_params=True)\n\n mock_input_generator = mocks.MockInputGenerator(batch_size=_BATCH_SIZE)\n export_dir = os.path.join(model_dir, _EXPORT_DIR)\n hook_builder = async_export_hook_builder.AsyncExportHookBuilder(\n export_dir=export_dir,\n create_export_fn=async_export_hook_builder.default_create_export_fn)\n\n gin.parse_config('tf.contrib.tpu.TPUConfig.iterations_per_loop=1')\n gin.parse_config('tf.estimator.RunConfig.save_checkpoints_steps=1')\n\n # We optimize our network.\n train_eval.train_eval_model(\n t2r_model=mock_t2r_model,\n input_generator_train=mock_input_generator,\n train_hook_builders=[hook_builder],\n model_dir=model_dir,\n max_train_steps=_MAX_STEPS)\n self.assertNotEmpty(tf.io.gfile.listdir(model_dir))\n self.assertNotEmpty(tf.io.gfile.listdir(export_dir))\n for exported_model_dir in tf.io.gfile.listdir(export_dir):\n self.assertNotEmpty(\n tf.io.gfile.listdir(os.path.join(export_dir, exported_model_dir)))\n predictor = exported_savedmodel_predictor.ExportedSavedModelPredictor(\n export_dir=export_dir)\n self.assertTrue(predictor.restore())\n\n\nif __name__ == '__main__':\n tf.test.main()\n" ]
[ [ "tensorflow.compat.v1.random.uniform", "tensorflow.compat.v1.concat", "tensorflow.compat.v1.equal", "numpy.arange", "tensorflow.compat.v1.reshape", "tensorflow.compat.v1.map_fn", "numpy.random.shuffle", "tensorflow.compat.v1.math.floor", "numpy.concatenate", "tensorflow.compat.v1.range", "tensorflow.compat.v1.cond", "tensorflow.compat.v1.cast", "tensorflow.compat.v1.sort", "numpy.zeros", "numpy.random.randint" ], [ "numpy.broadcast", "numpy.std", "numpy.mean", "numpy.random.randn" ], [ "tensorflow.compat.v1.io.gfile.listdir", "tensorflow.compat.v1.test.main" ] ]
mandaltanmoy1938/VisualGPT
[ "9ba78948282fdca502d5030f4eccc3df562982c3" ]
[ "evaluation/cider/cider_scorer.py" ]
[ "\n\nimport copy\nfrom collections import defaultdict\nimport numpy as np\nimport math\n\ndef precook(s, n=4):\n \"\"\"\n Takes a string as input and returns an object that can be given to\n either cook_refs or cook_test. This is optional: cook_refs and cook_test\n can take string arguments as well.\n :param s: string : sentence to be converted into ngrams\n :param n: int : number of ngrams for which representation is calculated\n :return: term frequency vector for occuring ngrams\n \"\"\"\n words = s.split()\n counts = defaultdict(int)\n for k in range(1,n+1):\n for i in range(len(words)-k+1):\n ngram = tuple(words[i:i+k])\n counts[ngram] += 1\n return counts\n\ndef cook_refs(refs, n=4): ## lhuang: oracle will call with \"average\"\n '''Takes a list of reference sentences for a single segment\n and returns an object that encapsulates everything that BLEU\n needs to know about them.\n :param refs: list of string : reference sentences for some image\n :param n: int : number of ngrams for which (ngram) representation is calculated\n :return: result (list of dict)\n '''\n return [precook(ref, n) for ref in refs]\n\ndef cook_test(test, n=4):\n '''Takes a test sentence and returns an object that\n encapsulates everything that BLEU needs to know about it.\n :param test: list of string : hypothesis sentence for some image\n :param n: int : number of ngrams for which (ngram) representation is calculated\n :return: result (dict)\n '''\n return precook(test, n)\n\nclass CiderScorer(object):\n \"\"\"CIDEr scorer.\n \"\"\"\n\n def __init__(self, refs, test=None, n=4, sigma=6.0, doc_frequency=None, ref_len=None):\n ''' singular instance '''\n self.n = n\n self.sigma = sigma\n self.crefs = []\n self.ctest = []\n self.doc_frequency = defaultdict(float)\n self.ref_len = None\n\n for k in refs.keys():\n self.crefs.append(cook_refs(refs[k]))\n if test is not None:\n self.ctest.append(cook_test(test[k][0])) ## N.B.: -1\n else:\n self.ctest.append(None) # lens of crefs and ctest have to match\n\n if doc_frequency is None and ref_len is None:\n # compute idf\n self.compute_doc_freq()\n # compute log reference length\n self.ref_len = np.log(float(len(self.crefs)))\n else:\n self.doc_frequency = doc_frequency\n self.ref_len = ref_len\n\n def compute_doc_freq(self):\n '''\n Compute term frequency for reference data.\n This will be used to compute idf (inverse document frequency later)\n The term frequency is stored in the object\n :return: None\n '''\n for refs in self.crefs:\n # refs, k ref captions of one image\n for ngram in set([ngram for ref in refs for (ngram,count) in ref.items()]):\n self.doc_frequency[ngram] += 1\n # maxcounts[ngram] = max(maxcounts.get(ngram,0), count)\n\n def compute_cider(self):\n def counts2vec(cnts):\n \"\"\"\n Function maps counts of ngram to vector of tfidf weights.\n The function returns vec, an array of dictionary that store mapping of n-gram and tf-idf weights.\n The n-th entry of array denotes length of n-grams.\n :param cnts:\n :return: vec (array of dict), norm (array of float), length (int)\n \"\"\"\n vec = [defaultdict(float) for _ in range(self.n)]\n length = 0\n norm = [0.0 for _ in range(self.n)]\n for (ngram,term_freq) in cnts.items():\n # give word count 1 if it doesn't appear in reference corpus\n df = np.log(max(1.0, self.doc_frequency[ngram]))\n # ngram index\n n = len(ngram)-1\n # tf (term_freq) * idf (precomputed idf) for n-grams\n vec[n][ngram] = float(term_freq)*(self.ref_len - df)\n # compute norm for the vector. the norm will be used for computing similarity\n norm[n] += pow(vec[n][ngram], 2)\n\n if n == 1:\n length += term_freq\n norm = [np.sqrt(n) for n in norm]\n return vec, norm, length\n\n def sim(vec_hyp, vec_ref, norm_hyp, norm_ref, length_hyp, length_ref):\n '''\n Compute the cosine similarity of two vectors.\n :param vec_hyp: array of dictionary for vector corresponding to hypothesis\n :param vec_ref: array of dictionary for vector corresponding to reference\n :param norm_hyp: array of float for vector corresponding to hypothesis\n :param norm_ref: array of float for vector corresponding to reference\n :param length_hyp: int containing length of hypothesis\n :param length_ref: int containing length of reference\n :return: array of score for each n-grams cosine similarity\n '''\n delta = float(length_hyp - length_ref)\n # measure consine similarity\n val = np.array([0.0 for _ in range(self.n)])\n for n in range(self.n):\n # ngram\n for (ngram,count) in vec_hyp[n].items():\n # vrama91 : added clipping\n val[n] += min(vec_hyp[n][ngram], vec_ref[n][ngram]) * vec_ref[n][ngram]\n\n if (norm_hyp[n] != 0) and (norm_ref[n] != 0):\n val[n] /= (norm_hyp[n]*norm_ref[n])\n\n assert(not math.isnan(val[n]))\n # vrama91: added a length based gaussian penalty\n val[n] *= np.e**(-(delta**2)/(2*self.sigma**2))\n return val\n\n scores = []\n for test, refs in zip(self.ctest, self.crefs):\n # compute vector for test captions\n vec, norm, length = counts2vec(test)\n # compute vector for ref captions\n score = np.array([0.0 for _ in range(self.n)])\n for ref in refs:\n vec_ref, norm_ref, length_ref = counts2vec(ref)\n score += sim(vec, vec_ref, norm, norm_ref, length, length_ref)\n # change by vrama91 - mean of ngram scores, instead of sum\n score_avg = np.mean(score)\n # divide by number of references\n score_avg /= len(refs)\n # multiply score by 10\n score_avg *= 10.0\n # append score of an image to the score list\n scores.append(score_avg)\n return scores\n\n def compute_score(self):\n # compute cider score\n score = self.compute_cider()\n # debug\n # print score\n return np.mean(np.array(score)), np.array(score)" ]
[ [ "numpy.array", "numpy.mean", "numpy.sqrt" ] ]
shahidul56/computer-vision-resource
[ "fd9f2a328e015bc0bf083578496e980681204614" ]
[ "CSE-6239-assignment-1/code/average_gray.py" ]
[ "\r\n\r\nimport numpy as np\r\nimport cv2\r\nimport sys\r\nimport getopt\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef readImage(filename):\r\n \"\"\"\r\n Read in an image file, errors out if we can't find the file\r\n :param filename: The image filename.\r\n :return: The img object in matrix form.\r\n \"\"\"\r\n img = cv2.imread(filename, 0)\r\n if img is None:\r\n print('Invalid image:' + filename)\r\n return None\r\n else:\r\n print('Image successfully read...')\r\n return img\r\n\r\n\r\ndef integralImage(img):\r\n \"\"\"\r\n\r\n :param img:\r\n :return:\r\n \"\"\"\r\n height = img.shape[0]\r\n width = img.shape[1]\r\n int_image = np.zeros((height, width), np.uint64)\r\n for y in range(height):\r\n for x in range(width):\r\n up = 0 if (y-1 < 0) else int_image.item((y-1, x))\r\n left = 0 if (x-1 < 0) else int_image.item((y, x-1))\r\n diagonal = 0 if (\r\n x-1 < 0 or y-1 < 0) else int_image.item((y-1, x-1))\r\n val = img.item((y, x)) + int(up) + int(left) - int(diagonal)\r\n int_image.itemset((y, x), val)\r\n return int_image\r\n\r\n\r\ndef adjustEdges(height, width, point):\r\n \"\"\"\r\n This handles the edge cases if the box's bounds are outside the image range based on current pixel.\r\n :param height: Height of the image.\r\n :param width: Width of the image.\r\n :param point: The current point.\r\n :return:\r\n \"\"\"\r\n newPoint = [point[0], point[1]]\r\n if point[0] >= height:\r\n newPoint[0] = height - 1\r\n\r\n if point[1] >= width:\r\n newPoint[1] = width - 1\r\n return tuple(newPoint)\r\n\r\n\r\ndef findArea(int_img, a, b, c, d):\r\n \"\"\"\r\n Finds the area for a particular square using the integral image. See summed area wiki.\r\n :param int_img: The\r\n :param a: Top left corner.\r\n :param b: Top right corner.\r\n :param c: Bottom left corner.\r\n :param d: Bottom right corner.\r\n :return: The integral image.\r\n \"\"\"\r\n height = int_img.shape[0]\r\n width = int_img.shape[1]\r\n a = adjustEdges(height, width, a)\r\n b = adjustEdges(height, width, b)\r\n c = adjustEdges(height, width, c)\r\n d = adjustEdges(height, width, d)\r\n\r\n a = 0 if (a[0] < 0 or a[0] >= height) or (\r\n a[1] < 0 or a[1] >= width) else int_img.item(a[0], a[1])\r\n b = 0 if (b[0] < 0 or b[0] >= height) or (\r\n b[1] < 0 or b[1] >= width) else int_img.item(b[0], b[1])\r\n c = 0 if (c[0] < 0 or c[0] >= height) or (\r\n c[1] < 0 or c[1] >= width) else int_img.item(c[0], c[1])\r\n d = 0 if (d[0] < 0 or d[0] >= height) or (\r\n d[1] < 0 or d[1] >= width) else int_img.item(d[0], d[1])\r\n\r\n return a + d - b - c\r\n\r\n\r\ndef boxFilter(img, filterSize):\r\n \"\"\"\r\n Runs the subsequent box filtering steps. Prints original image, finds integral image, and then outputs final image\r\n :param img: An image in matrix form.\r\n :param filterSize: The filter size of the matrix\r\n :return: A final image written as finalimage.png\r\n \"\"\"\r\n print(\"Printing original image...\")\r\n print(img)\r\n height = img.shape[0]\r\n width = img.shape[1]\r\n intImg = integralImage(img)\r\n finalImg = np.ones((height, width), np.uint64)\r\n print(\"Printing integral image...\")\r\n print(intImg)\r\n cv2.imwrite(\"integral_image.png\", intImg)\r\n loc = filterSize//2\r\n for y in range(height):\r\n for x in range(width):\r\n finalImg.itemset((y, x), findArea(intImg, (y-loc-1, x-loc-1),\r\n (y-loc-1, x+loc), (y+loc, x-loc-1), (y+loc, x+loc))//(filterSize**2))\r\n print(\"Printing final image...\")\r\n print(finalImg)\r\n plt.imshow(finalImg)\r\n\r\n cv2.imwrite(\"finalimage.png\", finalImg)\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n Reads in image and handles argument parsing\r\n :return: None\r\n \"\"\"\r\n args, img_name = getopt.getopt(sys.argv[1:], '', ['filter_size='])\r\n args = dict(args)\r\n filter_size = args.get('--filter_size')\r\n\r\n print(\"Image Name: \" + str(img_name[0]))\r\n print(\"Filter Size: \" + str(filter_size))\r\n\r\n img = readImage(img_name[0])\r\n if img is not None:\r\n print(\"Shape: \" + str(img.shape))\r\n print(\"Size: \" + str(img.size))\r\n print(\"Type: \" + str(img.dtype))\r\n boxFilter(img, int(filter_size))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n" ]
[ [ "matplotlib.pyplot.imshow", "numpy.zeros", "numpy.ones" ] ]
mdecourse/lightDRL
[ "4eff160f3797f88d20a059104c75e49d5295d932" ]
[ "worker.py" ]
[ "\nimport tensorflow as tf\nimport numpy as np\nimport yaml\nimport threading\nimport time\n\n# for connect to server\nfrom flask_socketio import Namespace, emit\n# DRL import \nfrom DRL.Base import RL, DRL\nfrom DRL.DDPG import DDPG\nfrom DRL.DQN import DQN\nfrom DRL.A3C import A3C\nfrom DRL.Qlearning import Qlearning\nfrom DRL.component.reward import Reward\nfrom DRL.component.noise import Noise\n# for debug \nfrom DRL.component.utils import print_tf_var\n\nclass WorkerBase(object):\n def base_init(self, cfg, graph, sess, model_log_dir, net_scope = None):\n self.graph = graph\n # RL or DRL Init\n np.random.seed( cfg['misc']['random_seed'])\n #----------------------------setup RL method--------------------------#\n method_class = globals()[cfg['RL']['method'] ]\n self.method_class = method_class\n if issubclass(method_class, DRL):\n '''Use DRL'''\n self.sess = sess\n # with tf.variable_scope(client_id): \n with self.graph.as_default():\n if cfg['RL']['method']=='A3C': # for multiple worker\n self.RL = method_class(cfg, model_log_dir, self.sess, net_scope)\n else:\n self.RL = method_class(cfg, model_log_dir, self.sess )\n self.RL.init_or_restore_model(self.sess) # init or check model\n\n # print_tf_var('worker after init DRL method')\n elif issubclass(method_class, RL):\n '''Use RL'''\n self.RL = method_class(cfg, model_log_dir, None)\n pass\n else:\n print('E: Worker::__init__() say error method name={}'.format(cfg['RL']['method'] ))\n\n # print(\"({}) Worker Ready!\".format(self.client_id))\n \n \n #--------------setup var---------------#\n self.var_init(cfg)\n\n # tf_summary_init\n print('model_log_dir = ', model_log_dir)\n self.tf_writer = tf.summary.FileWriter(model_log_dir)\n \n\n def var_init(self, cfg):\n self.frame_count = 0\n \n self.state_buf = []\n self.action_buf = []\n self.reward_buf = []\n self.done_buf = []\n self.next_state_buf = []\n\n self.start_time = time.time()\n self.ep_s_time = time.time()\n self.train_s_time = self.ep_s_time\n self.ep = 1#0\n self.ep_use_step = 0\n self.ep_reward = 0\n self.ep_max_reward = 0\n self.all_step = 0\n self.all_ep_reward = 0 # sum of all ep reward\n self._is_max_ep = False\n self.max_ep = cfg['misc']['max_ep']\n self.ep_max_step = cfg['misc']['ep_max_step'] # default: None -> unlimit steps, max steps in one episode\n self.a_discrete = cfg['RL']['action_discrete'] \n self.train_multi_steps = cfg['RL']['train_multi_steps'] # default: 1, param: 'if_down', 'steps(int)'-> train if down or train after steps\n self.add_data_steps = cfg['RL']['add_data_steps'] # default: 1, param: 'if_down', 'steps(int)'-> add data if down or add data after steps \n\n if type(self.train_multi_steps) == int:\n self.train_multi_count = 0\n\n if type(self.add_data_steps) == int:\n self.add_data_count = 0\n\n \n\n # setup reward\n if cfg['RL']['reward_reverse'] == True:\n self.reward_reverse = cfg['RL']['reward_reverse']\n self.reward_process = Reward(cfg['RL']['reward_factor'], cfg['RL']['reward_gamma'])\n # self.one_step_buf = {'s':None, 'a':None, 'r':None, 'd':None, 's_':None} \n\n\n self.exploration_step = cfg['RL']['exploration']\n self.exploration_action_noise = cfg['RL']['exploration_action_noise']\n\n self.action_epsilon = cfg['RL']['action_epsilon']\n self.action_epsilon_add = cfg['RL']['action_epsilon_add']\n self.action_noise = cfg['RL']['action_noise']\n # setup noise\n if self.action_noise!=None:\n if self.action_noise =='epsilon-greedy':\n self.epsilon_greedy_value = cfg['epsilon-greedy']['value']\n self.epsilon_greedy_discount = cfg['epsilon-greedy']['discount']\n elif self.action_noise =='Uhlenbeck':\n self.noise = None\n # print('--------in cofigure noise-----')\n self.noise = Noise( cfg['Uhlenbeck']['delta'], cfg['Uhlenbeck']['sigma'], cfg['Uhlenbeck']['ou_a'], cfg['Uhlenbeck']['ou_mu'])\n self.noise_max_ep= cfg['Uhlenbeck']['max_ep']\n self.ou_level = 0\n # def tf_summary_init(self, model_log_dir )\n # self.tf_writer = tf.summary.FileWriter(model_log_dir)\n\n self.none_over_pos_count = 0 \n\n self.worker_nickname = cfg['misc']['worker_nickname']\n print('worker_nickname = ', self.worker_nickname)\n\n def train_process(self, data):\n \n state = data['state']\n action = data['action']\n reward = data['reward']\n done = data['done']\n next_state = data['next_state']\n\n self.all_step += 1\n self.ep_use_step += 1\n self.ep_reward += reward\n self.ep_max_reward = reward if reward > self.ep_max_reward else self.ep_max_reward\n\n if np.isscalar(state):\n state = np.array([state])\n\n if np.isscalar(next_state):\n next_state = np.array([next_state])\n\n # print('-------in train_process-------')\n # print('I: train get state.shape={}, type(state)={}'.format(np.shape(state), type(state)))\n # print('I: train get action.shape={}, type(action)={}'.format(np.shape(action), type(action)))\n # print('I: train get reward.shape={}, type(reward)={}'.format(np.shape(reward), type(reward)))\n # print('I: train get done = {}'.format(done)) \n train_done = done\n if done == True and self.ep_use_step >= self.ep_max_step:\n # if the env has end position which could get reward, try to get the end position (like maze) as the done\n # else like cartpole which is no end position, so it use the default done\n train_done = False \n\n # print('done = {}, train_done={}'.format(done, train_done))\n self.train_add_data(state, action, reward, train_done, next_state )\n\n if self.all_step > self.exploration_step:\n if self.train_multi_steps == 1: # usually do this\n self.train()\n elif type(self.train_multi_steps) == int:\n self.train_multi_count += 1\n if self.train_multi_count >= self.train_multi_steps:\n self.train()\n self.train_multi_count = 0\n elif self.train_multi_steps=='if_down' and done:\n self.train()\n else:\n assert False, 'Error train_multi_steps'\n\n\n if done:\n ep_time_str = self.time_str(self.ep_s_time,min=True)\n all_time_str = self.time_str(self.train_s_time)\n more_log = ''\n if self.action_noise =='epsilon-greedy':\n more_log += ' | epsilon: %5.4f' % self.epsilon_greedy_value\n # print('more_log = ' ,more_log)\n log_str = '(%s) EP%5d | EP_Step: %5d | EP_Reward: %8.2f | MAX_R: %4.2f %s | EP_Time: %s | All_Time: %s ' % \\\n (self.worker_nickname, self.ep, self.ep_use_step, self.ep_reward, self.ep_max_reward, more_log, ep_time_str, all_time_str )\n print(log_str)\n # if issubclass(self.method_class, DRL):\n # log_str = '%s| Avg_Q: %.4f' % (log_str, self.RL.get_avg_q())\n log_dict = self.RL.get_log_dic()\n # if self.action_epsilon !=None:\n # log_dict = dict() if log_dict == None else log_dict\n # log_dict['epsilon'] = self.action_epsilon\n\n if self.action_noise =='epsilon-greedy':\n log_dict = dict() if log_dict == None else log_dict\n log_dict['epsilon'] = self.epsilon_greedy_value\n # ep_time = time.time() - self.ep_s_time\n # log_dict['EP Time'] = ep_time\n \n if self.action_epsilon!=None and self.ep_max_reward > 0:\n self.action_epsilon += self.action_epsilon_add\n\n \n self.all_ep_reward+= self.ep_reward\n self.tf_summary(self.ep , self.ep_reward,self.ep_max_reward,self.ep_use_step, self.ep_s_time, log_dict)\n \n self.RL.notify_ep_done()\n self.ep_use_step = 0\n self.ep_reward = 0\n self.ep_max_reward = -99999\n \n if self.ep >= self.max_ep:\n # summary result\n avg_ep_reward = self.all_ep_reward / float(self.ep)\n avg_ep_step = self.all_step / float(self.ep) \n avg_ep_reward_str = 'average ep reward = ' + str(avg_ep_reward)\n avg_ep_step_str = 'average ep step = ' + str(avg_ep_step)\n self.tf_summary_text('EP Average', avg_ep_reward_str, self.ep)\n self.tf_summary_text('EP Average', avg_ep_step_str, self.ep)\n self.tf_writer.flush()\n self._is_max_ep = True\n # else:\n self.ep+=1\n self.ep_s_time = time.time() # update episode start time\n \n \n \n def tf_summary_text(self, tag, text, ep):\n text_tensor = tf.make_tensor_proto(text, dtype=tf.string)\n meta = tf.SummaryMetadata()\n meta.plugin_data.plugin_name = \"text\"\n summary = tf.Summary()\n summary.value.add(tag=tag, metadata=meta, tensor=text_tensor)\n self.tf_writer.add_summary(summary, ep)\n\n\n def tf_summary(self, ep, ep_r, ep_max_r, ep_use_step, ep_s_time, log_dict):\n summary = tf.Summary()\n summary.value.add(tag='EP Reward', simple_value=int(ep_r))\n summary.value.add(tag='EP Max_Reward', simple_value=int(ep_max_r))\n summary.value.add(tag='EP Use Steps', simple_value=int(ep_use_step))\n summary.value.add(tag='EP Time', simple_value=float(time.time() - ep_s_time))\n summary.value.add(tag='All Time', simple_value=float(time.time() - self.train_s_time))\n if log_dict != None:\n for key, value in log_dict.iteritems():\n # print('{} -> {} '.format(key, value))\n summary.value.add(tag=key, simple_value=float(value))\n\n # summary.value.add(tag='Perf/Qmax', simple_value=float(ep_ave_max_q / float(j)))\n self.tf_writer.add_summary(summary, ep)\n\n\n def train_add_data(self, state, action, reward, done, next_state ):\n # print('self.add_data_steps =', self.add_data_steps )\n if self.add_data_steps == 1:\n # print('in add_data_steps ==1')\n self.RL.add_data( state, action, reward, done, next_state)\n else:\n go_multi_add = False\n self.state_buf.append(state)\n self.action_buf.append(action)\n self.reward_buf.append(reward)\n self.done_buf.append(done)\n self.next_state_buf.append(next_state)\n if type(self.add_data_steps) == int:\n self.add_data_count += 1\n if self.add_data_count >= self.add_data_steps:\n go_multi_add = True\n self.add_data_count = 0\n elif self.add_data_steps=='if_down' and done:\n go_multi_add = True\n\n if go_multi_add:\n tmp_reward_buf = self.reward_buf\n if self.reward_reverse:\n # print('before reward process, len=', len(self.reward_buf), ',data =', self.reward_buf )\n tmp_reward_buf = self.reward_process.discount(self.reward_buf)\n # print('afeter reward process, len=', len(tmp_reward_buf), ',data =', tmp_reward_buf )\n\n states = np.array(self.state_buf) \n actions = np.array(self.action_buf) \n rewards = np.array(tmp_reward_buf) \n dones = np.array(self.done_buf) \n next_states = np.array(self.next_state_buf) \n\n self.RL.add_data(states, actions, rewards, dones, next_states)\n # if self.ep_max_reward > 0:\n # self.RL.add_data(states, actions, rewards, dones, next_states)\n # self.none_over_pos_count = 0 \n # else:\n # self.none_over_pos_count += 1\n # if self.none_over_pos_count <= 2:\n # self.RL.add_data(states, actions, rewards, dones, next_states)\n\n # print('self.none_over_pos_count = ', self.none_over_pos_count)\n\n self.state_buf = []\n self.action_buf = []\n self.reward_buf = []\n self.done_buf = []\n self.next_state_buf = []\n\n def predict(self, state):\n # print('--------------%03d-%03d----------------' % ( self.ep, self.ep_use_step))\n # print(\"I: predict() state.shape: {}, type(state)= {}, state={} \".format(np.shape(state), type(state), state) )\n state = np.array(state)\n a = self.RL.choose_action(state)\n \n # if self.noise!=None and self.ep < self.noise_max_ep:\n # self.ou_level = self.noise.ornstein_uhlenbeck_level(self.ou_level)\n # a = a + self.ou_level\n # print('ou_level = ' , self.ou_level)\n # action = a[0]\n\n # print('send action = ', action)\n\n return a\n\n def add_action_noise(self, a):\n # print('--------------%03d-%03d----------------' % ( self.ep, self.ep_use_step))\n # print('before a = ', a)\n if self.a_discrete==True:\n a_dim = self.RL.a_discrete_n\n if self.action_noise=='epsilon-greedy':\n if np.random.rand() < self.epsilon_greedy_value:\n a = np.zeros(a_dim)\n a[ np.random.randint(self.RL.a_discrete_n) ] =1\n self.epsilon_greedy_value -= self.epsilon_greedy_discount\n\n\n if self.action_noise=='Uhlenbeck' and self.ep < self.noise_max_ep:\n self.ou_level = self.noise.ornstein_uhlenbeck_level(self.ou_level)\n a = a + self.ou_level\n # print('in ornstein_uhlenbeck ou_level = ' , self.ou_level)\n # print('after a = ', a)\n return a\n '''\n if self.noise!=None and self.ep < self.noise_max_ep:\n self.ou_level = self.noise.ornstein_uhlenbeck_level(self.ou_level)\n a = a + self.ou_level\n # print('in ornstein_uhlenbeck ou_level = ' , self.ou_level)\n \n a_dim = a.shape[0]\n #------replace original action-----#\n if self.all_step < self.exploration_step:\n if self.action_discrete==True:\n \n if self.exploration_action_noise=='np_random':\n # print('in np_random')\n a = np.zeros(a_dim)\n a[ np.random.randint(a_dim) ] =1\n elif self.exploration_action_noise=='dirichlet':\n # print('in dirichlet')\n a = np.random.dirichlet(np.ones(a_dim) ) # random, and sum is 1 \n \n \n if self.action_epsilon!=None and self.all_step > self.exploration_step:\n if np.random.rand(1)[0] > self.action_epsilon:\n a = np.zeros(a_dim)\n a[ np.random.randint(a_dim) ] =1\n\n \n # if self.ep_max_reward > 0: \n # print('iniiniin self.ep_max_reward > 0')\n \n # print('self.action_epsilon = ' , self.action_epsilon)\n # print('after a=', a )\n # print('worker use action = ', np.argmax(a))\n '''\n \n\n def train(self):\n with self.graph.as_default():\n self.RL.train()\n\n\n def to_py_native(self, obj):\n if type(obj) == np.ndarray:\n return obj.tolist()\n if isinstance(obj, np.generic):\n return np.asscalar(obj)\n\n def time_str(self, start_time, min=False):\n use_secs = time.time() - start_time\n if min:\n return '%3dm%2ds' % (use_secs/60, use_secs % 60 )\n return '%3dh%2dm%2ds' % (use_secs/3600, (use_secs%3600)/60, use_secs % 60 )\n\n \n def avg_ep_reward_show(self):\n print('(%s) EP%5d | all_ep_reward: %lf ' % \\\n (self.worker_nickname, self.ep-1, self.all_ep_reward) )\n return float(self.all_ep_reward) / float(self.ep)\n\n @property\n def is_max_ep(self):\n return self._is_max_ep\n #return (self.ep >= (self.max_ep) )\n\nclass WorkerStandalone(WorkerBase):\n def __init__(self, cfg = None, model_log_dir = None, \n graph = None, sess = None, net_scope = None):\n\n # self.main_queue = main_queue\n self.lock = threading.Lock()\n self.client_id = \"standalone\"\n\n self.base_init(cfg, graph, sess, model_log_dir, net_scope)\n\n import Queue\n self.main_queue = Queue.Queue()\n \n def get_callback_queue(self):\n return self.main_queue \n\n\n def on_predict(self, data):\n \n self.lock.acquire()\n \n action = self.predict(data['state'])\n if self.action_noise != None:\n action = self.add_action_noise(action)\n self.main_queue.put(action)\n self.lock.release()\n \n def on_train_and_predict(self, data):\n self.lock.acquire()\n self.train_process(data)\n self.lock.release()\n\n # if not data['done']:\n # action = self.predict(data['next_state'])\n # action = self.add_action_noise(action)\n # # print('worker on_train_and_predict action = ' , action,', thread=' ,threading.current_thread().name )\n # self.main_queue.put(action)\n\n action = self.predict(data['next_state'])\n action = self.add_action_noise(action)\n # print('worker on_train_and_predict action = ' , action,', thread=' ,threading.current_thread().name )\n # Becareful here !!!\n if not data['done']:\n self.main_queue.put(action)\n else:\n self.main_queue.put('WORKER_GET_DONE')\n\n \n\n\nclass WorkerConn(WorkerBase, Namespace): # if you want to standalone, you could use Worker(object)\n\n def __init__(self, ns = \"\", client_id=\"\", cfg = None, model_log_dir = None, \n graph = None, sess = None, net_scope = None):\n\n super(WorkerConn, self).__init__(ns)\n self.client_id = client_id\n \n self.base_init(cfg, graph, sess, model_log_dir, net_scope)\n\n def on_connect(self):\n print('{} Worker Connect'.format(self.client_id))\n\n def on_disconnect(self):\n print('{} Worker Disconnect'.format(self.client_id))\n \n\n def on_predict(self, data):\n action = self.predict(data['state'])\n # print('worker on_predict action = ' , action,', type=', type(action))\n # for socketio_client (if dont use, error: is not JSON serializable)\n action = action.tolist() if type(action) == np.ndarray else action\n # print('worker on_predict action after = ' , action,', type=', type(action))\n \n emit('predict_response', action)\n\n \n\n def on_train_and_predict(self, data):\n self.train_process(data)\n if not data['done']:\n action = self.predict(data['next_state'])\n action = action.tolist() if type(action) == np.ndarray else action\n emit('predict_response', action)\n" ]
[ [ "tensorflow.summary.FileWriter", "numpy.asscalar", "numpy.random.seed", "tensorflow.SummaryMetadata", "numpy.isscalar", "tensorflow.make_tensor_proto", "numpy.random.rand", "tensorflow.Summary", "numpy.array", "numpy.zeros", "numpy.random.randint" ] ]
hehichens/BCI
[ "b5802d61b6f7dbef937233a2b90836def08b9797" ]
[ "utils/utils.py" ]
[ "\"\"\"\nsome useful tools\nedit by hichens\n\"\"\"\n\nfrom scipy import signal\nimport pywt\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport time\nimport warnings; warnings.filterwarnings(\"ignore\")\n\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.datasets import make_moons, make_circles, make_classification\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.gaussian_process import GaussianProcessClassifier\nfrom sklearn.gaussian_process.kernels import RBF\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis, LinearDiscriminantAnalysis\n\nfrom xgboost import XGBClassifier\n\n\n## 段波功率\ndef bandpowers(segment):\n features = []\n for i in range(len(segment)):\n f,Psd = signal.welch(segment[i,:], 100)\n power1 = 0\n power2 = 0\n f1 = []\n for j in range(0,len(f)):\n if(f[j]>=4 and f[j]<=13):\n power1 += Psd[j]\n if(f[j]>=14 and f[j]<=30):\n power2 += Psd[j]\n features.append(power1)\n features.append(power2)\n return features\n\n\n## 离散余弦变换\nfrom scipy.fftpack import fft, dct\ndef dct_features(segment):\n features = []\n for i in range(len(segment)):\n dct_coef = dct(segment[i,:], 2, norm='ortho')\n power = sum( j*j for j in dct_coef)\n features.append(power)\n return features\n\n\n##小波特征\ndef wavelet_features(epoch):\n cA_values = []\n cD_values = []\n cA_mean = []\n cA_std = []\n cA_Energy =[]\n cD_mean = []\n cD_std = []\n cD_Energy = []\n Entropy_D = []\n Entropy_A = []\n features = []\n for i in range(len(epoch)):\n cA,cD=pywt.dwt(epoch[i,:],'coif1')\n cA_values.append(cA)\n cD_values.append(cD)\t\t#calculating the coefficients of wavelet transform.\n for x in range(len(epoch)): \n cA_Energy.append(abs(np.sum(np.square(cA_values[x]))))\n features.append(abs(np.sum(np.square(cA_values[x]))))\n \n for x in range(len(epoch)): \n cD_Energy.append(abs(np.sum(np.square(cD_values[x]))))\n features.append(abs(np.sum(np.square(cD_values[x]))))\n \n return features\n\n\ndef csp_features():\n pass\n\n\n## test in different models\ndef test_model(df):\n \"\"\"\n df: DataFrame format data\n \"\"\"\n features, labels = df.iloc[:, :-1].values, df.iloc[:, -1].values\n X_train, X_test, y_train, y_test = train_test_split(features, labels, \\\n shuffle=True, test_size=0.3, random_state=42)\n\n ## classify model\n clfs = [\n # Bayes Method\n GaussianNB(priors=None, var_smoothing=1e-9),\n MultinomialNB(alpha=0.1, fit_prior=True, class_prior=None),\n BernoulliNB(alpha=1.0, binarize=0.0, fit_prior=True, class_prior=None),\n KNeighborsClassifier(n_neighbors=1, \n weights='uniform', # uniform、distance\n algorithm='auto', # {‘auto’,‘ball_tree’,‘kd_tree’,‘brute’}\n leaf_size=10, \n # p=1, \n metric='minkowski', \n metric_params=None, \n n_jobs=None),\n \n SVC(C=1e7, kernel='rbf',\n shrinking=True, \n probability=False, \n tol=1e-2,\n cache_size=200, \n class_weight=None, \n verbose=False, \n # max_iter=1e5, \n # decision_function_shape='ovr', \n random_state=42),\n \n GaussianProcessClassifier(kernel=1.0 * RBF(64.0), warm_start=True,\n n_restarts_optimizer=0, \n max_iter_predict=100),\n\n DecisionTreeClassifier(criterion='entropy', # entropy, gini, \n splitter='random', # best, random\n max_depth=16, \n min_samples_split=2,\n min_samples_leaf=1, \n min_weight_fraction_leaf=0.0, \n max_features=None, \n random_state=42, \n max_leaf_nodes=None, \n min_impurity_decrease=0.0, \n class_weight=None),\n \n RandomForestClassifier(n_estimators=256, \n criterion='entropy', \n max_depth=None, \n min_samples_split=2, \n min_samples_leaf=1,\n min_weight_fraction_leaf=0.0, \n max_features='auto',\n max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None,\n bootstrap=True, \n oob_score=False,\n n_jobs=1, \n verbose=0, \n warm_start=False, \n class_weight=None),\n \n AdaBoostClassifier(base_estimator=RandomForestClassifier(n_estimators=128, criterion='entropy', max_depth=None), \n n_estimators=32, \n learning_rate=1e-2, \n algorithm='SAMME.R', # SAMME.R, SAMME.R\n random_state=42),\n \n LinearDiscriminantAnalysis(solver='svd', # {‘svd’, ‘lsqr’, ‘eigen’}\n priors=None,\n n_components=None,\n tol=1e-4),\n\n QuadraticDiscriminantAnalysis(priors=None, \n reg_param=0.0, \n store_covariance=False, \n tol=1e-4),\n \n XGBClassifier(learning_rate=None,\n booster='gbtree', # gbtree, gblinear, dart\n n_estimators=2000, # 树的个数\n # max_depth=10, # 树的深度 \n # min_child_weight = 1, # 叶子节点最小权重\n # gamma=0., # 惩罚项中叶子结点个数前的参数\n # subsample=1, # 所有样本建立决策树\n # colsample_btree=1, # 所有特征建立决策树\n scale_pos_weight=1, # 解决样本个数不平衡的问题\n # slient = 0,\n # reg_alpha=1e-4,\n # reg_lambda=1e-4,\n # use_label_encoder=False,\n random_state=42,\n n_jobs=8\n ),\n\n MLPClassifier(hidden_layer_sizes=128, \n activation='relu', # {‘identity’, ‘logistic’, ‘tanh’, ‘relu’}\n solver='adam', # {‘lbfgs’, ‘sgd’, ‘adam’}\n alpha=1e-3, \n batch_size=256, # \n learning_rate='invscaling', # {‘constant’, ‘invscaling’, ‘adaptive’}\n learning_rate_init=1e-3, \n power_t=0.5, \n max_iter=10000, \n shuffle=True, \n random_state=42, \n tol=1e-7, \n verbose=False, \n warm_start=False, \n momentum=0.9, \n nesterovs_momentum=True, \n early_stopping=False, \n validation_fraction=0.1, \n beta_1=0.9, \n beta_2=0.999, \n epsilon=1e-08, \n n_iter_no_change=10, \n max_fun=15000)\n ]\n \n ## train and print(accuracy)\n print(\"=\"*40, \"result\", \"=\"*40)\n print(\"%40s %10s %10s\"%(\"Model \", \"Accuracy\", \"time\"))\n result = []\n weights = [] # model vote weight\n score_list = []\n train_score_list = []\n for clf in clfs:\n start = time.time()\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n score = accuracy_score(y_pred, y_test)\n train_score = clf.score(X_train, y_train)\n score_list.append(score)\n train_score_list.append(train_score)\n weights.append(score)\n print(\"%40s %5.4f|%5.4f %10.2f s\"%(type(clf).__name__, train_score, score, time.time() - start))\n result.append([type(clf).__name__, score])\n print(\"%40s %5.4f|%5.4f %10.2f s\"%(\"Average\", np.mean(train_score_list), np.mean(score_list), 0.0))\n result.append([\"Average\", np.mean(score)])\n\n ## model merge\n N = len(weights)\n split_index = sum(weights) / 2\n pred = np.zeros(len(y_pred))\n start = time.time()\n for i, clf in enumerate(clfs):\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n pred += weights[i] * y_pred\n \n pred[pred<=split_index] = 0\n pred[pred>split_index] = 1\n score = accuracy_score(pred, y_test)\n print(\"%40s %10.4f %10.2f s\"%(\"Model Stack\", score, time.time() - start))\n result.append([\"Model Stack\", score])\n \n print(\"=\"*40, \"end\", \"=\"*40)\n return result\n\n \ndef save_csv(result, path=None):\n res_df = pd.DataFrame(result)\n res_df.columns = ['method', 'score']\n res_df.to_csv(path, index=None)\n\n\n## plot and show\ndef plot(data):\n pass" ]
[ [ "sklearn.neural_network.MLPClassifier", "numpy.square", "sklearn.naive_bayes.GaussianNB", "sklearn.ensemble.RandomForestClassifier", "sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis", "sklearn.naive_bayes.MultinomialNB", "sklearn.model_selection.train_test_split", "pandas.DataFrame", "sklearn.neighbors.KNeighborsClassifier", "sklearn.naive_bayes.BernoulliNB", "sklearn.tree.DecisionTreeClassifier", "numpy.mean", "sklearn.svm.SVC", "sklearn.discriminant_analysis.LinearDiscriminantAnalysis", "sklearn.gaussian_process.kernels.RBF", "scipy.fftpack.dct", "scipy.signal.welch", "sklearn.metrics.accuracy_score" ] ]
jspaaks/vak
[ "581ec4869d342e5d52bc057de54c10901f06d343" ]
[ "tests/test_nn/test_functional.py" ]
[ "import pytest\n\nimport torch\n\nimport vak.nn.functional as F\n\n\n# adapted from kornia, https://github.com/kornia/kornia/blob/master/test/utils/test_one_hot.py\ndef test_onehot():\n num_classes = 4\n labels = torch.zeros(2, 2, 1, dtype=torch.int64)\n labels[0, 0, 0] = 0\n labels[0, 1, 0] = 1\n labels[1, 0, 0] = 2\n labels[1, 1, 0] = 3\n\n # convert labels to one hot tensor\n one_hot = F.one_hot(labels, num_classes)\n\n assert 1.0 == pytest.approx(one_hot[0, labels[0, 0, 0], 0, 0].item())\n assert 1.0 == pytest.approx(one_hot[0, labels[0, 1, 0], 1, 0].item())\n assert 1.0 == pytest.approx(one_hot[1, labels[1, 0, 0], 0, 0].item())\n assert 1.0 == pytest.approx(one_hot[1, labels[1, 1, 0], 1, 0].item())\n" ]
[ [ "torch.zeros" ] ]
granttremblay/MUSEmovie
[ "979f61bb90aa6de7f553c715a9da11d27329538f" ]
[ "make_cars_movies.py" ]
[ "import os\nimport glob\n\nimport warnings\n\nfrom astropy.io import fits\nfrom astropy.wcs import WCS\n\nfrom astroquery.ned import Ned\n\nimport numpy as np\n\n# import seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nfrom matplotlib import cm\n\nimport imageio\n\n# Some things we'll be doing throw runtimewarnings that we won't care about.\nwarnings.filterwarnings('ignore')\n\ncarsdata = '../data/MUSE/*/*binned.fits*'\nline_restwav = 6563 # Set the rest wavelength of the emission line you'd like\nscalefactor = 2.0 # Set the DPI scaling of the output image.\n\ncubes = []\nfor cube in glob.glob(carsdata):\n cubes.append(cube)\n\ncubes.sort()\n\n# Target names are uniformly found in 13th through 24th indices. Lazily slice.\ntarget_names = []\nfor string in cubes:\n name = string[13:24]\n target_names.append(name)\n\nprint(\"Querying NED for Target Redshifts\")\n\nredshifts = []\nemission_line_centers = []\n\nfor name in target_names:\n z = Ned.query_object(name)[\"Redshift\"][0]\n\n if z > 0.1: # then something is wrong:\n if z == 0.414757:\n corrected_z = 0.053\n print(\"The NED redshift for {} of {} is wrong. Manually setting it to {}.\".format(\n name, z, corrected_z))\n z = corrected_z\n else:\n print(\"Some redshifts are greater than 0.1. Check your NED query.\")\n\n redshifts.append(z)\n emission_line_centers.append(line_restwav * (1 + z))\n\n\n# for index, name in enumerate(target_names):\n# print(\"{} is at z={}\".format(name, round(redshifts[index], 3)))\n\n\ndef makeMovie(cube, name, redshift, center, numframes=30):\n '''Make the movie'''\n\n ########### READ THE DATA CUBE ####################\n hdulist = fits.open(cube)\n data = hdulist[0].data\n header = hdulist[0].header\n wcs_3d = WCS(header)\n wcs = wcs_3d.dropaxis(2)\n hdulist.close()\n\n number_of_channels = len(data[:, 0, 0])\n\n # Create the wavelength array\n wavelength = ((np.arange(number_of_channels) + 1.0) -\n header['CRPIX3']) * header['CD3_3'] + header['CRVAL3']\n\n # This quick one liner finds the element in the wavelength array\n # that is closest to the \"target\" wavelength, then returns that element's\n # index.\n\n # It finds the deviation between each array element and the target value,\n # takes its absolute value, and then returns the index of\n # the element with the smallest value in the resulting array.\n # This is the number that is closest to the target.\n\n center_channel = (np.abs(wavelength - center)).argmin()\n #print(\"Emission line centroid for {} is in channel {}\".format(name,center_channel))\n\n movie_start = center_channel - numframes\n movie_end = center_channel + numframes\n\n slices_of_interest = np.arange(movie_start, movie_end, 1)\n\n ########### CREATE AND SCRUB THE TEMPORARY FRAMESTORE ##############\n temp_movie_dir = \"framestore/\"\n if not os.path.exists(temp_movie_dir):\n os.makedirs(temp_movie_dir)\n print(\"Created a temporary directory called '{}', where movie frame .png files are stored. You can delete this afterward if you'd like.\".format(temp_movie_dir))\n\n png_files = []\n\n # Clean the temporary movie directory first\n # If you don't remove all \"old\" movie frames, your gif is gonna be messed up.\n for f in glob.glob(temp_movie_dir + \"*.png\"):\n os.remove(f)\n #####################################################################\n\n print(\"Making movie for {} at z={}. Line centroid is in channel {}.\".format(\n name, round(redshift, 3), center_channel))\n\n for i, slice in enumerate(slices_of_interest):\n # Perform a dumb continuum subtraction. Risky if you land on another line.\n cont_sub_image = data[slice, :, :] - data[center_channel - 200, :, :]\n cont_sub_image[cont_sub_image < 0.005] = np.nan\n\n sizes = np.shape(cont_sub_image)\n height = float(sizes[0]) * scalefactor\n width = float(sizes[1]) * scalefactor\n\n fig = plt.figure()\n fig.set_size_inches(width / height, 1, forward=False)\n ax = plt.Axes(fig, [0., 0., 1., 1.])\n ax.set_axis_off()\n fig.add_axes(ax)\n\n #cmap = sns.cubehelix_palette(20, light=0.95, dark=0.15, as_cmap=True)\n cmap = cm.magma\n cmap.set_bad('black', 1)\n\n ax.imshow(cont_sub_image, origin='lower', norm=LogNorm(),\n cmap=cmap, interpolation='None')\n\n fig.subplots_adjust(bottom=0)\n fig.subplots_adjust(top=1)\n fig.subplots_adjust(right=1)\n fig.subplots_adjust(left=0)\n\n fig.savefig(temp_movie_dir + '{}'.format(i) + '.png', dpi=height)\n png_files.append(temp_movie_dir + '{}'.format(i) + '.png')\n plt.close(fig)\n\n ########### CREATE AND SCRUB THE GIF DIRECTORY ##############\n gif_output_dir = \"movies/\"\n if not os.path.exists(gif_output_dir):\n os.makedirs(gif_output_dir)\n print(\"Saving output movies to '{}'.\".format(gif_output_dir))\n #############################################################\n\n gif_name = gif_output_dir + '{}.gif'.format(name)\n gif_frames = []\n\n # Remove any old GIFs you might have made\n if os.path.isfile(gif_name):\n os.remove(gif_name)\n\n for filename in png_files:\n gif_frames.append(imageio.imread(filename))\n\n imageio.mimsave(gif_name, gif_frames)\n print(\"Done. Saved to {}.\".format(gif_name))\n\n\nfor index, cube in enumerate(cubes):\n makeMovie(cube, target_names[index], redshifts[index],\n emission_line_centers[index], numframes=30)\n\nprint(\"Done. Enjoy the show.\")\n" ]
[ [ "matplotlib.colors.LogNorm", "numpy.abs", "numpy.arange", "matplotlib.pyplot.Axes", "numpy.shape", "matplotlib.pyplot.close", "matplotlib.pyplot.figure" ] ]
ContentSide/rezojdm-sds
[ "ee1203afdcbabc9a3c8abace6723cfeaa077808c" ]
[ "src/modules/ConvKB.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom .Model import Model\n\nclass ConvKB(Model):\n\n def __init__(self, ent_tot, rel_tot, convkb_drop_prob, out_channels, kernel_size, hidden_size = 100):\n super(ConvKB, self).__init__(ent_tot, rel_tot)\n \n self.hidden_size = hidden_size\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n self.convkb_drop_prob = convkb_drop_prob\n\n\n self.ent_embeddings = nn.Embedding(self.ent_tot, self.hidden_size)\n self.rel_embeddings = nn.Embedding(self.rel_tot, self.hidden_size)\n\n self.conv1_bn = nn.BatchNorm2d(1)\n self.conv_layer = nn.Conv2d(1, self.out_channels, (self.kernel_size, 3)) # kernel size x 3\n self.conv2_bn = nn.BatchNorm2d(self.out_channels)\n self.dropout = nn.Dropout(self.convkb_drop_prob)\n self.non_linearity = nn.ReLU() # you should also tune with torch.tanh() or torch.nn.Tanh()\n self.fc_layer = nn.Linear((self.hidden_size - self.kernel_size + 1) * self.out_channels, 1, bias=False)\n\n self.criterion = nn.Softplus()\n\n nn.init.xavier_uniform_(self.ent_embeddings.weight.data)\n nn.init.xavier_uniform_(self.rel_embeddings.weight.data)\t\t\n\n nn.init.xavier_uniform_(self.fc_layer.weight.data)\n nn.init.xavier_uniform_(self.conv_layer.weight.data)\n\n\n def _calc(self, h, t, r):\n print(h.shape, r.shape, t.shape)\n h = h.unsqueeze(1) # bs x 1 x dim\n r = r.unsqueeze(1)\n t = t.unsqueeze(1)\n print(h.shape, r.shape, t.shape)\n\n conv_input = torch.cat([h, r[:h.shape[0]], t], 1) # bs x 3 x dim\n conv_input = conv_input.transpose(1, 2)\n # To make tensor of size 4, where second dim is for input channels\n conv_input = conv_input.unsqueeze(1)\n conv_input = self.conv1_bn(conv_input)\n out_conv = self.conv_layer(conv_input)\n out_conv = self.conv2_bn(out_conv)\n out_conv = self.non_linearity(out_conv)\n out_conv = out_conv.view(-1, (self.hidden_size - self.kernel_size + 1) * self.out_channels)\n input_fc = self.dropout(out_conv)\n score = self.fc_layer(input_fc).view(-1)\n\n return -score\n\n def loss(self, score, regul, batch_y):\n return 0.4 * regul\n\n\n def forward(self, data):\n batch_h = data['batch_h']\n batch_t = data['batch_t']\n batch_r = data['batch_r']\n print(\"batch_x\", batch_h.shape, batch_r.shape)\n\n\n h = self.ent_embeddings(batch_h)\n t = self.ent_embeddings(batch_t)\n r = self.rel_embeddings(batch_r)\n print(\"batch\", h.shape, r.shape)\n\n\n score = self._calc(h, r, t)\n\n # regularization\n l2_reg = torch.mean(h ** 2) + torch.mean(t ** 2) + torch.mean(r ** 2)\n for W in self.conv_layer.parameters():\n l2_reg = l2_reg + W.norm(2)\n for W in self.fc_layer.parameters():\n l2_reg = l2_reg + W.norm(2)\n\n return self.loss(score, l2_reg, data['batch_y'])\n\n\n def predict(self, data):\n \n score = self.forward(data)\n\n return score.cpu().data.numpy()" ]
[ [ "torch.mean", "torch.nn.Dropout", "torch.nn.Softplus", "torch.cat", "torch.nn.Conv2d", "torch.nn.Embedding", "torch.nn.Linear", "torch.nn.init.xavier_uniform_", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ] ]
aditya10/vilbert-multi-task
[ "dda8c16187ac6cc4f6266a823fbde528f65af720" ]
[ "vilbert/datasets/visual_genome_dataset.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport os\nimport json\nimport _pickle as cPickle\nimport logging\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nfrom pytorch_transformers.tokenization_bert import BertTokenizer\n\nfrom ._image_features_reader import ImageFeaturesH5Reader\n\nlogger = logging.getLogger(__name__) # pylint: disable=invalid-name\nos.environ[\"HDF5_USE_FILE_LOCKING\"] = \"FALSE\"\n\n\ndef assert_eq(real, expected):\n assert real == expected, \"%s (true) vs %s (expected)\" % (real, expected)\n\n\ndef _create_entry(item):\n entry = {\n \"question_id\": item[\"question_id\"],\n \"image_id\": item[\"image_id\"],\n \"question\": item[\"question\"],\n \"answer\": item,\n }\n return entry\n\n\ndef _load_dataset(dataroot, name, clean_datasets):\n \"\"\"Load entries\n\n dataroot: root path of dataset\n name: 'train', 'val'\n \"\"\"\n if name == \"train\":\n items_path = os.path.join(dataroot, \"cache\", \"trainval_target.pkl\")\n items = cPickle.load(open(items_path, \"rb\"))\n items = sorted(items, key=lambda x: x[\"question_id\"])\n items = items[:-5000]\n elif name == \"val\":\n items_path = os.path.join(dataroot, \"cache\", \"trainval_target.pkl\")\n items = cPickle.load(open(items_path, \"rb\"))\n items = sorted(items, key=lambda x: x[\"question_id\"])\n items = items[-5000:]\n else:\n assert False, \"data split is not recognized.\"\n\n if \"test\" in name:\n entries = []\n for item in items:\n entries.append(item)\n else:\n entries = []\n remove_ids = []\n if clean_datasets:\n remove_ids = np.load(os.path.join(dataroot, \"cache\", \"genome_test_ids.npy\"))\n remove_ids = [int(x) for x in remove_ids]\n for item in items:\n if int(item[\"image_id\"]) in remove_ids:\n continue\n entries.append(_create_entry(item))\n return entries\n\n\nclass GenomeQAClassificationDataset(Dataset):\n def __init__(\n self,\n task: str,\n dataroot: str,\n annotations_jsonpath: str,\n split: str,\n image_features_reader: ImageFeaturesH5Reader,\n gt_image_features_reader: ImageFeaturesH5Reader,\n tokenizer: BertTokenizer,\n bert_model,\n clean_datasets,\n padding_index: int = 0,\n max_seq_length: int = 16,\n max_region_num: int = 37,\n ):\n super().__init__()\n self.split = split\n ans2label_path = os.path.join(dataroot, \"cache\", \"trainval_ans2label.pkl\")\n label2ans_path = os.path.join(dataroot, \"cache\", \"trainval_label2ans.pkl\")\n self.ans2label = cPickle.load(open(ans2label_path, \"rb\"))\n self.label2ans = cPickle.load(open(label2ans_path, \"rb\"))\n self.num_labels = len(self.ans2label)\n self._max_region_num = max_region_num\n self._max_seq_length = max_seq_length\n self._image_features_reader = image_features_reader\n self._tokenizer = tokenizer\n self._padding_index = padding_index\n\n clean_train = \"_cleaned\" if clean_datasets else \"\"\n\n if \"roberta\" in bert_model:\n cache_path = os.path.join(\n dataroot,\n \"cache\",\n task\n + \"_\"\n + split\n + \"_\"\n + \"roberta\"\n + \"_\"\n + str(max_seq_length)\n + clean_train\n + \".pkl\",\n )\n else:\n cache_path = os.path.join(\n dataroot,\n \"cache\",\n task + \"_\" + split + \"_\" + str(max_seq_length) + clean_train + \".pkl\",\n )\n\n if not os.path.exists(cache_path):\n self.entries = _load_dataset(dataroot, split, clean_datasets)\n self.tokenize(max_seq_length)\n self.tensorize()\n cPickle.dump(self.entries, open(cache_path, \"wb\"))\n else:\n logger.info(\"Loading from %s\" % cache_path)\n self.entries = cPickle.load(open(cache_path, \"rb\"))\n\n def tokenize(self, max_length=16):\n \"\"\"Tokenizes the questions.\n\n This will add q_token in each entry of the dataset.\n -1 represent nil, and should be treated as padding_index in embedding\n \"\"\"\n for entry in self.entries:\n # tokens = self._tokenizer.tokenize(entry[\"question\"])\n # tokens = [\"[CLS]\"] + tokens + [\"[SEP]\"]\n\n # tokens = [\n # self._tokenizer.vocab.get(w, self._tokenizer.vocab[\"[UNK]\"])\n # for w in tokens\n # ]\n tokens = self._tokenizer.encode(entry[\"question\"])\n tokens = tokens[: max_length - 2]\n tokens = self._tokenizer.add_special_tokens_single_sentence(tokens)\n\n segment_ids = [0] * len(tokens)\n input_mask = [1] * len(tokens)\n\n if len(tokens) < max_length:\n # Note here we pad in front of the sentence\n padding = [self._padding_index] * (max_length - len(tokens))\n tokens = tokens + padding\n input_mask += padding\n segment_ids += padding\n\n assert_eq(len(tokens), max_length)\n entry[\"q_token\"] = tokens\n entry[\"q_input_mask\"] = input_mask\n entry[\"q_segment_ids\"] = segment_ids\n\n def tensorize(self):\n\n for entry in self.entries:\n question = torch.from_numpy(np.array(entry[\"q_token\"]))\n entry[\"q_token\"] = question\n\n q_input_mask = torch.from_numpy(np.array(entry[\"q_input_mask\"]))\n entry[\"q_input_mask\"] = q_input_mask\n\n q_segment_ids = torch.from_numpy(np.array(entry[\"q_segment_ids\"]))\n entry[\"q_segment_ids\"] = q_segment_ids\n\n if \"test\" not in self.split:\n answer = entry[\"answer\"]\n labels = np.array(answer[\"labels\"])\n scores = np.array(answer[\"scores\"], dtype=np.float32)\n if len(labels):\n labels = torch.from_numpy(labels)\n scores = torch.from_numpy(scores)\n entry[\"answer\"][\"labels\"] = labels\n entry[\"answer\"][\"scores\"] = scores\n else:\n entry[\"answer\"][\"labels\"] = None\n entry[\"answer\"][\"scores\"] = None\n\n def __getitem__(self, index):\n entry = self.entries[index]\n image_id = entry[\"image_id\"]\n question_id = entry[\"question_id\"]\n features, num_boxes, boxes, _ = self._image_features_reader[image_id]\n\n mix_num_boxes = min(int(num_boxes), self._max_region_num)\n mix_boxes_pad = np.zeros((self._max_region_num, 5))\n mix_features_pad = np.zeros((self._max_region_num, 2048))\n\n image_mask = [1] * (int(mix_num_boxes))\n while len(image_mask) < self._max_region_num:\n image_mask.append(0)\n\n mix_boxes_pad[:mix_num_boxes] = boxes[:mix_num_boxes]\n mix_features_pad[:mix_num_boxes] = features[:mix_num_boxes]\n\n features = torch.tensor(mix_features_pad).float()\n image_mask = torch.tensor(image_mask).long()\n spatials = torch.tensor(mix_boxes_pad).float()\n\n question = entry[\"q_token\"]\n input_mask = entry[\"q_input_mask\"]\n segment_ids = entry[\"q_segment_ids\"]\n\n co_attention_mask = torch.zeros((self._max_region_num, self._max_seq_length))\n target = torch.zeros(self.num_labels)\n\n if \"test\" not in self.split:\n answer = entry[\"answer\"]\n labels = answer[\"labels\"]\n scores = answer[\"scores\"]\n if labels is not None:\n target.scatter_(0, labels, scores)\n\n return (\n features,\n spatials,\n image_mask,\n question,\n target,\n input_mask,\n segment_ids,\n co_attention_mask,\n question_id,\n )\n\n def __len__(self):\n return len(self.entries)\n" ]
[ [ "torch.zeros", "torch.from_numpy", "torch.tensor", "numpy.array", "numpy.zeros" ] ]
olonok69/TIME_SERIES_MODELING_KERAS
[ "c0e5a6f274d707551e3bcad2d2ccf75b18c39464" ]
[ "raw_data/library.py" ]
[ "import pandas\nimport numpy as np\n#from sklearn import preprocessing\n#from sklearn import svm\n#from sklearn import cross_validation\n#import pandas_datareader.data as web\n#import quandl\n\ndaysAhead = 270\n\ndef get_web_data(symbols, dates):\n #\"\"\"Read stock data (adjusted close) for given symbols from CSV files.\"\"\"\n\tdf_final = pd.DataFrame(index=dates)\n\ti=0\n\tfechastart='2007-01-01'\n\tfechaend='2017-01-01'\n \n\tfor symbol in symbols:\n \n\t\tdf_temp = web.DataReader(symbol, start=fechastart, end=fechaend,data_source='yahoo')[\"Date\", \"Adj Close\"]\n\t\tdf_temp = df_temp.rename(columns={\"Adj Close\": symbol})\n\t\tdf_final = df_final.join(df_temp)\n\t\ti+=1\n\t\tif i == 1: # drop dates SPY did not trade\n\t\t\tdf_final = df_final.dropna(subset=[symbol])\n\treturn df_final\n\n\t\ndef get_web_quandl(symbol, simbolo):\n\n\tdf = quandl.get(symbol, trim_start = \"01/01/2007\", trim_end =\"01/01/2017\", authtoken=\"_N85bWLCNCWz14smKHSi\")\n\tname=simbolo\n\tdf.columns.values[-1] = 'AdjClose'\n\tdf.columns = df.columns + '_' + name\n\tdf['Return_%s' %name] = df['AdjClose_%s' %name].pct_change()\n\treturn df\n\ndef calcPriceVolatility(numDays, priceArray):\n\n\tglobal daysAhead\n\n\t# make price volatility array\n\n\tvolatilityArray = []\n\n\tmovingVolatilityArray = []\n\n\tfor i in range(1, numDays+1):\n\n\t\tpercentChange = 100 * (priceArray[i] - priceArray[i-1]) / priceArray[i-1]\n\n\t\tmovingVolatilityArray.append(percentChange)\n\n\tvolatilityArray.append(np.mean(movingVolatilityArray))\n\n\tfor i in range(numDays + 1, len(priceArray) - daysAhead):\n\n\t\tdel movingVolatilityArray[0]\n\n\t\tpercentChange = 100 * (priceArray[i] - priceArray[i-1]) / priceArray[i-1]\n\n\t\tmovingVolatilityArray.append(percentChange)\n\n\t\tvolatilityArray.append(np.mean(movingVolatilityArray))\n\n\n\n\treturn volatilityArray\n\n# calculate momentum array\n\ndef calcMomentum(numDays, priceArray):\n\n\t#global daysAhead\n\n\t# now calculate momentum\n\n\tmomentumArray = []\n\n\tmovingMomentumArray = []\n\n\tfor i in range(1, numDays + 1):\n\n\t\tmovingMomentumArray.append(1 if priceArray[i] > priceArray[i-1] else -1)\n\n\tmomentumArray.append(np.mean(movingMomentumArray))\n\n\tfor i in range(numDays+1, len(priceArray) - daysAhead):\n\n\t\tdel movingMomentumArray[0]\n\n\t\tmovingMomentumArray.append(1 if priceArray[i] > priceArray[i-1] else -1)\n\n\t\tmomentumArray.append(np.mean(movingMomentumArray))\n\n\n\n\treturn momentumArray" ]
[ [ "numpy.mean" ] ]
jiviteshjain/cast-away
[ "1b244fe0df24cb570739ae82626df35fccbe3a22" ]
[ "utils.py" ]
[ "import os\nimport numpy as np\nfrom colorama import init as cinit\nfrom colorama import Fore, Back, Style\nimport random\nfrom time import monotonic as clock\nimport random\nimport math\n\nimport config as conf\nimport obstacle\n\ndef intersect(rec_a, rec_b):\n '''\n checks if two rectangles intersect and returns their intersection area\n '''\n\n if type(rec_a) != list or type(rec_b) != list or len(rec_a) != 4 or len(rec_b) != 4:\n raise ValueError\n\n # rectangle representation: [x_start, x_end, y_start, y_end]\n\n x_start = max(rec_a[0], rec_b[0])\n x_end = min(rec_a[1], rec_b[1])\n y_start = max(rec_a[2], rec_b[2])\n y_end = min(rec_a[3], rec_b[3])\n\n if x_start > x_end or y_start > y_end:\n return False, [0, 0, 0, 0]\n else:\n return True, [x_start, x_end, y_start, y_end]\n\ndef get_art(path):\n '''\n reads the art text file and returns an np array\n '''\n\n path = os.path.join(conf.ART_BASE_PATH, path)\n arr = []\n try:\n with open(path, 'r') as f:\n for line in f:\n arr.append(list(line.strip('\\n')))\n except FileNotFoundError as e:\n return None\n\n return np.array(arr, dtype='object')\n\ndef make_coin_group(game_height, game_width, x=0, y=0, h=1, w=1):\n '''\n makes a group of coins of the specified size and at that position, appends to list\n coins do not place themselves, so need to be externally placed\n keep them in groups so as to not clutter the screen\n '''\n \n coins = []\n for i in range(h):\n drawing = False\n for j in range(w):\n if not drawing:\n if random.random() < 0.65:\n drawing = True\n if drawing:\n coins.append(obstacle.Coin(game_height, game_width, x + i, y + j))\n if random.random() < 0.3:\n drawing = False\n break\n \n return coins\n\ndef vector_decompose(mag, start, end):\n '''\n decomposes a vector of magnitude mag along direction start to end and returns its 2D components\n '''\n\n if type(start) != np.ndarray or type(end) != np.ndarray:\n raise ValueError\n\n x_cap = abs(start[0] - end[0])\n y_cap = abs(start[1] - end[1])\n\n theta = math.atan2(x_cap, y_cap)\n x_force = abs(mag * math.sin(theta))\n y_force = abs(mag * math.cos(theta))\n\n if end[0] < start[0]:\n x_force = -x_force\n\n if end[1] < start[1]:\n y_force = -y_force\n\n return [x_force, y_force]\n\ndef get_bar(length, left, total):\n '''\n generates a loading bar and returns a string representation\n '''\n \n if left >= total:\n return Style.BRIGHT + Back.RED + (' ' * length)\n if left <= 0:\n return Style.BRIGHT + Back.GREEN + (' ' * length)\n perc = int(round((left / total) * length))\n s = Style.BRIGHT + Back.RED + (' ' * perc)\n s += Back.GREEN + (' ' * (length - perc))\n return s\n" ]
[ [ "numpy.array" ] ]
johnjasa/CADRE
[ "a4ffd61582b8474953fc309aa540838a14f29dcf" ]
[ "CADRE/rw_dymos/rw_dynamics.py" ]
[ "\"\"\"\nReaction Wheel discipline for CADRE: Reaction Wheel Dynamics component.\n\"\"\"\nfrom __future__ import print_function, division, absolute_import\nfrom six.moves import range\n\nimport numpy as np\n\nfrom openmdao.api import ExplicitComponent\n\n\nclass ReactionWheelDynamics(ExplicitComponent):\n \"\"\"\n Compute the angular velocity vector of reaction wheel.\n \"\"\"\n\n def initialize(self):\n self.options.declare('num_nodes', types=(int, ),\n desc=\"Number of time points.\")\n self.options.declare('J_RW', 2.8e-5,\n desc=\"Mass moment of inertia of the reaction wheel.\")\n\n def setup(self):\n nn = self.options['num_nodes']\n J_RW = self.options['J_RW']\n\n # Inputs\n self.add_input('w_B', np.zeros((nn, 3)), units='1/s',\n desc='Angular velocity vector in body-fixed frame over time')\n\n self.add_input('T_RW', np.zeros((nn, 3)), units='N*m',\n desc='Torque vector of reaction wheel over time')\n\n self.add_input('w_RW', np.zeros((nn, 3)), units='1/s',\n desc='Angular velocity vector of reaction wheel over time')\n\n # Outputs\n self.add_output('dXdt:w_RW', np.zeros((nn, 3)), units='1/s**2',\n desc='Rate of change of reaction wheel angular velocity vector over time')\n\n #self.options['state_var'] = 'w_RW'\n #self.options['init_state_var'] = 'w_RW0'\n #self.options['external_vars'] = ['w_B', 'T_RW']\n\n ar = np.arange(3*nn)\n\n self.declare_partials(of='dXdt:w_RW', wrt='T_RW', rows=ar, cols=ar, val=-1.0/J_RW)\n\n # Sparsity pattern across a cross product.\n row = np.array([2, 0, 1])\n col = np.array([1, 2, 0])\n row1 = np.tile(row, nn) + np.repeat(3*np.arange(nn), 3)\n col1 = np.tile(col, nn) + np.repeat(3*np.arange(nn), 3)\n\n row = np.array([1, 2, 0])\n col = np.array([2, 0, 1])\n row2 = np.tile(row, nn) + np.repeat(3*np.arange(nn), 3)\n col2 = np.tile(col, nn) + np.repeat(3*np.arange(nn), 3)\n\n rows = np.concatenate([row1, row2])\n cols = np.concatenate([col1, col2])\n\n self.declare_partials(of='dXdt:w_RW', wrt='w_B', rows=rows, cols=cols)\n self.declare_partials(of='dXdt:w_RW', wrt='w_RW', rows=rows, cols=cols)\n\n def compute(self, inputs, outputs):\n nn = self.options['num_nodes']\n J_RW = self.options['J_RW']\n\n w_B = inputs['w_B']\n T_RW = inputs['T_RW']\n state = inputs['w_RW']\n\n jy = np.zeros((nn, 3, 3))\n jy[:, 0, 1] = -w_B[:, 2]\n jy[:, 0, 2] = w_B[:, 1]\n jy[:, 1, 0] = w_B[:, 2]\n jy[:, 1, 2] = -w_B[:, 0]\n jy[:, 2, 0] = -w_B[:, 1]\n jy[:, 2, 1] = w_B[:, 0]\n\n outputs['dXdt:w_RW'] = -T_RW / J_RW - np.einsum(\"ijk,ik->ij\", jy, state)\n\n def compute_partials(self, inputs, partials):\n \"\"\"\n Calculate and save derivatives. (i.e., Jacobian)\n \"\"\"\n nn = self.options['num_nodes']\n J_RW = self.options['J_RW']\n\n w_B = inputs['w_B']\n state = inputs['w_RW']\n\n d_wRW = w_B.flatten()\n partials['dXdt:w_RW', 'w_RW'][:3*nn] = -d_wRW\n partials['dXdt:w_RW', 'w_RW'][3*nn:] = d_wRW\n\n d_wB = state.flatten()\n partials['dXdt:w_RW', 'w_B'][:3*nn] = d_wB\n partials['dXdt:w_RW', 'w_B'][3*nn:] = -d_wB\n" ]
[ [ "numpy.einsum", "numpy.arange", "numpy.tile", "numpy.concatenate", "numpy.array", "numpy.zeros" ] ]
robotenique/advancedProgramming
[ "d5472ffe5bc8f99be55b873a3637266d373d76dc" ]
[ "numeric-methods/splines.py" ]
[ "# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib as mpl\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport functools\n\n###############################################################################\n#\n# spline = a cubic b spline with equally spaced nodes\n#\n###############################################################################\n\nclass spline:\n\n# spline with support in [x_min,x_max] and n >= 10 weights,\n# which correspond to n - 3 intervals\n\n def __init__(self, weights, x_min = 0, x_max = 1):\n assert x_max > x_min, 'x_max must be greater than x_min'\n assert type(weights) == np.ndarray, 'weight must be a numpy array'\n assert len(weights) >= 10, 'there must be at least 10 weights'\n dx = x_max - x_min\n self.n = len(weights) - 3\n self.scale = self.n/dx\n self.x_min = x_min\n self.x_max = x_max\n self.weights = weights\n\n def locate(self, t):\n if t <= self.x_min:\n return [0.0, 0]\n\n if t >= self.x_max:\n return [1.0, self.n - 1]\n\n dt = self.scale * (t - self.x_min)\n\n if dt >= self.n:\n dt = 1.0\n return [1.0, self.n - 1]\n\n bin = int(np.floor(dt))\n dt -= bin\n return [dt,bin]\n\n\n def piece_0_0(self, x):\n return 240 - x * (720 - x * (720 - x * 240))\n\n def piece_1_0(self, x):\n return x * (720 - x * (1080 - x * 420))\n\n def piece_1_1(self,x):\n return 60 - x * (180 - x * (180 - x * 60))\n\n def piece_2_0(self,x):\n return x * x * (360 - 220 * x)\n\n def piece_2_1(self,x):\n return 140 + x * (60 - x * (300 - x * 140))\n\n def piece_2_2(self,x):\n return 40 - x * (120 - x * (120 - x * 40))\n\n def piece_3_0(self,x):\n return 40 * x * x * x\n\n def piece_3_1(self,x):\n return 40 + x * (120 + x * (120 - x * 120))\n\n def piece_3_2(self,x):\n return 160 - x * x * (240 - x * 120)\n\n def piece_3_3(self,x):\n return 40 - x * (120 - x * (120 - x * 40))\n\n def piece_4_1(self,x):\n return 40 * x * x * x\n\n def piece_4_2(self,x):\n return 40 + x * (120 + x * (120 - x * 140))\n\n def piece_4_3(self,x):\n return 140 - x * (60 + x * (300 - x * 220))\n\n def piece_5_2(self,x):\n return 60 * x * x * x\n\n def piece_5_3(self,x):\n return 60 + x * (180 + x * (180 - x * 420))\n\n def piece_6_3(self,x):\n return 240 * x * x * x\n\n def eval(self,x):\n dt, bin = self.locate(x)\n if bin <= 2:\n if bin <= 0:\n a = self.piece_0_0(dt) * self.weights[0] + self.piece_1_0(dt) * self.weights[1]\n return a + self.piece_2_0(dt) * self.weights[2] + self.piece_3_0(dt) * self.weights[3]\n#\n if bin == 1:\n a = self.piece_1_1(dt) * self.weights[1] + self.piece_2_1(dt) * self.weights[2]\n return a + self.piece_3_1(dt) * self.weights[3] + self.piece_3_0(dt) * self.weights[4]\n else: # bin = 2\n a = self.piece_2_2(dt) * self.weights[2] + self.piece_3_2(dt) * self.weights[3]\n return a + self.piece_3_1(dt) * self.weights[4] + self.piece_3_0(dt) * self.weights[5]\n\n # now bin > 2\n nw = len(self.weights)\n if bin >= nw - 6:\n if bin == nw - 6:\n a = self.piece_3_3(dt) * self.weights[bin] + self.piece_3_2(dt) * self.weights[bin + 1]\n return a + self.piece_3_1(dt) * self.weights[bin + 2] + self.piece_4_1(dt) * self.weights[bin + 3]\n\n if bin == nw - 5:\n a = self.piece_3_3(dt) * self.weights[bin] + self.piece_3_2(dt) * self.weights[bin + 1]\n return a + self.piece_4_2(dt) * self.weights[bin + 2] + self.piece_5_2(dt) * self.weights[bin + 3]\n\n # now bin = nw - 4\n a = self.piece_3_3(dt) * self.weights[bin] + self.piece_4_3(dt) * self.weights[bin + 1]\n return a + self.piece_5_3(dt) * self.weights[bin + 2] + self.piece_6_3(dt) * self.weights[bin + 3]\n\n # finally, the normal case 3 <= bin < nw - 6\n a = self.piece_3_3(dt) * self.weights[bin] + self.piece_3_2(dt) * self.weights[bin + 1]\n return a + self.piece_3_1(dt) * self.weights[bin + 2] + self.piece_3_0(dt) * self.weights[bin + 3]\n\n def eval_beta_j(self, j, x):\n\n dt, bin = self.locate(x)\n\n if ((j < bin) or (j > bin + 3)):\n return 0\n\n if bin <= 2:\n if bin <= 0:\n if j < 2:\n if j == 1:\n return self.piece_1_0(dt)\n else:\n return self.piece_0_0(dt)\n else:\n if j == 2:\n return self.piece_2_0(dt)\n else:\n return self.piece_3_0(dt)\n#\n if bin == 1:\n if j < 3:\n if j == 1:\n return self.piece_1_1(dt)\n else:\n return self.piece_2_1(dt)\n else:\n if j == 3:\n return self.piece_3_1(dt)\n else:\n return self.piece_3_0(dt)\n else: # bin = 2\n if (j < 4):\n if (j == 2):\n return self.piece_2_2(dt)\n else:\n return self.piece_3_2(dt)\n else:\n if (j == 4):\n return self.piece_3_1(dt)\n else:\n return self.piece_3_0(dt)\n\n # now bin > 2\n nw = len(self.weights)\n if bin >= nw - 6:\n if bin == nw - 6:\n if j < bin + 2:\n if j == bin:\n return self.piece_3_3(dt)\n else:\n return self.piece_3_2(dt)\n else:\n if j == bin + 2:\n return self.piece_3_1(dt)\n else:\n return self.piece_4_1(dt)\n\n if bin == nw - 5:\n if j < bin + 2:\n if j == bin:\n return self.piece_3_3(dt)\n else:\n return self.piece_3_2(dt)\n else:\n if j == bin + 2:\n return self.piece_4_2(dt)\n else:\n return self.piece_5_2(dt)\n\n # now bin = nw - 4\n if j < bin + 2:\n if j == bin:\n return self.piece_3_3(dt)\n else:\n return self.piece_4_3(dt)\n else:\n if j == bin + 2:\n return self.piece_5_3(dt)\n else:\n return self.piece_6_3(dt)\n\n # finally, the normal case 3 <= bin < nw - 6\n\n if j < bin + 2:\n if j == bin:\n return self.piece_3_3(dt)\n else:\n return self.piece_3_2(dt)\n else:\n if j == bin + 2:\n return self.piece_3_1(dt)\n else:\n return self.piece_3_0(dt)\n\n def beta_j(self, j, x):\n if type(x) == np.ndarray:\n y = x.copy()\n for i in range(len(x)):\n y[i] = self.eval_beta_j(j,x[i])\n return y\n else:\n return self.eval_beta_j(j,x)\n\n\n def __call__(self, x):\n if type(x) == np.ndarray:\n y = x.copy()\n for i in range(len(x)):\n y[i] = self.eval(x[i])\n return y\n else:\n return self.eval(x)\n\n###############################################################################\n#\n# d_spline = the derivative of the previous spline\n#\n###############################################################################\n\nclass d_spline:\n\n# the derivative of an spline with support in [x_min,x_max] and n >= 10 intervals\n# which correspond to n -3 intervals\n\n def __init__(self, weights, x_min = 0, x_max = 1):\n assert x_max > x_min, 'x_max must be greater than x_min'\n assert type(weights) == np.ndarray, 'weight must be a numpy array'\n assert len(weights) >= 10, 'there must be at least 10 weights'\n dx = x_max - x_min\n self.n = len(weights) - 3\n self.scale = self.n/dx\n self.x_min = x_min\n self.x_max = x_max\n self.weights = weights\n\n def locate(self, t):\n if t <= self.x_min:\n return [0.0, 0]\n\n if t >= self.x_max:\n return [1.0, self.n - 1]\n\n dt = self.scale * (t - self.x_min)\n\n if dt >= self.n:\n dt = 1.0\n return [1.0, self.n - 1]\n\n bin = int(np.floor(dt))\n dt -= bin\n return [dt,bin]\n\n def piece_0_0(self, x):\n return -720 + x * (1440 - x * 720)\n\n def piece_1_0(self, x):\n return 720 - x * (2160 - x * 1260)\n\n def piece_1_1(self,x):\n return (-180 + x * (360 - x * 180))\n\n def piece_2_0(self,x):\n return x * (720 - 660 * x)\n\n def piece_2_1(self,x):\n return 60 - x * (600 - x * 420)\n\n def piece_2_2(self,x):\n return -120 + x * (240 - x * 120)\n\n def piece_3_0(self,x):\n return 120 * x * x;\n\n def piece_3_1(self,x):\n return 120 + x * (240 - x * 360)\n\n def piece_3_2(self,x):\n return x * (-480 + x * 360)\n\n def piece_3_3(self,x):\n return -120 + x * (240 - x * 120)\n\n def piece_4_1(self,x):\n return 120 * x * x\n\n def piece_4_2(self,x):\n return 120 + x * (240 - x * 420)\n\n def piece_4_3(self,x):\n return -60 - x * (600 - x * 660)\n\n def piece_5_2(self,x):\n return 180 * x * x\n\n def piece_5_3(self,x):\n return 180 + x * (360 - x * 1260)\n\n def piece_6_3(self,x):\n return 720 * x * x;\n\n def eval(self,x):\n dt, bin = self.locate(x)\n if bin <= 2:\n if bin <= 0:\n a = self.piece_0_0(dt) * self.weights[0] + self.piece_1_0(dt) * self.weights[1]\n return a + self.piece_2_0(dt) * self.weights[2] + self.piece_3_0(dt) * self.weights[3]\n#\n if bin == 1:\n a = self.piece_1_1(dt) * self.weights[1] + self.piece_2_1(dt) * self.weights[2]\n return a + self.piece_3_1(dt) * self.weights[3] + self.piece_3_0(dt) * self.weights[4]\n else: # bin = 2\n a = self.piece_2_2(dt) * self.weights[2] + self.piece_3_2(dt) * self.weights[3]\n return a + self.piece_3_1(dt) * self.weights[4] + self.piece_3_0(dt) * self.weights[5]\n\n # now bin > 2\n nw = len(self.weights)\n if bin >= nw - 6:\n if bin == nw - 6:\n a = self.piece_3_3(dt) * self.weights[bin] + self.piece_3_2(dt) * self.weights[bin + 1]\n return a + self.piece_3_1(dt) * self.weights[bin + 2] + self.piece_4_1(dt) * self.weights[bin + 3]\n\n if bin == nw - 5:\n a = self.piece_3_3(dt) * self.weights[bin] + self.piece_3_2(dt) * self.weights[bin + 1]\n return a + self.piece_4_2(dt) * self.weights[bin + 2] + self.piece_5_2(dt) * self.weights[bin + 3]\n\n # now bin = nw - 4\n a = self.piece_3_3(dt) * self.weights[bin] + self.piece_4_3(dt) * self.weights[bin + 1]\n return a + self.piece_5_3(dt) * self.weights[bin + 2] + self.piece_6_3(dt) * self.weights[bin + 3]\n\n # finally, the normal case 3 < bin < nw - 6\n a = self.piece_3_3(dt) * self.weights[bin] + self.piece_3_2(dt) * self.weights[bin + 1]\n return a + self.piece_3_1(dt) * self.weights[bin + 2] + self.piece_3_0(dt) * self.weights[bin + 3]\n\n def __call__(self, x):\n if type(x) == np.ndarray:\n y = x.copy()\n for i in range(len(x)):\n y[i] = self.eval(x[i])\n return y\n else:\n return self.eval(x)\n\n###############################################################################\n#\n# d2_spline = the second derivative of the previous spline\n#\n###############################################################################\n\nclass d2_spline:\n\n# the derivative of an spline with support in [x_min,x_max] and n >= 10 weights,\n# which correspond to n - 3 intervals\n\n def __init__(self, weights, x_min = 0, x_max = 1):\n assert x_max > x_min, 'x_max must be greater than x_min'\n assert type(weights) == np.ndarray, 'weight must be a numpy array'\n assert len(weights) >= 10, 'there must be at least 10 weights'\n dx = x_max - x_min\n self.n = len(weights) - 3\n self.scale = self.n/dx\n self.x_min = x_min\n self.x_max = x_max\n self.weights = weights\n\n def locate(self, t):\n if t <= self.x_min:\n return [0.0, 0]\n\n if t >= self.x_max:\n return [1.0, self.n - 1]\n\n dt = self.scale * (t - self.x_min)\n\n if dt >= self.n:\n dt = 1.0\n return [1.0, self.n - 1]\n\n bin = int(np.floor(dt))\n dt -= bin\n return [dt,bin]\n\n def piece_0_0(self, x):\n return 1440 - x * 1440\n\n def piece_1_0(self, x):\n return -2160 + x * 2520\n\n def piece_1_1(self,x):\n return 360 - x * 360\n\n def piece_2_0(self,x):\n return 720 - x * 1320\n\n def piece_2_1(self,x):\n return -600 + x * 840\n\n def piece_2_2(self,x):\n return 240 - x * 240\n\n def piece_3_0(self,x):\n return 240 * x\n\n def piece_3_1(self,x):\n return 240 - x * 720\n\n def piece_3_2(self,x):\n return -480 + x * 720\n\n def piece_3_3(self,x):\n return 240 - x * 240\n\n def piece_4_1(self,x):\n return 240 * x\n\n def piece_4_2(self,x):\n return 240 - x * 840\n\n def piece_4_3(self,x):\n return -600 + x * 1320\n\n def piece_5_2(self,x):\n return 360 * x\n\n def piece_5_3(self,x):\n return 360 - x * 2520\n\n def piece_6_3(self,x):\n return 1440 * x\n\n def eval(self,x):\n dt, bin = self.locate(x)\n if bin <= 2:\n if bin <= 0:\n a = self.piece_0_0(dt) * self.weights[0] + self.piece_1_0(dt) * self.weights[1]\n return a + self.piece_2_0(dt) * self.weights[2] + self.piece_3_0(dt) * self.weights[3]\n\n if bin == 1:\n a = self.piece_1_1(dt) * self.weights[1] + self.piece_2_1(dt) * self.weights[2]\n return a + self.piece_3_1(dt) * self.weights[3] + self.piece_3_0(dt) * self.weights[4]\n else: # bin = 2\n a = self.piece_2_2(dt) * self.weights[2] + self.piece_3_2(dt) * self.weights[3]\n return a + self.piece_3_1(dt) * self.weights[4] + self.piece_3_0(dt) * self.weights[5]\n\n # now bin > 2\n nw = len(self.weights)\n if bin >= nw - 6:\n if bin == nw - 6:\n a = self.piece_3_3(dt) * self.weights[bin] + self.piece_3_2(dt) * self.weights[bin + 1]\n return a + self.piece_3_1(dt) * self.weights[bin + 2] + self.piece_4_1(dt) * self.weights[bin + 3]\n\n if bin == nw - 5:\n a = self.piece_3_3(dt) * self.weights[bin] + self.piece_3_2(dt) * self.weights[bin + 1]\n return a + self.piece_4_2(dt) * self.weights[bin + 2] + self.piece_5_2(dt) * self.weights[bin + 3]\n\n # now bin = nw - 4\n a = self.piece_3_3(dt) * self.weights[bin] + self.piece_4_3(dt) * self.weights[bin + 1]\n return a + self.piece_5_3(dt) * self.weights[bin + 2] + self.piece_6_3(dt) * self.weights[bin + 3]\n\n # finally, the normal case 3 < bin < nw - 6\n a = self.piece_3_3(dt) * self.weights[bin] + self.piece_3_2(dt) * self.weights[bin + 1]\n return a + self.piece_3_1(dt) * self.weights[bin + 2] + self.piece_3_0(dt) * self.weights[bin + 3]\n\n def eval_beta_j(self, j, x):\n\n dt, bin = self.locate(x)\n\n if ((j < bin) or (j > bin + 3)):\n return 0\n\n if bin <= 2:\n if bin <= 0:\n if j < 2:\n if j == 1:\n return self.piece_1_0(dt)\n else:\n return self.piece_0_0(dt)\n else:\n if j == 2:\n return self.piece_2_0(dt)\n else:\n return self.piece_3_0(dt)\n#\n if bin == 1:\n if j < 3:\n if j == 1:\n return self.piece_1_1(dt)\n else:\n return self.piece_2_1(dt)\n else:\n if j == 3:\n return self.piece_3_1(dt)\n else:\n return self.piece_3_0(dt)\n else: # bin = 2\n if (j < 4):\n if (j == 2):\n return self.piece_2_2(dt)\n else:\n return self.piece_3_2(dt)\n else:\n if (j == 4):\n return self.piece_3_1(dt)\n else:\n return self.piece_3_0(dt)\n\n # now bin > 2\n nw = len(self.weights)\n if bin >= nw - 6:\n if bin == nw - 6:\n if j < bin + 2:\n if j == bin:\n return self.piece_3_3(dt)\n else:\n return self.piece_3_2(dt)\n else:\n if j == bin + 2:\n return self.piece_3_1(dt)\n else:\n return self.piece_4_1(dt)\n\n if bin == nw - 5:\n if j < bin + 2:\n if j == bin:\n return self.piece_3_3(dt)\n else:\n return self.piece_3_2(dt)\n else:\n if j == bin + 2:\n return self.piece_4_2(dt)\n else:\n return self.piece_5_2(dt)\n\n # now bin = nw - 4\n if j < bin + 2:\n if j == bin:\n return self.piece_3_3(dt)\n else:\n return self.piece_4_3(dt)\n else:\n if j == bin + 2:\n return self.piece_5_3(dt)\n else:\n return self.piece_6_3(dt)\n\n # finally, the normal case 3 <= bin < nw - 6\n\n if j < bin + 2:\n if j == bin:\n return self.piece_3_3(dt)\n else:\n return self.piece_3_2(dt)\n else:\n if j == bin + 2:\n return self.piece_3_1(dt)\n else:\n return self.piece_3_0(dt)\n\n def beta_j(self, j, x):\n if type(x) == np.ndarray:\n y = x.copy()\n for i in range(len(x)):\n y[i] = self.eval_beta_j(j,x[i])\n return y\n else:\n return self.eval_beta_j(j,x)\n\n\n def __call__(self, x):\n if type(x) == np.ndarray:\n y = x.copy()\n for i in range(len(x)):\n y[i] = self.eval(x[i])\n return y\n else:\n return self.eval(x)\n\n# use '%matplotlib qt' for plotting on external window\n\n#plotting a 3d curve\n\ndef curve(t, spx, spy, spz):\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n ax.plot(spx(t), spy(t), spz(t))\n ax.legend()\n plt.show()\n\n# Computing the matrix m2 = integral of the square of the second derivative\n# The function we are integrating is quadratic, and Simpson's rule is\n# exact in this case\n\ndef simpson_fg(f, g, a, b, n):\n assert n % 2 == 0, 'the number of points must be even'\n\n h = (b - a) / n\n s = f(a) * g(a) + f(b) * g(b)\n\n for i in range(1, n, 2):\n fi = f(a + i * h)\n gi = g(a + i * h)\n s += 4 * fi * gi\n\n for i in range(2, n-1, 2):\n fi = f(a + i * h)\n gi = g(a + i * h)\n s += 2 * fi * gi\n\n return s * h / 3\n\n# n is the number of weights, and the spline is sum_(i = 0)^(n-1) aj beta_j\n\ndef matrix_m2(n):\n na = 12\n w = np.random.rand(na)\n d2s = d2_spline(w, 0, na - 3)\n a = np.zeros(shape=(na,na))\n i = 0\n while i < na:\n j = i\n bind_i = lambda z : d2s.beta_j(i,z)\n while (j < i + 4) and (j < na):\n bind_j = lambda z : d2s.beta_j(j,z)\n a[i,j] = simpson_fg(bind_i, bind_j, 0, na - 3, 2 * (na - 3))\n a[j,i] = a[i,j]\n j = j + 1\n i = i + 1\n\n b = np.zeros(shape=(n,n))\n i = 0\n while i < 6:\n j = 0\n while j < i + 4:\n b[i,j] = a[i,j]\n b[j,i] = b[i,j]\n j = j + 1\n i = i + 1\n\n while i < n - 6:\n k = -3\n while k < 4:\n b[i,i + k] = a[6,6 + k]\n b[i + k,i] = b[i,i + k]\n k = k + 1\n i = i + 1\n\n while i < n:\n k = - 3\n while k < n - i:\n b[i,i + k] = a[12 + (i - n), 12 + (i - n) + k]\n b[i + k,i] = b[i,i + k]\n k = k + 1\n i = i + 1\n\n #checking\n\n i = 0\n while i < n:\n j = 0\n while j < n:\n error = abs(b[i,j] - b[n - 1 - i, n - 1-j])\n assert error < 1.0e-5, 'bug....' + str(i) + ',' + str(j)\n j = j + 1\n i = i + 1\n\n\n return 1.0e-5 * b\n\n\n\"\"\"\nSome fixed data:\nweights =[0.43470768679675065, 0.70234026438735053, 0.06557777761086947, 0.1600460261762634, 0.54135062262335298, 0.050856016107522328, 0.17473709130199, 0.74161650357776676, 0.45860648789704928, 0.14159481604757318, 0.84721980315075984, 0.086969974586579846, 0.10755203343042352, 0.7009617941803733, 0.62476516555503137, 0.84680596019512555]\n\nerr = [4.0407246040420395, 17.923076414120604, -10.767841085140835, 4.1393430179930775, 10.565085709868121, -3.584372809095576, -11.774566767372946, 17.257106170388049, 2.6757461616453817, -10.527234880136081, 8.9848685270152622, -6.6169058175221496, -3.7332405500642714, -13.02819409732825, 22.750078462351926, -4.2842739152321094, 14.96757783200326, -2.4553840583728324, 18.861396668965529, -6.738813066862412, -8.4186285044590647, 7.4745396854916644, -13.559257482658458, -7.0204800255297615, 10.190792445314555, -17.823240291866707, 6.8026629126934148, 28.076870129591931, 9.1254265942523141, -11.364608723643313, 11.130477983696728, -14.425502355253265, -5.806975177393717, 2.6439377596784928, 5.9834056423728752, -44.09287902866226, 3.2457202857835865, 8.9932719431376658, -16.281282503217362, -18.738001438454987, -26.660671082997442, -8.6756844257800267, -11.304234163552247, -4.7872864657413361, 3.4258073451241695, -16.146674499028919, 9.0544681137787215, 24.848650542341094, 17.249853581359027, -0.30283797800742379, 0.37855493839974697, 4.4639944302046128, 20.225936254776382, 7.2556634177390036, 9.7897475601732431, -5.113334423387788, 7.0289069745437285, 24.19659714478404, -15.070958575128437, -11.974895353808336, -7.9217580071927234, 23.293920381732761, -6.7173190176511053, 2.1251620231213275, 3.9208470023037778, -9.2048186380279429, -12.031589993324703, 15.441730221060265, 14.197219907797001, -1.5403968817083806, 2.2266240309869718, 9.8391447338750222, -8.7659657931732315, 4.7198740432965476, -7.6448678383435258, 8.2774563718206426, 14.215887214498119, -5.8908381646577146, 6.6490880175057407, 5.4571918097483625, -9.7642109675504702, 8.7614178777467249, 7.660913381188883, -12.562982700498488, 5.5425282272514256, 20.084548902645526, -2.1418877013537481, 20.792510705733893, 26.207094680784824, -6.5188612054901851, -20.379346648258174, -34.356217384323699, 13.522426602406133, 24.637814902341464, 4.3255971858103592, -12.096729849949023, 14.903784302042354, -8.9308771583215361, 5.1727237461466506, 4.2302726340482]\n\ncalculated = [0.46215165101240407, 0.72451809655289978, 0.034505942139361853, 0.20103394093477878, 0.50756752382645198, 0.10693555052448254, 0.052481669158447326, 0.78396137171634217,\n 0.50607678792654842, 0.11057751400915164, 0.88526496637460661, 0.067658833366388976, 0.16218838312986433, 0.66793335862573522, 0.65314875153266527, 0.85473860433433557]\n\n\"\"\"\n\n\ndef ep_labnum(t, x_t, num_splines):\n default_spl = spline(np.ones(num_splines), x_min=t[0], x_max=t[-1])\n mu = np.zeros((len(t), num_splines))\n for i in range(len(t)):\n for j in range(num_splines):\n mu[i][j] = default_spl.beta_j(j, t[i])\n lmbda = 5\n m_1 = mu.T@mu\n b = mu.T@x_t.T\n m_2 = matrix_m2(num_splines)\n M = m_1 + lmbda*m_2\n res = np.linalg.solve(M, b)\n return res\n\ndef get_points(m_data, n_splines, x_min=0, x_max=1):\n t = np.linspace(x_min, x_max, m_data)\n weights = np.random.rand(n_splines)\n weights = np.array(weights)\n spl = spline(weights, x_min=t[0], x_max=t[-1])\n spl_t = spl(t)\n mu, sigma = 0, np.std(spl_t) / 3\n err = np.random.normal(mu, sigma, m_data)\n err = np.array(err)\n x_t = spl_t + err\n return t, x_t, spl_t\n\n\ndef main():\n # Testing the get points\n num_splines = 1600\n num_dados = 10001\n t, x_t, spl_t = get_points(num_dados, num_splines, 0, 10)\n t = np.linspace(0, 5, num_dados)\n x_t = np.sin(1/t)\n if len(t) < 1000:\n plt.scatter(t, x_t, label=\"Simulated with noise\", color=np.random.rand(3,))\n #plt.plot(t, spl_t, label=\"Original data\")\n plt.plot(t, x_t, label=\"Original data\")\n plt.xlabel(\"t\")\n plt.ylabel(\"spl(t)\")\n plt.title(\"Dados\")\n default_spl = spline(np.ones(num_splines), x_min=t[0], x_max=t[-1])\n mu = np.zeros((len(t), num_splines))\n for i in range(len(t)):\n for j in range(num_splines):\n mu[i][j] = default_spl.beta_j(j, t[i])\n print(mu)\n lmbda = 20\n m_1 = mu.T@mu\n b = mu.T@x_t.T\n m_2 = matrix_m2(num_splines)\n M = m_1 + lmbda*m_2\n res = np.linalg.solve(M, b)\n new_spline = spline(res, x_min=t[0], x_max=t[-1])\n plt.plot(t, new_spline(t), label=\"Simulated data\")\n plt.legend(loc=\"upper right\")\n plt.show()\n\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.linalg.solve", "numpy.linspace", "matplotlib.pyplot.title", "numpy.sin", "matplotlib.pyplot.plot", "numpy.ones", "numpy.random.normal", "matplotlib.pyplot.ylabel", "numpy.std", "numpy.random.rand", "numpy.floor", "matplotlib.pyplot.xlabel", "numpy.array", "matplotlib.pyplot.show", "numpy.zeros", "matplotlib.pyplot.figure" ] ]
jaentrouble/reinforcement
[ "3557b37d83e380e1a711876320ad5247157957f3" ]
[ "grid_1d.py" ]
[ "from constants import *\nimport numpy as np\nimport tool\nimport math\nimport random\n\nclass Grid() :\n def __init__ (self, width, height, snakelength : int, rand = True, trap = 0) :\n \"\"\"\n Grid\n snakelength : initial snake length\n \"\"\"\n self.width = width\n self.height = height\n self.grid = np.full((width,height), G_EMPTY)\n self.answer_buffer = None\n self.answer_buffer_filled = False\n self.rand = rand\n self.trap_num = trap\n self.snakelength = snakelength\n if self.rand : \n self.snake = Snake(*tool.randposlist(self.snakelength, self.width, self.height))\n else :\n self.s_init = tool.randposlist(self.snakelength, self.width, self.height)\n # self.s_init = [[self.width-3,self.height-3]]\n self.snake = Snake(*self.s_init)\n for pos in self.snake.get_list() :\n self.grid[pos[0]][pos[1]] = G_SNAKE\n self.apples = []\n self.traps = []\n self.t_init = []\n # self.create_apple()\n self.a_init = [1,1]\n self.create_apple(self.a_init)\n for _ in range(self.trap_num) :\n self.create_trap()\n self.control_choice = 3\n self.info = self.get_state().shape\n\n def action_size(self) :\n return self.control_choice\n\n def state_size(self) :\n return self.info\n\n def create_trap(self, pos = None) :\n if pos == None :\n tmpos = tool.randpos(0, self.width-1, 0, self.height-1)\n while self.grid[tmpos[0]][tmpos[1]] != G_EMPTY :\n tmpos = tool.randpos(0, self.width-1, 0, self.height-1)\n if not self.rand :\n self.t_init.append(tmpos)\n else :\n tmpos = pos\n self.traps.append(tmpos)\n self.grid[tmpos[0]][tmpos[1]] = G_TRAP\n\n def create_apple(self, pos = None) :\n if pos == None :\n tmpos = tool.randpos(0, self.width-1, 0, self.height-1)\n while self.grid[tmpos[0]][tmpos[1]] != G_EMPTY :\n tmpos = tool.randpos(0, self.width-1, 0, self.height-1)\n # if not self.rand :\n # self.a_init = tmpos\n else :\n tmpos = pos\n self.apples.append(tmpos)\n self.grid[tmpos[0]][tmpos[1]] = G_APPLE\n\n def get_obj (self) :\n \"\"\"\n returns\n {type(object) : list of pos}\n \"\"\"\n d = {}\n d[G_SNAKE] = self.snake.get_list()\n d[G_APPLE] = self.apples\n d[G_TRAP] = self.traps\n return d\n\n def snake_health (self) :\n return self.snake.get_health()\n\n def snake_head(self) :\n return self.snake.get_head()\n\n def apple(self) :\n \"\"\"\n returns the first apple's pos\n \"\"\"\n return self.apples[0]\n \n def reward(self, move_direction) :\n \"\"\"\n gets action (direction to move)\n returns reward, done\n done : bool\n \"\"\"\n self.grid_buffer = self.grid.copy()\n trgt = self.snake_head()\n tail = self.snake.get_tail()\n bef = trgt.copy()\n app = self.apple()\n state = None\n direction, _ = self.snake.move(move_direction)\n\n trgt[0] += DIRECTION_LIST[direction][0]\n trgt[1] += DIRECTION_LIST[direction][1]\n\n if (trgt[0] > self.width-1 or\n trgt[0] < 0 or\n trgt[1] > self.height-1 or\n trgt[1] < 0) :\n \n return Reward_dead, True\n else :\n aft = trgt.copy()\n\n if self.grid[trgt[0]][trgt[1]] == G_EMPTY :\n self.grid[tail[0]][tail[1]] = G_EMPTY\n self.grid[trgt[0]][trgt[1]] = G_SNAKE\n state = MOVED\n elif self.grid[trgt[0]][trgt[1]] in (G_SNAKE, G_TRAP) :\n state = DEAD\n elif self.grid[trgt[0]][trgt[1]] == G_APPLE :\n # if self.rand :\n self.apples.remove(trgt)\n self.grid[trgt[0]][trgt[1]] = G_SNAKE\n self.create_apple()\n self.snake.eat_apple()\n state = GROW\n \n if self.snake.get_health() < 0 :\n starve = True\n else :\n starve = False\n\n if state == DEAD :\n return Reward_dead, True\n elif state == MOVED :\n befdist = abs(bef[0]-app[0]) + abs(bef[1]-app[1])\n aftdist = abs(aft[0]-app[0]) + abs(aft[1]-app[1])\n tmp = befdist - aftdist\n if tmp < 0 :\n return Reward_movement_far, starve\n else :\n return Reward_movement_close, starve\n elif state == GROW :\n return Reward_grow, False\n\n def get_state(self) :\n r, l, u, d = 0, 0, 0, 0\n ru, lu, ld, rd = 0, 0, 0, 0\n head = self.snake_head()\n direction = self.snake.get_direction()\n x = head[0]\n y = head[1]\n for column in self.grid[x+1: ] :\n if column[y] in (G_SNAKE, G_TRAP) :\n break\n else :\n r += 1\n for column in reversed(self.grid[:x]) :\n if column[y] in (G_SNAKE, G_TRAP) :\n break\n else :\n l += 1\n for row in self.grid[x][y+1:] :\n if row in (G_SNAKE, G_TRAP) :\n break\n else :\n d += 1\n for row in reversed(self.grid[x][:y]) :\n if row in (G_SNAKE, G_TRAP) :\n break\n else :\n u += 1\n for delta in range(1, min(self.width-x, y+1)):\n if self.grid[x+delta, y-delta] in (G_SNAKE, G_TRAP) :\n break\n else :\n ru += 1\n for delta in range(1, min(x+1, y+1)) :\n if self.grid[x-delta, y-delta] in (G_SNAKE, G_TRAP) :\n break\n else :\n lu += 1\n for delta in range(1, min(x+1, self.height-y)) :\n if self.grid[x-delta, y+delta] in (G_SNAKE, G_TRAP) :\n break\n else :\n ld += 1\n for delta in range(1, min(self.width-x, self.height-y)) :\n if self.grid[x+delta, y+delta] in (G_SNAKE, G_TRAP) :\n break\n else :\n rd += 1\n ap = [self.apple()[0]-x, self.apple()[1]-y]\n ap = np.dot(ROTATION_ARRAY[direction], ap)\n raw_straight = [r,u,l,d]\n conv_straight = [0,0,0]\n conv_straight[RIGHT] = raw_straight[DIRECTION_CONVERT[direction][RIGHT]]\n conv_straight[UP] = raw_straight[DIRECTION_CONVERT[direction][UP]]\n conv_straight[LEFT] = raw_straight[DIRECTION_CONVERT[direction][LEFT]]\n raw_diag = [ru,lu,ld,rd]\n conv_diag = [0,0,0,0]\n conv_diag[RU] = raw_diag[DIRECTION_CONVERT[direction][RU]]\n conv_diag[LU] = raw_diag[DIRECTION_CONVERT[direction][LU]]\n conv_diag[LD] = raw_diag[DIRECTION_CONVERT[direction][LD]]\n conv_diag[RD] = raw_diag[DIRECTION_CONVERT[direction][RD]]\n answer = np.concatenate((conv_straight,conv_diag,ap))\n if not self.answer_buffer_filled :\n self.answer_buffer = answer\n self.answer_buffer_filled = True\n return np.stack((self.answer_buffer, answer), axis = -1)\n \n def current_snake_length(self) :\n return len(self.snake)\n \n def get_snake_length(self) :\n return self.snakelength\n\n def set_snake_length(self, l : int) :\n self.snakelength = l\n\n def reset(self) :\n self.grid = np.full((self.width, self.height), G_EMPTY)\n if self.rand :\n self.snake = Snake(*tool.randposlist(self.snakelength, self.width, self.height))\n else :\n self.snake = Snake(*self.s_init)\n for pos in self.snake.get_list() :\n self.grid[pos[0]][pos[1]] = G_SNAKE\n self.apples = []\n if not self.rand:\n self.create_apple(self.a_init)\n else :\n self.create_apple()\n self.traps = []\n if not self.rand :\n for tpos in self.t_init :\n self.create_trap(tpos)\n else :\n for _ in range(self.trap_num) :\n self.create_trap()\n\nclass Snake() :\n def __init__(self, bodypos : list, direction : int) :\n \"\"\"\n Snake\n bodypos : head -> tail order\n \"\"\"\n self.body = bodypos.copy()\n self.health = Init_health\n self.direction = direction\n self.temp = None\n\n def __len__ (self) :\n return len(self.body)\n\n def move(self, move_direction) :\n \"\"\"\n return head direction, health\n \"\"\"\n trgt = self.body[0].copy()\n self.direction = DIRECTION_CONVERT[move_direction][self.direction]\n trgt[0] += DIRECTION_LIST[self.direction][0]\n trgt[1] += DIRECTION_LIST[self.direction][1]\n self.body.insert(0,trgt)\n self.health -= Consume_health\n self.temp = self.body.pop()\n \n return self.direction, self.health\n\n def get_list (self) :\n return self.body.copy()\n\n def get_head (self) :\n return self.body[0].copy()\n\n def get_tail (self) :\n return self.body[-1].copy()\n\n def get_health(self) :\n return self.health\n\n def eat_apple (self) :\n self.body.append(self.temp)\n self.health += Apple_health\n\n def get_direction(self):\n return self.direction\n\n# class Apple() :\n# def __init__(self, pos : list) :\n# self.pos = pos\n\n# def get_pos(self) :\n# return self.pos.copy()\n\n# class Trap() :\n# def __init__(self, pos : list) :\n# self.pos = pos\n\n# def get_pos(self) :\n# return self.pos.copy()" ]
[ [ "numpy.concatenate", "numpy.dot", "numpy.stack", "numpy.full" ] ]
tuanlm173/TensorflowProjects
[ "80d8990fd769958211701495cd6169644f37045f" ]
[ "data_loader/data_generator.py" ]
[ "import numpy as np\n\n\nclass DataGenerator:\n def __init__(self):\n self.config = config\n # load data here\n self.input = np.ones((500, 784))\n self.y = np.ones((500, 10))\n\n def next_batch(self, batch_size):\n idx = np.random.choice(500, batch_size)\n yield self.input[idx], self.y[idx]\n" ]
[ [ "numpy.random.choice", "numpy.ones" ] ]
dulude/drizzlepac
[ "e0e05faea7ea7be3009e131d43189beb187c542c" ]
[ "drizzlepac/align.py" ]
[ "#!/usr/bin/env python\n\n\"\"\"This script is a modernized implementation of tweakreg.\n\n\"\"\"\nimport copy\nimport datetime\nimport sys\nimport glob\nimport math\nimport os\nimport pickle\nfrom collections import OrderedDict\nimport traceback\n\nimport numpy as np\nfrom astropy.table import Table\nfrom astropy.io import fits\n\nfrom stsci.tools import logutil\n\nfrom . import util\nfrom .haputils import astrometric_utils as amutils\nfrom .haputils import astroquery_utils as aqutils\nfrom .haputils import get_git_rev_info\nfrom .haputils import align_utils\nfrom .haputils import config_utils\n\n__taskname__ = 'align'\n\nMIN_CATALOG_THRESHOLD = 3\nMIN_OBSERVABLE_THRESHOLD = 4\nMIN_CROSS_MATCHES = 3\nMIN_FIT_MATCHES = 4\nMAX_FIT_RMS = 10 # RMS now in mas, 1.0\nMAX_FIT_LIMIT = 150 # Maximum RMS that a result is useful\nMAX_SOURCES_PER_CHIP = 250 # Maximum number of sources per chip to include in source catalog\n# MAX_RMS_RATIO = 1.0 # Maximum ratio between RMS in RA and DEC which still represents a valid fit\nMAS_TO_ARCSEC = 1000. # Conversion factor from milli-arcseconds to arcseconds\n\n\nMSG_DATEFMT = '%Y%j%H%M%S'\nSPLUNK_MSG_FORMAT = '%(asctime)s %(levelname)s src=%(name)s- %(message)s'\nlog = logutil.create_logger(__name__, level=logutil.logging.NOTSET, stream=sys.stdout,\n format=SPLUNK_MSG_FORMAT, datefmt=MSG_DATEFMT)\n\n__version__ = 0.0\n__version_date__ = '21-Aug-2019'\n\n# ----------------------------------------------------------------------------------------------------------\ndef check_and_get_data(input_list, **pars):\n \"\"\"Verify that all specified files are present. If not, retrieve them from MAST.\n\n This function relies on the `AstroQuery interface to MAST\n <https://astroquery.readthedocs.io/en/latest/mast/mast.html>`_\n to retrieve the exposures from the `input_list` that are not found in the current directory. This\n function calls the simplified interface in\n `~haputils/astroquery_utils/retrieve_observation`_\n to get the files through AstroQuery.\n\n Parameters\n ----------\n input_list : list\n List of one or more calibrated fits images that will be used for catalog generation.\n\n Returns\n =======\n total_input_list: list\n list of full filenames\n\n See Also\n ========\n `~haputils/astroquery_utils/retrieve_observation`\n\n \"\"\"\n empty_list = []\n retrieve_list = [] # Actual files retrieved via astroquery and resident on disk\n candidate_list = [] # File names gathered from *_asn.fits file\n ipppssoot_list = [] # ipppssoot names used to avoid duplicate downloads\n total_input_list = [] # Output full filename list of data on disk\n member_suffix = '_flc.fits'\n\n # Loop over the input_list to determine if the item in the input_list is a full association file\n # (*_asn.fits), a full individual image file (aka singleton, *_flt.fits), or a root name specification\n # (association or singleton, ipppssoot).\n for input_item in input_list:\n log.info('Input item: {}'.format(input_item))\n indx = input_item.find('_')\n\n # Input with a suffix (_xxx.fits)\n if indx != -1:\n lc_input_item = input_item.lower()\n suffix = lc_input_item[indx + 1:indx + 4]\n log.info('file: {}'.format(lc_input_item))\n # For an association, need to open the table and read the image names as this could\n # be a custom association. The assumption is this file is on local disk when specified\n # in this manner (vs just the ipppssoot of the association).\n # This \"if\" block just collects the wanted full file names.\n if suffix == 'asn':\n try:\n asntab = Table.read(input_item, format='fits')\n except FileNotFoundError:\n log.error('File {} not found.'.format(input_item))\n return(empty_list)\n for row in asntab:\n if row['MEMTYPE'].startswith('PROD'):\n continue\n memname = row['MEMNAME'].lower().strip()\n # Need to check if the MEMNAME is a full filename or an ipppssoot\n if memname.find('_') != -1:\n candidate_list.append(memname)\n else:\n # Define suffix for all members based on what files are present\n if not os.path.exists(memname + member_suffix):\n member_suffix = '_flt.fits'\n\n candidate_list.append(memname + member_suffix)\n elif suffix in ['flc', 'flt']:\n if lc_input_item not in candidate_list:\n candidate_list.append(lc_input_item)\n else:\n log.error(\n 'Inappropriate file suffix: {}. Looking for \"asn.fits\", '\n '\"flc.fits\", or \"flt.fits\".'.format(\n suffix))\n return (empty_list)\n\n # Input is an ipppssoot (association or singleton), nine characters by definition.\n # This \"else\" block actually downloads the data specified as ipppssoot.\n elif len(input_item) == 9:\n try:\n if input_item not in ipppssoot_list:\n # An ipppssoot of an individual file which is part of an association cannot be\n # retrieved from MAST\n retrieve_list = aqutils.retrieve_observation(input_item, **pars)\n\n # If the retrieved list is not empty, add filename(s) to the total_input_list.\n # Also, update the ipppssoot_list so we do not try to download the data again. Need\n # to do this since retrieve_list can be empty because (1) data cannot be acquired (error)\n # or (2) data is already on disk (ok).\n if retrieve_list:\n total_input_list += retrieve_list\n ipppssoot_list.append(input_item)\n else:\n log.error('File {} cannot be retrieved from MAST.'.format(input_item))\n return(empty_list)\n except Exception:\n exc_type, exc_value, exc_tb = sys.exc_info()\n traceback.print_exception(exc_type, exc_value, exc_tb, file=sys.stdout)\n\n # Only the retrieve_list files via astroquery have been put into the total_input_list thus far.\n # Now check candidate_list to detect or acquire the requested files from MAST via astroquery.\n for file in candidate_list:\n # If the file is found on disk, add it to the total_input_list and continue\n if glob.glob(file):\n total_input_list.append(file)\n continue\n else:\n log.error('File {} cannot be found on the local disk.'.format(file))\n return(empty_list)\n\n log.info(\"TOTAL INPUT LIST: {}\".format(total_input_list))\n return(total_input_list)\n\n# ------------------------------------------------------------------------------------------------------------\n\ndef perform_align(input_list, archive=False, clobber=False, debug=False, update_hdr_wcs=False, result=None,\n runfile=None, print_fit_parameters=True, print_git_info=False, output=False, num_sources=500,\n headerlet_filenames=None, catalog_list=['GAIADR2', 'GAIADR1'], fit_label=None,\n **alignment_pars):\n \"\"\"Actual Main calling function.\n\n This function performs `a posteriori` astrometric fits to the images specified in the\n `input_list`. The images are fit to all the catalogs listed in the `catalog_list` parameter with\n the results being saved and returned as an Astropy Table object. This allows the user\n to select the solution that is most appropriate.\n\n Parameters\n ----------\n input_list : list\n List of one or more IPPSSOOTs (rootnames) to align.\n\n archive : Boolean\n Retain copies of the downloaded files in the astroquery created\n sub-directories?\n\n clobber : Boolean\n Download and overwrite existing local copies of input files?\n\n debug : Boolean\n Attempt to use saved sourcelists stored in pickle files if they exist, or if they do not exist, save\n sourcelists in pickle files for reuse so that step 4 can be skipped for faster subsequent\n debug/development runs??\n\n update_hdr_wcs : Boolean\n Write newly computed WCS information to image image headers?\n\n result: Table\n name of variable to be updated by subroutine run.\n\n runfile : string\n log file name\n\n print_fit_parameters : Boolean\n Specify whether or not to print out FIT results for each chip.\n\n print_git_info : Boolean\n Display git repository information?\n\n output : Boolean\n Should utils.astrometric_utils.create_astrometric_catalog() generate file 'ref_cat.ecsv' and should\n the alignment source catalogs get written out to files?\n\n num_sources : int, optional\n Maximum number of **brightest sources per chip** which will be used for cross-matching and fitting.\n If set to None, all sources will be used.\n\n headerlet_filenames : dictionary, optional\n dictionary that maps the flt/flc.fits file name to the corresponding custom headerlet filename.\n\n catalog_list : list\n Set of astrometric catalogs which should be used as references for fitting the input images. A\n separate fit will be performed for each catalog specified. The catalog name will also be used\n as part of the output `WCSNAME` value for the fit determined from that catalog.\n\n fit_label : str\n String to use as a unique tag for the WCS solutions generated by these fits. This tag will be\n inserted between the `-FIT` and the catalog name in the `WCSNAME` keyword value; for example,\n `fit_label=\"User\"` will result in fits to GAIADR2 with names ending in `-FIT_User_GAIADR2`.\n\n alignment_pars : dictionary or keyword args\n keyword-arg parameters containing user-specified values for the parameters used in source identification and\n alignment which should replace the default values found in the JSON parameter files in\n `drizzlepac.pars.hap_pars` based on the instrument and detector.\n The code will look for default values for all the parameters in the JSON parameter files using\n `~get_default_pars`. For example, should the user feel it would be more successful to only look\n out to a radius of 25 pixels during alignment, the user could simply specify `searchrad=25`.\n\n Updates\n -------\n filtered_table: Astropy Table\n Table which contains processing information and alignment results for every raw image evaluated\n\n \"\"\"\n log.info(\"*** HAP PIPELINE Processing Version {!s} ({!s}) started at: {!s} ***\\n\".format(__version__, __version_date__, util._ptime()[0]))\n\n if debug:\n loglevel = logutil.logging.DEBUG\n else:\n loglevel = logutil.logging.INFO\n\n if runfile is not None:\n loglevel = logutil.logging.DEBUG\n fh = logutil.logging.FileHandler(runfile)\n fh.setLevel(loglevel)\n log.addHandler(fh)\n\n log.setLevel(loglevel)\n\n # 0: print git info\n if print_git_info:\n log.info(\"{} STEP 0: Display Git revision info {}\".format(\"-\" * 20, \"-\" * 49))\n full_path = os.path.dirname(__file__)\n repo_path = None\n if \"drizzlepac/drizzlepac\" in full_path:\n repo_path = full_path.split(\"drizzlepac/drizzlepac\")[0] + \"drizzlepac\"\n elif \"hlapipeline\" in full_path:\n repo_path = full_path.split(\"drizzlepac\")[0] + \"drizzlepac\"\n else:\n pass\n if not os.path.exists(repo_path): repo_path = None # protect against non-existent paths\n if repo_path:\n get_git_rev_info.print_rev_id(repo_path) # Display git repository information\n else:\n log.warning(\"WARNING: Unable to display Git repository revision information.\")\n\n # Initialize key variables\n filtered_table = None\n\n # 1: Interpret input data and optional parameters\n log.info(\"{} STEP 1: Get data {}\".format(\"-\" * 20, \"-\" * 66))\n zero_dt = starting_dt = datetime.datetime.now()\n log.info(str(starting_dt))\n imglist = check_and_get_data(input_list, archive=archive, clobber=clobber)\n log.info(\"SUCCESS\")\n\n log.info(make_label('Processing time of [STEP 1]', starting_dt))\n starting_dt = datetime.datetime.now()\n\n # Get default alignment parameters if not provided by the user...\n inst = fits.getval(imglist[0], 'instrume')\n det = fits.getval(imglist[0], 'detector')\n apars = get_default_pars(inst, det)\n alignment_pars.update(apars)\n\n try:\n # Instantiate AlignmentTable class with these input files\n alignment_table = align_utils.AlignmentTable(imglist, log_level=loglevel,\n **alignment_pars)\n if alignment_table.process_list is None:\n log.warning(\"NO viable images to align.\")\n alignment_table.close()\n return None\n\n process_list = alignment_table.process_list\n\n # Define fitting algorithm list in priority order\n # The match_relative_fit algorithm must have more than one image as the first image is\n # the reference for the remaining images.\n fit_algorithm_list = alignment_table.get_fit_methods()\n\n if len(process_list) == 1:\n fit_algorithm_list.remove(\"relative\")\n\n log.info(make_label('Processing time of [STEP 2]', starting_dt))\n starting_dt = datetime.datetime.now()\n # 3: Build WCS for full set of input observations\n log.info(\"{} STEP 3: Build WCS {}\".format(\"-\" * 20, \"-\" * 65))\n # refwcs = amutils.build_reference_wcs(process_list)\n log.info(\"SUCCESS\")\n\n log.info(make_label('Processing time of [STEP 3]', starting_dt))\n starting_dt = datetime.datetime.now()\n # 4: Extract catalog of observable sources from each input image\n log.info(\n \"{} STEP 4: Source finding {}\".format(\"-\" * 20, \"-\" * 60))\n if debug:\n pickle_filename = \"{}.source_catalog.pickle\".format(process_list[0])\n if os.path.exists(pickle_filename):\n pickle_in = open(pickle_filename, \"rb\")\n alignment_table.extracted_sources = pickle.load(pickle_in)\n log.info(\"Using sourcelist extracted from {} generated during the last run to save time.\".format(\n pickle_filename))\n else:\n alignment_table.find_alignment_sources(output=True)\n\n pickle_out = open(pickle_filename, \"wb\")\n pickle.dump(alignment_table.extracted_sources, pickle_out)\n pickle_out.close()\n log.info(\"Wrote {}\".format(pickle_filename))\n else:\n alignment_table.find_alignment_sources(output=output)\n\n\n alignment_table.configure_fit()\n\n for imgname in alignment_table.extracted_sources.keys():\n table = alignment_table.extracted_sources[imgname]\n\n # Get the location of the current image in the filtered table\n index = np.where(alignment_table.filtered_table['imageName'] == imgname)[0][0]\n\n # First ensure sources were found\n\n if table is None or not table[1]:\n log.warning(\"No sources found in image {}\".format(imgname))\n alignment_table.filtered_table[:]['status'] = 1\n alignment_table.filtered_table[:]['processMsg'] = \"No sources found\"\n log.info(make_label('Processing time of [STEP 4]', starting_dt))\n alignment_table.close()\n return None\n\n # The catalog of observable sources must have at least MIN_OBSERVABLE_THRESHOLD entries to be useful\n total_num_sources = 0\n for chipnum in table.keys():\n total_num_sources += len(table[chipnum])\n\n # Update filtered table with number of found sources\n alignment_table.filtered_table[index]['foundSources'] = total_num_sources\n\n if total_num_sources < MIN_OBSERVABLE_THRESHOLD:\n log.warning(\"Not enough sources ({}) found in image {}\".format(total_num_sources, imgname))\n alignment_table.filtered_table[:]['status'] = 1\n alignment_table.filtered_table[:]['processMsg'] = \"Not enough sources found\"\n log.info(make_label('Processing time of [STEP 4]', starting_dt))\n alignment_table.close()\n return None\n\n log.info(\"SUCCESS\")\n log.info(make_label('Processing time of [STEP 4]', starting_dt))\n starting_dt = datetime.datetime.now()\n # 5: Retrieve list of astrometric sources from database\n\n # Convert input images to tweakwcs-compatible FITSWCS objects and\n # attach source catalogs to them.\n imglist = []\n for group_id, image in enumerate(process_list):\n img = amutils.build_wcscat(image, group_id,\n alignment_table.extracted_sources[image])\n imglist.extend(img)\n # store mapping of group_id to filename/chip\n group_id_dict = {}\n for image in imglist:\n group_id_dict[\"{}_{}\".format(image.meta[\"rootname\"], image.meta[\"chip\"])] = image.meta[\"group_id\"]\n\n best_fit_rms = -99999.0\n best_fit_status_dict = {}\n best_fit_qual = 5\n best_fit_label = [None, None]\n # create pristine copy of imglist that will be used to restore imglist back so it always starts exactly the same\n # for each run.\n orig_imglist = copy.deepcopy(imglist)\n # create dummy list that will be used to preserve imglist best_meta information through the imglist reset process\n # best_imglist = []\n fit_info_dict = OrderedDict()\n for algorithm_name in fit_algorithm_list: # loop over fit algorithm type\n log.info(\"Applying {} fit method\".format(algorithm_name))\n for catalog_index, catalog_name in enumerate(catalog_list): # loop over astrometric catalog\n log.info(\"{} STEP 5: Detect astrometric sources {}\".format(\"-\" * 20, \"-\" * 48))\n log.info(\"Astrometric Catalog: {}\".format(catalog_name))\n # store reference catalogs in a dictionary so that generate_astrometric_catalog() doesn't\n # execute unnecessarily after it's been run once for a given astrometric catalog.\n if catalog_name in alignment_table.reference_catalogs:\n log.info(\"Using {} reference catalog from earlier this run.\".format(catalog_name))\n reference_catalog = alignment_table.reference_catalogs[catalog_name]\n else:\n log.info(\"Generating new reference catalog for {};\"\n \" Storing it for potential re-use later this run.\".format(catalog_name))\n reference_catalog = generate_astrometric_catalog(process_list,\n catalog=catalog_name,\n output=output)\n alignment_table.reference_catalogs[catalog_name] = reference_catalog\n log.info(make_label('Processing time of [STEP 5]', starting_dt))\n starting_dt = datetime.datetime.now()\n\n if len(reference_catalog) < MIN_CATALOG_THRESHOLD:\n log.warning(\"Not enough sources found in catalog {}\".format(catalog_name))\n fit_quality = 5\n if catalog_index < len(catalog_list) - 1:\n log.info(\"Try again with other catalog\")\n else:\n # bail out if not enough sources can be found any of the astrometric catalogs\n log.warning(\"ERROR! No astrometric sources found in any catalog. Exiting...\")\n alignment_table.filtered_table['status'][:] = 1\n alignment_table.filtered_table['processMsg'][:] = \"No astrometric sources found\"\n alignment_table.filtered_table['fit_qual'][:] = fit_quality\n current_dt = datetime.datetime.now()\n delta_dt = (current_dt - starting_dt).total_seconds()\n log.info('Processing time of [STEP 5]: {} sec'.format(delta_dt))\n alignment_table.close()\n return alignment_table\n else:\n log.info(\"{} Cross matching and \"\n \"fitting {}\".format(\"-\" * 20, \"-\" * 47))\n imglist = copy.deepcopy(orig_imglist) # reset imglist to pristine state\n\n log.info(\n \"{} Catalog {} matched using {} {}\".format(\"-\" * 18,\n catalog_name,\n algorithm_name, \"-\" * 18))\n try:\n # restore group IDs to their pristine state prior to each run.\n alignment_table.reset_group_id(len(reference_catalog))\n\n # execute the correct fitting/matching algorithm\n alignment_table.imglist = alignment_table.perform_fit(algorithm_name, catalog_name, reference_catalog)\n\n # determine the quality of the fit\n fit_rms, fit_num, fit_quality, filtered_table, fit_status_dict = \\\n determine_fit_quality(\n alignment_table.imglist,\n alignment_table.filtered_table,\n (catalog_index < (len(catalog_list) - 1)),\n print_fit_parameters=print_fit_parameters)\n alignment_table.filtered_table = filtered_table\n\n # save fit algorithm name to dictionary key \"fit method\" in imglist.\n for imglist_ctr in range(0, len(imglist)):\n table_fit = alignment_table.fit_dict[(catalog_name, algorithm_name)]\n table_fit[imglist_ctr].meta['fit method'] = algorithm_name\n table_fit[imglist_ctr].meta['fit quality'] = fit_quality\n\n # populate fit_info_dict\n fit_info_dict[\"{} {}\".format(catalog_name, algorithm_name)] = \\\n fit_status_dict[next(iter(fit_status_dict))]\n fit_info_dict[\"{} {}\".format(catalog_name,\n algorithm_name)]['fit_qual'] = fit_quality\n\n # Figure out which fit solution to go with based on fit_quality value and maybe also total_rms\n if fit_quality < 5:\n if fit_quality == 1: # valid, non-comprimised solution with total rms < 10 mas...go with this solution.\n best_fit_rms = fit_rms\n best_fit_label = (catalog_name, algorithm_name)\n\n best_fit_status_dict = fit_status_dict.copy()\n best_fit_qual = fit_quality\n break # break out of while loop\n elif fit_quality < best_fit_qual: # better solution found. keep looping but with the better solution as \"best\" for now.\n log.info(\"Better solution found!\")\n best_fit_rms = fit_rms\n best_fit_label = (catalog_name, algorithm_name)\n\n best_fit_status_dict = fit_status_dict.copy()\n best_fit_qual = fit_quality\n elif fit_quality == best_fit_qual: # new solution same level of fit_quality. Choose whichever one has the lowest total rms as \"best\" and keep looping.\n if best_fit_rms >= 0.:\n if fit_rms < best_fit_rms:\n best_fit_rms = fit_rms\n best_fit_label = (catalog_name, algorithm_name)\n\n best_fit_status_dict = fit_status_dict.copy()\n best_fit_qual = fit_quality\n else: # new solution has worse fit_quality. discard and continue looping.\n continue\n\n except Exception:\n exc_type, exc_value, exc_tb = sys.exc_info()\n traceback.print_exception(exc_type, exc_value, exc_tb, file=sys.stdout)\n log.warning(\n \"WARNING: Catastrophic fitting failure with catalog {} and matching \"\n \"algorithm {}.\".format(catalog_name,\n algorithm_name))\n alignment_table.filtered_table['status'][:] = 1\n alignment_table.filtered_table['processMsg'][:] = \"Fitting failure\"\n # It may be there are additional catalogs and algorithms to try, so keep going\n fit_quality = 5 # Flag this fit with the 'bad' quality value\n alignment_table.filtered_table['fit_qual'][:] = fit_quality\n continue\n if fit_quality == 1: # break out of inner astrometric catalog loop\n break\n # break out of outer fit algorithm loop\n # either with a fit_rms < 10 or a 'valid' relative fit\n if fit_quality == 1 or (best_fit_qual in [2, 3, 4] and\n \"relative\" in algorithm_name):\n break\n log.info(\"best_fit found to be: {}\".format(best_fit_label))\n log.info(\"FIT_DICT: {}\".format(alignment_table.fit_dict.keys()))\n # Reset imglist to point to best solution...\n alignment_table.select_fit(best_fit_label[0], best_fit_label[1])\n imglist = alignment_table.selected_fit\n filtered_table = alignment_table.filtered_table\n\n # Report processing time for this step\n log.info(make_label('Processing time of [STEP 5b]', starting_dt))\n starting_dt = datetime.datetime.now()\n\n # 6: Populate the filtered_table\n log.info(\n \"{} STEP 6: Collect up information and populate the filtered table \"\n \"{}\".format(\"-\" * 20, \"-\" * 20))\n if 0 < best_fit_rms < MAX_FIT_RMS:\n log.info(\"The fitting process was successful with a best fit total \"\n \"rms of {} mas\".format(best_fit_rms))\n else:\n log.info(\n \"The fitting process was unsuccessful with a best fit total rms \"\n \"of {} mas\".format(best_fit_rms))\n\n if 0 < best_fit_rms < MAX_FIT_LIMIT:\n # Update filtered table with best fit results\n filtered_table['status'][:] = 0\n fit_status_dict = best_fit_status_dict.copy()\n\n for item in imglist:\n imgname = item.meta['name']\n index = np.where(filtered_table['imageName'] == imgname)[0][0]\n\n # populate self.filtered_table fields \"status\", \"compromised\" and\n # \"processMsg\" with fit_status_dict fields \"valid\", \"compromised\"\n # and \"reason\".\n explicit_dict_key = \"{},{}\".format(item.meta['name'], item.meta['chip'])\n if fit_status_dict[explicit_dict_key]['valid'] is True:\n filtered_table[index]['status'] = 0\n else:\n filtered_table[index]['status'] = 1\n if fit_status_dict[explicit_dict_key]['compromised'] is False:\n filtered_table['compromised'] = 0\n else:\n filtered_table['compromised'] = 1\n\n filtered_table[index]['processMsg'] = fit_status_dict[explicit_dict_key]['reason']\n filtered_table['fit_qual'][index] = item.meta['fit quality']\n\n log.info(make_label('Processing time of [STEP 6]', starting_dt))\n starting_dt = datetime.datetime.now()\n # 7: Write new fit solution to input image headers\n log.info(\"{} STEP 7: Update image headers with new WCS information \"\n \"{}\".format(\"-\" * 20, \"-\" * 29))\n if (0 < best_fit_rms < 9999.) and update_hdr_wcs:\n # determine the quality of the fit\n alignment_table.apply_fit(headerlet_filenames)\n log.info(\"SUCCESS\")\n else:\n log.info(\" STEP SKIPPED\")\n\n log.info(make_label('Processing time of [STEP 7]', starting_dt))\n log.info('TOTAL Processing time of {} sec'.format(\n (datetime.datetime.now() - zero_dt).total_seconds()))\n log.info(best_fit_status_dict)\n log.info(\"-\" * 104)\n\n log.info(\"-\" * 104)\n log.info(\" SUMMARY OF ALL FIT ATTEMPTS\")\n for item in fit_info_dict.keys():\n log.info(\"{} {}\".format(item, fit_info_dict[item]))\n log.info(\"-\" * 104)\n\n except Exception:\n exc_type, exc_value, exc_tb = sys.exc_info()\n traceback.print_exception(exc_type, exc_value, exc_tb, file=sys.stdout)\n\n finally:\n # Always make sure that all file handles are closed\n alignment_table.close()\n\n # Now update the result with the filtered_table contents\n if result:\n result.meta = filtered_table.meta\n for col in filtered_table.colnames:\n result.add_column(filtered_table[col], name=col)\n if filtered_table is not None:\n filtered_table.pprint(max_width=-1)\n return alignment_table\n\n\n\n# ----------------------------------------------------------------------------------------------------------\n\ndef make_label(label, starting_dt):\n \"\"\"Create a time-stamped label for use in log messages\"\"\"\n current_dt = datetime.datetime.now()\n delta_dt = (current_dt - starting_dt).total_seconds()\n return '{}: {} sec'.format(label, delta_dt)\n\n\n\n# ----------------------------------------------------------------------------------------------------------\n\n\ndef determine_fit_quality(imglist, filtered_table, catalogs_remaining, print_fit_parameters=True):\n \"\"\"Determine the quality of the fit to the data\n\n Parameters\n ----------\n imglist : list\n output of interpret_fits. Contains sourcelist tables, newly computed WCS info, etc. for every chip of\n every valid input image. This list should have been updated, in-place, with the new RMS values;\n specifically,\n\n * 'FIT_RMS': RMS of the separations between fitted image positions and reference positions\n * 'TOTAL_RMS': mean of the FIT_RMS values for all observations\n * 'NUM_FITS': number of images/group_id's with successful fits included in the TOTAL_RMS\n\n These entries are added to the 'fit_info' dictionary.\n\n filtered_table : object\n Astropy Table object containing data pertaining to the associated dataset, including\n the doProcess bool. It is intended this table is updated by subsequent functions for\n bookkeeping purposes.\n\n catalogs_remaining : bool\n Specify whether additional catalogs remain to be fit against.\n\n print_fit_parameters : bool\n Specify whether or not to print out FIT results for each chip\n\n Returns\n -------\n max_rms_val : float\n The best Total rms determined from all of the images\n\n num_xmatches: int\n The number of stars used in matching the data\n\n\n fit_quality : int\n fit quality category:\n * 1 = valid solution with rms < 10 mas\n * 2 = Valid but compromised solution with rms < 10 mas\n * 3 = Valid solution with RMS >= 10 mas\n * 4 = Valid but compromised solution with RMS >= 10 mas\n * 5 = Not valid solution\n\n filtered_table : object\n modified filtered_table object\n\n fit_status_dict : dictionary\n Dictionary containing the following:\n * overall fit validity (Boolean)\n * total (visit-level) RMS value in mas (float)\n * number of matched sources (int)\n * fit compromised status (Boolean)\n * reason fit is considered 'compromised' (only populated if \"compromised\" field is \"True\")\n \"\"\"\n max_rms_val = 1e9\n num_xmatches = 0\n fit_status_dict = {}\n xshifts = []\n yshifts = []\n overall_valid = True\n overall_comp = False\n for item in imglist:\n if item.meta['fit_info']['status'].startswith('FAILED') is False:\n xshifts.append(item.meta['fit_info']['shift'][0])\n yshifts.append(item.meta['fit_info']['shift'][1])\n\n for item in imglist:\n image_name = item.meta['name']\n chip_num = item.meta['chip']\n\n # Build fit_status_dict entry\n dict_key = \"{},{}\".format(image_name, chip_num)\n fit_status_dict[dict_key] = {'valid': False,\n 'max_rms': max_rms_val,\n 'num_matches': num_xmatches,\n 'compromised': False,\n 'reason': \"\"}\n # Handle fitting failures (no matches found)\n if item.meta['fit_info']['status'].startswith(\"FAILED\") is True:\n log.warning(\"No cross matches found in any catalog for {} \"\n \"- no processing done.\".format(image_name))\n overall_valid = False\n continue\n fit_rms_val = item.meta['fit_info']['FIT_RMS']\n max_rms_val = item.meta['fit_info']['TOTAL_RMS']\n # fit_rms_ra = item.meta['fit_info']['RMS_RA']\n # fit_rms_dec = item.meta['fit_info']['RMS_DEC']\n # rms_ratio = abs(fit_rms_ra - fit_rms_dec) / min(fit_rms_ra, fit_rms_dec)\n num_xmatches = item.meta['fit_info']['nmatches']\n fit_status_dict[dict_key]['max_rms'] = max_rms_val\n fit_status_dict[dict_key]['num_matches'] = num_xmatches\n\n if num_xmatches < MIN_CROSS_MATCHES:\n if catalogs_remaining:\n log.warning(\n \"Not enough cross matches found between astrometric\"\n \"catalog and sources found in {}\".format(image_name))\n overall_valid = False\n continue\n\n # Compute correlation between input and GAIA magnitudes\n if num_xmatches < max(0.1 * item.meta['num_ref_catalog'], 10):\n cross_match_check = amutils.check_mag_corr([item])[0]\n log.info(\"Cross-match check: {} on {} ref sources\".format(cross_match_check,\n item.meta['num_ref_catalog']))\n else:\n cross_match_check = True\n\n # Execute checks\n nmatches_check = False\n if num_xmatches > 4 or (num_xmatches > 2 and fit_rms_val > 0.5):\n nmatches_check = True\n\n radial_offset_check = False\n radial_offset = math.sqrt(\n float(item.meta['fit_info']['shift'][0])**2 +\n float(item.meta['fit_info']['shift'][0])**2) * item.wcs.pscale # radial offset in arssec\n if float(num_xmatches) * 0.36 > 0.8 + (radial_offset / 10.0)**8:\n radial_offset_check = True\n\n large_rms_check = True\n if fit_rms_val > 150. or max_rms_val > 150.:\n large_rms_check = False\n\n # fitRmsCheck = False\n # if fit_rms_val < max_rms_val:\n # fitRmsCheck = True\n\n consistency_check = True\n rms_limit = max(item.meta['fit_info']['TOTAL_RMS'], 10.)\n if not math.sqrt(np.std(np.asarray(xshifts)) ** 2 + np.std(\n np.asarray(yshifts)) ** 2) <= (rms_limit / MAS_TO_ARCSEC) / (item.wcs.pscale): # \\\n # or rms_ratio > MAX_RMS_RATIO:\n consistency_check = False\n\n # Decide if fit solutions are valid based on checks\n if not consistency_check: # Failed consistency check\n fit_status_dict[dict_key]['valid'] = False\n fit_status_dict[dict_key]['compromised'] = False\n fit_status_dict[dict_key]['reason'] = \"Consistency violation!\"\n elif not large_rms_check: # RMS value(s) too large\n fit_status_dict[dict_key]['valid'] = False\n fit_status_dict[dict_key]['compromised'] = False\n fit_status_dict[dict_key]['reason'] = \"RMS too large (>150 mas)!\"\n elif not radial_offset_check: # Failed radial offset check\n fit_status_dict[dict_key]['valid'] = False\n fit_status_dict[dict_key]['compromised'] = False\n fit_status_dict[dict_key]['reason'] = \"Radial offset value too large!\"\n elif not nmatches_check: # Too few matches\n fit_status_dict[dict_key]['valid'] = False\n fit_status_dict[dict_key]['compromised'] = True\n fit_status_dict[dict_key]['reason'] = \"Too few matches!\"\n elif not cross_match_check:\n fit_status_dict[dict_key]['valid'] = True\n fit_status_dict[dict_key]['compromised'] = True\n fit_status_dict[dict_key]['reason'] = \"Cross-match magnitudes not correlated!\"\n else: # all checks passed. Valid solution.\n fit_status_dict[dict_key]['valid'] = True\n fit_status_dict[dict_key]['compromised'] = False\n fit_status_dict[dict_key]['reason'] = \"\"\n # for now, generate overall valid and compromised values. Basically, if any of the entries for \"valid\" is False,\n # \"valid\" is False, treat the whole dataset as not valid. Same goes for compromised.\n if not fit_status_dict[dict_key]['valid']:\n overall_valid = False\n if fit_status_dict[dict_key]['compromised']:\n overall_comp = True\n\n log.info('RESULTS FOR {} Chip {}: FIT_RMS = {} mas, TOTAL_RMS = {}'\n ' mas, NUM = {}'.format(image_name,\n item.meta['chip'],\n fit_rms_val,\n max_rms_val,\n num_xmatches))\n # print fit params to screen\n if print_fit_parameters:\n log_info_keys = ['status', 'fitgeom', 'eff_minobj', 'matrix', 'shift', 'center',\n 'proper_rot', 'proper',\n '<rot>', '<scale>', 'skew', 'rmse', 'mae', 'nmatches', 'FIT_RMS', 'TOTAL_RMS', 'NUM_FITS',\n 'RMS_RA', 'RMS_DEC', 'catalog']\n log.info(\"{} FIT PARAMETERS {}\".format(\"~\" * 35, \"~\" * 34))\n log.info(\"image: {}\".format(image_name))\n log.info(\"chip: {}\".format(item.meta['chip']))\n log.info(\"group_id: {}\".format(item.meta['group_id']))\n for tweakwcs_info_key in log_info_keys:\n log.info(\"{} : {}\".format(tweakwcs_info_key, item.meta['fit_info'][tweakwcs_info_key]))\n log.info(\"~\" * 84)\n log.info(\"nmatches_check: {} radial_offset_check: {}\"\n \" large_rms_check: {},\"\n \" consistency_check: {}\".format(nmatches_check,\n radial_offset_check,\n large_rms_check,\n consistency_check))\n\n\n # determine which fit quality category this latest fit falls into\n if overall_valid is False:\n fit_quality = 5\n log.info(\"FIT SOLUTION REJECTED\")\n filtered_table['status'][:] = 1\n for ctr in range(0, len(filtered_table)):\n imgname = filtered_table[ctr]['imageName'] + \",1\"\n if imgname in fit_status_dict:\n filtered_table[ctr]['processMsg'] = fit_status_dict[imgname][\"reason\"]\n else:\n filtered_table[ctr]['processMsg'] = \"Not a valid exposure\"\n else:\n for ctr in range(0, len(filtered_table)):\n filtered_table[ctr]['processMsg'] = \"\"\n if overall_comp is False and max_rms_val < 10.:\n log.info(\"Valid solution with RMS < 10 mas found!\")\n fit_quality = 1\n elif overall_comp is True and max_rms_val < 10.:\n log.info(\"Valid but compromised solution with RMS < 10 mas found!\")\n fit_quality = 2\n elif overall_comp is False and 1000. >= max_rms_val >= 10.:\n log.info(\"Valid solution with RMS >= 10 mas found!\")\n fit_quality = 3\n else:\n log.info(\"Valid but compromised solution with RMS >= 10 mas found!\")\n fit_quality = 4\n\n if print_fit_parameters:\n for item in imglist: log.info(fit_status_dict[\"{},{}\".format(item.meta['name'], item.meta['chip'])])\n\n if max_rms_val > MAX_FIT_RMS:\n log.info(\"Total fit RMS value = {} mas greater than the maximum threshold value {}.\".format(max_rms_val, MAX_FIT_RMS))\n if not overall_valid:\n log.info(\"The fit solution for some or all of the images is not valid.\")\n if max_rms_val > MAX_FIT_RMS or not overall_valid:\n log.info(\"Try again with the next catalog\")\n else:\n log.info(\"Fit calculations successful.\")\n return max_rms_val, num_xmatches, fit_quality, filtered_table, fit_status_dict\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n\ndef generate_astrometric_catalog(imglist, **pars):\n \"\"\"Generates a catalog of all sources from an existing astrometric catalog are\n in or near the FOVs of the images in the input list.\n\n Parameters\n ----------\n imglist : list\n List of one or more calibrated fits images that will be used for catalog generation.\n\n Returns\n =======\n ref_table : object\n Astropy Table object of the catalog\n\n \"\"\"\n # generate catalog\n temp_pars = pars.copy()\n if pars['output'] is True:\n pars['output'] = 'ref_cat.ecsv'\n else:\n pars['output'] = None\n out_catalog = amutils.create_astrometric_catalog(imglist, **pars)\n pars = temp_pars.copy()\n # if the catalog has contents, write the catalog to ascii text file\n if len(out_catalog) > 0 and pars['output']:\n catalog_filename = \"refcatalog.cat\"\n out_catalog.write(catalog_filename, format=\"ascii.fast_commented_header\")\n log.info(\"Wrote reference catalog {}.\".format(catalog_filename))\n\n return(out_catalog)\n\n# ----------------------------------------------------------------------------------------------------------------------\n\ndef get_default_pars(instrument, detector, step='alignment',\n condition=['filter_basic']):\n\n step_list = config_utils.step_title_list\n if step not in step_list:\n log.error(\"{} not valid! Needs to be one of: {}\".format(step,\n step_list))\n raise ValueError\n\n full_cfg_index, pars_dir = config_utils.read_index(instrument, detector)\n\n par_class = config_utils.step_name_list[step_list.index(step)]\n apars = par_class(full_cfg_index[step], condition,\n pars_dir, step, True, None)\n\n return apars.outpars\n" ]
[ [ "numpy.asarray", "numpy.where" ] ]
lastcoolnameleft/whisky-training
[ "1a8eb24942f65ab3055357bfbfca9eca6d2a93be" ]
[ "whiskme_ml.py" ]
[ "\n# coding: utf-8\n\n# In[106]:\n\nfrom flask import Flask\nfrom flask import request\nfrom flask import jsonify\nimport pprint\nimport os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.neighbors import NearestNeighbors\n\napp = Flask(__name__)\n\n#create scaler instance\nscaler=MinMaxScaler()\n\n\n# In[3]:\n\n\n#Import data\nwhiskey = pd.read_csv('content/data/whisky_subset_ml.csv')\n\n\n\n# In[103]:\n\[email protected](\"/hello\")\ndef hello():\n name = request.args.get('name', '')\n pref1 = request.args.get('pref1')\n pref2 = request.args.get('pref2')\n return \"Hello \" + name + \". You like: \" + pref1 + \" \" + pref2\n\[email protected](\"/whiskme\")\ndef whiskme_ws():\n whiskey = request.args.get('whiskey', '')\n pref1 = request.args.get('pref1')\n pref2 = request.args.get('pref2')\n whiskme_result = whiskme(whiskey, pref1, pref2)\n pprint.pprint(whiskme_result)\n\n #result = {\n # 'input_whiskey': whiskey,\n # 'pref1': pref1,\n # 'pref2': pref2,\n # 'result': str(whiskme_result)\n #}\n return jsonify(whiskme_result)\n\ndef whiskme(input_bottle,pref1,pref2,whiskey_db=whiskey,KNN=False):\n \n #Create numeric df and drop unused fields, create a reference table for ID and distiller\n whis=whiskey_db.drop(['Distillery','Postcode','Latitude','Longitude'],axis=1).iloc[:,1:].add(1)\n w_ref=whiskey_db[['Distillery','RowID']]\n input_idx=w_ref[w_ref['Distillery']==input_bottle].index\n\n #Find consistency weights, grab indices\n pr_idx=[w_ref[w_ref['Distillery']==pref1].index,w_ref[w_ref['Distillery']==pref2].index]\n\n weight_temp=(whis.iloc[pr_idx[0],:].values-whis.iloc[pr_idx[1],:].values)\n #Compute dispersion ('entropy') amongst preferences\n weight=(weight_temp.reshape(12,))*10+1\n #.abs().mul(10,axis=0).add(1,axis=0))\n\n #Compute weighted input values\n #broadcast values\n #arr1=np.transpose(weight)\n #S1=pd.Series(weight)\n w_in_up=whis.mul(weight)\n w_in_dn=whis.div(weight)\n\n \n #Compute the new Preference match columns, individuals\n temp=w_in_dn.iloc[pr_idx[0],:].sum(axis=1).values.reshape(1,)\n temp2=pd.DataFrame(w_in_dn.sum(axis=1).values/temp).add(-1,axis=0).abs().add(.1,axis=0)\n w_pref1_perc=temp2\n w_pref1_perc.columns=['Pref1']\n #Compute the new Preference match columns, individuals\n temp1=w_in_dn.iloc[pr_idx[1],:].sum(axis=1).values.reshape(1,)\n temp3=pd.DataFrame(w_in_dn.sum(axis=1).values/temp1).add(-1,axis=0).abs().add(.1,axis=0)\n w_pref2_perc=temp3\n w_pref2_perc.columns=['Pref2']\n\n #Rescale the preference match cols\n w_pref1_trans=pd.DataFrame(scaler.fit_transform(np.log(w_pref1_perc)), index=w_pref1_perc.index).add(-1,axis=0).abs()\n w_pref2_trans=pd.DataFrame(scaler.fit_transform(np.log(w_pref2_perc)), index=w_pref2_perc.index).add(-1,axis=0).abs()\n\n #Combine and avg the pref cols\n #join new preference % to table\n w_pref_avg=pd.DataFrame(pd.concat([w_pref1_trans,w_pref2_trans],axis=1).mean(axis=1))\n w_pref_avg.columns=['Preference_Match']\n whiskey_full=pd.concat([whiskey_db,w_pref_avg],axis=1)\n\n output={'Input_Bottle':w_ref['Distillery'].iloc[input_idx].iloc[0],\n 'Output_Score':float(np.round(whiskey_full['Preference_Match'].iloc[input_idx].multiply(100),1)),\n 'Recommended':[whiskey_full.sort_values('Preference_Match',ascending=False)['Distillery'].iloc[1],whiskey_full.sort_values('Preference_Match',ascending=False)['Distillery'].iloc[2] ],\n 'Input_Pref':[ w_ref['Distillery'].iloc[pr_idx[0]].iloc[0], w_ref['Distillery'].iloc[pr_idx[1]].iloc[0] ]\n }\n return output\n #if KNN==False:\n #return: Preferred Match Value, Bottle1, Bottle2, Bottle3\n #return w_ref['Distillery'].iloc[input_idx],np.round(whiskey_full['Preference_Match'].iloc[input_idx].multiply(100),1), whiskey_full.sort_values('Preference_Match',ascending=False)['Distillery'].iloc[1],whiskey_full.sort_values('Preference_Match',ascending=False)['Distillery'].iloc[2] \n\n\n\n#pprint.pprint(whiskme('Aberlour','Ardmore','Tomatin'))\n\n" ]
[ [ "pandas.concat", "pandas.read_csv", "numpy.log", "sklearn.preprocessing.MinMaxScaler" ] ]
plkmo/Tacotron2-adapted
[ "4b57f35b2400ebd0b2a40f1671655522bd7289c2" ]
[ "train.py" ]
[ "# *****************************************************************************\r\n# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\r\n#\r\n# Redistribution and use in source and binary forms, with or without\r\n# modification, are permitted provided that the following conditions are met:\r\n# * Redistributions of source code must retain the above copyright\r\n# notice, this list of conditions and the following disclaimer.\r\n# * Redistributions in binary form must reproduce the above copyright\r\n# notice, this list of conditions and the following disclaimer in the\r\n# documentation and/or other materials provided with the distribution.\r\n# * Neither the name of the NVIDIA CORPORATION nor the\r\n# names of its contributors may be used to endorse or promote products\r\n# derived from this software without specific prior written permission.\r\n#\r\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n# DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY\r\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n#\r\n# *****************************************************************************\r\n\r\nimport os\r\nimport time\r\nimport argparse\r\nimport numpy as np\r\nfrom contextlib import contextmanager\r\n\r\nimport torch\r\nfrom torch.utils.data import DataLoader\r\nfrom torch.autograd import Variable\r\nfrom torch.nn.parameter import Parameter\r\nfrom inference import unwrap_distributed, checkpoint_from_distributed\r\n\r\nimport torch.distributed as dist\r\nfrom torch.utils.data.distributed import DistributedSampler\r\n\r\nif torch.distributed.is_available():\r\n from apex.parallel import DistributedDataParallel as DDP\r\n\r\nimport models\r\nimport loss_functions\r\nimport data_functions\r\n\r\nfrom dllogger.logger import LOGGER\r\nimport dllogger.logger as dllg\r\nfrom dllogger import tags\r\nfrom dllogger.autologging import log_hardware, log_args\r\nfrom scipy.io.wavfile import write as write_wav\r\n\r\nfrom apex import amp\r\namp.lists.functional_overrides.FP32_FUNCS.remove('softmax')\r\namp.lists.functional_overrides.FP16_FUNCS.append('softmax')\r\n\r\n\r\ndef parse_args(parser):\r\n \"\"\"\r\n Parse commandline arguments.\r\n \"\"\"\r\n\r\n parser.add_argument('-o', '--output_directory', type=str, required=True,\r\n help='Directory to save checkpoints')\r\n parser.add_argument('-d', '--dataset-path', type=str,\r\n default='./', help='Path to dataset')\r\n parser.add_argument('-m', '--model-name', type=str, default='', required=True,\r\n help='Model to train')\r\n parser.add_argument('--log-file', type=str, default='nvlog.json',\r\n help='Filename for logging')\r\n parser.add_argument('--phrase-path', type=str, default=None,\r\n help='Path to phrase sequence file used for sample generation')\r\n parser.add_argument('--waveglow-checkpoint', type=str, default=None,\r\n help='Path to pre-trained WaveGlow checkpoint for sample generation')\r\n parser.add_argument('--tacotron2-checkpoint', type=str, default=None,\r\n help='Path to pre-trained Tacotron2 checkpoint for sample generation')\r\n parser.add_argument('--anneal-steps', nargs='*',\r\n help='Epochs after which decrease learning rate')\r\n parser.add_argument('--anneal-factor', type=float, choices=[0.1, 0.3], default=0.1,\r\n help='Factor for annealing learning rate')\r\n\r\n # training\r\n training = parser.add_argument_group('training setup')\r\n training.add_argument('--epochs', type=int, required=True,\r\n help='Number of total epochs to run')\r\n training.add_argument('--epochs-per-checkpoint', type=int, default=1,\r\n help='Number of epochs per checkpoint')\r\n training.add_argument('--seed', type=int, default=1234,\r\n help='Seed for PyTorch random number generators')\r\n training.add_argument('--dynamic-loss-scaling', type=bool, default=True,\r\n help='Enable dynamic loss scaling')\r\n training.add_argument('--amp-run', action='store_true',\r\n help='Enable AMP')\r\n training.add_argument('--cudnn-enabled', action='store_true',\r\n help='Enable cudnn')\r\n training.add_argument('--cudnn-benchmark', action='store_true',\r\n help='Run cudnn benchmark')\r\n training.add_argument('--disable-uniform-initialize-bn-weight', action='store_true',\r\n help='disable uniform initialization of batchnorm layer weight')\r\n training.add_argument('--checkpoint', type=str, default=\"\",\\\r\n help=\"Path to checkpoint model if resuming training\")\r\n\r\n optimization = parser.add_argument_group('optimization setup')\r\n optimization.add_argument(\r\n '--use-saved-learning-rate', default=False, type=bool)\r\n optimization.add_argument('-lr', '--learning-rate', type=float, required=True,\r\n help='Learing rate')\r\n optimization.add_argument('--weight-decay', default=1e-6, type=float,\r\n help='Weight decay')\r\n optimization.add_argument('--grad-clip-thresh', default=1.0, type=float,\r\n help='Clip threshold for gradients')\r\n optimization.add_argument('-bs', '--batch-size', type=int, required=True,\r\n help='Batch size per GPU')\r\n optimization.add_argument('--grad-clip', default=5.0, type=float,\r\n help='Enables gradient clipping and sets maximum gradient norm value')\r\n\r\n # dataset parameters\r\n dataset = parser.add_argument_group('dataset parameters')\r\n dataset.add_argument('--load-mel-from-disk', action='store_true',\r\n help='Loads mel spectrograms from disk instead of computing them on the fly')\r\n dataset.add_argument('--training-files',\r\n default='filelists/ljs_audio_text_train_filelist.txt',\r\n type=str, help='Path to training filelist')\r\n dataset.add_argument('--validation-files',\r\n default='filelists/ljs_audio_text_val_filelist.txt',\r\n type=str, help='Path to validation filelist')\r\n dataset.add_argument('--text-cleaners', nargs='*',\r\n default=['english_cleaners'], type=str,\r\n help='Type of text cleaners for input text')\r\n\r\n # audio parameters\r\n audio = parser.add_argument_group('audio parameters')\r\n audio.add_argument('--max-wav-value', default=32768.0, type=float,\r\n help='Maximum audiowave value')\r\n audio.add_argument('--sampling-rate', default=22050, type=int,\r\n help='Sampling rate')\r\n audio.add_argument('--filter-length', default=1024, type=int,\r\n help='Filter length')\r\n audio.add_argument('--hop-length', default=256, type=int,\r\n help='Hop (stride) length')\r\n audio.add_argument('--win-length', default=1024, type=int,\r\n help='Window length')\r\n audio.add_argument('--mel-fmin', default=0.0, type=float,\r\n help='Minimum mel frequency')\r\n audio.add_argument('--mel-fmax', default=8000.0, type=float,\r\n help='Maximum mel frequency')\r\n\r\n distributed = parser.add_argument_group('distributed setup')\r\n # distributed.add_argument('--distributed-run', default=True, type=bool,\r\n # help='enable distributed run')\r\n distributed.add_argument('--rank', default=0, type=int,\r\n help='Rank of the process, do not set! Done by multiproc module')\r\n distributed.add_argument('--world-size', default=1, type=int,\r\n help='Number of processes, do not set! Done by multiproc module')\r\n distributed.add_argument('--dist-url', type=str, default='tcp://localhost:23456',\r\n help='Url used to set up distributed training')\r\n distributed.add_argument('--group-name', type=str, default='group_name',\r\n required=False, help='Distributed group name')\r\n distributed.add_argument('--dist-backend', default='nccl', type=str, choices={'nccl'},\r\n help='Distributed run backend')\r\n\r\n return parser\r\n\r\n\r\ndef reduce_tensor(tensor, num_gpus):\r\n rt = tensor.clone()\r\n dist.all_reduce(rt, op=dist.reduce_op.SUM)\r\n rt /= num_gpus\r\n return rt\r\n\r\n\r\ndef init_distributed(args, world_size, rank, group_name):\r\n assert torch.cuda.is_available(), \"Distributed mode requires CUDA.\"\r\n print(\"Initializing Distributed\")\r\n\r\n # Set cuda device so everything is done on the right GPU.\r\n torch.cuda.set_device(rank % torch.cuda.device_count())\r\n\r\n # Initialize distributed communication\r\n dist.init_process_group(\r\n backend=args.dist_backend, init_method=args.dist_url,\r\n world_size=world_size, rank=rank, group_name=group_name)\r\n\r\n print(\"Done initializing distributed\")\r\n\r\n\r\ndef save_checkpoint(model, epoch, config, filepath):\r\n print(\"Saving model and optimizer state at epoch {} to {}\".format(\r\n epoch, filepath))\r\n torch.save({'epoch': epoch,\r\n 'config': config,\r\n 'state_dict': model.state_dict()}, filepath)\r\n\r\n\r\ndef save_sample(model_name, model, waveglow_path, tacotron2_path, phrase_path, filepath, sampling_rate):\r\n if phrase_path is None:\r\n return\r\n phrase = torch.load(phrase_path, map_location='cpu')\r\n if model_name == 'Tacotron2':\r\n if waveglow_path is None:\r\n raise Exception(\r\n \"WaveGlow checkpoint path is missing, could not generate sample\")\r\n with torch.no_grad():\r\n checkpoint = torch.load(waveglow_path, map_location='cpu')\r\n waveglow = models.get_model(\r\n 'WaveGlow', checkpoint['config'], to_cuda=False)\r\n waveglow.eval()\r\n model.eval()\r\n mel = model.infer(phrase.cuda())[0].cpu()\r\n model.train()\r\n audio = waveglow.infer(mel, sigma=0.6)\r\n elif model_name == 'WaveGlow':\r\n if tacotron2_path is None:\r\n raise Exception(\r\n \"Tacotron2 checkpoint path is missing, could not generate sample\")\r\n with torch.no_grad():\r\n checkpoint = torch.load(tacotron2_path, map_location='cpu')\r\n tacotron2 = models.get_model(\r\n 'Tacotron2', checkpoint['config'], to_cuda=False)\r\n tacotron2.eval()\r\n mel = tacotron2.infer(phrase)[0].cuda()\r\n model.eval()\r\n audio = model.infer(mel, sigma=0.6).cpu()\r\n model.train()\r\n else:\r\n raise NotImplementedError(\r\n \"unknown model requested: {}\".format(model_name))\r\n audio = audio[0].numpy()\r\n audio = audio.astype('int16')\r\n write_wav(filepath, sampling_rate, audio)\r\n\r\n# adapted from: https://discuss.pytorch.org/t/opinion-eval-should-be-a-context-manager/18998/3\r\n# Following snippet is licensed under MIT license\r\n\r\n\r\n@contextmanager\r\ndef evaluating(model):\r\n '''Temporarily switch to evaluation mode.'''\r\n istrain = model.training\r\n try:\r\n model.eval()\r\n yield model\r\n finally:\r\n if istrain:\r\n model.train()\r\n\r\n\r\ndef validate(model, criterion, valset, iteration, batch_size, world_size,\r\n collate_fn, distributed_run, rank, batch_to_gpu):\r\n \"\"\"Handles all the validation scoring and printing\"\"\"\r\n with evaluating(model), torch.no_grad():\r\n val_sampler = DistributedSampler(valset) if distributed_run else None\r\n val_loader = DataLoader(valset, num_workers=1, shuffle=False,\r\n sampler=val_sampler,\r\n batch_size=batch_size, pin_memory=False,\r\n collate_fn=collate_fn)\r\n\r\n val_loss = 0.0\r\n for i, batch in enumerate(val_loader):\r\n x, y, len_x = batch_to_gpu(batch)\r\n y_pred = model(x)\r\n loss = criterion(y_pred, y)\r\n if distributed_run:\r\n reduced_val_loss = reduce_tensor(loss.data, world_size).item()\r\n else:\r\n reduced_val_loss = loss.item()\r\n val_loss += reduced_val_loss\r\n val_loss = val_loss / (i + 1)\r\n\r\n LOGGER.log(key=\"val_iter_loss\", value=reduced_val_loss)\r\n\r\n\r\ndef adjust_learning_rate(epoch, optimizer, learning_rate,\r\n anneal_steps, anneal_factor):\r\n\r\n p = 0\r\n if anneal_steps is not None:\r\n for i, a_step in enumerate(anneal_steps):\r\n if epoch >= int(a_step):\r\n p = p+1\r\n\r\n if anneal_factor == 0.3:\r\n lr = learning_rate*((0.1 ** (p//2))*(1.0 if p % 2 == 0 else 0.3))\r\n else:\r\n lr = learning_rate*(anneal_factor ** p)\r\n\r\n if optimizer.param_groups[0]['lr'] != lr:\r\n LOGGER.log_event(\"learning_rate changed\",\r\n value=str(optimizer.param_groups[0]['lr']) + \" -> \" + str(lr))\r\n\r\n for param_group in optimizer.param_groups:\r\n param_group['lr'] = lr\r\n\r\n\r\ndef main():\r\n\r\n parser = argparse.ArgumentParser(description='PyTorch Tacotron 2 Training')\r\n parser = parse_args(parser)\r\n args, _ = parser.parse_known_args()\r\n\r\n LOGGER.set_model_name(\"Tacotron2_PyT\")\r\n LOGGER.set_backends([\r\n dllg.StdOutBackend(log_file=None,\r\n logging_scope=dllg.TRAIN_ITER_SCOPE, iteration_interval=1),\r\n dllg.JsonBackend(log_file=args.log_file if args.rank == 0 else None,\r\n logging_scope=dllg.TRAIN_ITER_SCOPE, iteration_interval=1)\r\n ])\r\n\r\n LOGGER.timed_block_start(\"run\")\r\n LOGGER.register_metric(tags.TRAIN_ITERATION_LOSS,\r\n metric_scope=dllg.TRAIN_ITER_SCOPE)\r\n LOGGER.register_metric(\"iter_time\",\r\n metric_scope=dllg.TRAIN_ITER_SCOPE)\r\n LOGGER.register_metric(\"epoch_time\",\r\n metric_scope=dllg.EPOCH_SCOPE)\r\n LOGGER.register_metric(\"run_time\",\r\n metric_scope=dllg.RUN_SCOPE)\r\n LOGGER.register_metric(\"val_iter_loss\",\r\n metric_scope=dllg.EPOCH_SCOPE)\r\n LOGGER.register_metric(\"train_epoch_items/sec\",\r\n metric_scope=dllg.EPOCH_SCOPE)\r\n LOGGER.register_metric(\"train_epoch_avg_items/sec\",\r\n metric_scope=dllg.EPOCH_SCOPE)\r\n LOGGER.register_metric(\"train_epoch_avg_loss\",\r\n metric_scope=dllg.EPOCH_SCOPE)\r\n\r\n #log_hardware()\r\n\r\n model_name = args.model_name\r\n parser = models.parse_model_args(model_name, parser)\r\n parser.parse_args()\r\n\r\n args = parser.parse_args()\r\n\r\n log_args(args)\r\n\r\n torch.backends.cudnn.enabled = args.cudnn_enabled\r\n torch.backends.cudnn.benchmark = args.cudnn_benchmark\r\n\r\n distributed_run = args.world_size > 1\r\n if distributed_run:\r\n init_distributed(args, args.world_size, args.rank, args.group_name)\r\n\r\n LOGGER.log(key=tags.RUN_START)\r\n run_start_time = time.time()\r\n\r\n model_config = models.get_model_config(model_name, args)\r\n model = models.get_model(model_name, model_config,\r\n to_cuda=True,\r\n uniform_initialize_bn_weight=not args.disable_uniform_initialize_bn_weight)\r\n\r\n if args.checkpoint != \"\":\r\n state_dict = torch.load(args.checkpoint)['state_dict']\r\n if checkpoint_from_distributed(state_dict):\r\n state_dict = unwrap_distributed(state_dict)\r\n\r\n model.load_state_dict(state_dict)\r\n print(\"Loaded from checkpoint: %s !\" % args.checkpoint)\r\n\r\n if not args.amp_run and distributed_run:\r\n model = DDP(model)\r\n\r\n optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate,\r\n weight_decay=args.weight_decay)\r\n\r\n if args.amp_run:\r\n model, optimizer = amp.initialize(model, optimizer, opt_level=\"O1\")\r\n if distributed_run:\r\n model = DDP(model)\r\n\r\n try:\r\n sigma = args.sigma\r\n except AttributeError:\r\n sigma = None\r\n\r\n criterion = loss_functions.get_loss_function(model_name, sigma)\r\n\r\n try:\r\n n_frames_per_step = args.n_frames_per_step\r\n except AttributeError:\r\n n_frames_per_step = None\r\n\r\n collate_fn = data_functions.get_collate_function(\r\n model_name, n_frames_per_step)\r\n trainset = data_functions.get_data_loader(\r\n model_name, args.dataset_path, args.training_files, args)\r\n train_sampler = DistributedSampler(trainset) if distributed_run else None\r\n train_loader = DataLoader(trainset, num_workers=1, shuffle=False,\r\n sampler=train_sampler,\r\n batch_size=args.batch_size, pin_memory=False,\r\n drop_last=True, collate_fn=collate_fn)\r\n\r\n valset = data_functions.get_data_loader(\r\n model_name, args.dataset_path, args.validation_files, args)\r\n\r\n batch_to_gpu = data_functions.get_batch_to_gpu(model_name)\r\n\r\n iteration = 0\r\n model.train()\r\n\r\n LOGGER.log(key=tags.TRAIN_LOOP)\r\n\r\n for epoch in range(args.epochs):\r\n LOGGER.epoch_start()\r\n epoch_start_time = time.time()\r\n LOGGER.log(key=tags.TRAIN_EPOCH_START, value=epoch)\r\n\r\n # used to calculate avg items/sec over epoch\r\n reduced_num_items_epoch = 0\r\n\r\n # used to calculate avg loss over epoch\r\n train_epoch_avg_loss = 0.0\r\n train_epoch_avg_items_per_sec = 0.0\r\n num_iters = 0\r\n\r\n # if overflow at the last iteration then do not save checkpoint\r\n overflow = False\r\n\r\n for i, batch in enumerate(train_loader):\r\n print(\"Batch: {}/{} epoch {}\".format(i, len(train_loader), epoch))\r\n LOGGER.iteration_start()\r\n iter_start_time = time.time()\r\n LOGGER.log(key=tags.TRAIN_ITER_START, value=i)\r\n\r\n start = time.perf_counter()\r\n adjust_learning_rate(epoch, optimizer, args.learning_rate,\r\n args.anneal_steps, args.anneal_factor)\r\n\r\n model.zero_grad()\r\n x, y, num_items = batch_to_gpu(batch)\r\n\r\n y_pred = model(x)\r\n loss = criterion(y_pred, y)\r\n\r\n if distributed_run:\r\n reduced_loss = reduce_tensor(loss.data, args.world_size).item()\r\n reduced_num_items = reduce_tensor(num_items.data, 1).item()\r\n else:\r\n reduced_loss = loss.item()\r\n reduced_num_items = num_items.item()\r\n if np.isnan(reduced_loss):\r\n raise Exception(\"loss is NaN\")\r\n\r\n LOGGER.log(key=tags.TRAIN_ITERATION_LOSS, value=reduced_loss)\r\n\r\n train_epoch_avg_loss += reduced_loss\r\n num_iters += 1\r\n\r\n # accumulate number of items processed in this epoch\r\n reduced_num_items_epoch += reduced_num_items\r\n\r\n if args.amp_run:\r\n with amp.scale_loss(loss, optimizer) as scaled_loss:\r\n scaled_loss.backward()\r\n grad_norm = torch.nn.utils.clip_grad_norm_(\r\n amp.master_params(optimizer), args.grad_clip_thresh)\r\n else:\r\n loss.backward()\r\n grad_norm = torch.nn.utils.clip_grad_norm_(\r\n model.parameters(), args.grad_clip_thresh)\r\n\r\n optimizer.step()\r\n\r\n iteration += 1\r\n\r\n LOGGER.log(key=tags.TRAIN_ITER_STOP, value=i)\r\n\r\n iter_stop_time = time.time()\r\n iter_time = iter_stop_time - iter_start_time\r\n items_per_sec = reduced_num_items/iter_time\r\n train_epoch_avg_items_per_sec += items_per_sec\r\n\r\n LOGGER.log(key=\"train_iter_items/sec\",\r\n value=items_per_sec)\r\n LOGGER.log(key=\"iter_time\", value=iter_time)\r\n LOGGER.iteration_stop()\r\n\r\n LOGGER.log(key=tags.TRAIN_EPOCH_STOP, value=epoch)\r\n epoch_stop_time = time.time()\r\n epoch_time = epoch_stop_time - epoch_start_time\r\n\r\n LOGGER.log(key=\"train_epoch_items/sec\",\r\n value=(reduced_num_items_epoch/epoch_time))\r\n LOGGER.log(key=\"train_epoch_avg_items/sec\",\r\n value=(train_epoch_avg_items_per_sec/num_iters if num_iters > 0 else 0.0))\r\n LOGGER.log(key=\"train_epoch_avg_loss\", value=(\r\n train_epoch_avg_loss/num_iters if num_iters > 0 else 0.0))\r\n LOGGER.log(key=\"epoch_time\", value=epoch_time)\r\n\r\n LOGGER.log(key=tags.EVAL_START, value=epoch)\r\n\r\n validate(model, criterion, valset, iteration,\r\n args.batch_size, args.world_size, collate_fn,\r\n distributed_run, args.rank, batch_to_gpu)\r\n\r\n LOGGER.log(key=tags.EVAL_STOP, value=epoch)\r\n\r\n if (epoch % args.epochs_per_checkpoint == 0) and args.rank == 0:\r\n checkpoint_path = os.path.join(\r\n args.output_directory, \"checkpoint_{}_{}\".format(model_name, epoch))\r\n save_checkpoint(model, epoch, model_config, checkpoint_path)\r\n save_sample(model_name, model, args.waveglow_checkpoint,\r\n args.tacotron2_checkpoint, args.phrase_path,\r\n os.path.join(args.output_directory, \"sample_{}_{}.wav\".format(model_name, iteration)), args.sampling_rate)\r\n\r\n LOGGER.epoch_stop()\r\n\r\n run_stop_time = time.time()\r\n run_time = run_stop_time - run_start_time\r\n LOGGER.log(key=\"run_time\", value=run_time)\r\n LOGGER.log(key=tags.RUN_FINAL)\r\n\r\n print(\"training time\", run_stop_time - run_start_time)\r\n\r\n LOGGER.timed_block_stop(\"run\")\r\n\r\n if args.rank == 0:\r\n LOGGER.finish()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n" ]
[ [ "scipy.io.wavfile.write", "torch.distributed.init_process_group", "torch.utils.data.distributed.DistributedSampler", "torch.load", "numpy.isnan", "torch.utils.data.DataLoader", "torch.distributed.is_available", "torch.no_grad", "torch.cuda.is_available", "torch.cuda.device_count", "torch.distributed.all_reduce" ] ]
abhigenbdn/Capsule-Networks-on-MNIST
[ "dde980ba0de3602df1c95c08cb1113e0cecdd389" ]
[ "capsulenet.py" ]
[ "\"\"\"\nKeras implementation of CapsNet in Hinton's paper Dynamic Routing Between Capsules.\n\n\n ... ...\n\"\"\"\n\nimport numpy as np\nfrom keras import layers, models, optimizers\nfrom keras import backend as K\nfrom keras.utils import to_categorical\nimport matplotlib.pyplot as plt\nfrom utils import combine_images\nfrom PIL import Image\nfrom capsulelayers import CapsuleLayer, PrimaryCap, Length, Mask\n\nK.set_image_data_format('channels_last')\n\n\ndef CapsNet(input_shape, n_class, routings):\n \"\"\"\n A Capsule Network on MNIST.\n :param input_shape: data shape, 3d, [width, height, channels]\n :param n_class: number of classes\n :param routings: number of routing iterations\n :return: Two Keras Models, the first one used for training, and the second one for evaluation.\n `eval_model` can also be used for training.\n \"\"\"\n x = layers.Input(shape=input_shape)\n\n # Layer 1: Just a conventional Conv2D layer\n conv1 = layers.Conv2D(filters=256, kernel_size=9, strides=1, padding='valid', activation='relu', name='conv1')(x)\n\n # Layer 2: Conv2D layer with `squash` activation, then reshape to [None, num_capsule, dim_capsule]\n primarycaps = PrimaryCap(conv1, dim_capsule=8, n_channels=32, kernel_size=9, strides=2, padding='valid')\n\n # Layer 3: Capsule layer. Routing algorithm works here.\n digitcaps = CapsuleLayer(num_capsule=n_class, dim_capsule=16, routings=routings,\n name='digitcaps')(primarycaps)\n\n # Layer 4: This is an auxiliary layer to replace each capsule with its length. Just to match the true label's shape.\n # If using tensorflow, this will not be necessary. :)\n out_caps = Length(name='capsnet')(digitcaps)\n\n # Decoder network.\n y = layers.Input(shape=(n_class,))\n masked_by_y = Mask()([digitcaps, y]) # The true label is used to mask the output of capsule layer. For training\n masked = Mask()(digitcaps) # Mask using the capsule with maximal length. For prediction\n\n # Shared Decoder model in training and prediction\n decoder = models.Sequential(name='decoder')\n decoder.add(layers.Dense(512, activation='relu', input_dim=16*n_class))\n decoder.add(layers.Dense(1024, activation='relu'))\n decoder.add(layers.Dense(np.prod(input_shape), activation='sigmoid'))\n decoder.add(layers.Reshape(target_shape=input_shape, name='out_recon'))\n\n # Models for training and evaluation (prediction)\n train_model = models.Model([x, y], [out_caps, decoder(masked_by_y)])\n eval_model = models.Model(x, [out_caps, decoder(masked)])\n\n # manipulate model\n noise = layers.Input(shape=(n_class, 16))\n noised_digitcaps = layers.Add()([digitcaps, noise])\n masked_noised_y = Mask()([noised_digitcaps, y])\n manipulate_model = models.Model([x, y, noise], decoder(masked_noised_y))\n return train_model, eval_model, manipulate_model\n\n\ndef margin_loss(y_true, y_pred):\n \"\"\"\n Margin loss for Eq.(4). When y_true[i, :] contains not just one `1`, this loss should work too. Not test it.\n :param y_true: [None, n_classes]\n :param y_pred: [None, num_capsule]\n :return: a scalar loss value.\n \"\"\"\n L = y_true * K.square(K.maximum(0., 0.9 - y_pred)) + \\\n 0.5 * (1 - y_true) * K.square(K.maximum(0., y_pred - 0.1))\n\n return K.mean(K.sum(L, 1))\n\n\ndef train(model, data, args):\n \"\"\"\n Training a CapsuleNet\n :param model: the CapsuleNet model\n :param data: a tuple containing training and testing data, like `((x_train, y_train), (x_test, y_test))`\n :param args: arguments\n :return: The trained model\n \"\"\"\n # unpacking the data\n (x_train, y_train), (x_test, y_test) = data\n\n # callbacks\n log = callbacks.CSVLogger(args.save_dir + '/log.csv')\n tb = callbacks.TensorBoard(log_dir=args.save_dir + '/tensorboard-logs',\n batch_size=args.batch_size, histogram_freq=int(args.debug))\n checkpoint = callbacks.ModelCheckpoint(args.save_dir + '/weights-{epoch:02d}.h5', monitor='val_capsnet_acc',\n save_best_only=True, save_weights_only=True, verbose=1)\n lr_decay = callbacks.LearningRateScheduler(schedule=lambda epoch: args.lr * (args.lr_decay ** epoch))\n\n # compile the model\n model.compile(optimizer=optimizers.Adam(lr=args.lr),\n loss=[margin_loss, 'mse'],\n loss_weights=[1., args.lam_recon],\n metrics={'capsnet': 'accuracy'})\n\n \"\"\"\n # Training without data augmentation:\n model.fit([x_train, y_train], [y_train, x_train], batch_size=args.batch_size, epochs=args.epochs,\n validation_data=[[x_test, y_test], [y_test, x_test]], callbacks=[log, tb, checkpoint, lr_decay])\n \"\"\"\n\n # Begin: Training with data augmentation ---------------------------------------------------------------------#\n def train_generator(x, y, batch_size, shift_fraction=0.):\n train_datagen = ImageDataGenerator(width_shift_range=shift_fraction,\n height_shift_range=shift_fraction) # shift up to 2 pixel for MNIST\n generator = train_datagen.flow(x, y, batch_size=batch_size)\n while 1:\n x_batch, y_batch = generator.next()\n yield ([x_batch, y_batch], [y_batch, x_batch])\n\n # Training with data augmentation. If shift_fraction=0., also no augmentation.\n model.fit_generator(generator=train_generator(x_train, y_train, args.batch_size, args.shift_fraction),\n steps_per_epoch=int(y_train.shape[0] / args.batch_size),\n epochs=args.epochs,\n validation_data=[[x_test, y_test], [y_test, x_test]],\n callbacks=[log, tb, checkpoint, lr_decay])\n # End: Training with data augmentation -----------------------------------------------------------------------#\n\n model.save_weights(args.save_dir + '/trained_model.h5')\n print('Trained model saved to \\'%s/trained_model.h5\\'' % args.save_dir)\n\n from utils import plot_log\n plot_log(args.save_dir + '/log.csv', show=True)\n\n return model\n\n\ndef test(model, data, args):\n x_test, y_test = data\n y_pred, x_recon = model.predict(x_test, batch_size=100)\n print('-'*30 + 'Begin: test' + '-'*30)\n print('Test acc:', np.sum(np.argmax(y_pred, 1) == np.argmax(y_test, 1))/y_test.shape[0])\n\n img = combine_images(np.concatenate([x_test[:50],x_recon[:50]]))\n image = img * 255\n Image.fromarray(image.astype(np.uint8)).save(args.save_dir + \"/real_and_recon.png\")\n print()\n print('Reconstructed images are saved to %s/real_and_recon.png' % args.save_dir)\n print('-' * 30 + 'End: test' + '-' * 30)\n plt.imshow(plt.imread(args.save_dir + \"/real_and_recon.png\"))\n plt.show()\n\n\ndef manipulate_latent(model, data, args):\n print('-'*30 + 'Begin: manipulate' + '-'*30)\n x_test, y_test = data\n index = np.argmax(y_test, 1) == args.digit\n number = np.random.randint(low=0, high=sum(index) - 1)\n x, y = x_test[index][number], y_test[index][number]\n x, y = np.expand_dims(x, 0), np.expand_dims(y, 0)\n noise = np.zeros([1, 10, 16])\n x_recons = []\n for dim in range(16):\n for r in [-0.25, -0.2, -0.15, -0.1, -0.05, 0, 0.05, 0.1, 0.15, 0.2, 0.25]:\n tmp = np.copy(noise)\n tmp[:,:,dim] = r\n x_recon = model.predict([x, y, tmp])\n x_recons.append(x_recon)\n\n x_recons = np.concatenate(x_recons)\n\n img = combine_images(x_recons, height=16)\n image = img*255\n Image.fromarray(image.astype(np.uint8)).save(args.save_dir + '/manipulate-%d.png' % args.digit)\n print('manipulated result saved to %s/manipulate-%d.png' % (args.save_dir, args.digit))\n print('-' * 30 + 'End: manipulate' + '-' * 30)\n\n\ndef load_mnist():\n # the data, shuffled and split between train and test sets\n from keras.datasets import mnist\n (x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255.\n x_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255.\n y_train = to_categorical(y_train.astype('float32'))\n y_test = to_categorical(y_test.astype('float32'))\n return (x_train, y_train), (x_test, y_test)\n\n\nif __name__ == \"__main__\":\n import os\n import argparse\n from keras.preprocessing.image import ImageDataGenerator\n from keras import callbacks\n\n # setting the hyper parameters\n parser = argparse.ArgumentParser(description=\"Capsule Network on MNIST.\")\n parser.add_argument('--epochs', default=50, type=int)\n parser.add_argument('--batch_size', default=100, type=int)\n parser.add_argument('--lr', default=0.001, type=float,\n help=\"Initial learning rate\")\n parser.add_argument('--lr_decay', default=0.9, type=float,\n help=\"The value multiplied by lr at each epoch. Set a larger value for larger epochs\")\n parser.add_argument('--lam_recon', default=0.392, type=float,\n help=\"The coefficient for the loss of decoder\")\n parser.add_argument('-r', '--routings', default=3, type=int,\n help=\"Number of iterations used in routing algorithm. should > 0\")\n parser.add_argument('--shift_fraction', default=0.1, type=float,\n help=\"Fraction of pixels to shift at most in each direction.\")\n parser.add_argument('--debug', action='store_true',\n help=\"Save weights by TensorBoard\")\n parser.add_argument('--save_dir', default='./result')\n parser.add_argument('-t', '--testing', action='store_true',\n help=\"Test the trained model on testing dataset\")\n parser.add_argument('--digit', default=5, type=int,\n help=\"Digit to manipulate\")\n parser.add_argument('-w', '--weights', default=None,\n help=\"The path of the saved weights. Should be specified when testing\")\n args = parser.parse_args()\n print(args)\n\n if not os.path.exists(args.save_dir):\n os.makedirs(args.save_dir)\n\n # load data\n (x_train, y_train), (x_test, y_test) = load_mnist()\n\n # define model\n model, eval_model, manipulate_model = CapsNet(input_shape=x_train.shape[1:],\n n_class=len(np.unique(np.argmax(y_train, 1))),\n routings=args.routings)\n model.summary()\n\n # train or test\n if args.weights is not None: # init the model weights with provided one\n model.load_weights(args.weights)\n if not args.testing:\n train(model=model, data=((x_train, y_train), (x_test, y_test)), args=args)\n else: # as long as weights are given, will run testing\n if args.weights is None:\n print('No weights are provided. Will test using random initialized weights.')\n manipulate_latent(manipulate_model, (x_test, y_test), args)\n test(model=eval_model, data=(x_test, y_test), args=args)\n" ]
[ [ "numpy.expand_dims", "matplotlib.pyplot.imread", "numpy.concatenate", "numpy.copy", "numpy.argmax", "numpy.prod", "matplotlib.pyplot.show", "numpy.zeros" ] ]
javerbukh/specutils
[ "b5720f6d1dc1a184b882a71e9058785c350a74c8", "b5720f6d1dc1a184b882a71e9058785c350a74c8" ]
[ "specutils/spectra/spectrum1d.py", "specutils/tests/test_fitting.py" ]
[ "import logging\n\nimport numpy as np\nfrom astropy import units as u\nfrom astropy.nddata import NDDataRef\nfrom astropy.utils.decorators import lazyproperty\nfrom astropy.nddata import NDUncertainty\nfrom ..wcs import WCSWrapper, WCSAdapter\nfrom .spectrum_mixin import OneDSpectrumMixin\n\n__all__ = ['Spectrum1D']\n\n__doctest_skip__ = ['Spectrum1D.spectral_resolution']\n\n\nclass Spectrum1D(OneDSpectrumMixin, NDDataRef):\n \"\"\"\n Spectrum container for 1D spectral data.\n\n Parameters\n ----------\n flux : `astropy.units.Quantity` or astropy.nddata.NDData`-like\n The flux data for this spectrum.\n spectral_axis : `astropy.units.Quantity`\n Dispersion information with the same shape as the last (or only)\n dimension of flux.\n wcs : `astropy.wcs.WCS` or `gwcs.wcs.WCS`\n WCS information object.\n velocity_convention : {\"doppler_relativistic\", \"doppler_optical\", \"doppler_radio\"}\n Convention used for velocity conversions.\n rest_value : `~astropy.units.Quantity`\n Any quantity supported by the standard spectral equivalencies\n (wavelength, energy, frequency, wave number). Describes the rest value\n of the spectral axis for use with velocity conversions.\n uncertainty : `~astropy.nddata.NDUncertainty`\n Contains uncertainty information along with propagation rules for\n spectrum arithmetic. Can take a unit, but if none is given, will use\n the unit defined in the flux.\n meta : dict\n Arbitrary container for any user-specific information to be carried\n around with the spectrum container object.\n \"\"\"\n def __init__(self, flux=None, spectral_axis=None, wcs=None,\n velocity_convention=None, rest_value=None, *args, **kwargs):\n # If the flux (data) argument is a subclass of nddataref (as it would\n # be for internal arithmetic operations), avoid setup entirely.\n if isinstance(flux, NDDataRef):\n self._velocity_convention = flux._velocity_convention\n self._rest_value = flux._rest_value\n\n super(Spectrum1D, self).__init__(flux)\n return\n\n # Ensure that the flux argument is an astropy quantity\n if flux is not None and not isinstance(flux, u.Quantity):\n raise ValueError(\"Flux must be a `Quantity` object.\")\n\n # In cases of slicing, new objects will be initialized with `data`\n # instead of `flux`. Ensure we grab the `data` argument.\n if flux is None and 'data' in kwargs:\n flux = kwargs.pop('data')\n\n # Ensure that the unit information codified in the quantity object is\n # the One True Unit.\n kwargs.setdefault('unit', flux.unit if isinstance(flux, u.Quantity)\n else kwargs.get('unit'))\n\n # Attempt to parse the spectral axis. If none is given, try instead to\n # parse a given wcs. This is put into a GWCS object to\n # then be used behind-the-scenes for all specutils operations.\n if spectral_axis is not None:\n # Ensure that the spectral axis is an astropy quantity\n if not isinstance(spectral_axis, u.Quantity):\n raise ValueError(\"Spectral axis must be a `Quantity` object.\")\n\n wcs = WCSWrapper.from_array(spectral_axis)\n elif wcs is not None:\n if not issubclass(wcs.__class__, WCSAdapter):\n wcs = WCSWrapper(wcs)\n elif isinstance(flux, float) or isinstance(flux, int) or isinstance(flux, np.ndarray):\n # In the case where the arithmetic operation is being performed with\n # a single float, int, or array object, just go ahead and ignore wcs\n # requirements\n super(Spectrum1D, self).__init__(data=flux)\n return\n else:\n # If no wcs and no spectral axis has been given, raise an error\n raise LookupError(\"No WCS object or spectral axis information has \"\n \"been given. Please provide one.\")\n\n self._velocity_convention = velocity_convention\n\n if rest_value is None:\n if wcs.rest_frequency != 0:\n self._rest_value = wcs.rest_frequency * u.Hz\n elif wcs.rest_wavelength != 0:\n self._rest_value = wcs.rest_wavelength * u.AA\n else:\n self._rest_value = 0 * u.AA\n else:\n self._rest_value = rest_value\n\n if not isinstance(self._rest_value, u.Quantity):\n logging.info(\"No unit information provided with rest value. \"\n \"Assuming units of spectral axis ('%s').\",\n spectral_axis.unit)\n self._rest_value = u.Quantity(rest_value, spectral_axis.unit)\n elif not self._rest_value.unit.is_equivalent(u.AA) and not self._rest_value.unit.is_equivalent(u.Hz):\n raise u.UnitsError(\"Rest value must be energy/wavelength/frequency equivalent.\")\n\n super(Spectrum1D, self).__init__(\n data=flux.value if isinstance(flux, u.Quantity) else flux,\n wcs=wcs, **kwargs)\n\n @property\n def frequency(self):\n \"\"\"\n The frequency as a `~astropy.units.Quantity` in units of GHz\n \"\"\"\n return self.spectral_axis.to(u.GHz, u.spectral())\n\n @property\n def wavelength(self):\n \"\"\"\n The wavelength as a `~astropy.units.Quantity` in units of Angstroms\n \"\"\"\n return self.spectral_axis.to(u.AA, u.spectral())\n\n @property\n def energy(self):\n \"\"\"\n The energy of the spectral axis as a `~astropy.units.Quantity` in units\n of eV.\n \"\"\"\n return self.spectral_axis.to(u.eV, u.spectral())\n\n @property\n def photon_flux(self):\n \"\"\"\n The flux density of photons as a `~astropy.units.Quantity`, in units of\n photons per cm^2 per second per spectral_axis unit\n \"\"\"\n flux_in_spectral_axis_units = self.flux.to(u.W * u.cm**-2 * self.spectral_axis.unit**-1, u.spectral_density(self.spectral_axis))\n photon_flux_density = flux_in_spectral_axis_units / (self.energy / u.photon)\n return photon_flux_density.to(u.photon * u.cm**-2 * u.s**-1 *\n self.spectral_axis.unit**-1)\n\n @lazyproperty\n def bin_edges(self):\n return self.wcs.bin_edges()\n\n @property\n def shape(self):\n return self.flux.shape\n\n @staticmethod\n def _compare_wcs(this_operand, other_operand):\n \"\"\"\n NNData arithmetic callable to determine if two wcs's are compatible.\n \"\"\"\n # If the other operand is a simple number or array, allow the operations\n if (isinstance(other_operand, float) or isinstance(other_operand, int)\n or isinstance(other_operand, np.ndarray)):\n return True\n\n # First check if units are equivalent, if so, create a new spectrum\n # object with spectral axis in compatible units\n other_wcs = other_operand.wcs.with_spectral_unit(\n this_operand.wcs.spectral_axis_unit,\n rest_value=this_operand._rest_value,\n velocity_convention=this_operand._velocity_convention)\n\n if other_wcs is None:\n return False\n\n # Check if the shape of the axes are compatible\n if this_operand.spectral_axis.shape != other_operand.spectral_axis.shape:\n logging.error(\"Shape of spectral axes between operands must be \"\n \"equivalent.\")\n return False\n\n # And that they cover the same range\n if (this_operand.spectral_axis[0] != other_operand.spectral_axis[0] or\n this_operand.spectral_axis[-1] != other_operand.spectral_axis[-1]):\n logging.error(\"Spectral axes between operands must cover the \"\n \"same range. Interpolation may be required.\")\n return False\n\n # Check if the delta dispersion is equivalent between the two axes\n if not np.array_equal(np.diff(this_operand.spectral_axis),\n np.diff(other_operand.spectral_axis)):\n logging.error(\"Delta dispersion of spectral axes of operands \"\n \"must be equivalent. Interpolation may be required.\")\n return False\n\n return True\n\n def __add__(self, other):\n if not isinstance(other, NDDataRef):\n other = u.Quantity(other, unit=self.unit)\n\n return self.add(\n other, compare_wcs=lambda o1, o2: self._compare_wcs(self, other))\n\n def __sub__(self, other):\n if not isinstance(other, NDDataRef):\n other = u.Quantity(other, unit=self.unit)\n\n return self.subtract(\n other, compare_wcs=lambda o1, o2: self._compare_wcs(self, other))\n\n def __mul__(self, other):\n if not isinstance(other, NDDataRef):\n other = u.Quantity(other)\n\n return self.multiply(\n other, compare_wcs=lambda o1, o2: self._compare_wcs(self, other))\n\n def __div__(self, other):\n if not isinstance(other, NDDataRef):\n other = u.Quantity(other)\n\n return self.divide(\n other, compare_wcs=lambda o1, o2: self._compare_wcs(self, other))\n\n def __truediv__(self, other):\n if not isinstance(other, NDDataRef):\n other = u.Quantity(other)\n\n return self.divide(\n other, compare_wcs=lambda o1, o2: self._compare_wcs(self, other))\n\n def _format_array_summary(self, label, array):\n if len(array) > 0:\n mean = np.mean(array)\n s = \"{:17} [ {:.5}, ..., {:.5} ], mean={:.5}\"\n return s.format(label+':', array[0], array[-1], mean)\n else:\n return \"{:17} [ ], mean= n/a\".format(label+':')\n\n def __str__(self):\n result = \"Spectrum1D \"\n # Handle case of single value flux\n if self.flux.ndim == 0:\n result += \"(length=1)\\n\"\n return result + \"flux: {}\".format(self.flux)\n\n # Handle case of multiple flux arrays\n result += \"(length={})\\n\".format(len(self.spectral_axis))\n if self.flux.ndim > 1:\n for i, flux in enumerate(self.flux):\n label = 'flux{:2}'.format(i)\n result += self._format_array_summary(label, flux) + '\\n'\n else:\n result += self._format_array_summary('flux', self.flux) + '\\n'\n # Add information about spectral axis\n result += self._format_array_summary('spectral axis', self.spectral_axis)\n # Add information about uncertainties if available\n if self.uncertainty:\n result += \"\\nuncertainty: [ {}, ..., {} ]\".format(\n self.uncertainty[0], self.uncertainty[-1])\n return result\n\n def __repr__(self):\n inner_str = \"flux={}, spectral_axis={}\".format(repr(self.flux),\n repr(self.spectral_axis))\n\n if self.uncertainty is not None:\n inner_str += \", uncertainty={}\".format(repr(self.uncertainty))\n\n result = \"<Spectrum1D({})>\".format(inner_str)\n\n return result\n\n\n def spectral_resolution(self, true_dispersion, delta_dispersion, axis=-1):\n \"\"\"Evaluate the probability distribution of the spectral resolution.\n\n Examples\n --------\n\n To tabulate a binned resolution function at 6000A covering +/-10A in\n 0.2A steps:\n\n >>> R = spectrum1d.spectral_resolution(\n ... 6000 * u.Angstrom, np.linspace(-10, 10, 51) * u.Angstrom)\n >>> assert R.shape == (50,)\n >>> assert np.allclose(R.sum(), 1.)\n\n To build a sparse resolution matrix for true wavelengths 4000-8000A\n in 0.1A steps:\n\n >>> R = spectrum1d.spectral_resolution(\n ... np.linspace(4000, 8000, 40001)[:, np.newaxis] * u.Angstrom,\n ... np.linspace(-10, +10, 201) * u.Angstrom)\n >>> assert R.shape == (40000, 200)\n >>> assert np.allclose(R.sum(axis=1), 1.)\n\n Parameters\n ----------\n true_dispersion : `~astropy.units.Quantity`\n True value(s) of dispersion for which the resolution should be\n evaluated.\n delta_dispersion : `~astropy.units.Quantity`\n Array of (observed - true) dispersion bin edges to integrate the\n resolution probability density over.\n axis : int\n Which axis of ``delta_dispersion`` contains the strictly increasing\n dispersion values to interpret as bin edges. The dimension of\n ``delta_dispersion`` along this axis must be at least two.\n\n Returns\n -------\n numpy array\n Array of dimensionless probabilities calculated as the integral of\n P(observed | true) over each bin in (observed - true). The output\n shape is the result of broadcasting the input shapes.\n\n \"\"\"\n pass\n", "import numpy as np\n\nimport astropy.units as u\nfrom astropy.modeling import models\n\nfrom ..spectra import Spectrum1D, SpectralRegion\nfrom ..fitting import (fit_lines, find_lines_derivative,\n find_lines_threshold, estimate_line_parameters)\nfrom ..analysis import fwhm, centroid\nfrom ..manipulation import noise_region_uncertainty, spectrum_from_model\n\n\ndef single_peak():\n np.random.seed(0)\n x = np.linspace(0., 10., 200)\n y_single = 3 * np.exp(-0.5 * (x - 6.3)**2 / 0.8**2)\n y_single += np.random.normal(0., 0.2, x.shape)\n return x, y_single\n\n\ndef single_peak_continuum():\n np.random.seed(0)\n x = np.linspace(0., 10., 200)\n y_single = 3 * np.exp(-0.5 * (x - 6.3)**2 / 0.3**2)\n y_single += np.random.normal(0., 0.2, x.shape)\n\n y_continuum = 3.2 * np.exp(-0.5 * (x - 0.6)**2 / 2.8**2)\n y_single += y_continuum\n return x, y_single\n\n\ndef single_peak_extra():\n x, y_single = single_peak()\n extra = 4 * np.exp(-0.5 * (x + 8.3)**2 / 0.1**2)\n y_single_extra = y_single + extra\n return x, y_single_extra\n\n\ndef double_peak():\n np.random.seed(42)\n g1 = models.Gaussian1D(1, 4.6, 0.2)\n g2 = models.Gaussian1D(2.5, 5.5, 0.1)\n x = np.linspace(0, 10, 200)\n y_double = g1(x) + g2(x) + np.random.normal(0., 0.2, x.shape)\n return x, y_double\n\n\ndef double_peak_absorption_and_emission():\n np.random.seed(42)\n g1 = models.Gaussian1D(1, 4.6, 0.2)\n g2 = models.Gaussian1D(2.5, 5.5, 0.1)\n g3 = models.Gaussian1D(-1.7, 8.2, 0.1)\n x = np.linspace(0, 10, 200)\n y_double = g1(x) + g2(x) + g3(x) + np.random.normal(0., 0.2, x.shape)\n return x, y_double\n\n\ndef test_find_lines_derivative():\n\n # Create the spectrum to fit\n x_double, y_double = double_peak_absorption_and_emission()\n spectrum = Spectrum1D(flux=y_double*u.Jy, spectral_axis=x_double*u.um)\n\n # Derivative method\n lines = find_lines_derivative(spectrum, flux_threshold=0.75)\n\n emission_lines = lines[lines['line_type'] == 'emission']\n absorption_lines = lines[lines['line_type'] == 'absorption']\n\n assert emission_lines['line_center_index'].tolist() == [90, 109]\n assert absorption_lines['line_center_index'].tolist() == [163]\n\n\ndef test_find_lines_threshold():\n\n # Create the spectrum to fit\n x_double, y_double = double_peak_absorption_and_emission()\n spectrum = Spectrum1D(flux=y_double*u.Jy, spectral_axis=x_double*u.um)\n\n # Derivative method\n noise_region = SpectralRegion(0*u.um, 3*u.um)\n spectrum = noise_region_uncertainty(spectrum, noise_region)\n lines = find_lines_threshold(spectrum, noise_factor=3)\n\n emission_lines = lines[lines['line_type'] == 'emission']\n absorption_lines = lines[lines['line_type'] == 'absorption']\n\n assert emission_lines['line_center_index'].tolist() == [91, 96, 109, 179]\n assert absorption_lines['line_center_index'].tolist() == [163]\n\n\ndef test_single_peak_estimate():\n \"\"\"\n Single Peak fit.\n \"\"\"\n\n # Create the spectrum\n x_single, y_single = single_peak()\n s_single = Spectrum1D(flux=y_single*u.Jy, spectral_axis=x_single*u.um)\n\n #\n # Estimate parameter Gaussian1D\n #\n\n g_init = estimate_line_parameters(s_single, models.Gaussian1D())\n\n assert np.isclose(g_init.amplitude.value, 3.354169257846847)\n assert np.isclose(g_init.mean.value, 6.218588636687762)\n assert np.isclose(g_init.stddev.value, 1.608040201005025)\n\n assert g_init.amplitude.unit == u.Jy\n assert g_init.mean.unit == u.um\n assert g_init.stddev.unit == u.um\n\n #\n # Estimate parameter Lorentz1D\n #\n\n g_init = estimate_line_parameters(s_single, models.Lorentz1D())\n\n assert np.isclose(g_init.amplitude.value, 3.354169257846847)\n assert np.isclose(g_init.x_0.value, 6.218588636687762)\n assert np.isclose(g_init.fwhm.value, 1.608040201005025)\n\n assert g_init.amplitude.unit == u.Jy\n assert g_init.x_0.unit == u.um\n assert g_init.fwhm.unit == u.um\n\n #\n # Estimate parameter Voigt1D\n #\n\n g_init = estimate_line_parameters(s_single, models.Voigt1D())\n\n assert np.isclose(g_init.amplitude_L.value, 3.354169257846847)\n assert np.isclose(g_init.x_0.value, 6.218588636687762)\n assert np.isclose(g_init.fwhm_L.value, 1.1370561305512321)\n assert np.isclose(g_init.fwhm_G.value, 1.1370561305512321)\n\n assert g_init.amplitude_L.unit == u.Jy\n assert g_init.x_0.unit == u.um\n assert g_init.fwhm_L.unit == u.um\n assert g_init.fwhm_G.unit == u.um\n\n\n #\n # Estimate parameter MexicanHat1D\n #\n mh = models.MexicanHat1D()\n estimators = {\n 'amplitude': lambda s: max(s.flux),\n 'x_0': lambda s: centroid(s, region=None),\n 'stddev': lambda s: fwhm(s)\n }\n mh._constraints['parameter_estimator'] = estimators\n\n g_init = estimate_line_parameters(s_single, mh)\n\n assert np.isclose(g_init.amplitude.value, 3.354169257846847)\n assert np.isclose(g_init.x_0.value, 6.218588636687762)\n assert np.isclose(g_init.stddev.value, 1.608040201005025)\n\n assert g_init.amplitude.unit == u.Jy\n assert g_init.x_0.unit == u.um\n assert g_init.stddev.unit == u.um\n\n\ndef test_single_peak_fit():\n \"\"\"\n Single peak fit\n \"\"\"\n\n # Create the spectrum\n x_single, y_single = single_peak()\n s_single = Spectrum1D(flux=y_single*u.Jy, spectral_axis=x_single*u.um)\n\n # Fit the spectrum\n g_init = models.Gaussian1D(amplitude=3.*u.Jy, mean=6.1*u.um, stddev=1.*u.um)\n g_fit = fit_lines(s_single, g_init)\n y_single_fit = g_fit(x_single*u.um)\n\n # Comparing every 10th value.\n y_single_fit_expected = np.array([3.69669474e-13, 3.57992454e-11, 2.36719426e-09, 1.06879318e-07,\n 3.29498310e-06, 6.93605383e-05, 9.96945607e-04, 9.78431032e-03,\n 6.55675141e-02, 3.00017760e-01, 9.37356842e-01, 1.99969007e+00,\n 2.91286375e+00, 2.89719280e+00, 1.96758892e+00, 9.12412206e-01,\n 2.88900005e-01, 6.24602556e-02, 9.22061121e-03, 9.29427266e-04]) * u.Jy\n\n assert np.allclose(y_single_fit.value[::10], y_single_fit_expected.value, atol=1e-5)\n\n\ndef test_single_peak_fit_window():\n \"\"\"\n Single Peak fit with a window specified\n \"\"\"\n\n # Create the sepctrum\n x_single, y_single = single_peak()\n s_single = Spectrum1D(flux=y_single*u.Jy, spectral_axis=x_single*u.um)\n\n # Fit the spectrum\n g_init = models.Gaussian1D(amplitude=3.*u.Jy, mean=5.5*u.um, stddev=1.*u.um)\n g_fit = fit_lines(s_single, g_init, window=2*u.um)\n y_single_fit = g_fit(x_single*u.um)\n\n # Comparing every 10th value.\n y_single_fit_expected = np.array([3.69669474e-13, 3.57992454e-11, 2.36719426e-09, 1.06879318e-07,\n 3.29498310e-06, 6.93605383e-05, 9.96945607e-04, 9.78431032e-03,\n 6.55675141e-02, 3.00017760e-01, 9.37356842e-01, 1.99969007e+00,\n 2.91286375e+00, 2.89719280e+00, 1.96758892e+00, 9.12412206e-01,\n 2.88900005e-01, 6.24602556e-02, 9.22061121e-03, 9.29427266e-04]) * u.Jy\n\n assert np.allclose(y_single_fit.value[::10], y_single_fit_expected.value, atol=1e-5)\n\n\ndef test_single_peak_fit_tuple_window():\n \"\"\"\n Single Peak fit with a window specified as a tuple\n \"\"\"\n\n # Create the spectrum to fit\n x_single, y_single = single_peak()\n s_single = Spectrum1D(flux=y_single*u.Jy, spectral_axis=x_single*u.um)\n\n # Fit the spectrum\n g_init = models.Gaussian1D(amplitude=3.*u.Jy, mean=5.5*u.um, stddev=1.*u.um)\n g_fit = fit_lines(s_single, g_init, window=(6*u.um, 7*u.um))\n y_single_fit = g_fit(x_single*u.um)\n\n # Comparing every 10th value.\n y_single_fit_expected = np.array([2.29674788e-16, 6.65518998e-14, 1.20595958e-11, 1.36656472e-09,\n 9.68395624e-08, 4.29141576e-06, 1.18925100e-04, 2.06096976e-03,\n 2.23354585e-02, 1.51371211e-01, 6.41529836e-01, 1.70026100e+00,\n 2.81799025e+00, 2.92071068e+00, 1.89305291e+00, 7.67294570e-01,\n 1.94485245e-01, 3.08273612e-02, 3.05570344e-03, 1.89413625e-04])*u.Jy\n\n assert np.allclose(y_single_fit.value[::10], y_single_fit_expected.value, atol=1e-5)\n\n\ndef test_double_peak_fit():\n \"\"\"\n Double Peak fit.\n \"\"\"\n\n # Create the spectrum to fit\n x_double, y_double = double_peak()\n s_double = Spectrum1D(flux=y_double*u.Jy, spectral_axis=x_double*u.um)\n\n # Fit the spectrum\n g1_init = models.Gaussian1D(amplitude=2.3*u.Jy, mean=5.6*u.um, stddev=0.1*u.um)\n g2_init = models.Gaussian1D(amplitude=1.*u.Jy, mean=4.4*u.um, stddev=0.1*u.um)\n g12_fit = fit_lines(s_double, g1_init+g2_init)\n y12_double_fit = g12_fit(x_double*u.um)\n\n # Comparing every 10th value.\n y12_double_fit_expected = np.array([2.86790780e-130, 2.12984643e-103, 1.20060032e-079, 5.13707226e-059,\n 1.66839912e-041, 4.11292970e-027, 7.69608184e-016, 1.09308800e-007,\n 1.17844042e-002, 9.64333366e-001, 6.04322205e-002, 2.22653307e+000,\n 5.51964567e-005, 8.13581859e-018, 6.37320251e-038, 8.85834856e-055,\n 1.05230522e-074, 9.48850399e-098, 6.49412764e-124, 3.37373489e-153])\n\n assert np.allclose(y12_double_fit.value[::10], y12_double_fit_expected, atol=1e-5)\n\n\ndef test_double_peak_fit_tuple_window():\n \"\"\"\n Doulbe Peak fit with a window specified as a tuple\n \"\"\"\n\n # Create the spectrum to fit\n x_double, y_double = double_peak()\n s_double = Spectrum1D(flux=y_double*u.Jy, spectral_axis=x_double*u.um, rest_value=0*u.um)\n\n # Fit the spectrum.\n g2_init = models.Gaussian1D(amplitude=1.*u.Jy, mean=4.7*u.um, stddev=0.2*u.um)\n g2_fit = fit_lines(s_double, g2_init, window=(4.3*u.um, 5.3*u.um))\n y2_double_fit = g2_fit(x_double*u.um)\n\n # Comparing every 10th value.\n y2_double_fit_expected = np.array([2.82386634e-116, 2.84746284e-092, 4.63895634e-071, 1.22104254e-052,\n 5.19265653e-037, 3.56776869e-024, 3.96051875e-014, 7.10322789e-007,\n 2.05829545e-002, 9.63624806e-001, 7.28880815e-002, 8.90744929e-006,\n 1.75872724e-012, 5.61037526e-022, 2.89156942e-034, 2.40781783e-049,\n 3.23938019e-067, 7.04122962e-088, 2.47276807e-111, 1.40302869e-137])\n\n assert np.allclose(y2_double_fit.value[::10], y2_double_fit_expected, atol=1e-5)\n\n\ndef test_double_peak_fit_window():\n \"\"\"\n Double Peak fit with a window.\n \"\"\"\n\n # Create the specturm to fit\n x_double, y_double = double_peak()\n s_double = Spectrum1D(flux=y_double*u.Jy, spectral_axis=x_double*u.um, rest_value=0*u.um)\n\n # Fit the spectrum\n g2_init = models.Gaussian1D(amplitude=1.*u.Jy, mean=4.7*u.um, stddev=0.2*u.um)\n g2_fit = fit_lines(s_double, g2_init, window=0.3*u.um)\n y2_double_fit = g2_fit(x_double*u.um)\n\n # Comparing every 10th value.\n y2_double_fit_expected = np.array([1.66363393e-128, 5.28910721e-102, 1.40949521e-078, 3.14848385e-058,\n 5.89516506e-041, 9.25224449e-027, 1.21718016e-015, 1.34220626e-007,\n 1.24062432e-002, 9.61209273e-001, 6.24240938e-002, 3.39815491e-006,\n 1.55056770e-013, 5.93054936e-024, 1.90132233e-037, 5.10943886e-054,\n 1.15092572e-073, 2.17309153e-096, 3.43926290e-122, 4.56256813e-151])\n\n assert np.allclose(y2_double_fit.value[::10], y2_double_fit_expected, atol=1e-5)\n\n\ndef test_double_peak_fit_separate_window():\n \"\"\"\n Double Peak fit with a window.\n \"\"\"\n\n # Create the spectrum to fit\n x_double, y_double = double_peak()\n s_double = Spectrum1D(flux=y_double*u.Jy, spectral_axis=x_double*u.um, rest_value=0*u.um)\n\n # Fit the spectrum\n gl_init = models.Gaussian1D(amplitude=1.*u.Jy, mean=4.8*u.um, stddev=0.2*u.um)\n gr_init = models.Gaussian1D(amplitude=2.*u.Jy, mean=5.3*u.um, stddev=0.2*u.um)\n gl_fit, gr_fit = fit_lines(s_double, [gl_init, gr_init], window=0.2*u.um)\n yl_double_fit = gl_fit(x_double*u.um)\n yr_double_fit = gr_fit(x_double*u.um)\n\n # Comparing every 10th value.\n yl_double_fit_expected = np.array([3.40725147e-18, 5.05500395e-15, 3.59471319e-12, 1.22527176e-09,\n 2.00182467e-07, 1.56763547e-05, 5.88422893e-04, 1.05866724e-02,\n 9.12966452e-02, 3.77377148e-01, 7.47690410e-01, 7.10057397e-01,\n 3.23214276e-01, 7.05201207e-02, 7.37498248e-03, 3.69687164e-04,\n 8.88245844e-06, 1.02295712e-07, 5.64686114e-10, 1.49410879e-12])\n\n assert np.allclose(yl_double_fit.value[::10], yl_double_fit_expected, atol=1e-5)\n\n # Comparing every 10th value.\n yr_double_fit_expected = np.array([0.00000000e+000, 0.00000000e+000, 0.00000000e+000, 3.04416285e-259,\n 3.85323221e-198, 2.98888589e-145, 1.42075875e-100, 4.13864520e-064,\n 7.38793226e-036, 8.08191847e-016, 5.41792361e-004, 2.22575901e+000,\n 5.60338234e-005, 8.64468603e-018, 8.17287853e-039, 4.73508430e-068,\n 1.68115300e-105, 3.65774659e-151, 4.87693358e-205, 3.98480359e-267])\n\n assert np.allclose(yr_double_fit.value[::10], yr_double_fit_expected, atol=1e-5)\n\n\ndef test_double_peak_fit_separate_window_tuple_window():\n \"\"\"\n Double Peak fit with a window.\n \"\"\"\n\n x_double, y_double = double_peak()\n s_double = Spectrum1D(flux=y_double*u.Jy, spectral_axis=x_double*u.um, rest_value=0*u.um)\n\n g1_init = models.Gaussian1D(amplitude=2.*u.Jy, mean=5.3*u.um, stddev=0.2*u.um)\n g2_init = models.Gaussian1D(amplitude=1.*u.Jy, mean=4.9*u.um, stddev=0.1*u.um)\n g1_fit, g2_fit = fit_lines(s_double, [g1_init, g2_init], window=[(5.3*u.um, 5.8*u.um), (4.6*u.um, 5.3*u.um)])\n y1_double_fit = g1_fit(x_double*u.um)\n y2_double_fit = g2_fit(x_double*u.um)\n\n # Comparing every 10th value.\n y1_double_fit_expected = np.array([0.00000000e+000, 0.00000000e+000, 5.61595149e-307, 3.38362505e-242,\n 4.27358433e-185, 1.13149721e-135, 6.28008984e-094, 7.30683649e-060,\n 1.78214929e-033, 9.11192086e-015, 9.76623021e-004, 2.19429562e+000,\n 1.03350951e-004, 1.02043415e-016, 2.11206194e-036, 9.16388177e-064,\n 8.33495900e-099, 1.58920023e-141, 6.35191874e-192, 5.32209240e-250])\n\n\n assert np.allclose(y1_double_fit.value[::10], y1_double_fit_expected, atol=1e-5)\n\n # Comparing every 10th value.\n y2_double_fit_expected = np.array([2.52990802e-158, 5.15446435e-126, 2.07577138e-097, 1.65231432e-072,\n 2.59969849e-051, 8.08482210e-034, 4.96975664e-020, 6.03833143e-010,\n 1.45016006e-003, 6.88386116e-001, 6.45900222e-002, 1.19788723e-006,\n 4.39120391e-015, 3.18176751e-027, 4.55691000e-043, 1.28999976e-062,\n 7.21815119e-086, 7.98324559e-113, 1.74521997e-143, 7.54115780e-178])\n\n assert np.allclose(y2_double_fit.value[::10], y2_double_fit_expected, atol=1e-3)\n\n\ndef test_double_peak_fit_with_exclusion():\n \"\"\"\n Double Peak fit with a window.\n \"\"\"\n\n x_double, y_double = double_peak()\n s_double = Spectrum1D(flux=y_double*u.Jy, spectral_axis=x_double*u.um, rest_value=0*u.um)\n\n g1_init = models.Gaussian1D(amplitude=1.*u.Jy, mean=4.9*u.um, stddev=0.2*u.um)\n g1_fit = fit_lines(s_double, g1_init, exclude_regions=[SpectralRegion(5.2*u.um, 5.8*u.um)])\n y1_double_fit = g1_fit(x_double*u.um)\n\n # Comparing every 10th value.\n y1_double_fit_expected = np.array([4.64465938e-130, 3.11793334e-103, 1.60765691e-079, 6.36698036e-059,\n 1.93681098e-041, 4.52537486e-027, 8.12148549e-016, 1.11951515e-007,\n 1.18532671e-002, 9.63961653e-001, 6.02136613e-002, 2.88897581e-006,\n 1.06464879e-013, 3.01357787e-024, 6.55197242e-038, 1.09414605e-054,\n 1.40343441e-074, 1.38268273e-097, 1.04632487e-123, 6.08168818e-153])\n\n assert np.allclose(y1_double_fit.value[::10], y1_double_fit_expected, atol=1e-5)\n\n\ndef tie_center(model):\n \"\"\" Dummy method for testing passing of tied parameter \"\"\"\n mean = 50 * model.stddev\n return mean\n\n\ndef test_fixed_parameters():\n \"\"\"\n Test to confirm fixed parameters do not change.\n \"\"\"\n\n x = np.linspace(0., 10., 200)\n y = 3 * np.exp(-0.5 * (x - 6.3)**2 / 0.8**2)\n y += np.random.normal(0., 0.2, x.shape)\n spectrum = Spectrum1D(flux=y*u.Jy, spectral_axis=x*u.um)\n\n # Test passing fixed and bounds parameters\n g_init = models.Gaussian1D(amplitude=3.*u.Jy, mean=6.1*u.um, stddev=1.*u.um,\n fixed={'mean': True},\n bounds={'amplitude': (2, 5)*u.Jy})\n\n g_fit = fit_lines(spectrum, g_init)\n\n assert g_fit.mean == 6.1*u.um\n assert g_fit.bounds == g_init.bounds\n\n # Test passing of tied parameter\n g_init = models.Gaussian1D(amplitude=3.*u.Jy, mean=6.1*u.um, stddev=1.*u.um,\n tied={'mean': tie_center})\n g_fit = fit_lines(spectrum, g_init)\n\n assert g_fit.tied == g_init.tied\n\n\ndef test_ignore_units():\n \"\"\"\n Ignore the units\n \"\"\"\n\n #\n # Ignore the units based on there not being units on the model\n #\n\n # Create the spectrum\n x_single, y_single = single_peak()\n s_single = Spectrum1D(flux=y_single*u.Jy, spectral_axis=x_single*u.um)\n\n # Fit the spectrum\n g_init = models.Gaussian1D(amplitude=3, mean=6.1, stddev=1.)\n g_fit = fit_lines(s_single, g_init)\n y_single_fit = g_fit(x_single*u.um)\n\n # Comparing every 10th value.\n y_single_fit_expected = np.array([3.69669474e-13, 3.57992454e-11, 2.36719426e-09, 1.06879318e-07,\n 3.29498310e-06, 6.93605383e-05, 9.96945607e-04, 9.78431032e-03,\n 6.55675141e-02, 3.00017760e-01, 9.37356842e-01, 1.99969007e+00,\n 2.91286375e+00, 2.89719280e+00, 1.96758892e+00, 9.12412206e-01,\n 2.88900005e-01, 6.24602556e-02, 9.22061121e-03, 9.29427266e-04])\n\n assert np.allclose(y_single_fit.value[::10], y_single_fit_expected, atol=1e-5)\n assert y_single_fit.unit == s_single.flux.unit\n\n #\n # Ignore the units based on not being in the model\n #\n\n # Create the spectrum to fit\n x_double, y_double = double_peak()\n s_double = Spectrum1D(flux=y_double*u.Jy, spectral_axis=x_double*u.um)\n\n # Fit the spectrum\n g1_init = models.Gaussian1D(amplitude=2.3, mean=5.6, stddev=0.1)\n g2_init = models.Gaussian1D(amplitude=1., mean=4.4, stddev=0.1)\n g12_fit = fit_lines(s_double, g1_init+g2_init)\n y12_double_fit = g12_fit(x_double*u.um)\n\n # Comparing every 10th value.\n y12_double_fit_expected = np.array([2.86790780e-130, 2.12984643e-103, 1.20060032e-079, 5.13707226e-059,\n 1.66839912e-041, 4.11292970e-027, 7.69608184e-016, 1.09308800e-007,\n 1.17844042e-002, 9.64333366e-001, 6.04322205e-002, 2.22653307e+000,\n 5.51964567e-005, 8.13581859e-018, 6.37320251e-038, 8.85834856e-055,\n 1.05230522e-074, 9.48850399e-098, 6.49412764e-124, 3.37373489e-153])\n\n assert np.allclose(y12_double_fit.value[::10], y12_double_fit_expected, atol=1e-5)\n\n\ndef test_fitter_parameters():\n \"\"\"\n Single Peak fit.\n \"\"\"\n\n # Create the spectrum\n x_single, y_single = single_peak()\n s_single = Spectrum1D(flux=y_single*u.Jy, spectral_axis=x_single*u.um)\n\n # Fit the spectrum\n g_init = models.Gaussian1D(amplitude=3.*u.Jy, mean=6.1*u.um, stddev=1.*u.um)\n\n fit_params = {'maxiter': 200}\n\n g_fit = fit_lines(s_single, g_init, **fit_params)\n y_single_fit = g_fit(x_single*u.um)\n\n # Comparing every 10th value.\n y_single_fit_expected = np.array([3.69669474e-13, 3.57992454e-11, 2.36719426e-09, 1.06879318e-07,\n 3.29498310e-06, 6.93605383e-05, 9.96945607e-04, 9.78431032e-03,\n 6.55675141e-02, 3.00017760e-01, 9.37356842e-01, 1.99969007e+00,\n 2.91286375e+00, 2.89719280e+00, 1.96758892e+00, 9.12412206e-01,\n 2.88900005e-01, 6.24602556e-02, 9.22061121e-03, 9.29427266e-04]) * u.Jy\n\n assert np.allclose(y_single_fit.value[::10], y_single_fit_expected.value, atol=1e-5)\n\n\ndef test_spectrum_from_model():\n \"\"\"\n This test fits the the first simulated spectrum from the fixture. The\n initial guesses are manually set here with bounds that essentially make\n sense as the functionality of the test is to make sure the fit works and\n we get a reasonable answer out **given** good initial guesses.\n \"\"\"\n\n np.random.seed(0)\n x = np.linspace(0., 10., 200)\n y = 3 * np.exp(-0.5 * (x - 6.3)**2 / 0.1**2)\n y += np.random.normal(0., 0.2, x.shape)\n\n y_continuum = 3.2 * np.exp(-0.5 * (x - 5.6)**2 / 4.8**2)\n y += y_continuum\n\n spectrum = Spectrum1D(flux=y*u.Jy, spectral_axis=x*u.um)\n\n # Unitless test\n chebyshev = models.Chebyshev1D(3, c0=0.1, c1=4, c2=5)\n spectrum_chebyshev = spectrum_from_model(chebyshev, spectrum)\n\n flux_expected = np.array([-4.90000000e+00, -3.64760991e-01, 9.22085553e+00, 2.38568496e+01,\n 4.35432211e+01, 6.82799702e+01, 9.80670968e+01, 1.32904601e+02,\n 1.72792483e+02, 2.17730742e+02, 2.67719378e+02, 3.22758392e+02,\n 3.82847784e+02, 4.47987553e+02, 5.18177700e+02, 5.93418224e+02,\n 6.73709126e+02, 7.59050405e+02, 8.49442062e+02, 9.44884096e+02])\n\n assert np.allclose(spectrum_chebyshev.flux.value[::10], flux_expected, atol=1e-5)\n\n # Unitfull test\n gaussian = models.Gaussian1D(amplitude=5*u.Jy, mean=4*u.um, stddev=2.3*u.um)\n spectrum_gaussian = spectrum_from_model(gaussian, spectrum)\n\n flux_expected = np.array([1.1020263, 1.57342489, 2.14175093, 2.77946243, 3.4389158,\n 4.05649712, 4.56194132, 4.89121902, 4.99980906, 4.872576,\n 4.52723165, 4.01028933, 3.3867847, 2.72689468, 2.09323522,\n 1.5319218, 1.06886794, 0.71101768, 0.45092638, 0.27264641])\n\n assert np.allclose(spectrum_gaussian.flux.value[::10], flux_expected, atol=1e-5)\n" ]
[ [ "numpy.mean", "numpy.diff" ], [ "numpy.allclose", "numpy.random.seed", "numpy.linspace", "numpy.random.normal", "numpy.exp", "numpy.array", "numpy.isclose" ] ]
HighCWu/neural-renderer-paddle
[ "c5c8375b0400a0b7722ab893e46ca706153b5a43" ]
[ "tests/test_look_at.py" ]
[ "import unittest\n\nimport paddle\nimport numpy as np\n\nimport neural_renderer_paddle as nr\n\nclass TestLookAt(unittest.TestCase):\n def test_case1(self):\n eyes = [\n [1, 0, 1],\n [0, 0, -10],\n [-1, 1, 0],\n ]\n answers = [\n [-np.sqrt(2) / 2, 0, np.sqrt(2) / 2],\n [1, 0, 10],\n [0, np.sqrt(2) / 2, 3. / 2. * np.sqrt(2)],\n ]\n vertices = paddle.to_tensor(np.array([1, 0, 0], np.float32))\n vertices = vertices[None, None, :]\n for e, a in zip(eyes, answers):\n eye = np.array(e, np.float32)\n transformed = nr.look_at(vertices, eye)\n assert(np.allclose(transformed.squeeze().numpy(), np.array(a)))\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.array", "numpy.sqrt" ] ]
fangwudi/mmcv
[ "7655fa1a92bad1504511fd11bd34371b9dbd0c37" ]
[ "tests/test_runner/test_eval_hook.py" ]
[ "import os.path as osp\nimport tempfile\nimport unittest.mock as mock\nfrom collections import OrderedDict\nfrom unittest.mock import MagicMock, patch\n\nimport pytest\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader, Dataset\n\nfrom mmcv.runner import DistEvalHook as BaseDistEvalHook\nfrom mmcv.runner import EpochBasedRunner\nfrom mmcv.runner import EvalHook as BaseEvalHook\nfrom mmcv.runner import IterBasedRunner\nfrom mmcv.utils import get_logger\n\n\nclass ExampleDataset(Dataset):\n\n def __init__(self):\n self.index = 0\n self.eval_result = [1, 4, 3, 7, 2, -3, 4, 6]\n\n def __getitem__(self, idx):\n results = dict(x=torch.tensor([1]))\n return results\n\n def __len__(self):\n return 1\n\n @mock.create_autospec\n def evaluate(self, results, logger=None):\n pass\n\n\nclass EvalDataset(ExampleDataset):\n\n def evaluate(self, results, logger=None):\n acc = self.eval_result[self.index]\n output = OrderedDict(\n acc=acc, index=self.index, score=acc, loss_top=acc)\n self.index += 1\n return output\n\n\nclass Model(nn.Module):\n\n def __init__(self):\n super().__init__()\n self.linear = nn.Linear(2, 1)\n\n def forward(self, x, **kwargs):\n return x\n\n def train_step(self, data_batch, optimizer, **kwargs):\n if not isinstance(data_batch, dict):\n data_batch = dict(x=data_batch)\n return data_batch\n\n def val_step(self, x, **kwargs):\n return dict(loss=self(x))\n\n\ndef _build_epoch_runner():\n\n model = Model()\n tmp_dir = tempfile.mkdtemp()\n\n runner = EpochBasedRunner(\n model=model, work_dir=tmp_dir, logger=get_logger('demo'))\n return runner\n\n\ndef _build_iter_runner():\n\n model = Model()\n tmp_dir = tempfile.mkdtemp()\n\n runner = IterBasedRunner(\n model=model, work_dir=tmp_dir, logger=get_logger('demo'))\n return runner\n\n\nclass EvalHook(BaseEvalHook):\n\n greater_keys = ['acc', 'top']\n less_keys = ['loss', 'loss_top']\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n\nclass DistEvalHook(BaseDistEvalHook):\n\n greater_keys = ['acc', 'top']\n less_keys = ['loss', 'loss_top']\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n\ndef test_eval_hook():\n with pytest.raises(AssertionError):\n # `save_best` should be a str\n test_dataset = Model()\n data_loader = DataLoader(test_dataset)\n EvalHook(data_loader, save_best=True)\n\n with pytest.raises(TypeError):\n # dataloader must be a pytorch DataLoader\n test_dataset = Model()\n data_loader = [DataLoader(test_dataset)]\n EvalHook(data_loader)\n\n with pytest.raises(ValueError):\n # key_indicator must be valid when rule_map is None\n test_dataset = ExampleDataset()\n data_loader = DataLoader(test_dataset)\n EvalHook(data_loader, save_best='unsupport')\n\n with pytest.raises(KeyError):\n # rule must be in keys of rule_map\n test_dataset = Model()\n data_loader = DataLoader(test_dataset)\n EvalHook(data_loader, save_best='auto', rule='unsupport')\n\n test_dataset = ExampleDataset()\n loader = DataLoader(test_dataset)\n model = Model()\n data_loader = DataLoader(test_dataset)\n eval_hook = EvalHook(data_loader, save_best=None)\n\n with tempfile.TemporaryDirectory() as tmpdir:\n\n # total_epochs = 1\n logger = get_logger('test_eval')\n runner = EpochBasedRunner(model=model, work_dir=tmpdir, logger=logger)\n runner.register_hook(eval_hook)\n runner.run([loader], [('train', 1)], 1)\n test_dataset.evaluate.assert_called_with(\n test_dataset, [torch.tensor([1])], logger=runner.logger)\n assert runner.meta is None or 'best_score' not in runner.meta[\n 'hook_msgs']\n assert runner.meta is None or 'best_ckpt' not in runner.meta[\n 'hook_msgs']\n\n # when `save_best` is set to 'auto', first metric will be used.\n loader = DataLoader(EvalDataset())\n model = Model()\n data_loader = DataLoader(EvalDataset())\n eval_hook = EvalHook(data_loader, interval=1, save_best='auto')\n\n with tempfile.TemporaryDirectory() as tmpdir:\n logger = get_logger('test_eval')\n runner = EpochBasedRunner(model=model, work_dir=tmpdir, logger=logger)\n runner.register_checkpoint_hook(dict(interval=1))\n runner.register_hook(eval_hook)\n runner.run([loader], [('train', 1)], 8)\n\n ckpt_path = osp.join(tmpdir, 'best_acc_epoch_4.pth')\n\n assert runner.meta['hook_msgs']['best_ckpt'] == ckpt_path\n assert osp.exists(ckpt_path)\n assert runner.meta['hook_msgs']['best_score'] == 7\n\n # total_epochs = 8, return the best acc and corresponding epoch\n loader = DataLoader(EvalDataset())\n model = Model()\n data_loader = DataLoader(EvalDataset())\n eval_hook = EvalHook(data_loader, interval=1, save_best='acc')\n\n with tempfile.TemporaryDirectory() as tmpdir:\n logger = get_logger('test_eval')\n runner = EpochBasedRunner(model=model, work_dir=tmpdir, logger=logger)\n runner.register_checkpoint_hook(dict(interval=1))\n runner.register_hook(eval_hook)\n runner.run([loader], [('train', 1)], 8)\n\n ckpt_path = osp.join(tmpdir, 'best_acc_epoch_4.pth')\n\n assert runner.meta['hook_msgs']['best_ckpt'] == ckpt_path\n assert osp.exists(ckpt_path)\n assert runner.meta['hook_msgs']['best_score'] == 7\n\n # total_epochs = 8, return the best loss_top and corresponding epoch\n loader = DataLoader(EvalDataset())\n model = Model()\n data_loader = DataLoader(EvalDataset())\n eval_hook = EvalHook(data_loader, interval=1, save_best='loss_top')\n\n with tempfile.TemporaryDirectory() as tmpdir:\n logger = get_logger('test_eval')\n runner = EpochBasedRunner(model=model, work_dir=tmpdir, logger=logger)\n runner.register_checkpoint_hook(dict(interval=1))\n runner.register_hook(eval_hook)\n runner.run([loader], [('train', 1)], 8)\n\n ckpt_path = osp.join(tmpdir, 'best_loss_top_epoch_6.pth')\n\n assert runner.meta['hook_msgs']['best_ckpt'] == ckpt_path\n assert osp.exists(ckpt_path)\n assert runner.meta['hook_msgs']['best_score'] == -3\n\n # total_epochs = 8, return the best score and corresponding epoch\n data_loader = DataLoader(EvalDataset())\n eval_hook = EvalHook(\n data_loader, interval=1, save_best='score', rule='greater')\n with tempfile.TemporaryDirectory() as tmpdir:\n logger = get_logger('test_eval')\n runner = EpochBasedRunner(model=model, work_dir=tmpdir, logger=logger)\n runner.register_checkpoint_hook(dict(interval=1))\n runner.register_hook(eval_hook)\n runner.run([loader], [('train', 1)], 8)\n\n ckpt_path = osp.join(tmpdir, 'best_score_epoch_4.pth')\n\n assert runner.meta['hook_msgs']['best_ckpt'] == ckpt_path\n assert osp.exists(ckpt_path)\n assert runner.meta['hook_msgs']['best_score'] == 7\n\n # total_epochs = 8, return the best score using less compare func\n # and indicate corresponding epoch\n data_loader = DataLoader(EvalDataset())\n eval_hook = EvalHook(data_loader, save_best='acc', rule='less')\n with tempfile.TemporaryDirectory() as tmpdir:\n logger = get_logger('test_eval')\n runner = EpochBasedRunner(model=model, work_dir=tmpdir, logger=logger)\n runner.register_checkpoint_hook(dict(interval=1))\n runner.register_hook(eval_hook)\n runner.run([loader], [('train', 1)], 8)\n\n ckpt_path = osp.join(tmpdir, 'best_acc_epoch_6.pth')\n\n assert runner.meta['hook_msgs']['best_ckpt'] == ckpt_path\n assert osp.exists(ckpt_path)\n assert runner.meta['hook_msgs']['best_score'] == -3\n\n # Test the EvalHook when resume happend\n data_loader = DataLoader(EvalDataset())\n eval_hook = EvalHook(data_loader, save_best='acc')\n with tempfile.TemporaryDirectory() as tmpdir:\n logger = get_logger('test_eval')\n runner = EpochBasedRunner(model=model, work_dir=tmpdir, logger=logger)\n runner.register_checkpoint_hook(dict(interval=1))\n runner.register_hook(eval_hook)\n runner.run([loader], [('train', 1)], 2)\n\n old_ckpt_path = osp.join(tmpdir, 'best_acc_epoch_2.pth')\n\n assert runner.meta['hook_msgs']['best_ckpt'] == old_ckpt_path\n assert osp.exists(old_ckpt_path)\n assert runner.meta['hook_msgs']['best_score'] == 4\n\n resume_from = old_ckpt_path\n loader = DataLoader(ExampleDataset())\n eval_hook = EvalHook(data_loader, save_best='acc')\n runner = EpochBasedRunner(model=model, work_dir=tmpdir, logger=logger)\n runner.register_checkpoint_hook(dict(interval=1))\n runner.register_hook(eval_hook)\n\n runner.resume(resume_from)\n assert runner.meta['hook_msgs']['best_ckpt'] == old_ckpt_path\n assert osp.exists(old_ckpt_path)\n assert runner.meta['hook_msgs']['best_score'] == 4\n\n runner.run([loader], [('train', 1)], 8)\n\n ckpt_path = osp.join(tmpdir, 'best_acc_epoch_4.pth')\n\n assert runner.meta['hook_msgs']['best_ckpt'] == ckpt_path\n assert osp.exists(ckpt_path)\n assert runner.meta['hook_msgs']['best_score'] == 7\n assert not osp.exists(old_ckpt_path)\n\n\n@patch('mmcv.engine.single_gpu_test', MagicMock)\n@patch('mmcv.engine.multi_gpu_test', MagicMock)\[email protected]('EvalHookParam', [EvalHook, DistEvalHook])\[email protected]('_build_demo_runner,by_epoch',\n [(_build_epoch_runner, True),\n (_build_iter_runner, False)])\ndef test_start_param(EvalHookParam, _build_demo_runner, by_epoch):\n # create dummy data\n dataloader = DataLoader(torch.ones((5, 2)))\n\n # 0.1. dataloader is not a DataLoader object\n with pytest.raises(TypeError):\n EvalHookParam(dataloader=MagicMock(), interval=-1)\n\n # 0.2. negative interval\n with pytest.raises(ValueError):\n EvalHookParam(dataloader, interval=-1)\n\n # 0.3. negative start\n with pytest.raises(ValueError):\n EvalHookParam(dataloader, start=-1)\n\n # 1. start=None, interval=1: perform evaluation after each epoch.\n runner = _build_demo_runner()\n evalhook = EvalHookParam(dataloader, interval=1, by_epoch=by_epoch)\n evalhook.evaluate = MagicMock()\n runner.register_hook(evalhook)\n runner.run([dataloader], [('train', 1)], 2)\n assert evalhook.evaluate.call_count == 2 # after epoch 1 & 2\n\n # 2. start=1, interval=1: perform evaluation after each epoch.\n runner = _build_demo_runner()\n evalhook = EvalHookParam(\n dataloader, start=1, interval=1, by_epoch=by_epoch)\n evalhook.evaluate = MagicMock()\n runner.register_hook(evalhook)\n runner.run([dataloader], [('train', 1)], 2)\n assert evalhook.evaluate.call_count == 2 # after epoch 1 & 2\n\n # 3. start=None, interval=2: perform evaluation after epoch 2, 4, 6, etc\n runner = _build_demo_runner()\n evalhook = EvalHookParam(dataloader, interval=2, by_epoch=by_epoch)\n evalhook.evaluate = MagicMock()\n runner.register_hook(evalhook)\n runner.run([dataloader], [('train', 1)], 2)\n assert evalhook.evaluate.call_count == 1 # after epoch 2\n\n # 4. start=1, interval=2: perform evaluation after epoch 1, 3, 5, etc\n runner = _build_demo_runner()\n evalhook = EvalHookParam(\n dataloader, start=1, interval=2, by_epoch=by_epoch)\n evalhook.evaluate = MagicMock()\n runner.register_hook(evalhook)\n runner.run([dataloader], [('train', 1)], 3)\n assert evalhook.evaluate.call_count == 2 # after epoch 1 & 3\n\n # 5. start=0, interval=1: perform evaluation after each epoch and\n # before epoch 1.\n runner = _build_demo_runner()\n evalhook = EvalHookParam(dataloader, start=0, by_epoch=by_epoch)\n evalhook.evaluate = MagicMock()\n runner.register_hook(evalhook)\n runner.run([dataloader], [('train', 1)], 2)\n assert evalhook.evaluate.call_count == 3 # before epoch1 and after e1 & e2\n\n # 6. resuming from epoch i, start = x (x<=i), interval =1: perform\n # evaluation after each epoch and before the first epoch.\n runner = _build_demo_runner()\n evalhook = EvalHookParam(dataloader, start=1, by_epoch=by_epoch)\n evalhook.evaluate = MagicMock()\n runner.register_hook(evalhook)\n if by_epoch:\n runner._epoch = 2\n else:\n runner._iter = 2\n runner.run([dataloader], [('train', 1)], 3)\n assert evalhook.evaluate.call_count == 2 # before & after epoch 3\n\n # 7. resuming from epoch i, start = i+1/None, interval =1: perform\n # evaluation after each epoch.\n runner = _build_demo_runner()\n evalhook = EvalHookParam(dataloader, start=2, by_epoch=by_epoch)\n evalhook.evaluate = MagicMock()\n runner.register_hook(evalhook)\n if by_epoch:\n runner._epoch = 1\n else:\n runner._iter = 1\n runner.run([dataloader], [('train', 1)], 3)\n assert evalhook.evaluate.call_count == 2 # after epoch 2 & 3\n" ]
[ [ "torch.nn.Linear", "torch.utils.data.DataLoader", "torch.ones", "torch.tensor" ] ]
felipenunezb/qa_project
[ "a233c7991c3c24a0e8ee489baeac41b831a93f72" ]
[ "examples/question-answering/run_squad_trainer_vqa_steroids_v2.py" ]
[ "# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\" Fine-tuning the library models for question-answering.\"\"\"\n\n\nimport logging\nimport os\nimport sys\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nimport torch\nfrom tqdm.auto import tqdm, trange\nimport json\n\nfrom transformers import AutoConfig, AutoModelForQuestionAnsweringSteroidsSG as AutoModelForQuestionAnswering, AutoTokenizer, HfArgumentParser, SquadDataset\nfrom transformers import SquadDataTrainingArguments as DataTrainingArguments\nfrom transformers import Trainer, TrainingArguments\nfrom transformers import squad_convert_examples_to_features\nfrom transformers.data.processors.squad import SquadResult, SquadV1Processor, SquadV2Processor, SquadProcessor\nfrom transformers import SymbolDict, initEmbRandom\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass\nclass ModelArguments:\n \"\"\"\n Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.\n \"\"\"\n\n model_name_or_path: str = field(\n metadata={\"help\": \"Path to pretrained model or model identifier from huggingface.co/models\"}\n )\n config_name: Optional[str] = field(\n default=None, metadata={\"help\": \"Pretrained config name or path if not the same as model_name\"}\n )\n tokenizer_name: Optional[str] = field(\n default=None, metadata={\"help\": \"Pretrained tokenizer name or path if not the same as model_name\"}\n )\n use_fast: bool = field(default=False, metadata={\"help\": \"Set this flag to use fast tokenization.\"})\n # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,\n # or just modify its tokenizer_config.json.\n cache_dir: Optional[str] = field(\n default=None, metadata={\"help\": \"Where do you want to store the pretrained models downloaded from s3\"}\n )\n predict_file: Optional[str] = field(\n default='dev-v2.0.json', metadata={\"help\": \"File to Evaluate\"}\n )\n\ndef main():\n # See all possible arguments in src/transformers/training_args.py\n # or by passing the --help flag to this script.\n # We now keep distinct sets of args, for a cleaner separation of concerns.\n\n parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))\n\n if len(sys.argv) == 2 and sys.argv[1].endswith(\".json\"):\n # If we pass only one argument to the script and it's the path to a json file,\n # let's parse it to get our arguments.\n model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))\n else:\n model_args, data_args, training_args = parser.parse_args_into_dataclasses()\n\n if (\n os.path.exists(training_args.output_dir)\n and os.listdir(training_args.output_dir)\n and training_args.do_train\n and not training_args.overwrite_output_dir\n ):\n raise ValueError(\n f\"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome.\"\n )\n\n # Setup logging\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt=\"%m/%d/%Y %H:%M:%S\",\n level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN,\n )\n logger.warning(\n \"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s\",\n training_args.local_rank,\n training_args.device,\n training_args.n_gpu,\n bool(training_args.local_rank != -1),\n training_args.fp16,\n )\n logger.info(\"Training/evaluation parameters %s\", training_args)\n\n # Prepare Question-Answering task\n # Load pretrained model and tokenizer\n #\n # Distributed training:\n # The .from_pretrained methods guarantee that only one local process can concurrently\n # download model & vocab.\n\n config = AutoConfig.from_pretrained(\n model_args.config_name if model_args.config_name else model_args.model_name_or_path,\n cache_dir=model_args.cache_dir,\n )\n tokenizer = AutoTokenizer.from_pretrained(\n model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,\n cache_dir=model_args.cache_dir,\n )\n model = AutoModelForQuestionAnswering.from_pretrained(\n model_args.model_name_or_path,\n from_tf=bool(\".ckpt\" in model_args.model_name_or_path),\n config=config,\n cache_dir=model_args.cache_dir,\n )\n\n # Get datasets\n is_language_sensitive = hasattr(model.config, \"lang2id\")\n train_dataset = (\n SquadDataset(\n data_args, tokenizer=tokenizer, is_language_sensitive=is_language_sensitive, cache_dir=model_args.cache_dir\n )\n if training_args.do_train\n else None\n )\n eval_dataset = (\n SquadDataset(\n data_args,\n tokenizer=tokenizer,\n mode=\"dev\",\n is_language_sensitive=is_language_sensitive,\n cache_dir=model_args.cache_dir,\n )\n if training_args.do_eval\n else None\n )\n\n #Load Scene graph, if provided\n if data_args.scene_file:\n scene_file_path = os.path.join(data_args.data_dir, data_args.scene_file)\n with open(scene_file_path, \"r\", encoding=\"utf-8\") as reader:\n scene_dataset = json.load(reader)\n\n sceneDict = SymbolDict()\n for scene in tqdm(scene_dataset.values(), desc=\"Creating Scene Dictionary\"):\n for obj in scene[\"objects\"].values():\n sceneDict.addSymbols(obj[\"name\"])\n sceneDict.addSymbols(obj[\"attributes\"])\n for rel in obj[\"relations\"]:\n sceneDict.addSymbols(rel[\"name\"])\n #create vocab \n sceneDict.createVocab(minCount=0)\n\n if data_args.cached_embedding:\n import numpy as np\n embedding = np.load(os.path.join(data_args.data_dir, data_args.cached_embedding))\n elif data_args.emb_file:\n embedding = initializeWordEmbeddings(data_args.emb_dim, \n wordsDict=sceneDict, \n random=False,\n filename=os.path.join(data_args.data_dir, data_args.emb_file))\n else:\n embedding = initEmbRandom(sceneDict.getNumSymbols(), data_args.emb_dim)\n else:\n scene_dataset = None\n sceneDict = None\n embedding = None\n\n # Initialize our Trainer\n trainer = Trainer(model=model, args=training_args, train_dataset=train_dataset, eval_dataset=eval_dataset, scene_dataset=scene_dataset, scene_dict = sceneDict, embedding = embedding)\n\n # Training\n if training_args.do_train:\n trainer.train(\n model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path) else None\n )\n trainer.save_model()\n # For convenience, we also re-save the tokenizer to the same directory,\n # so that you can share your model easily on huggingface.co/models =)\n if trainer.is_world_master():\n tokenizer.save_pretrained(training_args.output_dir)\n\n # Evaluation\n eval_results = {}\n if training_args.do_eval:\n logger.info(\"*** Evaluate ***\")\n evaluate(eval_dataset, trainer)\n\n\n return eval_results\n\ndef evaluate(eval_dataset, trainer):\n eval_dataloader = trainer.get_eval_dataloader(eval_dataset)\n batch_size = eval_dataloader.batch_size\n # Eval!\n logger.info(\"***** Running evaluation *****\")\n logger.info(\" Num examples = %d\", len(eval_dataset))\n logger.info(\" Batch size = %d\", batch_size)\n\n all_results = []\n model = trainer.model\n cnt = 0\n for inputs in tqdm(eval_dataloader, desc=\"Evaluating\"):\n model.eval()\n print(inputs.keys())\n inputs = trainer._prepare_inputs(inputs, model)\n cnt +=1\n\n with torch.no_grad():\n outputs = model(**inputs)\n print('outputs')\n print(outputs)\n if cnt > 0:\n break\n\n\ndef _mp_fn(index):\n # For xla_spawn (TPUs)\n main()\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "torch.no_grad" ] ]
DarwinSenior/moderngl
[ "632146f4da03b8cb9f14a0642938fbc819161be5" ]
[ "examples/next/julia_set.py" ]
[ "import os\n\nimport moderngl.next as mgl\nimport numpy as np\nfrom PIL import Image\n\nimport data\nfrom example_window import Example, run_example\n\n\nclass Fractal(Example):\n def __init__(self):\n self.ctx = mgl.create_context()\n\n self.prog = self.ctx.program(\n vertex_shader='''\n #version 330\n\n in vec2 in_vert;\n out vec2 v_text;\n\n void main() {\n gl_Position = vec4(in_vert, 0.0, 1.0);\n v_text = in_vert;\n }\n ''',\n fragment_shader='''\n #version 330\n\n in vec2 v_text;\n out vec4 f_color;\n\n uniform sampler2D Texture;\n uniform vec2 Seed;\n uniform int Iter;\n\n void main() {\n vec2 c = Seed;\n int i;\n\n vec2 z = vec2(3.0 * v_text.x, 2.0 * v_text.y);\n\n for (i = 0; i < Iter; i++) {\n float x = (z.x * z.x - z.y * z.y) + c.x;\n float y = (z.y * z.x + z.x * z.y) + c.y;\n\n if ((x * x + y * y) > 4.0) {\n break;\n }\n\n z.x = x;\n z.y = y;\n }\n\n f_color = texture(Texture, vec2((i == Iter ? 0.0 : float(i)) / 100.0, 0.0));\n }\n ''',\n )\n\n img = Image.open(data.find('pal.png')).convert('RGB')\n self.texture = self.ctx.texture(img.size, 3, img.tobytes())\n self.sampler = self.ctx.sampler(self.texture)\n self.sampler.use()\n\n vertices = np.array([-1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0])\n\n self.vbo = self.ctx.buffer(vertices.astype('f4').tobytes())\n self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, 'in_vert')\n\n def render(self):\n self.ctx.screen.viewport = self.wnd.viewport\n self.ctx.clear(1.0, 1.0, 1.0)\n\n self.prog['Seed'] = (-0.8, 0.156)\n self.prog['Iter'] = 100\n\n self.vao.render(mgl.TRIANGLE_STRIP)\n\n\nrun_example(Fractal)\n" ]
[ [ "numpy.array" ] ]
MelDur22/manim
[ "cfba888ad69a7ccd4a8c4a1c80662078171b73ed" ]
[ "manimlib/mobject/geometry.py" ]
[ "import itertools as it\n\nimport numpy as np\n\nfrom manimlib.constants import *\nfrom manimlib.mobject.mobject import Mobject\nfrom manimlib.mobject.types.vectorized_mobject import VGroup\nfrom manimlib.mobject.types.vectorized_mobject import VMobject\nfrom manimlib.utils.bezier import interpolate\nfrom manimlib.utils.config_ops import digest_config\nfrom manimlib.utils.config_ops import digest_locals\nfrom manimlib.utils.paths import path_along_arc\nfrom manimlib.utils.space_ops import angle_of_vector\nfrom manimlib.utils.space_ops import center_of_mass\nfrom manimlib.utils.space_ops import compass_directions\nfrom manimlib.utils.space_ops import get_norm\nfrom manimlib.utils.space_ops import rotate_vector\n\n\nclass Arc(VMobject):\n CONFIG = {\n \"radius\": 1.0,\n \"start_angle\": 0,\n \"num_anchors\": 9,\n \"anchors_span_full_range\": True,\n \"arc_center\": ORIGIN,\n }\n\n def __init__(self, angle, **kwargs):\n self.angle = angle\n VMobject.__init__(self, **kwargs)\n\n def generate_points(self):\n anchors = np.array([\n np.cos(a) * RIGHT + np.sin(a) * UP\n for a in np.linspace(\n self.start_angle,\n self.start_angle + self.angle,\n self.num_anchors\n )\n ])\n # Figure out which control points will give the\n # Appropriate tangent lines to the circle\n d_theta = self.angle / (self.num_anchors - 1.0)\n tangent_vectors = np.zeros(anchors.shape)\n tangent_vectors[:, 1] = anchors[:, 0]\n tangent_vectors[:, 0] = -anchors[:, 1]\n handles1 = anchors[:-1] + (d_theta / 3) * tangent_vectors[:-1]\n handles2 = anchors[1:] - (d_theta / 3) * tangent_vectors[1:]\n self.set_anchors_and_handles(\n anchors, handles1, handles2\n )\n self.scale(self.radius, about_point=ORIGIN)\n self.shift(self.arc_center)\n\n def add_tip(self, tip_length=0.25, at_start=False, at_end=True):\n # clear out any old tips\n for submob in self.submobjects:\n if submob.mark_paths_closed:\n self.remove(submob)\n\n # TODO, do this a better way\n p1 = p2 = p3 = p4 = None\n start_arrow = end_arrow = None\n if at_end:\n p1, p2 = self.points[-3:-1]\n # self.points[-2:] did overshoot\n start_arrow = Arrow(\n p1, 2 * p2 - p1,\n tip_length=tip_length,\n max_tip_length_to_length_ratio=2.0\n )\n self.add(start_arrow.split()[-1]) # just the tip\n\n if at_start:\n p4, p3 = self.points[1:3]\n # self.points[:2] did overshoot\n end_arrow = Arrow(\n p3, 2 * p4 - p3,\n tip_length=tip_length,\n max_tip_length_to_length_ratio=2.0\n )\n self.add(end_arrow.split()[-1])\n\n self.set_color(self.get_color())\n return self\n\n def get_arc_center(self):\n first_point = self.points[0]\n radial_unit_vector = np.array(\n [np.cos(self.start_angle), np.sin(self.start_angle), 0])\n arc_center = first_point - self.radius * radial_unit_vector\n return arc_center\n\n def move_arc_center_to(self, point):\n v = point - self.get_arc_center()\n self.shift(v)\n return self\n\n def stop_angle(self):\n return self.start_angle + self.angle\n\n def set_bound_angles(self, start=0, stop=np.pi):\n self.start_angle = start\n self.angle = stop - start\n\n return self\n\n\nclass ArcBetweenPoints(Arc):\n\n def __init__(self, start_point, end_point, angle=TAU / 4, **kwargs):\n if angle == 0:\n raise Exception(\"Arc with zero curve angle: use Line instead.\")\n\n midpoint = 0.5 * (start_point + end_point)\n distance_vector = end_point - start_point\n normal_vector = np.array([-distance_vector[1], distance_vector[0], 0])\n distance = get_norm(normal_vector)\n normal_vector /= distance\n if angle < 0:\n normal_vector *= -1\n\n radius = distance / 2 / np.sin(0.5 * np.abs(angle))\n length = distance / 2 / np.tan(0.5 * np.abs(angle))\n arc_center = midpoint + length * normal_vector\n w = start_point - arc_center\n if w[0] != 0:\n start_angle = np.arctan2(w[1], w[0])\n else:\n start_angle = np.pi / 2\n\n Arc.__init__(self, angle,\n radius=radius,\n start_angle=start_angle,\n **kwargs)\n\n self.move_arc_center_to(arc_center)\n\n\nclass CurvedArrow(ArcBetweenPoints):\n\n def __init__(self, start_point, end_point, angle=TAU / 4, **kwargs):\n # I know this is in reverse, but it works\n if angle >= 0:\n ArcBetweenPoints.__init__(\n self, start_point, end_point, angle=angle, **kwargs)\n self.add_tip(at_start=True, at_end=False)\n else:\n ArcBetweenPoints.__init__(\n self, end_point, start_point, angle=-angle, **kwargs)\n self.add_tip(at_start=False, at_end=True)\n\n\nclass CurvedDoubleArrow(ArcBetweenPoints):\n\n def __init__(self, start_point, end_point, angle=TAU / 4, **kwargs):\n ArcBetweenPoints.__init__(\n self, start_point, end_point, angle=angle, **kwargs)\n self.add_tip(at_start=True, at_end=True)\n\n\nclass Circle(Arc):\n CONFIG = {\n \"color\": RED,\n \"close_new_points\": True,\n \"anchors_span_full_range\": False\n }\n\n def __init__(self, **kwargs):\n Arc.__init__(self, TAU, **kwargs)\n\n def surround(self, mobject, dim_to_match=0, stretch=False, buffer_factor=1.2):\n # Ignores dim_to_match and stretch; result will always be a circle\n # TODO: Perhaps create an ellipse class to handle singele-dimension stretching\n\n # Something goes wrong here when surrounding lines?\n # TODO: Figure out and fix\n self.replace(mobject, dim_to_match, stretch)\n\n self.set_width(\n np.sqrt(mobject.get_width()**2 + mobject.get_height()**2))\n self.scale(buffer_factor)\n\n def get_point_from_angle(self, angle):\n start_angle = angle_of_vector(\n self.points[0] - self.get_center()\n )\n return self.point_from_proportion(\n (angle - start_angle) / TAU\n )\n\n\nclass Dot(Circle):\n CONFIG = {\n \"radius\": 0.08,\n \"stroke_width\": 0,\n \"fill_opacity\": 1.0,\n \"color\": WHITE\n }\n\n def __init__(self, point=ORIGIN, **kwargs):\n Circle.__init__(self, **kwargs)\n self.shift(point)\n self.init_colors()\n\n\nclass Ellipse(VMobject):\n CONFIG = {\n \"width\": 2,\n \"height\": 1\n }\n\n def generate_points(self):\n circle = Circle(radius=1)\n circle = circle.stretch_to_fit_width(self.width)\n circle = circle.stretch_to_fit_height(self.height)\n self.points = circle.points\n\n\nclass AnnularSector(VMobject):\n CONFIG = {\n \"inner_radius\": 1,\n \"outer_radius\": 2,\n \"angle\": TAU / 4,\n \"start_angle\": 0,\n \"fill_opacity\": 1,\n \"stroke_width\": 0,\n \"color\": WHITE,\n \"mark_paths_closed\": True,\n }\n\n def generate_points(self):\n arc1 = Arc(\n angle=self.angle,\n start_angle=self.start_angle,\n radius=self.inner_radius,\n )\n arc2 = Arc(\n angle=-1 * self.angle,\n start_angle=self.start_angle + self.angle,\n radius=self.outer_radius,\n )\n a1_to_a2_points = np.array([\n interpolate(arc1.points[-1], arc2.points[0], alpha)\n for alpha in np.linspace(0, 1, 4)\n ])\n a2_to_a1_points = np.array([\n interpolate(arc2.points[-1], arc1.points[0], alpha)\n for alpha in np.linspace(0, 1, 4)\n ])\n self.points = np.array(arc1.points)\n self.add_control_points(a1_to_a2_points[1:])\n self.add_control_points(arc2.points[1:])\n self.add_control_points(a2_to_a1_points[1:])\n\n def get_arc_center(self):\n first_point = self.points[0]\n last_point = self.points[-2]\n v = last_point - first_point\n radial_unit_vector = v / get_norm(v)\n arc_center = first_point - self.inner_radius * radial_unit_vector\n return arc_center\n\n def move_arc_center_to(self, point):\n v = point - self.get_arc_center()\n self.shift(v)\n return self\n\n\nclass Sector(AnnularSector):\n CONFIG = {\n \"outer_radius\": 1,\n \"inner_radius\": 0\n }\n\n @property\n def radius(self):\n return self.outer_radius\n\n @radius.setter\n def radius(self, new_radius):\n self.outer_radius = new_radius\n\n\nclass Annulus(Circle):\n CONFIG = {\n \"inner_radius\": 1,\n \"outer_radius\": 2,\n \"fill_opacity\": 1,\n \"stroke_width\": 0,\n \"color\": WHITE,\n \"mark_paths_closed\": False,\n \"propagate_style_to_family\": True\n }\n\n def generate_points(self):\n self.points = []\n self.radius = self.outer_radius\n outer_circle = Circle(radius=self.outer_radius)\n inner_circle = Circle(radius=self.inner_radius)\n inner_circle.flip()\n self.points = outer_circle.points\n self.add_subpath(inner_circle.points)\n\n\nclass Line(VMobject):\n CONFIG = {\n \"buff\": 0,\n \"path_arc\": None, # angle of arc specified here\n \"n_arc_anchors\": 10, # Only used if path_arc is not None\n }\n\n def __init__(self, start, end, **kwargs):\n digest_config(self, kwargs)\n self.set_start_and_end(start, end)\n VMobject.__init__(self, **kwargs)\n\n def generate_points(self):\n if self.path_arc is None:\n self.set_points_as_corners([self.start, self.end])\n else:\n path_func = path_along_arc(self.path_arc)\n self.set_points_smoothly([\n path_func(self.start, self.end, alpha)\n for alpha in np.linspace(0, 1, self.n_arc_anchors)\n ])\n self.account_for_buff()\n\n def set_path_arc(self, new_value):\n self.path_arc = new_value\n self.generate_points()\n\n def account_for_buff(self):\n length = self.get_arc_length()\n if length < 2 * self.buff or self.buff == 0:\n return\n buff_proportion = self.buff / length\n self.pointwise_become_partial(\n self, buff_proportion, 1 - buff_proportion\n )\n\n def set_start_and_end(self, start, end):\n start_to_end = self.pointify(end) - self.pointify(start)\n vect = np.zeros(len(start_to_end))\n longer_dim = np.argmax(list(map(abs, start_to_end)))\n vect[longer_dim] = start_to_end[longer_dim]\n self.start, self.end = [\n arg.get_edge_center(unit * vect)\n if isinstance(arg, Mobject)\n else np.array(arg)\n for arg, unit in zip([start, end], [1, -1])\n ]\n\n def pointify(self, mob_or_point):\n if isinstance(mob_or_point, Mobject):\n return mob_or_point.get_center()\n return np.array(mob_or_point)\n\n def get_length(self):\n start, end = self.get_start_and_end()\n return get_norm(start - end)\n\n def get_arc_length(self):\n if self.path_arc:\n anchors = self.get_anchors()\n return sum([\n get_norm(a2 - a1)\n for a1, a2 in zip(anchors, anchors[1:])\n ])\n else:\n return self.get_length()\n\n def get_start_and_end(self):\n return self.get_start(), self.get_end()\n\n def get_vector(self):\n return self.get_end() - self.get_start()\n\n def get_unit_vector(self):\n vect = self.get_vector()\n norm = get_norm(vect)\n if norm == 0:\n # TODO, is this the behavior I want?\n return np.array(ORIGIN)\n return vect / norm\n\n def get_start(self):\n return np.array(self.points[0])\n\n def get_end(self):\n return np.array(self.points[-1])\n\n def get_slope(self):\n start, end = self.get_start_and_end()\n rise, run = [\n float(end[i] - start[i])\n for i in [1, 0]\n ]\n return np.inf if run == 0 else rise / run\n\n def get_angle(self):\n start, end = self.get_start_and_end()\n return angle_of_vector(end - start)\n\n def set_angle(self, angle):\n self.rotate(\n angle - self.get_angle(),\n about_point=self.get_start(),\n )\n\n def put_start_and_end_on(self, new_start, new_end):\n self.start = new_start\n self.end = new_end\n self.buff = 0\n self.generate_points()\n return\n\n def put_start_and_end_on_with_projection(self, new_start, new_end):\n target_vect = np.array(new_end) - np.array(new_start)\n curr_vect = self.get_vector()\n curr_norm = get_norm(curr_vect)\n if curr_norm == 0:\n self.put_start_and_end_on(new_start, new_end)\n return\n target_norm = get_norm(target_vect)\n if target_norm == 0:\n epsilon = 0.001\n self.scale(epsilon / curr_norm)\n self.move_to(new_start)\n return\n unit_target = target_vect / target_norm\n unit_curr = curr_vect / curr_norm\n normal = np.cross(unit_target, unit_curr)\n if get_norm(normal) == 0:\n if unit_curr[0] == 0 and unit_curr[1] == 0:\n normal = UP\n else:\n normal = OUT\n angle_diff = np.arccos(\n np.clip(np.dot(unit_target, unit_curr), -1, 1)\n )\n self.scale(target_norm / curr_norm)\n self.rotate(-angle_diff, normal)\n self.shift(new_start - self.get_start())\n return self\n\n\nclass DashedLine(Line):\n CONFIG = {\n \"dashed_segment_length\": 0.05\n }\n\n def __init__(self, *args, **kwargs):\n self.init_kwargs = kwargs\n Line.__init__(self, *args, **kwargs)\n\n def generate_points(self):\n length = get_norm(self.end - self.start)\n if length == 0:\n self.add(Line(self.start, self.end))\n return self\n num_interp_points = int(length / self.dashed_segment_length)\n # Even number ensures that start and end points are hit\n if num_interp_points % 2 == 1:\n num_interp_points += 1\n points = [\n interpolate(self.start, self.end, alpha)\n for alpha in np.linspace(0, 1, num_interp_points)\n ]\n includes = it.cycle([True, False])\n self.submobjects = [\n Line(p1, p2, **self.init_kwargs)\n for p1, p2, include in zip(points, points[1:], includes)\n if include\n ]\n self.put_start_and_end_on_with_projection(self.start, self.end)\n return self\n\n def get_start(self):\n if len(self.points) > 0:\n return self[0].points[0]\n else:\n return self.start\n\n def get_end(self):\n if len(self) > 0:\n return self[-1].points[-1]\n else:\n return self.end\n\n\nclass Elbow(VMobject):\n CONFIG = {\n \"width\": 0.2,\n \"angle\": 0,\n }\n\n def __init__(self, **kwargs):\n VMobject.__init__(self, **kwargs)\n self.set_points_as_corners([UP, UP + RIGHT, RIGHT])\n self.set_width(self.width, about_point=ORIGIN)\n self.rotate(self.angle, about_point=ORIGIN)\n\n\nclass Arrow(Line):\n CONFIG = {\n \"tip_length\": 0.25,\n \"tip_width_to_length_ratio\": 1,\n \"max_tip_length_to_length_ratio\": 0.35,\n \"max_stem_width_to_tip_width_ratio\": 0.3,\n \"buff\": MED_SMALL_BUFF,\n \"propagate_style_to_family\": False,\n \"preserve_tip_size_when_scaling\": True,\n \"normal_vector\": OUT,\n \"use_rectangular_stem\": True,\n \"rectangular_stem_width\": 0.05,\n }\n\n def __init__(self, *args, **kwargs):\n points = list(map(self.pointify, args))\n if len(args) == 1:\n args = (points[0] + UP + LEFT, points[0])\n Line.__init__(self, *args, **kwargs)\n self.init_tip()\n if self.use_rectangular_stem and not hasattr(self, \"rect\"):\n self.add_rectangular_stem()\n self.init_colors()\n\n def init_tip(self):\n self.add_tip()\n\n def add_tip(self, add_at_end=True):\n tip = VMobject(\n close_new_points=True,\n mark_paths_closed=True,\n fill_color=self.color,\n fill_opacity=1,\n stroke_color=self.color,\n stroke_width=0,\n )\n tip.add_at_end = add_at_end\n self.set_tip_points(tip, add_at_end, preserve_normal=False)\n self.add(tip)\n if not hasattr(self, 'tip'):\n self.tip = VGroup()\n self.tip.match_style(tip)\n self.tip.add(tip)\n return tip\n\n def add_rectangular_stem(self):\n self.rect = Rectangle(\n stroke_width=0,\n fill_color=self.tip.get_fill_color(),\n fill_opacity=self.tip.get_fill_opacity()\n )\n self.add_to_back(self.rect)\n self.set_stroke(width=0)\n self.set_rectangular_stem_points()\n\n def set_rectangular_stem_points(self):\n start, end = self.get_start_and_end()\n tip_base_points = self.tip[0].get_anchors()[1:3]\n tip_base = center_of_mass(tip_base_points)\n tbp1, tbp2 = tip_base_points\n perp_vect = tbp2 - tbp1\n tip_base_width = get_norm(perp_vect)\n if tip_base_width > 0:\n perp_vect /= tip_base_width\n width = min(\n self.rectangular_stem_width,\n self.max_stem_width_to_tip_width_ratio * tip_base_width,\n )\n if hasattr(self, \"second_tip\"):\n start = center_of_mass(\n self.second_tip.get_anchors()[1:]\n )\n self.rect.set_points_as_corners([\n tip_base - perp_vect * width / 2,\n start - perp_vect * width / 2,\n start + perp_vect * width / 2,\n tip_base + perp_vect * width / 2,\n ])\n self.stem = self.rect # Alternate name\n return self\n\n def set_tip_points(\n self, tip,\n add_at_end=True,\n tip_length=None,\n preserve_normal=True,\n ):\n if tip_length is None:\n tip_length = self.tip_length\n if preserve_normal:\n normal_vector = self.get_normal_vector()\n else:\n normal_vector = self.normal_vector\n line_length = get_norm(self.points[-1] - self.points[0])\n tip_length = min(\n tip_length, self.max_tip_length_to_length_ratio * line_length\n )\n\n indices = (-2, -1) if add_at_end else (1, 0)\n pre_end_point, end_point = [\n self.get_anchors()[index]\n for index in indices\n ]\n vect = end_point - pre_end_point\n perp_vect = np.cross(vect, normal_vector)\n for v in vect, perp_vect:\n if get_norm(v) == 0:\n v[0] = 1\n v *= tip_length / get_norm(v)\n ratio = self.tip_width_to_length_ratio\n tip.set_points_as_corners([\n end_point,\n end_point - vect + perp_vect * ratio / 2,\n end_point - vect - perp_vect * ratio / 2,\n ])\n\n return self\n\n def get_normal_vector(self):\n p0, p1, p2 = self.tip[0].get_anchors()[:3]\n result = np.cross(p2 - p1, p1 - p0)\n norm = get_norm(result)\n if norm == 0:\n return self.normal_vector\n else:\n return result / norm\n\n def reset_normal_vector(self):\n self.normal_vector = self.get_normal_vector()\n return self\n\n def get_end(self):\n if hasattr(self, \"tip\"):\n return self.tip[0].get_anchors()[0]\n else:\n return Line.get_end(self)\n\n def get_tip(self):\n return self.tip\n\n def put_start_and_end_on(self, *args, **kwargs):\n Line.put_start_and_end_on(self, *args, **kwargs)\n self.set_tip_points(self.tip[0], preserve_normal=False)\n self.set_rectangular_stem_points()\n return self\n\n def scale(self, scale_factor, **kwargs):\n Line.scale(self, scale_factor, **kwargs)\n if self.preserve_tip_size_when_scaling:\n for t in self.tip:\n self.set_tip_points(t, add_at_end=t.add_at_end)\n if self.use_rectangular_stem:\n self.set_rectangular_stem_points()\n return self\n\n def copy(self):\n return self.deepcopy()\n\n\nclass Vector(Arrow):\n CONFIG = {\n \"color\": YELLOW,\n \"buff\": 0,\n }\n\n def __init__(self, direction, **kwargs):\n if len(direction) == 2:\n direction = np.append(np.array(direction), 0)\n Arrow.__init__(self, ORIGIN, direction, **kwargs)\n\n\nclass DoubleArrow(Arrow):\n def init_tip(self):\n self.tip = VGroup()\n for b in True, False:\n t = self.add_tip(add_at_end=b)\n t.add_at_end = b\n self.tip.add(t)\n self.tip.match_style(self.tip[0])\n\n\nclass CubicBezier(VMobject):\n def __init__(self, points, **kwargs):\n VMobject.__init__(self, **kwargs)\n self.set_points(points)\n\n\nclass Polygon(VMobject):\n CONFIG = {\n \"color\": GREEN_D,\n \"mark_paths_closed\": True,\n \"close_new_points\": True,\n }\n\n def __init__(self, *vertices, **kwargs):\n assert len(vertices) > 1\n digest_locals(self)\n VMobject.__init__(self, **kwargs)\n\n def generate_points(self):\n self.set_anchor_points(self.vertices, mode=\"corners\")\n\n def get_vertices(self):\n return self.get_anchors_and_handles()[0]\n\n\nclass RegularPolygon(Polygon):\n CONFIG = {\n \"start_angle\": 0\n }\n\n def __init__(self, n=3, **kwargs):\n digest_config(self, kwargs, locals())\n start_vect = rotate_vector(RIGHT, self.start_angle)\n vertices = compass_directions(n, start_vect)\n Polygon.__init__(self, *vertices, **kwargs)\n\n\nclass Rectangle(VMobject):\n CONFIG = {\n \"color\": WHITE,\n \"height\": 2.0,\n \"width\": 4.0,\n \"mark_paths_closed\": True,\n \"close_new_points\": True,\n }\n\n def generate_points(self):\n y, x = self.height / 2., self.width / 2.\n self.set_anchor_points([\n x * LEFT + y * UP,\n x * RIGHT + y * UP,\n x * RIGHT + y * DOWN,\n x * LEFT + y * DOWN\n ], mode=\"corners\")\n\n\nclass Square(Rectangle):\n CONFIG = {\n \"side_length\": 2.0,\n }\n\n def __init__(self, **kwargs):\n digest_config(self, kwargs)\n Rectangle.__init__(\n self,\n height=self.side_length,\n width=self.side_length,\n **kwargs\n )\n\n\nclass RoundedRectangle(Rectangle):\n CONFIG = {\n \"corner_radius\": 0.5,\n \"close_new_points\": True\n }\n\n def generate_points(self):\n y, x = self.height / 2., self.width / 2.\n r = self.corner_radius\n\n arc_ul = ArcBetweenPoints(x * LEFT + (y - r) * UP, (x - r) * LEFT + y * UP, angle = -TAU/4)\n arc_ur = ArcBetweenPoints((x - r) * RIGHT + y * UP, x * RIGHT + (y - r) * UP, angle = -TAU/4)\n arc_lr = ArcBetweenPoints(x * RIGHT + (y - r) * DOWN, (x - r) * RIGHT + y * DOWN, angle = -TAU/4)\n arc_ll = ArcBetweenPoints(x * LEFT + (y - r) * DOWN, (x - r) * LEFT + y * DOWN, angle = TAU/4) # sic! bug in ArcBetweenPoints?\n \n points = arc_ul.points\n points = np.append(points,np.array([y * UP]), axis = 0)\n points = np.append(points,np.array([y * UP]), axis = 0)\n points = np.append(points,arc_ur.points, axis = 0)\n points = np.append(points,np.array([x * RIGHT]), axis = 0)\n points = np.append(points,np.array([x * RIGHT]), axis = 0)\n points = np.append(points,arc_lr.points, axis = 0)\n points = np.append(points,np.array([y * DOWN]), axis = 0)\n points = np.append(points,np.array([y * DOWN]), axis = 0)\n points = np.append(points,arc_ll.points[::-1], axis = 0) # sic! see comment above\n points = np.append(points,np.array([x * LEFT]), axis = 0)\n points = np.append(points,np.array([x * LEFT]), axis = 0)\n points = np.append(points,np.array([x * LEFT + (y - r) * UP]), axis = 0)\n\n points = points[::-1]\n\n self.set_points(points)\n\n\nclass Grid(VMobject):\n CONFIG = {\n \"height\": 6.0,\n \"width\": 6.0,\n }\n\n def __init__(self, rows, columns, **kwargs):\n digest_config(self, kwargs, locals())\n VMobject.__init__(self, **kwargs)\n\n def generate_points(self):\n x_step = self.width / self.columns\n y_step = self.height / self.rows\n\n for x in np.arange(0, self.width + x_step, x_step):\n self.add(Line(\n [x - self.width / 2., -self.height / 2., 0],\n [x - self.width / 2., self.height / 2., 0],\n ))\n for y in np.arange(0, self.height + y_step, y_step):\n self.add(Line(\n [-self.width / 2., y - self.height / 2., 0],\n [self.width / 2., y - self.height / 2., 0]\n ))\n" ]
[ [ "numpy.dot", "numpy.abs", "numpy.linspace", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.arctan2", "numpy.append", "numpy.cross", "numpy.array", "numpy.zeros" ] ]
zhaonan68/QUANTAXIS
[ "b7d0108124b05168c82a53f00a11ba40a39a3964" ]
[ "QUANTAXIS/QASU/save_tdx.py" ]
[ "# coding:utf-8\n#\n# The MIT License (MIT)\n#\n# Copyright (c) 2016-2018 yutiansut/QUANTAXIS\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport concurrent\nimport datetime\nfrom concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor\nimport json\nimport pandas as pd\nimport pymongo\n\nfrom QUANTAXIS.QAFetch import QA_fetch_get_stock_block\nfrom QUANTAXIS.QAFetch.QATdx import (\n QA_fetch_get_option_day,\n QA_fetch_get_option_min,\n QA_fetch_get_index_day,\n QA_fetch_get_index_min,\n QA_fetch_get_stock_day,\n QA_fetch_get_stock_info,\n QA_fetch_get_stock_list,\n QA_fetch_get_future_list,\n QA_fetch_get_index_list,\n QA_fetch_get_future_day,\n QA_fetch_get_future_min,\n QA_fetch_get_stock_min,\n QA_fetch_get_stock_transaction,\n QA_fetch_get_stock_xdxr, select_best_ip)\nfrom QUANTAXIS.QAFetch.QATdx import (\n QA_fetch_get_50etf_option_contract_time_to_market,\n QA_fetch_get_commodity_option_CU_contract_time_to_market,\n QA_fetch_get_commodity_option_SR_contract_time_to_market,\n QA_fetch_get_commodity_option_M_contract_time_to_market,\n QA_fetch_get_50etf_option_contract_time_to_market,\n)\nfrom QUANTAXIS.QAUtil import (DATABASE, QA_util_get_next_day,\n QA_util_get_real_date, QA_util_log_info,\n QA_util_to_json_from_pandas, trade_date_sse)\n\n# ip=select_best_ip()\n\n\ndef now_time():\n return str(QA_util_get_real_date(str(datetime.date.today() - datetime.timedelta(days=1)), trade_date_sse, -1)) + \\\n ' 17:00:00' if datetime.datetime.now().hour < 15 else str(QA_util_get_real_date(\n str(datetime.date.today()), trade_date_sse, -1)) + ' 15:00:00'\n\n\n\n\ndef QA_SU_save_stock_day(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n save stock_day\n 保存日线数据\n :param client:\n :param ui_log: 给GUI qt 界面使用\n :param ui_progress: 给GUI qt 界面使用\n :param ui_progress_int_value: 给GUI qt 界面使用\n :return:\n '''\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n coll_stock_day = client.stock_day\n coll_stock_day.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_stock_day):\n try:\n QA_util_log_info(\n '##JOB01 Now Saving STOCK_DAY==== {}'.format(str(code)), ui_log)\n\n # 首选查找数据库 是否 有 这个代码的数据\n ref = coll_stock_day.find({'code': str(code)[0:6]})\n end_date = str(now_time())[0:10]\n\n # 当前数据库已经包含了这个代码的数据, 继续增量更新\n # 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现\n if ref.count() > 0:\n\n # 接着上次获取的日期继续更新\n start_date = ref[ref.count() - 1]['date']\n\n QA_util_log_info('UPDATE_STOCK_DAY \\n Trying updating {} from {} to {}'.format(\n code, start_date, end_date), ui_log)\n if start_date != end_date:\n coll_stock_day.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), QA_util_get_next_day(start_date), end_date, '00')))\n\n # 当前数据库中没有这个代码的股票数据, 从1990-01-01 开始下载所有的数据\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_STOCK_DAY \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log)\n if start_date != end_date:\n coll_stock_day.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), start_date, end_date, '00')))\n except Exception as error0:\n print(error0)\n err.append(str(code))\n\n for item in range(len(stock_list)):\n QA_util_log_info('The {} of Total {}'.format\n (item, len(stock_list)))\n\n strProgressToLog = 'DOWNLOAD PROGRESS {} {}'.format(\n str(float(item / len(stock_list) * 100))[0:4] + '%', ui_log)\n intProgressToLog = int(float(item / len(stock_list) * 100))\n QA_util_log_info(strProgressToLog, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intProgressToLog)\n\n __saving_work(stock_list[item], coll_stock_day)\n\n if len(err) < 1:\n QA_util_log_info('SUCCESS save stock day ^_^', ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log)\n QA_util_log_info(err, ui_log)\n\n\ndef QA_SU_save_stock_week(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_week\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n coll_stock_week = client.stock_week\n coll_stock_week.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_stock_week):\n try:\n QA_util_log_info('##JOB01 Now Saving STOCK_WEEK==== {}'.format(\n str(code)), ui_log=ui_log)\n\n ref = coll_stock_week.find({'code': str(code)[0:6]})\n end_date = str(now_time())[0:10]\n if ref.count() > 0:\n # 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现\n\n start_date = ref[ref.count() - 1]['date']\n\n QA_util_log_info('UPDATE_STOCK_WEEK \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n coll_stock_week.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), QA_util_get_next_day(start_date), end_date, '00', frequence='week')))\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_STOCK_WEEK \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n coll_stock_week.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), start_date, end_date, '00', frequence='week')))\n except:\n err.append(str(code))\n for item in range(len(stock_list)):\n QA_util_log_info('The {} of Total {}'.format\n (item, len(stock_list)), ui_log=ui_log)\n strProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(item / len(stock_list) * 100))[0:4] + '%')\n intProgress = int(float(item / len(stock_list) * 100))\n QA_util_log_info(strProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intProgress)\n\n __saving_work(stock_list[item], coll_stock_week)\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_stock_month(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_month\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n coll_stock_month = client.stock_month\n coll_stock_month.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_stock_month):\n try:\n QA_util_log_info('##JOB01 Now Saving STOCK_MONTH==== {}'.format(\n str(code)), ui_log=ui_log)\n\n ref = coll_stock_month.find({'code': str(code)[0:6]})\n end_date = str(now_time())[0:10]\n if ref.count() > 0:\n # 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现\n\n start_date = ref[ref.count() - 1]['date']\n\n QA_util_log_info('UPDATE_STOCK_MONTH \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n coll_stock_month.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), QA_util_get_next_day(start_date), end_date, '00', frequence='month')))\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_STOCK_MONTH \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n coll_stock_month.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), start_date, end_date, '00', frequence='month')))\n except:\n err.append(str(code))\n for item in range(len(stock_list)):\n QA_util_log_info('The {} of Total {}'.format(\n item, len(stock_list)), ui_log=ui_log)\n strProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(item / len(stock_list) * 100))[0:4] + '%')\n intProgress = int(float(item / len(stock_list) * 100))\n QA_util_log_info(strProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intProgress)\n\n __saving_work(stock_list[item], coll_stock_month)\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info('ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_stock_year(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_year\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n coll_stock_year = client.stock_year\n coll_stock_year.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_stock_year):\n try:\n QA_util_log_info(\n '##JOB01 Now Saving STOCK_YEAR==== {}'.format(str(code)), ui_log=ui_log)\n\n ref = coll_stock_year.find({'code': str(code)[0:6]})\n end_date = str(now_time())[0:10]\n if ref.count() > 0:\n # 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现\n\n start_date = ref[ref.count() - 1]['date']\n\n QA_util_log_info('UPDATE_STOCK_YEAR \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n coll_stock_year.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), QA_util_get_next_day(start_date), end_date, '00', frequence='year')))\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_STOCK_YEAR \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n coll_stock_year.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), start_date, end_date, '00', frequence='year')))\n except:\n err.append(str(code))\n for item in range(len(stock_list)):\n QA_util_log_info('The {} of Total {}'.format(\n item, len(stock_list)), ui_log=ui_log)\n\n strProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(item / len(stock_list) * 100))[0:4] + '%')\n intProgress = int(float(item / len(stock_list) * 100))\n QA_util_log_info(strProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intProgress)\n\n __saving_work(stock_list[item], coll_stock_year)\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_stock_xdxr(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"[summary]\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n #client.drop_collection('stock_xdxr')\n try:\n \n coll = client.stock_xdxr\n coll.create_index([('code', pymongo.ASCENDING),\n ('date', pymongo.ASCENDING)], unique=True)\n except:\n client.drop_collection('stock_xdxr')\n coll = client.stock_xdxr\n coll.create_index([('code', pymongo.ASCENDING),\n ('date', pymongo.ASCENDING)], unique=True)\n err = []\n\n def __saving_work(code, coll):\n QA_util_log_info('##JOB02 Now Saving XDXR INFO ==== {}'.format(\n str(code)), ui_log=ui_log)\n try:\n coll.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_xdxr(str(code))), ordered=False)\n\n except:\n\n err.append(str(code))\n for i_ in range(len(stock_list)):\n QA_util_log_info('The {} of Total {}'.format(\n i_, len(stock_list)), ui_log=ui_log)\n strLogInfo = 'DOWNLOAD PROGRESS {} '.format(\n str(float(i_ / len(stock_list) * 100))[0:4] + '%')\n intLogProgress = int(float(i_ / len(stock_list) * 100))\n QA_util_log_info(strLogInfo, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n __saving_work(stock_list[i_], coll)\n\n\ndef QA_SU_save_stock_min(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_min\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n coll = client.stock_min\n coll.create_index([('code', pymongo.ASCENDING), ('time_stamp',\n pymongo.ASCENDING), ('date_stamp', pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll):\n QA_util_log_info(\n '##JOB03 Now Saving STOCK_MIN ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find(\n {'code': str(code)[0:6], 'type': type})\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB03.{} Now Saving {} from {} to {} =={} '.format(['1min', '5min', '15min', '30min', '60min'].index(type),\n str(code), start_time, end_time, type),\n ui_log=ui_log)\n if start_time != end_time:\n __data = QA_fetch_get_stock_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data)[1::])\n else:\n start_time = '2015-01-01'\n QA_util_log_info(\n '##JOB03.{} Now Saving {} from {} to {} =={} '.format(['1min', '5min', '15min', '30min', '60min'].index(type),\n str(code), start_time, end_time, type),\n ui_log=ui_log)\n if start_time != end_time:\n __data = QA_fetch_get_stock_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data))\n except Exception as e:\n QA_util_log_info(e, ui_log=ui_log)\n err.append(code)\n QA_util_log_info(err, ui_log=ui_log)\n\n executor = ThreadPoolExecutor(max_workers=4)\n #executor.map((__saving_work, stock_list[i_], coll),URLS)\n res = {executor.submit(\n __saving_work, stock_list[i_], coll) for i_ in range(len(stock_list))}\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n QA_util_log_info('The {} of Total {}'.format(\n count, len(stock_list)), ui_log=ui_log)\n\n strProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(stock_list) * 100))[0:4] + '%')\n intProgress = int(count / len(stock_list) * 10000.0)\n QA_util_log_info(strProgress, ui_log, ui_progress=ui_progress,\n ui_progress_int_value=intProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_index_day(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save index_day\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n __index_list = QA_fetch_get_stock_list('index')\n coll = client.index_day\n coll.create_index([('code', pymongo.ASCENDING),\n ('date_stamp', pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll):\n\n try:\n ref_ = coll.find({'code': str(code)[0:6]})\n end_time = str(now_time())[0:10]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['date']\n\n QA_util_log_info('##JOB04 Now Saving INDEX_DAY==== \\n Trying updating {} from {} to {}'.format\n (code, start_time, end_time), ui_log=ui_log)\n\n if start_time != end_time:\n coll.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_index_day(str(code), QA_util_get_next_day(start_time), end_time)))\n else:\n try:\n start_time = '1990-01-01'\n QA_util_log_info('##JOB04 Now Saving INDEX_DAY==== \\n Trying updating {} from {} to {}'.format\n (code, start_time, end_time), ui_log=ui_log)\n coll.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_index_day(str(code), start_time, end_time)))\n except:\n start_time = '2009-01-01'\n QA_util_log_info('##JOB04 Now Saving INDEX_DAY==== \\n Trying updating {} from {} to {}'.format\n (code, start_time, end_time), ui_log=ui_log)\n coll.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_index_day(str(code), start_time, end_time)))\n except Exception as e:\n QA_util_log_info(e, ui_log=ui_log)\n err.append(str(code))\n QA_util_log_info(err, ui_log=ui_log)\n\n for i_ in range(len(__index_list)):\n # __saving_work('000001')\n QA_util_log_info('The {} of Total {}'.format(\n i_, len(__index_list)), ui_log=ui_log)\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(i_ / len(__index_list) * 100))[0:4] + '%')\n intLogProgress = int(float(i_ / len(__index_list) * 10000.0))\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n __saving_work(__index_list.index[i_][0], coll)\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_index_min(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save index_min\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n __index_list = QA_fetch_get_stock_list('index')\n coll = client.index_min\n coll.create_index([('code', pymongo.ASCENDING), ('time_stamp',\n pymongo.ASCENDING), ('date_stamp', pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll):\n\n QA_util_log_info(\n '##JOB05 Now Saving Index_MIN ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find(\n {'code': str(code)[0:6], 'type': type})\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB05.{} Now Saving {} from {} to {} =={} '.\n format(['1min', '5min', '15min', '30min', '60min'].\n index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_index_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data[1::]))\n else:\n start_time = '2015-01-01'\n\n QA_util_log_info(\n '##JOB05.{} Now Saving {} from {} to {} =={} '.\n format(['1min', '5min', '15min', '30min', '60min'].\n index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_index_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data))\n except:\n err.append(code)\n\n executor = ThreadPoolExecutor(max_workers=4)\n\n res = {executor.submit(\n __saving_work, __index_list.index[i_][0], coll) for i_ in range(len(__index_list))} # multi index ./.\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(__index_list) * 100))[0:4] + '%')\n intLogProgress = int(float(count / len(__index_list) * 10000.0))\n QA_util_log_info('The {} of Total {}'.format(\n count, len(__index_list)), ui_log=ui_log)\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_etf_day(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save etf_day\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n __index_list = QA_fetch_get_stock_list('etf')\n coll = client.index_day\n coll.create_index([('code', pymongo.ASCENDING),\n ('date_stamp', pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll):\n\n try:\n\n ref_ = coll.find({'code': str(code)[0:6]})\n end_time = str(now_time())[0:10]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['date']\n\n QA_util_log_info('##JOB06 Now Saving ETF_DAY==== \\n Trying updating {} from {} to {}'.format\n (code, start_time, end_time), ui_log=ui_log)\n\n if start_time != end_time:\n coll.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_index_day(str(code), QA_util_get_next_day(start_time), end_time)))\n else:\n start_time = '1990-01-01'\n QA_util_log_info('##JOB06 Now Saving ETF_DAY==== \\n Trying updating {} from {} to {}'.format\n (code, start_time, end_time), ui_log=ui_log)\n\n if start_time != end_time:\n coll.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_index_day(str(code), start_time, end_time)))\n except:\n err.append(str(code))\n for i_ in range(len(__index_list)):\n # __saving_work('000001')\n QA_util_log_info('The {} of Total {}'.format(\n i_, len(__index_list)), ui_log=ui_log)\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(i_ / len(__index_list) * 100))[0:4] + '%')\n intLogProgress = int(float(i_ / len(__index_list) * 10000.0))\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n\n __saving_work(__index_list.index[i_][0], coll)\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_etf_min(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save etf_min\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n __index_list = QA_fetch_get_stock_list('etf')\n coll = client.index_min\n coll.create_index([('code', pymongo.ASCENDING), ('time_stamp',\n pymongo.ASCENDING), ('date_stamp', pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll):\n\n QA_util_log_info(\n '##JOB07 Now Saving ETF_MIN ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find(\n {'code': str(code)[0:6], 'type': type})\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB07.{} Now Saving {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_index_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data[1::]))\n else:\n start_time = '2015-01-01'\n\n QA_util_log_info(\n '##JOB07.{} Now Saving {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type), ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_index_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data))\n except:\n err.append(code)\n\n executor = ThreadPoolExecutor(max_workers=4)\n\n res = {executor.submit(\n __saving_work, __index_list.index[i_][0], coll) for i_ in range(len(__index_list))} # multi index ./.\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n\n QA_util_log_info('The {} of Total {}'.format(\n count, len(__index_list)), ui_log=ui_log)\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(__index_list) * 100))[0:4] + '%')\n intLogProgress = int(float(count / len(__index_list) * 10000.0))\n\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_stock_list(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_list\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n client.drop_collection('stock_list')\n coll = client.stock_list\n coll.create_index('code')\n\n try:\n # 🛠todo 这个应该是第一个任务 JOB01, 先更新股票列表!!\n QA_util_log_info('##JOB08 Now Saving STOCK_LIST ====', ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=5000)\n stock_list_from_tdx = QA_fetch_get_stock_list()\n pandas_data = QA_util_to_json_from_pandas(stock_list_from_tdx)\n coll.insert_many(pandas_data)\n QA_util_log_info(\"完成股票列表获取\", ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=10000)\n except Exception as e:\n QA_util_log_info(e, ui_log=ui_log)\n print(\" Error save_tdx.QA_SU_save_stock_list exception!\")\n\n pass\n\n\ndef QA_SU_save_stock_block(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_block\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n client.drop_collection('stock_block')\n coll = client.stock_block\n coll.create_index('code')\n\n try:\n QA_util_log_info('##JOB09 Now Saving STOCK_BlOCK ====', ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=5000)\n coll.insert_many(QA_util_to_json_from_pandas(\n QA_fetch_get_stock_block('tdx')))\n QA_util_log_info('tdx Block ====', ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=5000)\n\n # 🛠todo fixhere here 获取同花顺板块, 还是调用tdx的\n coll.insert_many(QA_util_to_json_from_pandas(\n QA_fetch_get_stock_block('ths')))\n QA_util_log_info('ths Block ====', ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=8000)\n\n QA_util_log_info('完成股票板块获取=', ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=10000)\n\n except Exception as e:\n QA_util_log_info(e, ui_log=ui_log)\n print(\" Error save_tdx.QA_SU_save_stock_block exception!\")\n pass\n\n\ndef QA_SU_save_stock_info(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_info\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n client.drop_collection('stock_info')\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n coll = client.stock_info\n coll.create_index('code')\n err = []\n\n def __saving_work(code, coll):\n QA_util_log_info(\n '##JOB010 Now Saving STOCK INFO ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n coll.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_info(str(code))))\n\n except:\n err.append(str(code))\n for i_ in range(len(stock_list)):\n # __saving_work('000001')\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(i_ / len(stock_list) * 100))[0:4] + '%')\n intLogProgress = int(float(i_ / len(stock_list) * 10000.0))\n QA_util_log_info('The {} of Total {}'.format(i_, len(stock_list)))\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n\n __saving_work(stock_list[i_], coll)\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_stock_transaction(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_transaction\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n coll = client.stock_transaction\n coll.create_index('code')\n err = []\n\n def __saving_work(code):\n QA_util_log_info(\n '##JOB11 Now Saving STOCK_TRANSACTION ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n coll.insert_many(\n QA_util_to_json_from_pandas(\n # 🛠todo str(stock_list[code]) 参数不对?\n QA_fetch_get_stock_transaction(str(code), '1990-01-01', str(now_time())[0:10])))\n except:\n err.append(str(code))\n for i_ in range(len(stock_list)):\n # __saving_work('000001')\n QA_util_log_info('The {} of Total {}'.format(\n i_, len(stock_list)), ui_log=ui_log)\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(i_ / len(stock_list) * 100))[0:4] + '%')\n intLogProgress = int(float(i_ / len(stock_list) * 10000.0))\n\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n __saving_work(stock_list[i_])\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\n\ndef _save_option_commodity_sr_day(client=DATABASE, ui_log=None, ui_progress=None):\n ##################### sr 白糖 ############################################################################\n option_sr_contract_list = QA_fetch_get_commodity_option_SR_contract_time_to_market()\n coll_option_commodity_sr_day = client.option_commodity_sr_day\n coll_option_commodity_sr_day.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_option_commodity_sr_day):\n try:\n QA_util_log_info('##JOB12 Now Saving OPTION_DAY_COMMODITY_SR 白糖 ==== {}'.format(\n str(code)), ui_log=ui_log)\n\n # 首选查找数据库 是否 有 这个代码的数据\n ref = coll_option_commodity_sr_day.find({'code': str(code)[0:8]})\n end_date = str(now_time())[0:10]\n\n # 当前数据库已经包含了这个代码的数据, 继续增量更新\n # 加入这个判断的原因是因为如果是刚上市的 数据库会没有数据 所以会有负索引问题出现\n if ref.count() > 0:\n\n # 接着上次获取的日期继续更新\n start_date = ref[ref.count() - 1]['date']\n QA_util_log_info(' 上次获取期权sr白糖日线数据的最后日期是 {}'.format(\n start_date), ui_log=ui_log)\n\n QA_util_log_info('UPDATE_OPTION_M_DAY \\n 从上一次下载数据开始继续 Trying update {} from {} to {}'.format(\n code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n start_date0 = QA_util_get_next_day(start_date)\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date0, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 返回了{}条记录 , 准备写入数据库\"\n .format(start_date0, end_date, code, retCount), ui_log=ui_log)\n coll_option_commodity_sr_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\"^已经获取过这天的数据了^ {}\".format(\n start_date), ui_log=ui_log)\n\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_M_OPTION_DAY \\n 从新开始下载数据 Trying update {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 获取了{}条记录 , 准备写入数据库^_^ \"\n .format(start_date, end_date, code, retCount),\n ui_log=ui_log)\n\n coll_option_commodity_sr_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\n \"*已经获取过这天的数据了* {}\".format(start_date), ui_log=ui_log)\n\n except Exception as error0:\n print(error0)\n err.append(str(code))\n\n for item in range(len(option_sr_contract_list)):\n QA_util_log_info('The {} of Total {}'.format(\n item, len(option_sr_contract_list)), ui_log=ui_log)\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(item / len(option_sr_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(float(item / len(option_sr_contract_list) * 10000.0))\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n\n __saving_work(option_sr_contract_list[item].code, coll_option_commodity_sr_day)\n\n if len(err) < 1:\n QA_util_log_info('SUCCESS save option sr day ^_^ ', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef _save_option_commodity_m_day(client=DATABASE, ui_log=None, ui_progress=None):\n ##################### M 豆粕 ############################################################################\n option_m_contract_list = QA_fetch_get_commodity_option_M_contract_time_to_market()\n coll_option_commodity_m_day = client.option_commodity_m_day\n coll_option_commodity_m_day.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_option_commodity_m_day):\n try:\n QA_util_log_info('##JOB12 Now Saving OPTION_DAY_COMMODITY_M 豆粕 ==== {}'.format(\n str(code)), ui_log=ui_log)\n\n # 首选查找数据库 是否 有 这个代码的数据\n # M XXXXXX 编码格式\n\n\n ref = coll_option_commodity_m_day.find({'code': str(code)[0:8]})\n end_date = str(now_time())[0:10]\n\n # 当前数据库已经包含了这个代码的数据, 继续增量更新\n # 加入这个判断的原因是因为如果是刚上市的 数据库会没有数据 所以会有负索引问题出现\n if ref.count() > 0:\n\n # 接着上次获取的日期继续更新\n start_date = ref[ref.count() - 1]['date']\n QA_util_log_info(' 上次获取期权M豆粕日线数据的最后日期是 {}'.format(\n start_date), ui_log=ui_log)\n\n QA_util_log_info('UPDATE_OPTION_M_DAY \\n 从上一次下载数据开始继续 Trying update {} from {} to {}'.format(\n code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n start_date0 = QA_util_get_next_day(start_date)\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date0, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 返回了{}条记录 , 准备写入数据库\"\n .format(start_date0, end_date, code, retCount), ui_log=ui_log)\n coll_option_commodity_m_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\"^已经获取过这天的数据了^ {}\".format(\n start_date), ui_log=ui_log)\n\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_M_OPTION_DAY \\n 从新开始下载数据 Trying update {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 获取了{}条记录 , 准备写入数据库^_^ \"\n .format(start_date, end_date, code, retCount),\n ui_log=ui_log)\n\n coll_option_commodity_m_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\n \"*已经获取过这天的数据了* {}\".format(start_date), ui_log=ui_log)\n\n except Exception as error0:\n print(error0)\n err.append(str(code))\n\n for item in range(len(option_m_contract_list)):\n QA_util_log_info('The {} of Total {}'.format(\n item, len(option_m_contract_list)), ui_log=ui_log)\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(item / len(option_m_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(float(item / len(option_m_contract_list) * 10000.0))\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n\n __saving_work(option_m_contract_list[item].code, coll_option_commodity_m_day)\n\n if len(err) < 1:\n QA_util_log_info('SUCCESS save option m day ^_^ ', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef _save_option_commodity_cu_day(client=DATABASE, ui_log=None, ui_progress=None):\n ##################### CU 铜 ############################################################################\n option_cu_contract_list = QA_fetch_get_commodity_option_CU_contract_time_to_market()\n coll_option_commodity_cu_day = client.option_commodity_cu_day\n coll_option_commodity_cu_day.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_option_commodity_cu_day):\n try:\n QA_util_log_info('##JOB12 Now Saving OPTION_DAY_COMMODITY_CU 铜 ==== {}'.format(\n str(code)), ui_log=ui_log)\n\n # 首选查找数据库 是否 有 这个代码的数据\n # 期权代码 从 10000001 开始编码 10001228\n ref = coll_option_commodity_cu_day.find({'code': str(code)[0:8]})\n end_date = str(now_time())[0:10]\n\n # 当前数据库已经包含了这个代码的数据, 继续增量更新\n # 加入这个判断的原因是因为如果是刚上市的 数据库会没有数据 所以会有负索引问题出现\n if ref.count() > 0:\n\n # 接着上次获取的日期继续更新\n start_date = ref[ref.count() - 1]['date']\n QA_util_log_info(' 上次获取期权CU日线数据的最后日期是 {}'.format(\n start_date), ui_log=ui_log)\n\n QA_util_log_info('UPDATE_OPTION_CU_DAY \\n 从上一次下载数据开始继续 Trying update {} from {} to {}'.format(\n code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n start_date0 = QA_util_get_next_day(start_date)\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date0, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 返回了{}条记录 , 准备写入数据库\"\n .format(start_date0, end_date, code, retCount), ui_log=ui_log)\n coll_option_commodity_cu_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\"^已经获取过这天的数据了^ {}\".format(\n start_date), ui_log=ui_log)\n\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_CU_OPTION_DAY \\n 从新开始下载数据 Trying update {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 获取了{}条记录 , 准备写入数据库^_^ \"\n .format(start_date, end_date, code, retCount),\n ui_log=ui_log)\n\n coll_option_commodity_cu_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\n \"*已经获取过这天的数据了* {}\".format(start_date), ui_log=ui_log)\n\n except Exception as error0:\n print(error0)\n err.append(str(code))\n\n for item in range(len(option_cu_contract_list)):\n QA_util_log_info('The {} of Total {}'.format(\n item, len(option_cu_contract_list)), ui_log=ui_log)\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(item / len(option_cu_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(float(item / len(option_cu_contract_list) * 10000.0))\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n\n __saving_work(option_cu_contract_list[item].code, coll_option_commodity_cu_day)\n\n if len(err) < 1:\n QA_util_log_info('SUCCESS save option cu day ^_^ ', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\ndef QA_SU_save_option_commodity_day(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n :param client:\n :return:\n '''\n _save_option_commodity_cu_day(client=client,ui_log=ui_log,ui_progress=ui_progress)\n _save_option_commodity_m_day(client=client,ui_log=ui_log,ui_progress=ui_progress)\n _save_option_commodity_sr_day(client=client,ui_log=ui_log,ui_progress=ui_progress)\n\n\n\n\ndef _save_option_commodity_cu_min(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n\n :param client:\n :param ui_log:\n :param ui_progress:\n :return:\n '''\n '''\n :param client:\n :return:\n '''\n option_contract_list = QA_fetch_get_commodity_option_CU_contract_time_to_market()\n coll_option_min = client.option_commodity_cu_min\n coll_option_min.create_index([(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n # 索引 code\n\n err = []\n\n def __saving_work(code, coll):\n\n QA_util_log_info(\n '##JOB13 Now Saving Option CU 铜 MIN ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find({'code': str(code)[0:8], 'type': type})\n\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB13.{} Now Saving Option CU 铜 {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\" 写入 新增历史合约记录数 {} \".format(len(__data)))\n coll.insert_many(\n QA_util_to_json_from_pandas(__data[1::]))\n else:\n start_time = '2015-01-01'\n\n QA_util_log_info(\n '##JOB13.{} Now Option CU 铜 {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type), ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\" 写入 新增合约记录数 {} \".format(len(__data)))\n coll.insert_many(QA_util_to_json_from_pandas(__data))\n except:\n err.append(code)\n\n executor = ThreadPoolExecutor(max_workers=4)\n\n res = {executor.submit(\n __saving_work, option_contract_list[i_][\"code\"], coll_option_min) for i_ in\n range(len(option_contract_list))} # multi index ./.\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n QA_util_log_info('The {} of Total {}'.format(\n count, len(option_contract_list)), ui_log=ui_log)\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(option_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(float(count / len(option_contract_list) * 10000.0))\n\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n pass\n\n\n\n\n\n\ndef _save_option_commodity_sr_min(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n\n :param client:\n :param ui_log:\n :param ui_progress:\n :return:\n '''\n '''\n :param client:\n :return:\n '''\n option_contract_list = QA_fetch_get_commodity_option_SR_contract_time_to_market()\n coll_option_min = client.option_commodity_sr_min\n coll_option_min.create_index([(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n # 索引 code\n\n err = []\n\n def __saving_work(code, coll):\n\n QA_util_log_info(\n '##JOB13 Now Saving Option SR 白糖 ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find({'code': str(code)[0:8], 'type': type})\n\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB13.{} Now Saving Option SR 白糖 {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\" 写入 新增历史合约记录数 {} \".format(len(__data)))\n coll.insert_many(\n QA_util_to_json_from_pandas(__data[1::]))\n else:\n start_time = '2015-01-01'\n\n QA_util_log_info(\n '##JOB13.{} Now Option SR 白糖 {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type), ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\" 写入 新增合约记录数 {} \".format(len(__data)))\n coll.insert_many(QA_util_to_json_from_pandas(__data))\n except:\n err.append(code)\n\n executor = ThreadPoolExecutor(max_workers=4)\n\n res = {executor.submit(\n __saving_work, option_contract_list[i_][\"code\"], coll_option_min) for i_ in\n range(len(option_contract_list))} # multi index ./.\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n QA_util_log_info('The {} of Total {}'.format(\n count, len(option_contract_list)), ui_log=ui_log)\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(option_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(float(count / len(option_contract_list) * 10000.0))\n\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n pass\n\n\n\n\n\ndef _save_option_commodity_m_min(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n\n :param client:\n :param ui_log:\n :param ui_progress:\n :return:\n '''\n\n option_contract_list = QA_fetch_get_commodity_option_M_contract_time_to_market()\n coll_option_min = client.option_commodity_m_min\n coll_option_min.create_index([(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n # 索引 code\n\n err = []\n\n def __saving_work(code, coll):\n\n QA_util_log_info(\n '##JOB13 Now Saving Option M 豆粕 ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find({'code': str(code)[0:8], 'type': type})\n\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB13.{} Now Saving Option M 豆粕 {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\" 写入 新增历史合约记录数 {} \".format(len(__data)))\n coll.insert_many(\n QA_util_to_json_from_pandas(__data[1::]))\n else:\n start_time = '2015-01-01'\n\n QA_util_log_info(\n '##JOB13.{} Now Option M 豆粕 {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type), ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\" 写入 新增合约记录数 {} \".format(len(__data)))\n coll.insert_many(QA_util_to_json_from_pandas(__data))\n except:\n err.append(code)\n\n executor = ThreadPoolExecutor(max_workers=4)\n\n res = {executor.submit(\n __saving_work, option_contract_list[i_][\"code\"], coll_option_min) for i_ in\n range(len(option_contract_list))} # multi index ./.\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n QA_util_log_info('The {} of Total {}'.format(\n count, len(option_contract_list)), ui_log=ui_log)\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(option_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(float(count / len(option_contract_list) * 10000.0))\n\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n pass\n\n\n\ndef QA_SU_save_option_commodity_min(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n :param client:\n :return:\n '''\n _save_option_commodity_cu_min(client=client, ui_log=ui_log, ui_progress=ui_progress)\n _save_option_commodity_sr_min(client=client, ui_log=ui_log, ui_progress=ui_progress)\n _save_option_commodity_m_min(client=client, ui_log=ui_log, ui_progress=ui_progress)\n\n\ndef QA_SU_save_option_min(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n :param client:\n :return:\n '''\n option_contract_list = QA_fetch_get_50etf_option_contract_time_to_market()\n coll_option_min = client.option_day_min\n coll_option_min.create_index([(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n # 索引 code\n\n err = []\n\n def __saving_work(code, coll):\n\n QA_util_log_info(\n '##JOB13 Now Saving Option 50ETF MIN ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find({'code': str(code)[0:8], 'type': type})\n\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB13.{} Now Saving Option 50ETF {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\" 写入 新增历史合约记录数 {} \".format(len(__data)))\n coll.insert_many(\n QA_util_to_json_from_pandas(__data[1::]))\n else:\n start_time = '2015-01-01'\n\n QA_util_log_info(\n '##JOB13.{} Now Option 50ETF {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type), ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\" 写入 新增合约记录数 {} \".format(len(__data)))\n coll.insert_many(QA_util_to_json_from_pandas(__data))\n except:\n err.append(code)\n\n executor = ThreadPoolExecutor(max_workers=4)\n\n res = {executor.submit(\n __saving_work, option_contract_list[i_][\"code\"], coll_option_min) for i_ in range(len(option_contract_list))} # multi index ./.\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n QA_util_log_info('The {} of Total {}'.format(\n count, len(option_contract_list)), ui_log=ui_log)\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(option_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(float(count / len(option_contract_list) * 10000.0))\n\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_option_day(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n :param client:\n :return:\n '''\n option_contract_list = QA_fetch_get_50etf_option_contract_time_to_market()\n coll_option_day = client.option_day\n coll_option_day.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n # 索引 code\n\n def __saving_work(code, coll_option_day):\n try:\n QA_util_log_info('##JOB12 Now Saving OPTION_DAY==== {}'.format(\n str(code)), ui_log=ui_log)\n\n # 首选查找数据库 是否 有 这个代码的数据\n # 期权代码 从 10000001 开始编码 10001228\n ref = coll_option_day.find({'code': str(code)[0:8]})\n end_date = str(now_time())[0:10]\n\n # 当前数据库已经包含了这个代码的数据, 继续增量更新\n # 加入这个判断的原因是因为如果是刚上市的 数据库会没有数据 所以会有负索引问题出现\n if ref.count() > 0:\n\n # 接着上次获取的日期继续更新\n start_date = ref[ref.count() - 1]['date']\n QA_util_log_info(' 上次获取期权日线数据的最后日期是 {}'.format(\n start_date), ui_log=ui_log)\n\n QA_util_log_info('UPDATE_OPTION_DAY \\n 从上一次下载数据开始继续 Trying update {} from {} to {}'.format(\n code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n start_date0 = QA_util_get_next_day(start_date)\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date0, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 返回了{}条记录 , 准备写入数据库\"\n .format(start_date0, end_date, code, retCount), ui_log=ui_log)\n coll_option_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\"^已经获取过这天的数据了^ {}\".format(\n start_date), ui_log=ui_log)\n\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_OPTION_DAY \\n 从新开始下载数据 Trying update {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 获取了{}条记录 , 准备写入数据库^_^ \"\n .format(start_date, end_date, code, retCount),\n ui_log=ui_log)\n\n coll_option_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\n \"*已经获取过这天的数据了* {}\".format(start_date), ui_log=ui_log)\n\n except Exception as error0:\n print(error0)\n err.append(str(code))\n\n for item in range(len(option_contract_list)):\n QA_util_log_info('The {} of Total {}'.format(\n item, len(option_contract_list)), ui_log=ui_log)\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(item / len(option_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(float(item / len(option_contract_list) * 10000.0))\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n\n __saving_work(option_contract_list[item].code, coll_option_day)\n\n if len(err) < 1:\n QA_util_log_info('SUCCESS save option day ^_^ ', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_option_contract_list(client=DATABASE, ui_log=None, ui_progress=None):\n\n rows50etf = QA_fetch_get_50etf_option_contract_time_to_market()\n rows_cu = QA_fetch_get_commodity_option_CU_contract_time_to_market()\n rows_m = QA_fetch_get_commodity_option_M_contract_time_to_market()\n rows_sr = QA_fetch_get_commodity_option_SR_contract_time_to_market()\n\n\n\n try:\n # 🛠todo 这个应该是第一个任务 JOB01, 先更新股票列表!!\n QA_util_log_info('##JOB15 Now Saving OPTION_CONTRACT_LIST ====', ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=5000)\n\n coll = client.option_contract_list\n coll.create_index([('desc', pymongo.ASCENDING)], unique=True )\n\n # todo fixhere\n # from_items is deprecated. Please use DataFrame.from_dict(dict(items), ...) instead. DataFrame.from_dict\n\n try:\n\n df = pd.DataFrame.from_items([(s.desc, s) for s in rows50etf])\n df = (df.T)\n js = QA_util_to_json_from_pandas(df)\n result0 = coll.insert_many(js)\n\n except pymongo.errors.BulkWriteError as e:\n #https://ask.helplib.com/python/post_12740530\n panic = filter(lambda x: x['code'] != 11000, e.details['writeErrors'])\n if len(panic) > 0:\n print\n \"really panic\"\n\n\n try:\n df = pd.DataFrame.from_items([(s.desc, s) for s in rows_cu])\n df = (df.T)\n js = QA_util_to_json_from_pandas(df)\n coll.insert_many(js)\n except pymongo.errors.BulkWriteError as e:\n #https://ask.helplib.com/python/post_12740530\n panic = filter(lambda x: x['code'] != 11000, e.details['writeErrors'])\n if len(panic) > 0:\n print(\"really panic\")\n try:\n df = pd.DataFrame.from_items([(s.desc, s) for s in rows_m])\n df = (df.T)\n js = QA_util_to_json_from_pandas(df)\n coll.insert_many(js)\n except pymongo.errors.BulkWriteError as e:\n #https://ask.helplib.com/python/post_12740530\n panic = filter(lambda x: x['code'] != 11000, e.details['writeErrors'])\n if len(panic) > 0:\n print(\"really panic\")\n\n\n try:\n df = pd.DataFrame.from_items([(s.desc, s) for s in rows_sr])\n df = (df.T)\n js = QA_util_to_json_from_pandas(df)\n coll.insert_many(js)\n\n except pymongo.errors.BulkWriteError as e:\n #https://ask.helplib.com/python/post_12740530\n panic = filter(lambda x: x['code'] != 11000, e.details['writeErrors'])\n if len(panic) > 0:\n print(\"really panic\")\n\n QA_util_log_info(\"完成合约列表更新\", ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=10000)\n except Exception as e:\n QA_util_log_info(e, ui_log=ui_log)\n print(\" Error save_tdx.QA_SU_save_option_contract_list exception!\")\n\n\n\n\n\n\ndef QA_SU_save_future_list(client=DATABASE, ui_log=None, ui_progress=None):\n future_list = QA_fetch_get_future_list()\n coll_future_list = client.future_list\n coll_future_list.create_index(\"code\", unique=True)\n try:\n coll_future_list.insert_many(\n QA_util_to_json_from_pandas(future_list), ordered=False)\n except:\n pass\n\n\n\n\n\n\n\ndef QA_SU_save_index_list(client=DATABASE, ui_log=None, ui_progress=None):\n index_list = QA_fetch_get_index_list()\n coll_index_list = client.index_list\n coll_index_list.create_index(\"code\", unique=True)\n\n try:\n coll_index_list.insert_many(\n QA_util_to_json_from_pandas(index_list), ordered=False)\n except:\n pass\n\n\ndef QA_SU_save_future_day(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n save future_day\n 保存日线数据\n :param client:\n :param ui_log: 给GUI qt 界面使用\n :param ui_progress: 给GUI qt 界面使用\n :param ui_progress_int_value: 给GUI qt 界面使用\n :return:\n '''\n future_list = [item for item in QA_fetch_get_future_list().code.unique().tolist() if str(item)[-2:] in ['L8','L9']]\n coll_future_day = client.future_day\n coll_future_day.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_future_day):\n try:\n QA_util_log_info(\n '##JOB12 Now Saving Future_DAY==== {}'.format(str(code)), ui_log)\n\n # 首选查找数据库 是否 有 这个代码的数据\n ref = coll_future_day.find({'code': str(code)[0:4]})\n end_date = str(now_time())[0:10]\n\n # 当前数据库已经包含了这个代码的数据, 继续增量更新\n # 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现\n if ref.count() > 0:\n\n # 接着上次获取的日期继续更新\n start_date = ref[ref.count() - 1]['date']\n\n QA_util_log_info('UPDATE_Future_DAY \\n Trying updating {} from {} to {}'.format(\n code, start_date, end_date), ui_log)\n if start_date != end_date:\n coll_future_day.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_future_day(str(code), QA_util_get_next_day(start_date), end_date)))\n\n # 当前数据库中没有这个代码的股票数据, 从1990-01-01 开始下载所有的数据\n else:\n start_date = '2001-01-01'\n QA_util_log_info('UPDATE_Future_DAY \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log)\n if start_date != end_date:\n coll_future_day.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_future_day(str(code), start_date, end_date)))\n except Exception as error0:\n print(error0)\n err.append(str(code))\n\n for item in range(len(future_list)):\n QA_util_log_info('The {} of Total {}'.format\n (item, len(future_list)))\n\n strProgressToLog = 'DOWNLOAD PROGRESS {} {}'.format(\n str(float(item / len(future_list) * 100))[0:4] + '%', ui_log)\n intProgressToLog = int(float(item / len(future_list) * 100))\n QA_util_log_info(strProgressToLog, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intProgressToLog)\n\n __saving_work(future_list[item], coll_future_day)\n\n if len(err) < 1:\n QA_util_log_info('SUCCESS save future day ^_^', ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log)\n QA_util_log_info(err, ui_log)\n\n\ndef QA_SU_save_future_min(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save future_min\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n future_list = [item for item in QA_fetch_get_future_list().code.unique().tolist() if str(item)[-2:] in ['L8','L9']]\n coll = client.future_min\n coll.create_index([('code', pymongo.ASCENDING), ('time_stamp',\n pymongo.ASCENDING), ('date_stamp', pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll):\n\n QA_util_log_info(\n '##JOB13 Now Saving Future_MIN ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find(\n {'code': str(code)[0:6], 'type': type})\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB13.{} Now Saving Future {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data[1::]))\n else:\n start_time = '2015-01-01'\n\n QA_util_log_info(\n '##JOB13.{} Now Saving Future {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type), ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data))\n except:\n err.append(code)\n\n executor = ThreadPoolExecutor(max_workers=4)\n\n res = {executor.submit(\n __saving_work, future_list[i_], coll) for i_ in range(len(future_list))} # multi index ./.\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n\n QA_util_log_info('The {} of Total {}'.format(\n count, len(future_list)), ui_log=ui_log)\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(future_list) * 100))[0:4] + '%')\n intLogProgress = int(float(count / len(future_list) * 10000.0))\n\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\nif __name__ == '__main__':\n # QA_SU_save_stock_day()\n # QA_SU_save_stock_xdxr()\n # QA_SU_save_stock_min()\n # QA_SU_save_stock_transaction()\n # QA_SU_save_index_day()\n # QA_SU_save_stock_list()\n # QA_SU_save_index_min()\n # QA_SU_save_index_list()\n # QA_SU_save_future_list()\n\n QA_SU_save_future_day()\n\n QA_SU_save_future_min()\n" ]
[ [ "pandas.DataFrame.from_items" ] ]
oikosohn/lightweight-waste-classifier
[ "b3b332e8389e8a00e1d853c689226743bba00213" ]
[ "src/trainer.py" ]
[ "\"\"\"PyTorch trainer module.\n\n- Author: Jongkuk Lim, Junghoon Kim\n- Contact: [email protected], [email protected]\n\"\"\"\n\nimport os\nimport shutil\nfrom typing import Optional, Tuple, Union\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nfrom sklearn.metrics import f1_score\nfrom torch.utils.data.dataloader import DataLoader\nfrom torch.utils.data.dataset import Dataset\nfrom torch.utils.data.sampler import SequentialSampler, SubsetRandomSampler\nfrom tqdm import tqdm\n\nfrom src.utils.torch_utils import save_model\n\nimport wandb\n\ndef _get_n_data_from_dataloader(dataloader: DataLoader) -> int:\n \"\"\"Get a number of data in dataloader.\n\n Args:\n dataloader: torch dataloader\n\n Returns:\n A number of data in dataloader\n \"\"\"\n if isinstance(dataloader.sampler, SubsetRandomSampler):\n n_data = len(dataloader.sampler.indices)\n elif isinstance(dataloader.sampler, SequentialSampler):\n n_data = len(dataloader.sampler.data_source)\n else:\n n_data = len(dataloader) * dataloader.batch_size if dataloader.batch_size else 1\n\n return n_data\n\n\ndef _get_n_batch_from_dataloader(dataloader: DataLoader) -> int:\n \"\"\"Get a batch number in dataloader.\n\n Args:\n dataloader: torch dataloader\n\n Returns:\n A batch number in dataloader\n \"\"\"\n n_data = _get_n_data_from_dataloader(dataloader)\n n_batch = dataloader.batch_size if dataloader.batch_size else 1\n\n return n_data // n_batch\n\n\ndef _get_len_label_from_dataset(dataset: Dataset) -> int:\n \"\"\"Get length of label from dataset.\n\n Args:\n dataset: torch dataset\n\n Returns:\n A number of label in set.\n \"\"\"\n if isinstance(dataset, torchvision.datasets.ImageFolder) or isinstance(\n dataset, torchvision.datasets.vision.VisionDataset\n ):\n return len(dataset.classes)\n elif isinstance(dataset, torch.utils.data.Subset):\n return _get_len_label_from_dataset(dataset.dataset)\n else:\n raise NotImplementedError\n\n\nclass TorchTrainer:\n \"\"\"Pytorch Trainer.\"\"\"\n\n def __init__(\n self,\n model: nn.Module,\n criterion: nn.Module,\n optimizer: optim.Optimizer,\n scheduler,\n model_path: str,\n scaler=None,\n device: torch.device = \"cpu\",\n verbose: int = 1,\n ) -> None:\n \"\"\"Initialize TorchTrainer class.\n\n Args:\n model: model to train\n criterion: loss function module\n optimizer: optimization module\n device: torch device\n verbose: verbosity level.\n \"\"\"\n \n self.model = model\n self.model_path = model_path\n self.criterion = criterion\n self.optimizer = optimizer\n self.scheduler = scheduler\n self.scaler = scaler\n self.verbose = verbose\n self.device = device\n \n def train(\n self,\n train_dataloader: DataLoader,\n n_epoch: int,\n val_dataloader: Optional[DataLoader] = None,\n ) -> Tuple[float, float]:\n \"\"\"Train model.\n\n Args:\n train_dataloader: data loader module which is a iterator that returns (data, labels)\n n_epoch: number of total epochs for training\n val_dataloader: dataloader for validation\n\n Returns:\n loss and accuracy\n \"\"\"\n \n # # WandB watch\n wandb.watch(self.model, log=all)\n \n best_test_acc = -1.0\n best_test_f1 = -1.0\n num_classes = _get_len_label_from_dataset(train_dataloader.dataset)\n label_list = [i for i in range(num_classes)]\n\n for epoch in range(n_epoch):\n running_loss, correct, total = 0.0, 0, 0\n preds, gt = [], []\n pbar = tqdm(enumerate(train_dataloader), total=len(train_dataloader))\n self.model.train()\n\n # Mean avg loss array for WandB logging\n # train_avg_loss, train_avg_acc, train_avg_f1 = np.array([]), np.array([]), np.array([])\n\n for batch, (data, labels) in pbar:\n data, labels = data.to(self.device), labels.to(self.device)\n\n if self.scaler:\n with torch.cuda.amp.autocast():\n outputs = self.model(data)\n else:\n outputs = self.model(data)\n outputs = torch.squeeze(outputs)\n loss = self.criterion(outputs, labels)\n\n self.optimizer.zero_grad()\n\n if self.scaler:\n self.scaler.scale(loss).backward()\n self.scaler.step(self.optimizer)\n self.scaler.update()\n else:\n loss.backward()\n self.optimizer.step()\n self.scheduler.step()\n\n _, pred = torch.max(outputs, 1)\n total += labels.size(0)\n correct += (pred == labels).sum().item()\n preds += pred.to(\"cpu\").tolist()\n gt += labels.to(\"cpu\").tolist()\n\n running_loss += loss.item()\n pbar.update()\n pbar.set_description(\n f\"Train: [{epoch + 1:03d}] \"\n f\"Loss: {(running_loss / (batch + 1)):.3f}, \"\n f\"Acc: {(correct / total) * 100:.2f}% \"\n f\"F1(macro): {f1_score(y_true=gt, y_pred=preds, labels=label_list, average='macro', zero_division=0):.2f}\"\n )\n \n # append np.array\n # train_avg_loss = np.append(train_avg_loss, (running_loss / (batch + 1)))\n # train_avg_acc = np.append(train_avg_acc, (correct / total))\n # train_avg_f1 = np.append(train_avg_f1, f1_score(y_true=gt, y_pred=preds, labels=label_list, average='macro', zero_division=0))\n \n pbar.close()\n \n test_loss, test_f1, test_acc = self.test(\n model=self.model, test_dataloader=val_dataloader\n )\n\n \n # loss = running_loss / len(train_dataloader)\n # accuracy = correct / total\n # f1 = f1_score(\n # y_true=gt, y_pred=preds, labels=label_list, average=\"macro\", zero_division=0\n # )\n \n # WandB logging for train\n # wandb.log({'Train/Loss':np.mean(train_avg_loss), 'Train/Acc':np.mean(train_avg_acc), 'Train/F1(Macro)':np.mean(train_avg_f1), \n # }, step=epoch+1)\n \n # WandB logging for train\n wandb.log({'Train/Loss':running_loss / len(train_dataloader), 'Train/Acc':correct / total, 'Train/F1(Macro)':f1_score(y_true=gt, y_pred=preds, labels=label_list, average=\"macro\", zero_division=0), \n }, step=epoch+1)\n \n # WandB logging for valid\n wandb.log({'Valid/Loss':test_loss, 'Valid/Acc':test_acc, 'Valid/F1(Macro)':test_f1, }, step=epoch+1)\n \n if best_test_f1 > test_f1:\n continue\n best_test_acc = test_acc\n best_test_f1 = test_f1\n \n print(f\"Model saved. Current best test f1: {best_test_f1:.3f}\")\n save_model(\n model=self.model,\n path=self.model_path,\n data=data,\n device=self.device,\n )\n\n return best_test_acc, best_test_f1\n\n @torch.no_grad()\n def test(\n self, model: nn.Module, test_dataloader: DataLoader\n ) -> Tuple[float, float, float]:\n \"\"\"Test model.\n\n Args:\n test_dataloader: test data loader module which is a iterator that returns (data, labels)\n\n Returns:\n loss, f1, accuracy\n \"\"\"\n\n n_batch = _get_n_batch_from_dataloader(test_dataloader)\n\n running_loss = 0.0\n preds = []\n gt = []\n correct = 0\n total = 0\n\n num_classes = _get_len_label_from_dataset(test_dataloader.dataset)\n label_list = [i for i in range(num_classes)]\n\n pbar = tqdm(enumerate(test_dataloader), total=len(test_dataloader))\n model.to(self.device)\n model.eval()\n for batch, (data, labels) in pbar:\n data, labels = data.to(self.device), labels.to(self.device)\n\n if self.scaler:\n with torch.cuda.amp.autocast():\n outputs = model(data)\n else:\n outputs = model(data)\n outputs = torch.squeeze(outputs)\n running_loss += self.criterion(outputs, labels).item()\n\n _, pred = torch.max(outputs, 1)\n total += labels.size(0)\n correct += (pred == labels).sum().item()\n\n preds += pred.to(\"cpu\").tolist()\n gt += labels.to(\"cpu\").tolist()\n pbar.update()\n pbar.set_description(\n f\" Val: {'':5} Loss: {(running_loss / (batch + 1)):.3f}, \"\n f\"Acc: {(correct / total) * 100:.2f}% \"\n f\"F1(macro): {f1_score(y_true=gt, y_pred=preds, labels=label_list, average='macro', zero_division=0):.2f}\"\n )\n loss = running_loss / len(test_dataloader)\n accuracy = correct / total\n f1 = f1_score(\n y_true=gt, y_pred=preds, labels=label_list, average=\"macro\", zero_division=0\n )\n return loss, f1, accuracy\n\n\ndef count_model_params(\n model: torch.nn.Module,\n) -> int:\n \"\"\"Count model's parameters\"\"\"\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n" ]
[ [ "torch.max", "torch.cuda.amp.autocast", "torch.no_grad", "sklearn.metrics.f1_score", "torch.squeeze" ] ]
RegularizedML/pytorch-deepdream
[ "82f181fe43f15e75bfcbb111432e7006e9123c33" ]
[ "utils/constants.py" ]
[ "import enum\nimport os\n\n\nimport numpy as np\nimport torch\n\n\nIMAGENET_MEAN_1 = np.array([0.485, 0.456, 0.406], dtype=np.float32)\nIMAGENET_STD_1 = np.array([0.229, 0.224, 0.225], dtype=np.float32)\n\n\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # checking whether you have a GPU\n\n\nLOWER_IMAGE_BOUND = torch.tensor((-IMAGENET_MEAN_1 / IMAGENET_STD_1).reshape(1, -1, 1, 1)).to(DEVICE)\nUPPER_IMAGE_BOUND = torch.tensor(((1 - IMAGENET_MEAN_1) / IMAGENET_STD_1).reshape(1, -1, 1, 1)).to(DEVICE)\n\n\nclass TRANSFORMS(enum.Enum):\n ZOOM = 0\n ZOOM_ROTATE = 1\n TRANSLATE = 2\n\n\nclass SupportedModels(enum.Enum):\n VGG16 = 0\n VGG16_EXPERIMENTAL = 1\n GOOGLENET = 2\n RESNET50 = 3\n ALEXNET = 4\n\n\nclass SupportedPretrainedWeights(enum.Enum):\n IMAGENET = 0\n PLACES_365 = 1\n custom = 2\n\n\nSUPPORTED_VIDEO_FORMATS = ['.mp4']\nSUPPORTED_IMAGE_FORMATS = ['.jpg', '.jpeg', '.png', '.bmp']\n\nBINARIES_PATH = os.path.join(os.path.dirname(__file__), os.pardir, 'models', 'binaries')\nDATA_DIR_PATH = os.path.join(os.path.dirname(__file__), os.pardir, 'data')\n\nINPUT_DATA_PATH = os.path.join(DATA_DIR_PATH, 'input')\nOUT_IMAGES_PATH = os.path.join(DATA_DIR_PATH, 'out-images')\nOUT_VIDEOS_PATH = os.path.join(DATA_DIR_PATH, 'out-videos')\nOUT_GIF_PATH = os.path.join(OUT_VIDEOS_PATH, 'GIFS')\n\n# Make sure these exist as the rest of the code relies on it\nos.makedirs(BINARIES_PATH, exist_ok=True)\nos.makedirs(OUT_IMAGES_PATH, exist_ok=True)\nos.makedirs(OUT_VIDEOS_PATH, exist_ok=True)\nos.makedirs(OUT_GIF_PATH, exist_ok=True)\n\n\n\n\n" ]
[ [ "numpy.array", "torch.cuda.is_available" ] ]
Vooblin/model-optimization
[ "b1ab38824466dc008614e414bc854582c705eb1f" ]
[ "tensorflow_model_optimization/python/core/quantization/keras/quantize_aware_activation.py" ]
[ "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Activation layer which applies emulates quantization during training.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.keras import activations\nfrom tensorflow.python.keras.utils import tf_utils\n\n\nclass NoOpActivation(object):\n \"\"\"No-op activation which simply returns the incoming tensor.\n\n This activation is required to distinguish between `keras.activations.linear`\n which does the same thing. The main difference is that NoOpActivation should\n not have any quantize operation applied to it.\n \"\"\"\n\n def __call__(self, x):\n return x\n\n def get_config(self):\n return {}\n\n def __eq__(self, other):\n if not other or not isinstance(other, NoOpActivation):\n return False\n\n return True\n\n def __ne__(self, other):\n \"\"\"Ensure this works on Python2.\"\"\"\n return not self.__eq__(other)\n\n\nclass QuantizeAwareActivation(object):\n \"\"\"Activation wrapper for quantization aware training.\n\n The goal of this class is to apply quantize operations during training such\n that the training network mimics quantization loss experienced in activations\n during inference.\n\n It introduces quantization loss before and after activations as required to\n mimic inference loss. The layer has built-in knowledge of how quantized\n activations are laid out during inference to emulate exact behavior.\n\n For example, ReLU activations are typically fused into their parent layer\n such as Conv/Dense. Hence, loss is introduced only after the activation has\n been applied. For Softmax on the other hand quantization loss is experienced\n both before and after the activation.\n\n Input shape:\n Arbitrary.\n\n Output shape:\n Same shape as input.\n \"\"\"\n\n # TODO(pulkitb): Other activations such as elu, tanh etc., should just work\n # on inclusion. Verify in TFLite before enabling.\n\n # These activations should be quantized prior to the activation being applied.\n _PRE_QUANT_ACTIVATIONS = frozenset({'softmax'})\n\n # These activations should be quantized after the activation has been applied.\n _POST_QUANT_ACTIVATIONS = frozenset({'linear', 'relu'})\n\n # Don't take any quantize operations for these activations.\n _NO_QUANTIZE_ACTIVATIONS = frozenset({'NoOpActivation'})\n\n _CUSTOM_ACTIVATION_ERR_MSG = (\n 'Only some Keras activations under `tf.keras.activations` are supported. '\n 'For other activations, use `Quantizer` directly, and update layer '\n 'config using `QuantizeProvider`.'\n )\n\n def __init__(self, activation, quantizer, step, quantize_wrapper):\n \"\"\"Constructs object, and initializes weights for quantization.\n\n Args:\n activation: Activation function to use.\n quantizer: `Quantizer` to be used to quantize the activation.\n step: Variable which tracks optimizer step.\n quantize_wrapper: `QuantizeWrapper` which owns this activation.\n \"\"\"\n self.activation = activation\n self.quantizer = quantizer\n self.step = step\n self.quantize_wrapper = quantize_wrapper\n\n if not self._is_supported_activation(self.activation):\n raise ValueError(self._CUSTOM_ACTIVATION_ERR_MSG)\n\n if self._should_pre_quantize():\n self._min_pre_activation, self._max_pre_activation = \\\n quantizer.build(None, 'pre_activation', quantize_wrapper)\n\n self._min_post_activation, self._max_post_activation = \\\n quantizer.build(None, 'post_activation', quantize_wrapper)\n\n @staticmethod\n def _name(activation):\n if hasattr(activation, '__name__'):\n return activation.__name__\n return activation.__class__.__name__\n\n def _is_supported_activation(self, activation):\n activation_name = self._name(activation)\n\n return activation_name in self._PRE_QUANT_ACTIVATIONS \\\n or activation_name in self._POST_QUANT_ACTIVATIONS \\\n or activation_name in self._NO_QUANTIZE_ACTIVATIONS\n\n def _should_pre_quantize(self):\n return self._name(self.activation) in self._PRE_QUANT_ACTIVATIONS\n\n def _should_post_quantize(self):\n return self._name(self.activation) in self._POST_QUANT_ACTIVATIONS\n\n @property\n def training(self):\n return self._training\n\n @training.setter\n def training(self, value):\n self._training = value\n\n def _dict_vars(self, min_var, max_var):\n return {'min_var': min_var, 'max_var': max_var}\n\n def __call__(self, inputs, *args, **kwargs):\n\n def make_quantizer_fn(training, x, min_var, max_var):\n \"\"\"Use currying to return True/False specialized fns to the cond.\"\"\"\n\n def quantizer_fn(x=x,\n quantizer=self.quantizer,\n min_var=min_var,\n max_var=max_var):\n return quantizer(x, self.step, training,\n **self._dict_vars(min_var, max_var))\n\n return quantizer_fn\n\n x = inputs\n if self._should_pre_quantize():\n x = tf_utils.smart_cond(\n self._training,\n make_quantizer_fn(True, x, self._min_pre_activation,\n self._max_pre_activation),\n make_quantizer_fn(False, x, self._min_pre_activation,\n self._max_pre_activation))\n\n x = self.activation(x, *args, **kwargs)\n\n if self._should_post_quantize():\n x = tf_utils.smart_cond(\n self._training,\n make_quantizer_fn(True, x, self._min_post_activation,\n self._max_post_activation),\n make_quantizer_fn(False, x, self._min_post_activation,\n self._max_post_activation))\n\n return x\n\n # `QuantizeAwareActivation` wraps the activation within a layer to perform\n # quantization. In the process, the layer's activation is replaced with\n # `QuantizeAwareActivation`.\n # However, when the layer is serialized and deserialized, we want the original\n # activation to be reconstructed. This ensures that when `QuantizeWrapper`\n # wraps the layer, it can again replace the original activation.\n\n @classmethod\n def from_config(cls, config):\n return activations.deserialize(config['activation'])\n\n def get_config(self):\n return {\n 'activation': activations.serialize(self.activation)\n }\n" ]
[ [ "tensorflow.python.keras.activations.serialize", "tensorflow.python.keras.activations.deserialize" ] ]
chenxinye/ABBA
[ "d25cae182ae3e04776d6618103a3bf53f88c00b2" ]
[ "paper/mydefaults.py" ]
[ "import matplotlib as mpl\nimport matplotlib.font_manager\n\ndef mydefaults(fig, ax, r=0.71, s=1):\n \"\"\"\n Parameters\n ----------\n fig, ax : figure and axes handle from matplotlib\n r : height/width ratio\n s : scaling of font size\n\n Example\n -------\n from mydefaults import mydefaults\n fig, ax = mpl.pyplot.subplots()\n fig, ax = mydefaults(fig, ax)\n \"\"\"\n #fig, ax = mpl.pyplot.subplots()\n\n # Specify fig size\n fig.set_size_inches(s*(13.2/2.54), s*r*(13.2/2.54), forward=True)\n\n # Use tex and correct font\n #mpl.rcParams['font.family'] = 'Serif'\n mpl.rcParams['font.serif'] = ['computer modern roman']\n #mpl.rcParams['text.usetex'] = True # makes zeros bold?\n mpl.rcParams['font.size'] = 11\n mpl.rcParams['font.weight'] = 'normal'\n\n # MATLAB default (see MATLAB Axes Properties documentation)\n mpl.rcParams['axes.titlesize'] = 1.1*11\n mpl.rcParams['axes.titleweight'] = 'bold'\n\n # MATLAB default (see MATLAB Axes Properties documentation)\n mpl.rcParams['axes.labelsize'] = 1.1*11\n mpl.rcParams['axes.labelweight'] = 'normal'\n\n # MATLAB default (see MATLAB Axes Properties documentation)\n mpl.rcParams['legend.fontsize'] = 0.9*11\n\n # remove margine padding on axis\n mpl.rcParams['axes.xmargin'] = 0\n mpl.rcParams['axes.ymargin'] = 0\n\n # switch tick direction like MATLAB\n mpl.rcParams['xtick.direction'] = 'in'\n mpl.rcParams['ytick.direction'] = 'in'\n\n mpl.pyplot.tight_layout(pad=1.3) # padding as fraction of font size\n if isinstance(ax, tuple):\n for axi in ax:\n axi.tick_params(axis='both', which='both', direction='in')\n else:\n ax.tick_params(axis='both', which='both', direction='in')\n\n # Save fig with transparent background\n mpl.rcParams['savefig.transparent'] = True\n\n # Make legend frame border black and face white\n mpl.rcParams['legend.edgecolor'] = 'k'\n mpl.rcParams['legend.facecolor'] = 'w'\n mpl.rcParams['legend.framealpha'] = 1\n\n # Change colorcycle to MATLABS\n c = mpl.cycler(color=['#0072BD', '#D95319', '#EDB120', '#7E2F8E', '#77AC30', '#4DBEEE', '#A2142F'])\n\n if isinstance(ax, tuple):\n for axi in ax:\n axi.set_prop_cycle(c)\n else:\n ax.set_prop_cycle(c)\n # mpl.rcParams['axes.prop_cycle'] = c # doesnt work?\n\n return fig, ax\n" ]
[ [ "matplotlib.cycler", "matplotlib.pyplot.tight_layout" ] ]
Prism2/LSTM-flare-prediction
[ "9d6e2bb2c40c35a1defa0ce357140b5304124017" ]
[ "DEMONSTRATION/LSTM_M_sample_run/LSTMflare.py" ]
[ "# =========================================================================\n# (c) Copyright 2019\n# All rights reserved\n# Programs written by Hao Liu\n# Department of Computer Science\n# New Jersey Institute of Technology\n# University Heights, Newark, NJ 07102, USA\n#\n# Permission to use, copy, modify, and distribute this\n# software and its documentation for any purpose and without\n# fee is hereby granted, provided that this copyright\n# notice appears in all copies. Programmer(s) makes no\n# representations about the suitability of this\n# software for any purpose. It is provided \"as is\" without\n# express or implied warranty.\n# =========================================================================\nimport pandas as pd\nfrom keras.utils import np_utils\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.utils import class_weight\nfrom keras.models import *\nfrom keras.layers import *\nimport csv\nimport sys\nimport numpy as np\nimport os\n\n\n# data_mean = [9.26048596e+02, 2.58664488e-01, 1.06633638e+02, 5.11085855e-01,\n# 6.24011676e+02, 2.04194132e+23, 2.33909547e+01, 1.90406673e+13,\n# 3.32675181e+00, 1.32545323e+22, 5.96746073e+03, 1.85633869e-02,\n# 2.19502276e-06, 4.75747286e+12]\n# data_std = [1.08065295e+03, 7.01180865e-01, 2.02918470e+02, 1.41554237e+00,\n# 6.55378540e+02, 3.35568384e+23, 1.57301570e+01, 2.08734375e+13,\n# 7.34233192e+00, 1.44636883e+22, 4.10534455e+03, 1.20567656e-01,\n# 1.74265529e-05, 7.53463926e+12]\n# data_max = [1.42231700e+04, 9.61858226e+00, 4.05506900e+03, 1.80000000e+01,\n# 7.21147559e+03, 5.36934000e+24, 7.66870000e+01, 4.81340300e+14,\n# 8.70000000e+01, 2.07016000e+23, 2.80475700e+04, 1.05571716e+01,\n# 9.30000000e-04, 1.08546200e+14]\n# data_min = [2.720000e-01, 0.000000e+00, 1.000000e-03, 0.000000e+00, 6.860500e-02,\n# 3.117358e+19, 1.800000e-02, 9.951892e+09, 0.000000e+00, 3.300907e+18,\n# 5.640048e+02, 0.000000e+00, 0.000000e+00, 7.529357e+07]\n\n\ndef load_data(datafile, flare_label, series_len, start_feature, n_features, mask_value):\n df = pd.read_csv(datafile)\n df_values = df.values\n X = []\n y = []\n tmp = []\n for k in range(start_feature, start_feature + n_features):\n tmp.append(mask_value)\n for idx in range(0, len(df_values)):\n each_series_data = []\n row = df_values[idx]\n label = row[1][0]\n if flare_label == 'M' and label == 'X':\n label = 'M'\n if flare_label == 'M' and (label == 'B' or label == 'C'):\n label = 'N'\n has_zero_record = False\n # if at least one of the 25 physical feature values is missing, then discard it.\n if flare_label == 'M':\n for k in range(5, 10):\n if float(row[k]) == 0.0:\n has_zero_record = True\n break\n for k in range(13, 16):\n if float(row[k]) == 0.0:\n has_zero_record = True\n break\n if float(row[19]) == 0.0:\n has_zero_record = True\n if float(row[21]) == 0.0:\n has_zero_record = True\n for k in range(23, 26):\n if float(row[k]) == 0.0:\n has_zero_record = True\n break\n\n if has_zero_record is False:\n cur_noaa_num = int(row[3])\n each_series_data.append(row[start_feature:start_feature + n_features].tolist())\n itr_idx = idx - 1\n while itr_idx >= 0 and len(each_series_data) < series_len:\n prev_row = df_values[itr_idx]\n prev_noaa_num = int(prev_row[3])\n if prev_noaa_num != cur_noaa_num:\n break\n has_zero_record_tmp = False\n if flare_label == 'M':\n for k in range(5, 10):\n if float(row[k]) == 0.0:\n has_zero_record_tmp = True\n break\n for k in range(13, 16):\n if float(row[k]) == 0.0:\n has_zero_record_tmp = True\n break\n if float(row[19]) == 0.0:\n has_zero_record_tmp = True\n if float(row[21]) == 0.0:\n has_zero_record_tmp = True\n for k in range(23, 26):\n if float(row[k]) == 0.0:\n has_zero_record_tmp = True\n break\n\n if len(each_series_data) < series_len and has_zero_record_tmp is True:\n each_series_data.insert(0, tmp)\n\n if len(each_series_data) < series_len and has_zero_record_tmp is False:\n each_series_data.insert(0, prev_row[start_feature:start_feature + n_features].tolist())\n itr_idx -= 1\n\n while len(each_series_data) > 0 and len(each_series_data) < series_len:\n each_series_data.insert(0, tmp)\n\n if len(each_series_data) > 0:\n X.append(np.array(each_series_data).reshape(series_len, n_features).tolist())\n y.append(label)\n X_arr = np.array(X)\n y_arr = np.array(y)\n print(X_arr.shape)\n return X_arr, y_arr\n\n\ndef data_transform(data):\n encoder = LabelEncoder()\n encoder.fit(data)\n encoded_Y = encoder.transform(data)\n converteddata = np_utils.to_categorical(encoded_Y)\n return converteddata\n\n\ndef attention_3d_block(hidden_states, series_len):\n hidden_size = int(hidden_states.shape[2])\n hidden_states_t = Permute((2, 1), name='attention_input_t')(hidden_states)\n hidden_states_t = Reshape((hidden_size, series_len), name='attention_input_reshape')(hidden_states_t)\n score_first_part = Dense(series_len, use_bias=False, name='attention_score_vec')(hidden_states_t)\n score_first_part_t = Permute((2, 1), name='attention_score_vec_t')(score_first_part)\n h_t = Lambda(lambda x: x[:, :, -1], output_shape=(hidden_size, 1), name='last_hidden_state')(hidden_states_t)\n score = dot([score_first_part_t, h_t], [2, 1], name='attention_score')\n attention_weights = Activation('softmax', name='attention_weight')(score)\n context_vector = dot([hidden_states_t, attention_weights], [2, 1], name='context_vector')\n context_vector = Reshape((hidden_size,))(context_vector)\n h_t = Reshape((hidden_size,))(h_t)\n pre_activation = concatenate([context_vector, h_t], name='attention_output')\n attention_vector = Dense(hidden_size, use_bias=False, activation='tanh', name='attention_vector')(pre_activation)\n return attention_vector\n\n\ndef lstm(nclass, n_features, series_len):\n inputs = Input(shape=(series_len, n_features,))\n lstm_out = LSTM(10, return_sequences=True, dropout=0.5)(inputs)\n attention_mul = attention_3d_block(lstm_out, series_len)\n layer1_out = Dense(200, activation='relu')(attention_mul)\n layer2_out = Dense(500, activation='relu')(layer1_out)\n output = Dense(nclass, activation='softmax', activity_regularizer=regularizers.l2(0.0001))(layer2_out)\n model = Model(input=[inputs], output=output)\n return model\n\n\nif __name__ == '__main__':\n flare_label = sys.argv[1]\n train_again = int(sys.argv[2])\n filepath = './'\n n_features = 0\n if flare_label == 'M':\n n_features = 22\n start_feature = 5\n mask_value = 0\n series_len = 10\n epochs = 7\n batch_size = 256\n nclass = 2\n result_file = './output.csv'\n\n if train_again == 1:\n # Train\n X_train_data, y_train_data = load_data(datafile=filepath + 'normalized_training.csv',\n flare_label=flare_label, series_len=series_len,\n start_feature=start_feature, n_features=n_features,\n mask_value=mask_value)\n\n X_train = np.array(X_train_data)\n y_train = np.array(y_train_data)\n y_train_tr = data_transform(y_train)\n\n class_weights = class_weight.compute_class_weight('balanced',\n np.unique(y_train), y_train)\n class_weight_ = {0: class_weights[0], 1: class_weights[1]}\n # print(class_weight_)\n\n model = lstm(nclass, n_features, series_len)\n model.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n history = model.fit(X_train, y_train_tr,\n epochs=epochs, batch_size=batch_size,\n verbose=False, shuffle=True, class_weight=class_weight_)\n model.save('./model.h5')\n else:\n model = load_model('./model.h5')\n\n # Test\n X_test_data, y_test_data = load_data(datafile=filepath + 'normalized_testing.csv',\n flare_label=flare_label, series_len=series_len,\n start_feature=start_feature, n_features=n_features,\n mask_value=mask_value)\n X_test = np.array(X_test_data)\n y_test = np.array(y_test_data)\n y_test_tr = data_transform(y_test)\n\n classes = model.predict(X_test, batch_size=batch_size, verbose=0, steps=None)\n\n with open(result_file, 'w', encoding='UTF-8') as result_csv:\n w = csv.writer(result_csv)\n with open(filepath + 'normalized_testing.csv', encoding='UTF-8') as data_csv:\n reader = csv.reader(data_csv)\n i = -1\n for line in reader:\n if i == -1:\n line.insert(0, 'Predicted Label')\n else:\n if classes[i][0] >= 0.6:\n line.insert(0, 'Positive')\n else:\n line.insert(0, 'Negative')\n i += 1\n w.writerow(line)\n\n\n" ]
[ [ "sklearn.preprocessing.LabelEncoder", "numpy.array", "pandas.read_csv", "numpy.unique" ] ]
FilomenoSanchez/ample
[ "f38c8e5ce646d66638f1a88ff5cf34bd3b9e1490" ]
[ "ample/ensembler/single_model.py" ]
[ "\"\"\"Ensembler module for single model structures\"\"\"\n\n__author__ = \"Felix Simkovic, and Jens Thomas\"\n__date__ = \"16 Feb 2016\"\n__version__ = \"1.0\"\n\nimport logging\nimport os\nimport pandas as pd\n\nfrom ample.ensembler import _ensembler, truncation_util\nfrom ample.ensembler.constants import SIDE_CHAIN_TREATMENTS\nfrom ample.util import ample_util, pdb_edit\n\nlogger = logging.getLogger(__name__)\n\n\nclass SingleModelEnsembler(_ensembler.Ensembler):\n \"\"\"Ensemble creator using on a single input structure and a corresponding\n score file with per residue scores for truncation\n \"\"\"\n\n def __init__(self, **kwargs):\n # Inherit all functions from Parent Ensembler\n super(SingleModelEnsembler, self).__init__(**kwargs)\n\n # Set SingleModelEnsembler specific parameters\n self.truncation_scorefile = None\n\n return\n\n def generate_ensembles(\n self,\n models,\n ensembles_directory=None,\n nproc=None,\n percent_truncation=None,\n percent_fixed_intervals=None,\n side_chain_treatments=SIDE_CHAIN_TREATMENTS,\n truncation_method=None,\n truncation_pruning=None,\n truncation_scorefile=None,\n truncation_scorefile_header=None,\n ):\n \"\"\"Method to generate ensembles from a single structure based on \n residue scores\"\"\"\n\n if not truncation_method:\n truncation_method = self.truncation_method\n if not truncation_pruning:\n truncation_pruning = self.truncation_pruning\n if not truncation_scorefile:\n truncation_scorefile = self.truncation_scorefile\n\n if len(models) > 1:\n msg = \"More than 1 structure provided\"\n logger.critical(msg)\n raise RuntimeError(msg)\n\n if len(truncation_scorefile_header) < 2:\n msg = \"At least two header options for scorefile are required\"\n logger.critical(msg)\n raise RuntimeError(msg)\n\n # standardise the structure\n std_models_dir = os.path.join(self.work_dir, \"std_models\")\n os.mkdir(std_models_dir)\n\n std_model = ample_util.filename_append(models[0], 'std', std_models_dir)\n pdb_edit.standardise(pdbin=models[0], pdbout=std_model, del_hetatm=True)\n std_models = [std_model]\n logger.info('Standardised input model: %s', std_models[0])\n\n # Create final ensembles directory\n if not os.path.isdir(self.ensembles_directory):\n os.mkdir(self.ensembles_directory)\n\n truncate_dir = os.path.join(self.work_dir, \"single_truncate\")\n if not os.path.isdir(truncate_dir):\n os.mkdir(truncate_dir)\n\n # Read all the scores into a per residue dictionary\n assert len(truncation_scorefile_header) > 1, \"At least two column labels are required\"\n residue_scores = self._read_scorefile(truncation_scorefile)\n residue_key = truncation_scorefile_header.pop(0)\n truncation_scorefile_header = map(str.strip, truncation_scorefile_header)\n assert all(\n h in residue_scores[0] for h in truncation_scorefile_header\n ), \"Not all column labels are in your CSV file\"\n self.ensembles = []\n for score_key in truncation_scorefile_header:\n zipped_scores = self._generate_residue_scorelist(residue_key, score_key, residue_scores)\n score_truncate_dir = os.path.join(truncate_dir, \"{}\".format(score_key))\n if not os.path.isdir(score_truncate_dir):\n os.mkdir(score_truncate_dir)\n\n self.truncator = truncation_util.Truncator(work_dir=score_truncate_dir)\n self.truncator.theseus_exe = self.theseus_exe\n for truncation in self.truncator.truncate_models(\n models=std_models,\n truncation_method=truncation_method,\n percent_truncation=percent_truncation,\n percent_fixed_intervals=percent_fixed_intervals,\n truncation_pruning=truncation_pruning,\n residue_scores=zipped_scores,\n ):\n\n pre_ensemble = _ensembler.Ensemble()\n pre_ensemble.num_residues = truncation.num_residues\n pre_ensemble.truncation_dir = truncation.directory\n pre_ensemble.truncation_level = truncation.level\n pre_ensemble.truncation_method = truncation.method\n pre_ensemble.truncation_percent = truncation.percent\n pre_ensemble.truncation_residues = truncation.residues\n pre_ensemble.truncation_variance = truncation.variances\n pre_ensemble.truncation_score_key = score_key.lower()\n pre_ensemble.pdb = truncation.models[0]\n\n for ensemble in self.edit_side_chains(pre_ensemble, side_chain_treatments, single_structure=True):\n self.ensembles.append(ensemble)\n\n return self.ensembles\n\n def generate_ensembles_from_amoptd(self, models, amoptd):\n \"\"\"Generate ensembles from data in supplied ample data dictionary.\"\"\"\n kwargs = {\n 'percent_truncation': amoptd['percent'],\n 'percent_fixed_intervals': amoptd['percent_fixed_intervals'],\n 'side_chain_treatments': amoptd['side_chain_treatments'],\n 'truncation_method': amoptd['truncation_method'],\n 'truncation_pruning': amoptd['truncation_pruning'],\n 'truncation_scorefile': amoptd['truncation_scorefile'],\n 'truncation_scorefile_header': amoptd['truncation_scorefile_header'],\n }\n kwargs = {k: v for k, v in kwargs.iteritems() if v is not None}\n return self.generate_ensembles(models, **kwargs)\n\n @staticmethod\n def _generate_residue_scorelist(residue_key, score_key, scores):\n \"\"\"Generate a zipped list of residue indexes and corresponding scores\n \n :residue_key: residue column header keyword\n :score_key: score column header keyword\n :scores: list of dictionaries for each residue\n \n :returns: zipped list of residue index plus score\n \"\"\"\n assert residue_key in scores[0], \"Cannot find residue key {} in scoresfile header: {}\".format(\n residue_key, scores[0]\n )\n assert score_key in scores[0], \"Cannot find score key {} in scoresfile header: {}\".format(score_key, scores[0])\n return [(i[residue_key], i[score_key]) for i in scores]\n\n @staticmethod\n def _read_scorefile(scorefile):\n \"\"\"\n :scorefile: CSV score file INCLUDING header line\n \n :returns: list of per residue dictionaries containing column data\n \"\"\"\n df = pd.read_csv(scorefile)\n df.rename(columns=lambda x: x.strip(), inplace=True)\n return df.T.to_dict().values()\n" ]
[ [ "pandas.read_csv" ] ]
Sideboard/QUIP
[ "f41372609e4a92fcda9f33b695a666de3886822b" ]
[ "tests/test_filepot.py" ]
[ "# HQ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n# HQ X\n# HQ X quippy: Python interface to QUIP atomistic simulation library\n# HQ X\n# HQ X Copyright James Kermode 2019\n# HQ X\n# HQ X These portions of the source code are released under the GNU General\n# HQ X Public License, version 2, http://www.gnu.org/copyleft/gpl.html\n# HQ X\n# HQ X If you would like to license the source code under different terms,\n# HQ X please contact James Kermode, [email protected]\n# HQ X\n# HQ X When using this software, please cite the following reference:\n# HQ X\n# HQ X http://www.jrkermode.co.uk/quippy\n# HQ X\n# HQ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n\n\"\"\" Si structure to be studied was generated with the old vesion:\n$bash: python2\n> import quippy\n> quippy.system_reseed_rng(2065775975)\n> at = quippy.diamond(5.44, 14)\n> quippy.randomise(at.pos, 0.1)\n> print(at.positions)\n[[-0.04999922 0.01792964 0.01711494]\n [ 1.32315378 1.40346929 1.31076982]\n [ 2.74556053 2.70835021 -0.01165843]\n [ 4.07586501 4.08194164 1.31668422]\n [ 2.72327672 0.03309653 2.7117486 ]\n [ 4.05189592 1.31345721 4.09867727]\n [-0.04529554 2.67534616 2.72889766]\n [ 1.37788647 4.08297002 4.12304365]]\n\"\"\"\n\nimport unittest\nimport quippy\nimport numpy as np\nimport quippytest\nimport ase.build\nimport ase\n\ndiamond_pos = np.array([[-0.04999922, 0.01792964, 0.01711494],\n [1.32315378, 1.40346929, 1.31076982],\n [2.74556053, 2.70835021, -0.01165843],\n [4.07586501, 4.08194164, 1.31668422],\n [2.72327672, 0.03309653, 2.7117486],\n [4.05189592, 1.31345721, 4.09867727],\n [-0.04529554, 2.67534616, 2.72889766],\n [1.37788647, 4.08297002, 4.12304365]])\n\n\nclass TestCalculator_SW_Potential(quippytest.QuippyTestCase):\n def setUp(self):\n xml = \"\"\"\n <SW_params n_types=\"2\" label=\"PRB_31_plus_H\">\n <comment> Stillinger and Weber, Phys. Rev. B 31 p 5262 (1984), extended for other elements </comment>\n <per_type_data type=\"1\" atomic_num=\"1\" />\n <per_type_data type=\"2\" atomic_num=\"14\" />\n <per_pair_data atnum_i=\"1\" atnum_j=\"1\" AA=\"0.0\" BB=\"0.0\"\n p=\"0\" q=\"0\" a=\"1.0\" sigma=\"1.0\" eps=\"0.0\" />\n <per_pair_data atnum_i=\"1\" atnum_j=\"14\" AA=\"8.581214\" BB=\"0.0327827\"\n p=\"4\" q=\"0\" a=\"1.25\" sigma=\"2.537884\" eps=\"2.1672\" />\n <per_pair_data atnum_i=\"14\" atnum_j=\"14\" AA=\"7.049556277\" BB=\"0.6022245584\"\n p=\"4\" q=\"0\" a=\"1.80\" sigma=\"2.0951\" eps=\"2.1675\" />\n\n <!-- triplet terms: atnum_c is the center atom, neighbours j and k -->\n <per_triplet_data atnum_c=\"1\" atnum_j=\"1\" atnum_k=\"1\"\n lambda=\"21.0\" gamma=\"1.20\" eps=\"2.1675\" />\n <per_triplet_data atnum_c=\"1\" atnum_j=\"1\" atnum_k=\"14\"\n lambda=\"21.0\" gamma=\"1.20\" eps=\"2.1675\" />\n <per_triplet_data atnum_c=\"1\" atnum_j=\"14\" atnum_k=\"14\"\n lambda=\"21.0\" gamma=\"1.20\" eps=\"2.1675\" />\n\n <per_triplet_data atnum_c=\"14\" atnum_j=\"1\" atnum_k=\"1\"\n lambda=\"21.0\" gamma=\"1.20\" eps=\"2.1675\" />\n <per_triplet_data atnum_c=\"14\" atnum_j=\"1\" atnum_k=\"14\"\n lambda=\"21.0\" gamma=\"1.20\" eps=\"2.1675\" />\n <per_triplet_data atnum_c=\"14\" atnum_j=\"14\" atnum_k=\"14\"\n lambda=\"21.0\" gamma=\"1.20\" eps=\"2.1675\" />\n </SW_params>\n \"\"\"\n\n quippy.system_module.system_reseed_rng(2065775975)\n self.pot_calculator = quippy.potential.Potential(\"IP SW\", param_filename=\"SW_pot.xml\")\n\n self.at = ase.Atoms('Si8', positions=diamond_pos, pbc=True, cell=[5.44, 5.44, 5.44])\n\n self.f = np.zeros((3, len(self.at)), order='F')\n self.df = np.zeros((3, len(self.at)), order='F')\n self.v = np.zeros((3, 3), order='F')\n\n self.energy_ref = -34.5038375509\n\n self.forces_ref = np.array([[0.89920374, -0.38025157, -0.38727027],\n [0.36623356, -0.52403757, 0.7200206],\n [-0.36952654, 0.12899529, 0.00458111],\n [-0.19912365, -0.1632057, 1.08509495],\n [-0.67565314, -0.59410498, -0.47921521],\n [0.17097454, 0.5847822, -0.31088749],\n [0.43613712, 0.90811269, 0.1600328],\n [-0.62824563, 0.03970963, -0.79235649]])\n\n self.virial_ref = np.array([[-0.34103601, 0.60925144, -0.02138795],\n [0.60925144, -0.36145702, -0.19375487],\n [-0.02138795, -0.19375487, -0.34640615]]).T\n\n # Voigt notation by hand from virial\n self.stress_ref = - np.array([-0.34103601, -0.36145702, -0.34640615,\n - 0.19375487, -0.02138795, 0.60925144]) / self.at.get_volume()\n\n self.at.calc = self.pot_calculator\n\n def test_energy(self):\n self.assertAlmostEqual(self.at.get_potential_energy(), self.energy_ref)\n\n def test_forces(self):\n self.assertArrayAlmostEqual(self.at.get_forces(), self.forces_ref, tol=1E-06)\n\n def test_stress(self):\n self.assertArrayAlmostEqual(self.at.get_stress(), self.stress_ref)\n\n def test_virial(self):\n self.assertArrayAlmostEqual(self.pot_calculator.get_virial(self.at), self.virial_ref, tol=1E-06)\n\n # def test_numeric_forces(self):\n # self.assertArrayAlmostEqual(self.pot.get_numeric_forces(self.at), self.f_ref.T, tol=1e-4)\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
robots-helpinghandslab/or_ompl
[ "1e02092cfbff6e21c8050eb807017124a43deae9" ]
[ "tests/test_Planner.py" ]
[ "#!//bin/env python\nfrom __future__ import print_function\nimport numpy\nimport unittest\nimport openravepy\nimport os\nimport subprocess\nimport sys\n\n\n# Add the models included with OpenRAVE to the OPENRAVE_DATA path. These may\n# not be available if the user manually set the OPENRAVE_DATA environmental\n# variable, e.g. through openrave_catkin.\ntry:\n share_path = subprocess.check_output(['openrave-config', '--share-dir']).strip()\n os.environ['OPENRAVE_DATA'] = os.path.join(share_path, 'data')\nexcept subprocess.CalledProcessError as e:\n print('error: Failed using \"openrave-config\" to find the default'\n ' OPENRAVE_DATA path. Loading assets may fail.',\n file=sys.stderr)\n\n# Initialize OpenRAVE.\nopenravepy.RaveInitialize(True)\nopenravepy.misc.InitOpenRAVELogging()\nopenravepy.RaveSetDebugLevel(openravepy.DebugLevel.Debug)\n\n\nclass PlannerTestsMeta(type):\n PLANNER_NAMES = [\n \"BKPIECE1\",\n \"EST\",\n \"KPIECE1\",\n \"LazyRRT\",\n \"LBKPIECE1\",\n \"PRM\",\n \"LazyPRM\",\n \"PRMstar\",\n \"RRT\",\n \"RRTConnect\",\n \"SBL\",\n #\"PDST\", # often fails to find a solution\n #\"RRTstar\", # often fails to find a solution\n #\"SPARS\", # often fails to find a solution\n #\"SPARStwo\", # often fails to find a solution\n #\"TRRT\", # often fails to find a solution\n #\"pRRT\", # immediately SEGFAULTs\n #\"pSBL\", # immediately throws an InvalidState exception\n ]\n\n\n def __init__(self, names, bases, attrs):\n super(PlannerTestsMeta, self).__init__(names, bases, attrs)\n\n\n def __new__(cls, name, bases, attrs):\n # Create a test for each planner in PLANNER_NAMES.\n for planner_name in cls.PLANNER_NAMES:\n func = cls.create_test(planner_name)\n attrs[func.__name__] = func\n\n return super(PlannerTestsMeta, cls).__new__(cls, name, bases, attrs)\n\n\n @classmethod\n def create_test(self, planner_name):\n def func(self):\n return self.run_planner(planner_name)\n\n func.__name__ = 'test_' + planner_name\n return func\n\n\nclass PlannerTests(unittest.TestCase):\n __metaclass__ = PlannerTestsMeta\n\n NUM_ATTEMPTS = 5\n START_CONFIG = numpy.array([\n 0.80487864, 0.42326865, -0.54016693, 2.28895761,\n -0.34930645, -1.19702164, 1.95971213 ])\n GOAL_CONFIG = numpy.array([\n 2.41349473, -1.43062044, -2.69016693, 2.12681216,\n -0.75643783, -1.52392537, 1.01239878 ])\n TRAJECTORY_XML = \"\"\"\\\n<trajectory>\n<configuration>\n<group name=\"joint_values BarrettWAM 0 1 2 3 4 5 6\" offset=\"0\" dof=\"7\" interpolation=\"linear\"/>\n</configuration>\n<data count=\"8\">\n0.80487864 0.42326865 -0.5401669299999999 2.28895761 -0.3493064500000005 -1.19702164 1.95971213 -0.3668195289171482 -0.1719619318499316 0.340737234496427 2.338352935126714 -1.140328948362108 -0.4582953771266394 0.1660684228974656 -0.4316746373996911 -0.1254090482184572 1.337385046499522 0.7087144047880871 -1.48802896774604 0.4679460445583862 -1.337254061021721 0.624583530772981 1.117893213994084 2.633833996473851 0.05391426760723994 -1.669197857527277 0.9002033682607622 -2.714157270255535 0.6372202491284563 1.09989072774182 2.596225701405203 0.06855704409449326 -1.662750197409222 0.8830795265988333 -2.687833191529146 1.229311742752304 0.2563870051612129 0.8340948242701349 0.7546420827296624 -1.360646074939481 0.08074456106588879 -1.454422534352764 1.821403236376152 -0.5871167174193935 -0.9280360528649325 1.440727121364831 -1.058541952469741 -0.7215904044670555 -0.2210118771763818 2.41349473 -1.43062044 -2.69016693 2.12681216 -0.75643783 -1.52392537 1.01239878 </data>\n</trajectory>\"\"\"\n\n\n def setUp(self):\n self.env = openravepy.Environment()\n self.env.Load('wamtest1.env.xml')\n self.robot = self.env.GetRobot('BarrettWAM')\n self.manipulator = self.robot.GetManipulator('arm')\n\n with self.env:\n self.robot.SetActiveDOFs(self.manipulator.GetArmIndices())\n self.robot.SetActiveDOFValues(self.START_CONFIG)\n self.robot.SetActiveManipulator(self.manipulator)\n\n\n def tearDown(self):\n self.env.Destroy()\n\n\n def run_planner(self, planner_name):\n with self.env:\n # Setup\n params = openravepy.Planner.PlannerParameters()\n params.SetRobotActiveJoints(self.robot)\n params.SetGoalConfig(self.GOAL_CONFIG)\n params.SetExtraParameters('<time_limit>60</time_limit>')\n\n cspec = self.robot.GetActiveConfigurationSpecification()\n\n traj = openravepy.RaveCreateTrajectory(self.env, '')\n\n for i in xrange(self.NUM_ATTEMPTS):\n # Act\n planner = openravepy.RaveCreatePlanner(\n self.env, 'OMPL_' + planner_name)\n planner.InitPlan(self.robot, params)\n result = planner.PlanPath(traj)\n\n if result == openravepy.PlannerStatus.HasSolution:\n break\n\n # Assert\n self.assertEqual(result, openravepy.PlannerStatus.HasSolution)\n self.assertGreaterEqual(traj.GetNumWaypoints(), 1)\n numpy.testing.assert_array_almost_equal(\n traj.GetWaypoint(0, cspec),\n self.START_CONFIG)\n numpy.testing.assert_array_almost_equal(\n traj.GetWaypoint(traj.GetNumWaypoints() - 1, cspec),\n self.GOAL_CONFIG)\n\n\n def test_Simplifier(self):\n with self.env:\n # Setup\n simplifier = openravepy.RaveCreatePlanner(self.env, 'OMPL_Simplifier')\n params = openravepy.Planner.PlannerParameters()\n\n cspec = self.robot.GetActiveConfigurationSpecification()\n\n traj = openravepy.RaveCreateTrajectory(self.env, '')\n traj.deserialize(self.TRAJECTORY_XML)\n\n # Act\n simplifier.InitPlan(self.robot, params)\n result = simplifier.PlanPath(traj)\n\n # Assert\n self.assertEqual(result, openravepy.PlannerStatus.HasSolution)\n self.assertGreaterEqual(traj.GetNumWaypoints(), 1)\n numpy.testing.assert_array_almost_equal(\n traj.GetWaypoint(0, cspec),\n self.START_CONFIG)\n numpy.testing.assert_array_almost_equal(\n traj.GetWaypoint(traj.GetNumWaypoints() - 1, cspec),\n self.GOAL_CONFIG)\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.array" ] ]
ankushagarwal/tensor2tensor
[ "42a788355a209f21bbf5fd52d56d514405e193a3" ]
[ "tensor2tensor/bin/t2t_decoder.py" ]
[ "# coding=utf-8\n# Copyright 2018 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nr\"\"\"Decode from trained T2T models.\n\nThis binary performs inference using the Estimator API.\n\nExample usage to decode from dataset:\n\n t2t-decoder \\\n --data_dir ~/data \\\n --problem=algorithmic_identity_binary40 \\\n --model=transformer\n --hparams_set=transformer_base\n\nSet FLAGS.decode_interactive or FLAGS.decode_from_file for alternative decode\nsources.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\n# Dependency imports\n\nfrom tensor2tensor.bin import t2t_trainer\nfrom tensor2tensor.data_generators import text_encoder\nfrom tensor2tensor.utils import decoding\nfrom tensor2tensor.utils import registry\nfrom tensor2tensor.utils import trainer_lib\nfrom tensor2tensor.utils import usr_dir\n\nimport tensorflow as tf\n\nflags = tf.flags\nFLAGS = flags.FLAGS\n\n# Additional flags in bin/t2t_trainer.py and utils/flags.py\nflags.DEFINE_string(\"checkpoint_path\", None,\n \"Path to the model checkpoint. Overrides output_dir.\")\nflags.DEFINE_string(\"decode_from_file\", None,\n \"Path to the source file for decoding\")\nflags.DEFINE_string(\"decode_to_file\", None,\n \"Path to the decoded (output) file\")\nflags.DEFINE_bool(\"keep_timestamp\", False,\n \"Set the mtime of the decoded file to the \"\n \"checkpoint_path+'.index' mtime.\")\nflags.DEFINE_bool(\"decode_interactive\", False,\n \"Interactive local inference mode.\")\nflags.DEFINE_integer(\"decode_shards\", 1, \"Number of decoding replicas.\")\nflags.DEFINE_string(\"score_file\", \"\", \"File to score. Each line in the file \"\n \"must be in the format input \\t target.\")\n\n\ndef create_hparams():\n return trainer_lib.create_hparams(\n FLAGS.hparams_set,\n FLAGS.hparams,\n data_dir=os.path.expanduser(FLAGS.data_dir),\n problem_name=FLAGS.problem)\n\n\ndef create_decode_hparams():\n decode_hp = decoding.decode_hparams(FLAGS.decode_hparams)\n decode_hp.add_hparam(\"shards\", FLAGS.decode_shards)\n decode_hp.add_hparam(\"shard_id\", FLAGS.worker_id)\n return decode_hp\n\n\ndef decode(estimator, hparams, decode_hp):\n if FLAGS.decode_interactive:\n decoding.decode_interactively(estimator, hparams, decode_hp,\n checkpoint_path=FLAGS.checkpoint_path)\n elif FLAGS.decode_from_file:\n decoding.decode_from_file(estimator, FLAGS.decode_from_file, hparams,\n decode_hp, FLAGS.decode_to_file,\n checkpoint_path=FLAGS.checkpoint_path)\n if FLAGS.checkpoint_path and FLAGS.keep_timestamp:\n ckpt_time = os.path.getmtime(FLAGS.checkpoint_path + \".index\")\n os.utime(FLAGS.decode_to_file, (ckpt_time, ckpt_time))\n else:\n decoding.decode_from_dataset(\n estimator,\n FLAGS.problem,\n hparams,\n decode_hp,\n decode_to_file=FLAGS.decode_to_file,\n dataset_split=\"test\" if FLAGS.eval_use_test_set else None)\n\n\ndef score_file(filename):\n \"\"\"Score each line in a file and return the scores.\"\"\"\n # Prepare model.\n hparams = create_hparams()\n encoders = registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir)\n has_inputs = \"inputs\" in encoders\n\n # Prepare features for feeding into the model.\n if has_inputs:\n inputs_ph = tf.placeholder(dtype=tf.int32) # Just length dimension.\n batch_inputs = tf.reshape(inputs_ph, [1, -1, 1, 1]) # Make it 4D.\n targets_ph = tf.placeholder(dtype=tf.int32) # Just length dimension.\n batch_targets = tf.reshape(targets_ph, [1, -1, 1, 1]) # Make it 4D.\n features = {\n \"inputs\": batch_inputs,\n \"targets\": batch_targets,\n } if has_inputs else {\"targets\": batch_targets}\n\n # Prepare the model and the graph when model runs on features.\n model = registry.model(FLAGS.model)(hparams, tf.estimator.ModeKeys.EVAL)\n _, losses = model(features)\n saver = tf.train.Saver()\n\n with tf.Session() as sess:\n # Load weights from checkpoint.\n ckpts = tf.train.get_checkpoint_state(FLAGS.output_dir)\n ckpt = ckpts.model_checkpoint_path\n saver.restore(sess, ckpt)\n # Run on each line.\n results = []\n for line in open(filename):\n tab_split = line.split(\"\\t\")\n if len(tab_split) > 2:\n raise ValueError(\"Each line must have at most one tab separator.\")\n if len(tab_split) == 1:\n targets = tab_split[0].strip()\n else:\n targets = tab_split[1].strip()\n inputs = tab_split[0].strip()\n # Run encoders and append EOS symbol.\n targets_numpy = encoders[\"targets\"].encode(\n targets) + [text_encoder.EOS_ID]\n if has_inputs:\n inputs_numpy = encoders[\"inputs\"].encode(inputs) + [text_encoder.EOS_ID]\n # Prepare the feed.\n feed = {\n inputs_ph: inputs_numpy,\n targets_ph: targets_numpy\n } if has_inputs else {targets_ph: targets_numpy}\n # Get the score.\n np_loss = sess.run(losses[\"training\"], feed)\n results.append(np_loss)\n return results\n\n\ndef main(_):\n tf.logging.set_verbosity(tf.logging.INFO)\n trainer_lib.set_random_seed(FLAGS.random_seed)\n usr_dir.import_usr_dir(FLAGS.t2t_usr_dir)\n FLAGS.use_tpu = False # decoding not supported on TPU\n\n if FLAGS.score_file:\n filename = os.path.expanduser(FLAGS.score_file)\n if not tf.gfile.Exists(filename):\n raise ValueError(\"The file to score doesn't exist: %s\" % filename)\n results = score_file(filename)\n if not FLAGS.decode_to_file:\n raise ValueError(\"To score a file, specify --decode_to_file for results.\")\n write_file = open(os.path.expanduser(FLAGS.decode_to_file), \"w\")\n for score in results:\n write_file.write(\"%.6f\\n\" % score)\n write_file.close()\n return\n\n hp = create_hparams()\n decode_hp = create_decode_hparams()\n\n estimator = trainer_lib.create_estimator(\n FLAGS.model,\n hp,\n t2t_trainer.create_run_config(hp),\n decode_hparams=decode_hp,\n use_tpu=False)\n\n decode(estimator, hp, decode_hp)\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n" ]
[ [ "tensorflow.train.get_checkpoint_state", "tensorflow.gfile.Exists", "tensorflow.reshape", "tensorflow.placeholder", "tensorflow.logging.set_verbosity", "tensorflow.Session", "tensorflow.train.Saver", "tensorflow.app.run" ] ]
fscottfoti/activitysim
[ "cc18cce84b2e4b5f380f58c7919953d2cd03ee73" ]
[ "activitysim/core/test/test_los.py" ]
[ "# ActivitySim\n# See full license in LICENSE.txt.\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport numpy.testing as npt\nimport pandas.testing as pdt\nimport pytest\n\nfrom activitysim.core import orca\n\nfrom .. import inject\nfrom .. import los\n\n\ndef teardown_function(func):\n inject.clear_cache()\n inject.reinject_decorated_tables()\n\n\ndef add_canonical_dirs(configs_dir_name):\n\n configs_dir = os.path.join(os.path.dirname(__file__), f'los/{configs_dir_name}')\n inject.add_injectable(\"configs_dir\", configs_dir)\n\n data_dir = os.path.join(os.path.dirname(__file__), f'los/data')\n inject.add_injectable(\"data_dir\", data_dir)\n\n output_dir = os.path.join(os.path.dirname(__file__), f'output')\n inject.add_injectable(\"output_dir\", output_dir)\n\n\ndef test_legacy_configs():\n\n add_canonical_dirs('configs_legacy_settings')\n\n with pytest.warns(FutureWarning):\n network_los = los.Network_LOS()\n\n assert network_los.setting('zone_system') == los.ONE_ZONE\n\n assert 'z1_taz_skims.omx' in network_los.omx_file_names('taz')\n\n\ndef test_one_zone():\n\n add_canonical_dirs('configs_1z')\n\n network_los = los.Network_LOS()\n\n assert network_los.setting('zone_system') == los.ONE_ZONE\n\n assert 'z1_taz_skims.omx' in network_los.omx_file_names('taz')\n\n network_los.load_data()\n\n # OMAZ, DMAZ, DIST, DISTBIKE\n # 23000,21000,1.89,1.89\n # 23000,22000,0.89,0.89\n # 23000,23000,0.19,0.19\n\n od_df = pd.DataFrame({\n 'orig': [5, 23, 23, 23],\n 'dest': [7, 20, 21, 22]\n })\n\n skim_dict = network_los.get_default_skim_dict()\n\n # skims should be the same as maz_to_maz distances in test data where 1 MAZ per TAZ\n # OMAZ, DMAZ, DIST, DISTBIKE\n # 1000, 2000, 0.24, 0.24\n # 23000,20000,2.55,2.55\n # 23000,21000,1.9,1.9\n # 23000,22000,0.62,0.62\n skims = skim_dict.wrap('orig', 'dest')\n skims.set_df(od_df)\n pdt.assert_series_equal(skims['DIST'], pd.Series([0.4, 2.55, 1.9, 0.62]).astype(np.float32))\n\n # OMAZ, DMAZ, DIST, DISTBIKE\n # 2000, 1000, 0.37, 0.37\n # 20000,23000,2.45,2.45\n # 21000,23000,1.89,1.89\n # 22000,23000,0.89,0.89\n\n skims = skim_dict.wrap('dest', 'orig')\n skims.set_df(od_df)\n pdt.assert_series_equal(skims['DIST'], pd.Series([0.46, 2.45, 1.89, 0.89]).astype(np.float32))\n\n\ndef test_two_zone():\n\n add_canonical_dirs('configs_2z')\n\n network_los = los.Network_LOS()\n\n assert network_los.setting('zone_system') == los.TWO_ZONE\n\n assert 'z2_taz_skims.omx' in network_los.omx_file_names('taz')\n\n assert network_los.blend_distance_skim_name == 'DIST'\n\n network_los.load_data()\n\n skim_dict = network_los.get_default_skim_dict()\n\n # skims should be the same as maz_to_maz distances when no blending\n od_df = pd.DataFrame({\n 'orig': [1000, 2000, 23000, 23000, 23000],\n 'dest': [2000, 2000, 20000, 21000, 22000]\n })\n # compare to distances from maz_to_maz table\n dist = pd.Series(network_los.get_mazpairs(od_df.orig, od_df.dest, 'DIST')).astype(np.float32)\n # make sure we got the right values\n pdt.assert_series_equal(dist, pd.Series([0.24, 0.14, 2.55, 1.9, 0.62]).astype(np.float32))\n\n skims = skim_dict.wrap('orig', 'dest')\n skims.set_df(od_df)\n # assert no blending for DISTBIKE\n assert network_los.max_blend_distance.get('DISTBIKE', 0) == 0\n\n skim_dist = skims['DISTBIKE']\n\n print(type(skims), type(skim_dist.iloc[0]))\n print(type(dist.iloc[0]))\n pdt.assert_series_equal(skim_dist, dist)\n\n # but should be different where maz-maz distance differs from skim backstop and blending desired\n # blending enabled for DIST\n assert network_los.max_blend_distance.get('DIST') > 0\n with pytest.raises(AssertionError) as excinfo:\n pdt.assert_series_equal(skims['DIST'], dist)\n\n\ndef test_three_zone():\n\n add_canonical_dirs('configs_3z')\n\n network_los = los.Network_LOS()\n\n assert network_los.setting('zone_system') == los.THREE_ZONE\n\n assert 'z3_taz_skims.omx' in network_los.omx_file_names('taz')\n\n assert network_los.blend_distance_skim_name == 'DIST'\n\n network_los.load_data()\n\n od_df = pd.DataFrame({\n 'orig': [1000, 2000, 23000, 23000, 23000],\n 'dest': [2000, 2000, 20000, 21000, 22000]\n })\n\n dist = network_los.get_mazpairs(od_df.orig, od_df.dest, 'DIST').astype(np.float32)\n np.testing.assert_almost_equal(dist, [0.24, 0.14, 2.55, 1.9, 0.62])\n\n\ndef test_30_minute_windows():\n\n add_canonical_dirs('configs_test_misc')\n network_los = los.Network_LOS(los_settings_file_name='settings_30_min.yaml')\n\n assert network_los.skim_time_period_label(1) == 'EA'\n assert network_los.skim_time_period_label(16) == 'AM'\n assert network_los.skim_time_period_label(24) == 'MD'\n assert network_los.skim_time_period_label(36) == 'PM'\n assert network_los.skim_time_period_label(46) == 'EV'\n\n pd.testing.assert_series_equal(\n network_los.skim_time_period_label(pd.Series([1, 16, 24, 36, 46])),\n pd.Series(['EA', 'AM', 'MD', 'PM', 'EV']))\n\n\ndef test_60_minute_windows():\n\n add_canonical_dirs('configs_test_misc')\n network_los = los.Network_LOS(los_settings_file_name='settings_60_min.yaml')\n\n assert network_los.skim_time_period_label(1) == 'EA'\n assert network_los.skim_time_period_label(8) == 'AM'\n assert network_los.skim_time_period_label(12) == 'MD'\n assert network_los.skim_time_period_label(18) == 'PM'\n assert network_los.skim_time_period_label(23) == 'EV'\n\n pd.testing.assert_series_equal(\n network_los.skim_time_period_label(pd.Series([1, 8, 12, 18, 23])),\n pd.Series(['EA', 'AM', 'MD', 'PM', 'EV']))\n\n\ndef test_1_week_time_window():\n\n add_canonical_dirs('configs_test_misc')\n network_los = los.Network_LOS(los_settings_file_name='settings_1_week.yaml')\n\n assert network_los.skim_time_period_label(1) == 'Sunday'\n assert network_los.skim_time_period_label(2) == 'Monday'\n assert network_los.skim_time_period_label(3) == 'Tuesday'\n assert network_los.skim_time_period_label(4) == 'Wednesday'\n assert network_los.skim_time_period_label(5) == 'Thursday'\n assert network_los.skim_time_period_label(6) == 'Friday'\n assert network_los.skim_time_period_label(7) == 'Saturday'\n\n weekly_series = network_los.skim_time_period_label(pd.Series([1, 2, 3, 4, 5, 6, 7]))\n\n pd.testing.assert_series_equal(weekly_series,\n pd.Series(['Sunday', 'Monday', 'Tuesday', 'Wednesday',\n 'Thursday', 'Friday', 'Saturday']))\n\n\ndef test_skim_time_periods_future_warning():\n\n add_canonical_dirs('configs_test_misc')\n\n with pytest.warns(FutureWarning) as warning_test:\n network_los = los.Network_LOS(los_settings_file_name='settings_legacy_hours_key.yaml')\n" ]
[ [ "numpy.testing.assert_almost_equal", "pandas.testing.assert_series_equal", "pandas.Series", "pandas.DataFrame" ] ]
perillaroc/reki-data-tool
[ "047424a2f8a1f0e16684bffaeded4044366f63c0" ]
[ "reki_data_tool/ml/moml/validate/index.py" ]
[ "import numpy as np\nimport xarray as xr\nimport pandas as pd\n\n\ndef rmse(forecast, analysis):\n return np.sqrt(\n np.sum(\n np.power(forecast - analysis, 2)\n /\n np.product(analysis.shape)\n )\n )\n" ]
[ [ "numpy.product", "numpy.power" ] ]
ranapratapdas/aipnd-project
[ "5108b3c2f12d4fa5a4b1e0a5131344f2c39c3a74" ]
[ "predict.py" ]
[ "import matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch import tensor\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torchvision import datasets, transforms\nimport torchvision.models as models\nfrom collections import OrderedDict\nimport json\nimport PIL\nfrom PIL import Image\nimport argparse\n\nimport nn_helper\n\n#Command Line Arguments\n\nap = argparse.ArgumentParser(\n description='predict.py')\nap.add_argument('input_img', default='flowers/test/1/image_06752.jpg', nargs='*', action=\"store\", type = str)\nap.add_argument('checkpoint', default='/home/workspace/aipnd-project-project/checkpoint.pth', nargs='*', action=\"store\",type = str)\nap.add_argument('--top_k', default=5, dest=\"top_k\", action=\"store\", type=int)\nap.add_argument('--category_names', dest=\"category_names\", action=\"store\", default='cat_to_name.json')\nap.add_argument('--gpu', default=\"gpu\", action=\"store\", dest=\"gpu\")\n\npa = ap.parse_args()\npath_image = pa.input_img\nnumber_of_outputs = pa.top_k\npower = pa.gpu\ninput_img = pa.input_img\npath = pa.checkpoint\n\n\nmodel = nn_helper.load_checkpoint(path)\n\nwith open('cat_to_name.json', 'r') as json_file:\n cat_to_name = json.load(json_file)\n\n\nprobabilities = nn_helper.predict(path_image, model, number_of_outputs, power)\n\n\nlabels = [cat_to_name[str(index + 1)] for index in np.array(probabilities[1][0])]\nprobability = np.array(probabilities[0][0])\n\ni=0\nwhile i < number_of_outputs:\n print(\"{} , probability {}\".format(labels[i], probability[i]))\n i += 1\n" ]
[ [ "numpy.array" ] ]
TanUkkii007/wavenet
[ "0df8ddb17b14d1f6a0ad5530977b6591f0feb642" ]
[ "datasets/dataset.py" ]
[ "import tensorflow as tf\nfrom collections import namedtuple\nfrom abc import abstractmethod\nfrom utils.tfrecord import decode_preprocessed_data, parse_preprocessed_data, PreprocessedData\n\n\nclass SourceData(namedtuple(\"SourceData\",\n [\"id\", \"key\", \"mel\", \"mel_length\", \"mel_width\", \"text\"])):\n pass\n\n\nclass TargetData(\n namedtuple(\"TargetData\",\n [\"id\", \"key\", \"waveform\", \"waveform_length\"])):\n pass\n\n\nclass SourceDataForPrediction(namedtuple(\"SourceDataForPrediction\",\n [\"id\", \"key\", \"mel\", \"mel_length\", \"mel_width\", \"text\", \"waveform\",\n \"waveform_length\"])):\n pass\n\n\ndef upsample_condition(condition, condition_length, times):\n last_dim = tf.shape(condition)[1]\n condition = tf.expand_dims(condition, 1)\n condition = tf.tile(condition, multiples=tf.convert_to_tensor([1, 1, times]))\n condition = tf.reshape(condition, shape=[-1, last_dim])\n condition_length = condition_length * times\n return condition, condition_length\n\n\ndef pad_waveform(wav, wav_length, condition_length):\n pad_length = condition_length - wav_length % condition_length\n wav = tf.pad(wav, paddings=tf.convert_to_tensor([[0, pad_length], [0, 0]]))\n wav_length = wav_length + pad_length\n return wav, wav_length\n\n\nclass DatasetSource:\n\n def __init__(self, dataset, hparams):\n self._dataset = dataset\n self._hparams = hparams\n\n @staticmethod\n def create_from_tfrecord_files(dataset_files, hparams, cycle_length=4,\n buffer_output_elements=None,\n prefetch_input_elements=None):\n dataset = tf.data.Dataset.from_generator(lambda: dataset_files, tf.string, tf.TensorShape([]))\n dataset = dataset.apply(tf.contrib.data.parallel_interleave(\n lambda filename: tf.data.TFRecordDataset(filename),\n cycle_length, sloppy=False,\n buffer_output_elements=buffer_output_elements,\n prefetch_input_elements=prefetch_input_elements))\n return DatasetSource(dataset, hparams)\n\n @property\n def hparams(self):\n return self._hparams\n\n def make_source_and_target(self):\n def make_pair(d: PreprocessedData):\n # ToDo: pad at the preprocessing time is more accurate\n waveform, waveform_length = pad_waveform(tf.expand_dims(d.waveform, axis=1), d.waveform_length,\n d.mel_length)\n times = waveform_length // d.mel_length\n mel, mel_length = upsample_condition(d.mel, d.mel_length, times)\n source = SourceData(id=d.id,\n key=d.key,\n mel=mel,\n mel_length=mel_length,\n mel_width=d.mel_width,\n text=d.text)\n target = TargetData(id=d.id,\n key=d.key,\n waveform=waveform,\n waveform_length=waveform_length)\n return source, target\n\n zipped = self._decode_data().map(make_pair)\n return ZippedDataset(zipped, self.hparams)\n\n def _decode_data(self):\n return self._dataset.map(lambda d: decode_preprocessed_data(parse_preprocessed_data(d)))\n\n\nclass DatasetBase:\n\n @abstractmethod\n def apply(self, dataset, hparams):\n raise NotImplementedError(\"apply\")\n\n @property\n @abstractmethod\n def dataset(self):\n raise NotImplementedError(\"dataset\")\n\n @property\n @abstractmethod\n def hparams(self):\n raise NotImplementedError(\"hparams\")\n\n def filter(self, predicate):\n return self.apply(self.dataset.filter(predicate), self.hparams)\n\n def filter_by_max_output_length(self):\n def predicate(s, t: PreprocessedData):\n max_output_length = self.hparams.max_output_length\n return tf.less_equal(t.waveform_length, max_output_length)\n\n return self.filter(predicate)\n\n def shuffle(self, buffer_size):\n return self.apply(self.dataset.shuffle(buffer_size), self.hparams)\n\n def repeat(self, count=None):\n return self.apply(self.dataset.repeat(count), self.hparams)\n\n def shuffle_and_repeat(self, buffer_size, count=None):\n dataset = self.dataset.apply(tf.contrib.data.shuffle_and_repeat(buffer_size, count))\n return self.apply(dataset, self.hparams)\n\n\nclass ZippedDataset(DatasetBase):\n\n def __init__(self, dataset, hparams):\n self._dataset = dataset\n self._hparams = hparams\n\n def apply(self, dataset, hparams):\n return ZippedDataset(dataset, hparams)\n\n @property\n def dataset(self):\n return self._dataset\n\n @property\n def hparams(self):\n return self._hparams\n\n def group_by_batch(self, batch_size=None):\n batch_size = batch_size if batch_size is not None else self.hparams.batch_size\n approx_min_target_length = self.hparams.approx_min_target_length\n bucket_width = self.hparams.batch_bucket_width\n num_buckets = self.hparams.batch_num_buckets\n\n def key_func(unused_source, target):\n target_length = tf.minimum(target.waveform_length - approx_min_target_length, 0)\n bucket_id = target_length // bucket_width\n return tf.minimum(tf.to_int64(num_buckets), bucket_id)\n\n def reduce_func(unused_key, window: tf.data.Dataset):\n return window.padded_batch(batch_size, padded_shapes=(\n SourceData(\n id=tf.TensorShape([]),\n key=tf.TensorShape([]),\n mel=tf.TensorShape([None, self.hparams.num_mels]),\n mel_length=tf.TensorShape([]),\n mel_width=tf.TensorShape([]),\n text=tf.TensorShape([]),\n ),\n TargetData(\n id=tf.TensorShape([]),\n key=tf.TensorShape([]),\n waveform=tf.TensorShape([None, 1]),\n waveform_length=tf.TensorShape([]),\n )), padding_values=(\n SourceData(\n id=tf.to_int64(0),\n key=\"\",\n mel=tf.to_float(0),\n mel_length=tf.to_int64(0),\n mel_width=tf.to_int64(0),\n text=\"\",\n ),\n TargetData(\n id=tf.to_int64(0),\n key=\"\",\n waveform=tf.to_float(0),\n waveform_length=tf.to_int64(0),\n )))\n\n batched = self.dataset.apply(tf.contrib.data.group_by_window(key_func,\n reduce_func,\n window_size=batch_size * 5))\n return BatchedDataset(batched, self.hparams)\n\n\nclass BatchedDataset(DatasetBase):\n\n def __init__(self, dataset: tf.data.Dataset, hparams):\n self._dataset = dataset\n self._hparams = hparams\n\n def apply(self, dataset, hparams):\n return BatchedDataset(dataset, hparams)\n\n @property\n def dataset(self):\n return self._dataset\n\n @property\n def hparams(self):\n return self._hparams\n\n def prefetch(self, buffer_size):\n return self.apply(self.dataset.prefetch(buffer_size), self.hparams)\n\n def arrange_for_prediction(self):\n def convert(s: SourceData, t: TargetData):\n return SourceDataForPrediction(\n id=s.id,\n key=s.key,\n mel=s.mel,\n mel_length=s.mel_length,\n mel_width=s.mel_width,\n text=s.text,\n waveform=t.waveform,\n waveform_length=t.waveform_length,\n ), t\n\n return self.apply(self.dataset.map(convert), self.hparams)\n" ]
[ [ "tensorflow.convert_to_tensor", "tensorflow.to_int64", "tensorflow.TensorShape", "tensorflow.shape", "tensorflow.data.TFRecordDataset", "tensorflow.reshape", "tensorflow.less_equal", "tensorflow.expand_dims", "tensorflow.minimum", "tensorflow.contrib.data.shuffle_and_repeat", "tensorflow.to_float", "tensorflow.contrib.data.group_by_window" ] ]
effigies/PySurfer
[ "4edbe61e55b13f3e8af9ff26597a1311b49bf8de" ]
[ "examples/plot_probabilistic_label.py" ]
[ "\"\"\"\n============================\nDisplay Probabilistic Labels\n============================\n\nFreesurfer ships with some probabilistic labels of cytoarchitectonic\nand visual areas. Here we show several ways to visualize these labels\nto help characterize the location of your data.\n\n\"\"\"\nfrom os import environ\nfrom os.path import join\nimport numpy as np\nfrom surfer import Brain\nfrom nibabel.freesurfer import read_label\n\nprint(__doc__)\n\nbrain = Brain(\"fsaverage\", \"lh\", \"inflated\", cortex=\"low_contrast\")\n\n\"\"\"\nThe easiest way to label any vertex that could be in the region is with\nadd_label.\n\"\"\"\nbrain.add_label(\"BA1\", color=\"#A6BDDB\")\n\n\"\"\"\nYou can also threshold based on the probability of that region being at each\nvertex.\n\"\"\"\nbrain.add_label(\"BA1\", color=\"#2B8CBE\", scalar_thresh=.5)\n\n\"\"\"\nIt's also possible to plot just the label boundary, in case you wanted to\noverlay the label on an activation plot to asses whether it falls within that\nregion.\n\"\"\"\nbrain.add_label(\"BA45\", color=\"#F0F8FF\", borders=3, scalar_thresh=.5)\nbrain.add_label(\"BA45\", color=\"#F0F8FF\", alpha=.3, scalar_thresh=.5)\n\n\"\"\"\nFinally, with a few tricks, you can display the whole probabilistic map.\n\"\"\"\nsubjects_dir = environ[\"SUBJECTS_DIR\"]\nlabel_file = join(subjects_dir, \"fsaverage\", \"label\", \"lh.BA6.label\")\n\nprob_field = np.zeros_like(brain._geo.x)\nids, probs = read_label(label_file, read_scalars=True)\nprob_field[ids] = probs\nbrain.add_data(prob_field, thresh=1e-5, colormap=\"RdPu\")\n" ]
[ [ "numpy.zeros_like" ] ]
The-Jyotiram-Koratkar/MyRegJK_V2.0
[ "0cf9bd42a77970af087a8fe8b7905a69ac307603" ]
[ "regression_model/train_pipeline.py" ]
[ "import numpy as np\nfrom sklearn.model_selection import train_test_split\n\nfrom regression_model.config import config\nfrom regression_model import pipeline\nfrom regression_model.processing.data_management import (\n load_dataset, save_pipeline)\n\n\n\ndef run_training() -> None:\n \"\"\"Train the model.\"\"\"\n\n # read training data\n data = load_dataset(file_name=config.TRAINING_DATA_FILE)\n\n # divide train and test\n X_train, X_test, y_train, y_test = train_test_split(\n data[config.FEATURES],\n data[config.TARGET],\n test_size=0.1,\n random_state=0) # we are setting the seed here\n\n # transform the target\n y_train = np.log(y_train)\n y_test = np.log(y_test)\n\n pipeline.price_pipe.fit(X_train[config.FEATURES],\n y_train)\n\n save_pipeline(pipeline_to_persist=pipeline.price_pipe)\n\n\nif __name__ == '__main__':\n run_training()\n" ]
[ [ "numpy.log", "sklearn.model_selection.train_test_split" ] ]
HalmonLui/copystrike
[ "80c7cbfcd4cff777d5a16472550b2306fd046e5a" ]
[ "poseDetection/driver 3-26-2019.py" ]
[ "import tkinter as tk, threading\r\nfrom tkinter import *\r\nimport tkinter.font\r\nfrom tkinter import filedialog\r\nfrom tkinter.font import *\r\nimport imageio\r\nfrom imageio import *\r\nfrom PIL import *\r\nimport cv2\r\nfrom cv2 import *\r\nimport PIL\r\nfrom PIL import Image, ImageTk\r\nfrom PIL import *\r\nimport os, sys\r\nimport time\r\nfrom time import *\r\nimport json\r\nfrom json import *\r\nimport requests\r\nfrom requests import *\r\nimport moviepy\r\nfrom moviepy import *\r\nimport moviepy.editor\r\nfrom moviepy.editor import VideoFileClip\r\nimport matplotlib\r\nfrom matplotlib import *\r\n# import matplotlib.pyplot\r\n# from matplotlib.pyplot import *\r\nimport math\r\nfrom math import *\r\n\r\n\r\nmainFile = None\r\nfileName = None\r\ndirectory = None\r\nframes = None\r\nvideo = None\r\nvideo2 = None\r\n\r\n\r\nclass Application(tk.Frame):\r\n def __init__(self, master=None):\r\n super().__init__(master)\r\n self.master = master\r\n master.title(\"Bowling Analysis\")\r\n master.resizable(False, False)\r\n\r\n self.pack()\r\n self.create_widgets()\r\n\r\n def create_widgets(self):\r\n self.categoryFont = Font(family=\"Times New Roman\", size=14, underline=True)\r\n self.normalFont = Font(family=\"Times New Roman\", size=12, underline=False)\r\n self.buttonFont = Font(family=\"Times New Roman\", size=16, underline=False)\r\n\r\n self.labelInfo = Label(root, text=\"Please Enter Information:\", font=self.categoryFont)\r\n self.labelInfo.pack()\r\n self.labelInfo.place(x=20, y=10, anchor=NW)\r\n\r\n self.labelName = Label(root, text=\"Name:\", font=self.normalFont)\r\n self.labelName.pack()\r\n self.labelName.place(x=20, y=40, anchor=NW)\r\n\r\n self.labelGender = Label(root, text=\"Gender:\", font=self.normalFont)\r\n self.labelGender.pack()\r\n self.labelGender.place(x=20, y=70, anchor=NW)\r\n\r\n self.labelAge = Label(root, text=\"Age:\", font=self.normalFont)\r\n self.labelAge.pack()\r\n self.labelAge.place(x=20, y=100, anchor=NW)\r\n\r\n self.labelHeight = Label(root, text=\"Height:\", font=self.normalFont)\r\n self.labelHeight.pack()\r\n self.labelHeight.place(x=20, y=130, anchor=NW)\r\n\r\n self.boxName = Text(root, height=1, width=14)\r\n self.boxName.pack()\r\n self.boxName.place(x=95, y=43, anchor=NW)\r\n\r\n genderChoices = [\"Male\", \"Female\"]\r\n genderMF = StringVar(root)\r\n genderMF.set(\"Male\")\r\n self.boxGender = OptionMenu(root, genderMF, *genderChoices)\r\n self.boxGender.config(width=12)\r\n self.boxGender.pack()\r\n self.boxGender.place(x=95, y=68, anchor=NW)\r\n\r\n self.boxAge = Text(root, height=1, width=14)\r\n self.boxAge.pack()\r\n self.boxAge.place(x=95, y=103, anchor=NW)\r\n\r\n self.labelFeet = Label(root, text=\"FT:\", font=self.normalFont)\r\n self.labelFeet.pack()\r\n self.labelFeet.place(x=95, y=130, anchor=NW)\r\n\r\n self.labelInches = Label(root, text=\"IN:\", font=self.normalFont)\r\n self.labelInches.pack()\r\n self.labelInches.place(x=160, y=130, anchor=NW)\r\n\r\n self.boxFeet = Text(root, height=1, width=2)\r\n self.boxFeet.pack()\r\n self.boxFeet.place(x=125, y=133, anchor=NW)\r\n\r\n self.boxInches = Text(root, height=1, width=2)\r\n self.boxInches.pack()\r\n self.boxInches.place(x=190, y=133, anchor=NW)\r\n\r\n self.startButton = Button(root, height=2, width=15, text='Start', font=self.buttonFont, command=playVideo)\r\n self.startButton.pack()\r\n self.startButton.place(x=20, y=200)\r\n\r\n self.restartButton = Button(root, height=2, width=15, text='Restart', font=self.buttonFont,\r\n command=restartVideo)\r\n self.restartButton.pack()\r\n self.restartButton.place(x=225, y=200)\r\n\r\n self.fileButton = Button(root, height=1, width=4, text='File:', font=self.normalFont, command=selectFile)\r\n self.fileButton.pack()\r\n self.fileButton.place(x=230, y=36, anchor=NW)\r\n\r\n self.fileBox = Text(root, height=1, width=14)\r\n self.fileBox.pack()\r\n self.fileBox.place(x=305, y=43, anchor=NW)\r\n\r\n self.labelFrames = Label(root, text=\"Frames:\", font=self.normalFont)\r\n self.labelFrames.pack()\r\n self.labelFrames.place(x=230, y=70, anchor=NW)\r\n\r\n self.framesBox = Text(root, height=1, width=14)\r\n self.framesBox.pack()\r\n self.framesBox.place(x=305, y=73, anchor=NW)\r\n\r\ndef cosineLaw(a,mid,c):\r\n\r\n # (mid^2) = (a^2)+(c^2)-(2*a*c)*cos(midAngle)\r\n midAngle = acos(((mid**2)-(a**2)-(c**2))/(-2*a*c))\r\n midAngle = midAngle * 180 / math.pi\r\n return midAngle\r\n\r\ndef pythag(x1,x2,y1,y2):\r\n distance = sqrt(pow((x1-x2),2)+pow((y1-y2),2))\r\n return distance\r\n\r\ndef selectFile():\r\n file = filedialog.askopenfilename(initialdir=\"/\", title=\"Select file\", filetypes=(\r\n (\"All Files\", \"*.*\"), (\"MOV files\", \"*.MOV\"), (\"MP4 files\", \"*.mp4\"), (\"AVI files\", \"*.avi\")))\r\n app.fileBox.insert(END, file)\r\n\r\ndef playVideo(): # Creates the threads where the videos are played\r\n\r\n thread = None\r\n thread2 = None\r\n\r\n if app.startButton.cget(\"text\") == \"Start\":\r\n\r\n global mainFile\r\n global fileName\r\n global directory\r\n global video\r\n global video2\r\n\r\n mainFile = app.fileBox.get(\"1.0\", 'end-1c')\r\n fileName = os.path.basename(mainFile)\r\n directory = os.path.splitext(mainFile)[0]\r\n\r\n newClip = VideoFileClip(mainFile)\r\n newFile = moviepy.video.fx.all.gamma_corr(newClip, .5)\r\n newFile = moviepy.video.fx.all.lum_contrast(newFile,0,1,.15)\r\n newFile.write_videofile(directory + \"_Processed\" + \".mp4\")\r\n\r\n if not os.path.exists(directory):\r\n os.makedirs(directory)\r\n\r\n # openPose = r\"C:\\Users\\okeefel\\Documents\\openpose-1.4.0-win64-gpu-binaries\\bin\\OpenPoseDemo.exe\"\r\n openPose = r\"bin\\OpenPoseDemo.exe\"\r\n fileFlag = r\" --video \" + directory + \"_Processed\" + \".mp4\" #unprocessed file to run\r\n dataFlag = r\" --write_json \" + directory #where it saves the raw data\r\n videoFlag = r\" --write_video \" + directory + \"_Processed\" + \".MOV\"\r\n # framesFlag = r\" --frame_step \" + app.framesBox.get(\"1.0\", 'end-1c')#skips however many frames\r\n displayFlag = r\" --display 0\" #Will not run on screen\r\n peopleFlag = r\" --number_people_max 1\"\r\n # trackingFlag = r\" --tracking 0\"\r\n scaleFlag = r\" --keypoint_scale 3\"\r\n\r\n os.chdir(r\"C:\\Users\\okeefel\\Documents\\openpose-1.4.0-win64-gpu-binaries\")\r\n os.system(openPose + fileFlag + dataFlag + videoFlag + displayFlag + peopleFlag + scaleFlag)\r\n\r\n video = imageio.get_reader(mainFile)\r\n video2 = imageio.get_reader(directory + \"_Processed\" + \".MOV\")\r\n\r\n videoLabel = tk.Label()\r\n videoLabel.pack()\r\n videoLabel.place(x=20, y=300, anchor=NW)\r\n thread = threading.Thread(target=stream, args=(videoLabel,))\r\n thread.daemon = 1\r\n thread.start()\r\n videoLabel2 = tk.Label()\r\n videoLabel2.pack()\r\n videoLabel2.place(x=520, y=300, anchor=NW)\r\n thread2 = threading.Thread(target=stream2, args=(videoLabel2,))\r\n thread2.daemon = 1\r\n thread2.start()\r\n\r\n # for root, dirs, files in os.walk(\"/mydir\"):\r\n # for file in files:\r\n # if file.endswith(\".txt\"):\r\n # print(os.path.join(root, file))\r\n\r\n #Parse through all data\r\n\r\n lastFrame = None\r\n\r\n fileCount = 0\r\n\r\n for file in os.listdir(directory): #file will be the json files\r\n if file.endswith(\".json\"):\r\n fileCount = fileCount + 1\r\n\r\n for fileNum in range(fileCount,0,-1): #file will be the json files\r\n jsonName = None\r\n if fileNum <= 10 :\r\n fileNum = fileNum-1\r\n fileNum = str(fileNum)\r\n jsonName = directory + r\"/\" + os.path.splitext(fileName)[0] + \"_Processed_00000000000\" + fileNum + \"_keypoints.json\"\r\n elif fileNum > 10 and fileNum <= 100:\r\n fileNum = fileNum - 1\r\n fileNum = str(fileNum)\r\n jsonName = directory + r\"/\" + os.path.splitext(fileName)[0] + \"_Processed_0000000000\" + fileNum + \"_keypoints.json\"\r\n elif fileNum > 100:\r\n fileNum = fileNum - 1\r\n fileNum = str(fileNum)\r\n jsonName = directory + r\"/\" + os.path.splitext(fileName)[0] + \"_Processed_000000000\" + fileNum + \"_keypoints.json\"\r\n\r\n with open(jsonName) as handle:\r\n jsonData = json.loads(handle.read())\r\n\r\n # jsonData[\"people\"][0][\"pose_keypoints_2d\"][0]\r\n #fill arrays then save graph\r\n x_list = [jsonData[\"people\"][0][\"pose_keypoints_2d\"][0], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][3], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][6], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][9], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][12], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][15], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][18], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][21], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][24], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][27], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][30], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][33], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][36], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][39], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][42], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][45], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][48], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][51], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][54], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][57], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][60], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][63], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][66], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][69], \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][72], \\\r\n ]\r\n y_list = [jsonData[\"people\"][0][\"pose_keypoints_2d\"][1]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][4]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][7]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][10]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][13]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][16]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][19]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][22]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][25]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][28]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][31]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][34]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][37]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][40]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][43]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][46]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][49]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][52]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][55]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][58]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][61]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][64]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][67]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][70]*-1+1000, \\\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][73]*-1+1000, \\\r\n ]\r\n\r\n words = [\"nose\", \\\r\n \"neck\", \\\r\n \"Rshoulder\", \\\r\n \"Relbow\", \\\r\n \"Rwrist\", \\\r\n \"Lshoulder\", \\\r\n \"Lelbow\", \\\r\n \"Lwrist\", \\\r\n \"Midhip\", \\\r\n \"Rhip\", \\\r\n \"Rknee\", \\\r\n \"Rankle\", \\\r\n \"Lhip\", \\\r\n \"Lknee\", \\\r\n \"Lankle\", \\\r\n \"Reye\", \\\r\n \"Leye\", \\\r\n \"Rear\", \\\r\n \"Lear\", \\\r\n \"LBigtoe\", \\\r\n \"LSmalltoe\", \\\r\n \"Lheel\", \\\r\n \"Rbigtoe\", \\\r\n \"Rsmalltoe\", \\\r\n \"Rheel\", \\\r\n ]\r\n\r\n fig, ax = matplotlib.pyplot.subplots()\r\n ax.scatter(x_list,y_list)\r\n\r\n for i, txt in enumerate(words):\r\n ax.annotate(txt,(x_list[i],y_list[i]))\r\n\r\n matplotlib.pyplot.axis([numpy.amin(x_list)-.1,numpy.amax(x_list)+.1,numpy.amin(y_list)-.1,numpy.amax(y_list)-.3])\r\n fig.savefig(directory + r\"/\" + os.path.splitext(fileName)[0] + \"_Processed_000\" + fileNum + \".png\")\r\n\r\n if fileNum == str(fileCount-1): #The first frame starts with when ball is being released\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][27] #RhipX\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][30] #RkneeX\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][33] #RankleX\r\n\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][28] #RhipY\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][31] #RkneeY\r\n jsonData[\"people\"][0][\"pose_keypoints_2d\"][34] #RankleY\r\n\r\n tibia = pythag(jsonData[\"people\"][0][\"pose_keypoints_2d\"][33],jsonData[\"people\"][0][\"pose_keypoints_2d\"][30],jsonData[\"people\"][0][\"pose_keypoints_2d\"][34],jsonData[\"people\"][0][\"pose_keypoints_2d\"][31])\r\n femur = pythag(jsonData[\"people\"][0][\"pose_keypoints_2d\"][30],jsonData[\"people\"][0][\"pose_keypoints_2d\"][27],jsonData[\"people\"][0][\"pose_keypoints_2d\"][31],jsonData[\"people\"][0][\"pose_keypoints_2d\"][28])\r\n mid = pythag(jsonData[\"people\"][0][\"pose_keypoints_2d\"][33],jsonData[\"people\"][0][\"pose_keypoints_2d\"][27],jsonData[\"people\"][0][\"pose_keypoints_2d\"][34],jsonData[\"people\"][0][\"pose_keypoints_2d\"][28])\r\n\r\n rkneeAngle = cosineLaw(tibia,mid,femur)\r\n\r\n print(tibia)\r\n print(femur)\r\n print(mid)\r\n print(rkneeAngle)\r\n\r\n lastFrame = jsonData\r\n\r\n\r\n # (x,y,confidence)\r\n # 0 Nose\r\n # 1 Neck\r\n # 2 RShoulder\r\n # 3 RElbow\r\n # 4 RWrist\r\n # 5 LShoulder\r\n # 6 LElbow\r\n # 7 LWrist\r\n # 8 MidHip\r\n # 9 RHip\r\n # 10 RKnee\r\n # 11 RAnkle\r\n # 12 LHip\r\n # 13 LKnee\r\n # 14 LAnkle\r\n # 15 REye\r\n # 16 LEye\r\n # 17 REar\r\n # 18 LEar\r\n # 19 LBigToe\r\n # 20 LSmallToe\r\n # 21 LHeel\r\n # 22 RBigToe\r\n # 23 RSmallToe\r\n # 24 RHeel\r\n # 25 Background\r\n\r\n os.remove(directory + \"_Processed\" + \".mp4\")\r\n app.startButton.config(text=\"Pause\")\r\n elif app.startButton.cget(\"text\") == \"Pause\":\r\n app.startButton.config(text=\"Continue\")\r\n elif app.startButton.cget(\"text\") == \"Continue\":\r\n app.startButton.config(text=\"Pause\")\r\n\r\ndef restartVideo():\r\n app.startButton.config(text=\"Start\")\r\n playVideo()\r\n\r\ndef stream(label): # First Video\r\n\r\n for image in video.iter_data():\r\n while app.startButton.cget(\"text\") == \"Continue\":\r\n sleep(1)\r\n\r\n img = Image.fromarray(image)\r\n img2 = img.resize((500, 500), Image.ANTIALIAS)\r\n img3 = ImageTk.PhotoImage(img2)\r\n label.config(image=img3)\r\n label.image = img3\r\n\r\ndef stream2(label): # Second Video\r\n\r\n for image in video2.iter_data():\r\n while app.startButton.cget(\"text\") == \"Continue\":\r\n sleep(1)\r\n\r\n img = Image.fromarray(image)\r\n img2 = img.resize((500, 500), Image.ANTIALIAS)\r\n img3 = ImageTk.PhotoImage(img2)\r\n label.config(image=img3)\r\n label.image = img3\r\n\r\nroot = tk.Tk()\r\nroot.state('zoomed')\r\napp = Application(master=root)\r\napp.mainloop()\r\n" ]
[ [ "matplotlib.pyplot.subplots" ] ]
neuronflow/torchio
[ "1d0a5ad069c59d74ec56ed6f340c87e9636a1488" ]
[ "torchio/data/sampler/sampler.py" ]
[ "import copy\nfrom typing import Tuple, Optional, Generator\n\nimport numpy as np\n\nfrom ... import TypePatchSize, TypeTripletInt\nfrom ...data.subject import Subject\nfrom ...utils import to_tuple\n\n\nclass PatchSampler:\n r\"\"\"Base class for TorchIO samplers.\n\n Args:\n patch_size: Tuple of integers :math:`(w, h, d)` to generate patches\n of size :math:`h \\times w \\times d`.\n If a single number :math:`n` is provided, :math:`w = h = d = n`.\n \"\"\"\n def __init__(self, patch_size: TypePatchSize):\n patch_size_array = np.array(to_tuple(patch_size, length=3))\n for n in patch_size_array:\n if n < 1 or not isinstance(n, (int, np.integer)):\n message = (\n 'Patch dimensions must be positive integers,'\n f' not {patch_size_array}'\n )\n raise ValueError(message)\n self.patch_size = patch_size_array.astype(np.uint16)\n\n def extract_patch(\n self,\n sample: Subject,\n index_ini: TypeTripletInt,\n ) -> Subject:\n index_ini = np.array(index_ini)\n index_fin = index_ini + self.patch_size\n cropped_sample = sample.crop(index_ini, index_fin)\n cropped_sample['index_ini'] = index_ini.astype(int)\n return cropped_sample\n\n\nclass RandomSampler(PatchSampler):\n r\"\"\"Base class for TorchIO samplers.\n\n Args:\n patch_size: Tuple of integers :math:`(w, h, d)` to generate patches\n of size :math:`h \\times w \\times d`.\n If a single number :math:`n` is provided, :math:`w = h = d = n`.\n \"\"\"\n def __call__(\n self,\n sample: Subject,\n num_patches: Optional[int] = None,\n ) -> Generator[Subject, None, None]:\n raise NotImplementedError\n\n def get_probability_map(self, sample: Subject):\n raise NotImplementedError\n" ]
[ [ "numpy.array" ] ]
hongliangduan/Reproducing-the-invention-of-a-named-reaction-Zero-shot-prediction-of-unseen-chemical-reactions
[ "2d688bff2202e37321dedba7cdac67cd3c1e1fad" ]
[ "data_generators/translate.py" ]
[ "# coding=utf-8\n# Copyright 2018 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Data generators for translation data-sets.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport tarfile\nfrom tensor2tensor.data_generators import generator_utils\nfrom tensor2tensor.data_generators import problem\nfrom tensor2tensor.data_generators import text_encoder\nfrom tensor2tensor.data_generators import text_problems\nfrom tensor2tensor.utils import bleu_hook\n\nimport tensorflow as tf\n\nFLAGS = tf.flags.FLAGS\n\n\nclass TranslateProblem(text_problems.Text2TextProblem):\n \"\"\"Base class for translation problems.\"\"\"\n\n def is_generate_per_split(self):\n return True\n\n @property\n def approx_vocab_size(self):\n return 2**15\n\n def source_data_files(self, dataset_split):\n \"\"\"Files to be passed to compile_data.\"\"\"\n raise NotImplementedError()\n\n def vocab_data_files(self):\n \"\"\"Files to be passed to get_or_generate_vocab.\"\"\"\n return self.source_data_files(problem.DatasetSplit.TRAIN)\n\n def generate_samples(self, data_dir, tmp_dir, dataset_split):\n datasets = self.source_data_files(dataset_split)\n tag = \"train\" if dataset_split == problem.DatasetSplit.TRAIN else \"dev\"\n data_path = compile_data(tmp_dir, datasets, \"%s-compiled-%s\" % (self.name,\n tag))\n return text_problems.text2text_txt_iterator(data_path + \".lang1\",\n data_path + \".lang2\")\n\n def generate_text_for_vocab(self, data_dir, tmp_dir):\n return generator_utils.generate_lines_for_vocab(tmp_dir,\n self.vocab_data_files())\n\n @property\n def decode_hooks(self):\n return [compute_bleu_summaries]\n\n\ndef compute_bleu_summaries(hook_args):\n \"\"\"Compute BLEU core summaries using the decoder output.\n\n Args:\n hook_args: DecodeHookArgs namedtuple\n Returns:\n A list of tf.Summary values if hook_args.hparams contains the\n reference file and the translated file.\n \"\"\"\n decode_hparams = hook_args.decode_hparams\n\n if (decode_hparams.decode_reference is None or\n decode_hparams.decode_to_file is None):\n return None\n\n values = []\n bleu = 100 * bleu_hook.bleu_wrapper(\n decode_hparams.decode_reference, decode_hparams.decode_to_file)\n values.append(tf.Summary.Value(tag=\"BLEU\", simple_value=bleu))\n tf.logging.info(\"%s: BLEU = %6.2f\" % (decode_hparams.decode_to_file, bleu))\n return values\n\n\ndef _preprocess_sgm(line, is_sgm):\n \"\"\"Preprocessing to strip tags in SGM files.\"\"\"\n if not is_sgm:\n return line\n # In SGM files, remove <srcset ...>, <p>, <doc ...> lines.\n if line.startswith(\"<srcset\") or line.startswith(\"</srcset\"):\n return \"\"\n if line.startswith(\"<doc\") or line.startswith(\"</doc\"):\n return \"\"\n if line.startswith(\"<p>\") or line.startswith(\"</p>\"):\n return \"\"\n # Strip <seg> tags.\n line = line.strip()\n if line.startswith(\"<seg\") and line.endswith(\"</seg>\"):\n i = line.index(\">\")\n return line[i + 1:-6] # Strip first <seg ...> and last </seg>.\n\n\ndef compile_data(tmp_dir, datasets, filename):\n \"\"\"Concatenate all `datasets` and save to `filename`.\"\"\"\n filename = os.path.join(tmp_dir, filename)\n # lang1_fname = filename + \".lang1\"\n # lang2_fname = filename + \".lang2\"\n lang1_fname = filename + \".source\"\n lang2_fname = filename + \".target\"\n if tf.gfile.Exists(lang1_fname) and tf.gfile.Exists(lang2_fname):\n tf.logging.info(\"Skipping compile data, found files:\\n%s\\n%s\", lang1_fname,\n lang2_fname)\n return filename\n with tf.gfile.GFile(lang1_fname, mode=\"w\") as lang1_resfile:\n with tf.gfile.GFile(lang2_fname, mode=\"w\") as lang2_resfile:\n for dataset in datasets:\n url = dataset[0]\n compressed_filename = os.path.basename(url)\n compressed_filepath = os.path.join(tmp_dir, compressed_filename)\n if url.startswith(\"http\"):\n generator_utils.maybe_download(tmp_dir, compressed_filename, url)\n\n if dataset[1][0] == \"tsv\":\n _, src_column, trg_column, glob_pattern = dataset[1]\n filenames = tf.gfile.Glob(os.path.join(tmp_dir, glob_pattern))\n if not filenames:\n # Capture *.tgz and *.tar.gz too.\n mode = \"r:gz\" if compressed_filepath.endswith(\"gz\") else \"r\"\n with tarfile.open(compressed_filepath, mode) as corpus_tar:\n corpus_tar.extractall(tmp_dir)\n filenames = tf.gfile.Glob(os.path.join(tmp_dir, glob_pattern))\n for tsv_filename in filenames:\n if tsv_filename.endswith(\".gz\"):\n new_filename = tsv_filename.strip(\".gz\")\n generator_utils.gunzip_file(tsv_filename, new_filename)\n tsv_filename = new_filename\n with tf.gfile.Open(tsv_filename) as tsv_file:\n for line in tsv_file:\n if line and \"\\t\" in line:\n parts = line.split(\"\\t\")\n source, target = parts[src_column], parts[trg_column]\n source, target = source.strip(), target.strip()\n if source and target:\n lang1_resfile.write(source)\n lang1_resfile.write(\"\\n\")\n lang2_resfile.write(target)\n lang2_resfile.write(\"\\n\")\n else:\n lang1_filename, lang2_filename = dataset[1]\n lang1_filepath = os.path.join(tmp_dir, lang1_filename)\n lang2_filepath = os.path.join(tmp_dir, lang2_filename)\n is_sgm = (\n lang1_filename.endswith(\"sgm\") and lang2_filename.endswith(\"sgm\"))\n\n if not (tf.gfile.Exists(lang1_filepath) and\n tf.gfile.Exists(lang2_filepath)):\n # For .tar.gz and .tgz files, we read compressed.\n mode = \"r:gz\" if compressed_filepath.endswith(\"gz\") else \"r\"\n with tarfile.open(compressed_filepath, mode) as corpus_tar:\n corpus_tar.extractall(tmp_dir)\n if lang1_filepath.endswith(\".gz\"):\n new_filepath = lang1_filepath.strip(\".gz\")\n generator_utils.gunzip_file(lang1_filepath, new_filepath)\n lang1_filepath = new_filepath\n if lang2_filepath.endswith(\".gz\"):\n new_filepath = lang2_filepath.strip(\".gz\")\n generator_utils.gunzip_file(lang2_filepath, new_filepath)\n lang2_filepath = new_filepath\n\n for example in text_problems.text2text_txt_iterator(\n lang1_filepath, lang2_filepath):\n line1res = _preprocess_sgm(example[\"inputs\"], is_sgm)\n line2res = _preprocess_sgm(example[\"targets\"], is_sgm)\n if line1res and line2res:\n lang1_resfile.write(line1res)\n lang1_resfile.write(\"\\n\")\n lang2_resfile.write(line2res)\n lang2_resfile.write(\"\\n\")\n\n return filename\n\n\nclass TranslateDistillProblem(TranslateProblem):\n \"\"\"Base class for translation problems.\"\"\"\n\n def is_generate_per_split(self):\n return True\n\n def example_reading_spec(self):\n data_fields = {\"dist_targets\": tf.VarLenFeature(tf.int64)}\n\n if self.has_inputs:\n data_fields[\"inputs\"] = tf.VarLenFeature(tf.int64)\n\n # hack: ignoring true targets and putting dist_targets in targets\n data_items_to_decoders = {\n \"inputs\": tf.contrib.slim.tfexample_decoder.Tensor(\"inputs\"),\n \"targets\": tf.contrib.slim.tfexample_decoder.Tensor(\"dist_targets\"),\n }\n\n return (data_fields, data_items_to_decoders)\n\n def get_or_create_vocab(self, data_dir, tmp_dir, force_get=False):\n \"\"\"Get vocab for distill problems.\"\"\"\n # We assume that vocab file is present in data_dir directory where the\n # data generated will be stored.\n vocab_filepath = os.path.join(data_dir, self.vocab_filename)\n encoder = text_encoder.SubwordTextEncoder(vocab_filepath)\n return encoder\n\n def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split):\n generator = self.generate_samples(data_dir, tmp_dir, dataset_split)\n vocab = self.get_or_create_vocab(data_dir, tmp_dir)\n # For each example, encode the text and append EOS ID.\n for sample in generator:\n if self.has_inputs:\n sample[\"inputs\"] = vocab.encode(sample[\"inputs\"])\n sample[\"inputs\"].append(text_encoder.EOS_ID)\n sample[\"targets\"] = vocab.encode(sample[\"targets\"])\n sample[\"targets\"].append(text_encoder.EOS_ID)\n sample[\"dist_targets\"] = vocab.encode(sample[\"dist_targets\"])\n sample[\"dist_targets\"].append(text_encoder.EOS_ID)\n yield sample\n\n def generate_samples(self, data_dir, tmp_dir, dataset_split):\n data_path = self.source_data_files(dataset_split)\n assert tf.gfile.Exists(data_path)\n return text_problems.text2text_distill_iterator(data_path + \"inputs\",\n data_path + \"gold\",\n data_path + \"prediction\")\n" ]
[ [ "tensorflow.gfile.Open", "tensorflow.gfile.Exists", "tensorflow.gfile.GFile", "tensorflow.Summary.Value", "tensorflow.logging.info", "tensorflow.contrib.slim.tfexample_decoder.Tensor", "tensorflow.VarLenFeature" ] ]
yee2542/CPE393-Coding-AI-Project
[ "b86203488eb72f6305ca9f58ebca68cd7d092428" ]
[ "model.summary.py" ]
[ "from tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.layers import AveragePooling2D\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam, SGD\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.preprocessing.image import load_img\nfrom tensorflow.keras.utils import to_categorical\nimport keras as K\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom imutils import paths\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport argparse\nimport os\n\nINIT_LR = 1e-5\nEPOCHS = 10000\nBS = 32\nbaseModel = MobileNetV2(weights=\"imagenet\", include_top=False,\n input_tensor=Input(shape=(224, 224, 3)))\n\nheadModel = baseModel.output\nheadModel = AveragePooling2D(pool_size=(4, 4))(headModel)\nheadModel = Flatten(name=\"flatten\")(headModel)\nheadModel = Dense(256, activation=\"relu\")(headModel)\nheadModel = Dropout(0.5)(headModel)\nheadModel = Dense(2, activation=\"softmax\")(headModel)\n\nmodel = Model(inputs=baseModel.input, outputs=headModel)\n\nfor layer in baseModel.layers:\n layer.trainable = False\n\nopt = Adam(lr=INIT_LR,\n decay=INIT_LR / EPOCHS\n )\nmodel.compile(loss=\"binary_crossentropy\", optimizer=opt,\n metrics=[\"accuracy\"])\n\nmodel.summary()" ]
[ [ "tensorflow.keras.layers.AveragePooling2D", "tensorflow.keras.models.Model", "tensorflow.keras.layers.Dense", "tensorflow.keras.optimizers.Adam", "tensorflow.keras.layers.Dropout", "tensorflow.keras.layers.Flatten", "tensorflow.keras.layers.Input" ] ]
aditya5252/Asynccode
[ "c52e36fc05e5eb2d8720e1f1674b956b69a94958" ]
[ "source/step_AT2_.py" ]
[ "import numpy as np\nimport probability_initial\nimport delay_file\n \ndef at2u0(pe,l,L, p_arr): \n a = l+1 \n b = -l \n temp = a*p_arr[int(L-1-l)][int(pe)]+b*p_arr[int(L-2-l)][int(pe)]\n return temp\n\n\ndef cd2u1(u,cx,dx,nx,Eqflag,Syncflag,L=None,PE=None,perPE=None,pstart=None,pend=None,ATolFLAG=None):\n '''For a given time step t to t+delt'''\n# u,du,C all take 1-D\n rhs=np.zeros_like(u)\n C=np.zeros_like(u)\n '''Concentration array'''\n if(Eqflag=='DBurgers'):\n C=u.copy()\n if((Eqflag=='DAdvection') or (Eqflag=='DAD')):\n for i in range(nx):\n C[i]=cx\n\n if(Syncflag=='DSync'):\n rhs[0] = -C[0]*(u[1] - u[nx-2])/(2*dx)\n rhs[nx-1] = -C[nx-1]*(u[1] - u[nx-2])/(2*dx)\n for i in range(1,nx-1):\n rhs[i] = -C[i]*(u[i+1] - u[i-1])/(2*dx)\n return rhs\n \n elif(Syncflag=='DAsync'):\n ## Interior point computations ##\n for pe in range(PE): \n for i in range(pe*perPE+1,perPE*(pe+1)-1):\n rhs[i] = -C[i]*(u[i+1] - u[i-1])/(2*dx)\n \n ## Assigning values to buffer array ##\n #L=max_delay\n\n ## pend with left_pt & pstart with right_pt ##\n #Different l use \n if(ATolFLAG==None):\n l=int(delay_file.delay_())\n rhs[0] = -C[0]*(u[1] - pend[L-1-l][PE-1])/(2*dx)\n l=int(delay_file.delay_())\n rhs[nx-1] = -C[nx-1]*(pstart[L-1-l][0*PE]- u[nx-2])/(2*dx)\n #Processor Boundary points\n for pe in range(PE-1):\n right_pt = perPE*(pe+1)-1\n l=int(delay_file.delay_())\n rhs[right_pt] = -C[right_pt]*(pstart[L-1-l][(right_pt+1)//perPE] - u[right_pt-1])/(2*dx)\n l=int(delay_file.delay_())\n left_pt = perPE*(pe+1)\n rhs[left_pt] = -C[left_pt]*(u[left_pt+1] - pend[L-1-l][(left_pt+1)//perPE - 1])/(2*dx)\n elif(ATolFLAG=='DAT2'):\n l=int(delay_file.delay_())\n rhs[0] = -C[0]*(u[1] - at2u0(PE-1,l,L,pend) )/(2*dx)\n l=int(delay_file.delay_())\n rhs[nx-1] = -C[nx-1]*( at2u0(0,l,L,pstart) - u[nx-2] )/(2*dx)\n #Processor Boundary points\n for pe in range(PE-1):\n right_pt = perPE*(pe+1)-1\n l=int(delay_file.delay_())\n rhs[right_pt] = -C[right_pt]*( at2u0((right_pt+1)/perPE,l,L,pstart)- u[right_pt-1])/(2*dx)\n l=int(delay_file.delay_())\n left_pt = perPE*(pe+1)\n rhs[left_pt] = -C[left_pt]*(u[left_pt+1] - at2u0((left_pt+1)//perPE - 1,l,L,pend))/(2*dx)\n pstart_out=pstart[1:]\n pend_out=pend[1:]\n \n return rhs,pstart_out,pend_out\n\ndef euler(u,rhs,dt,nx):\n# v=np.zeros_like(u)\n# for i in range(nx):\n# v[i]=u[i]+dt*rhs[i]\n u=u+dt*rhs\n return u\n\n# import numpy as np\n# import probability_initial\n# import delay_file\n# def cd2u1(u,cx,dx,nx,Eqflag,Syncflag,L=None,PE=None,perPE=None,pstart_in=None,pend_in=None):\n# '''For a given time step t to t+delt'''\n# # u,du,C all take 1-D\n# rhs=np.zeros_like(u)\n# C=np.zeros_like(u)\n# '''Concentration array'''\n# if(Eqflag=='DBurgers'):\n# C=u.copy()\n# if((Eqflag=='DAdvection') or (Eqflag=='DAD')):\n# for i in range(nx):\n# C[i]=cx\n\n# if(Syncflag=='DSync'):\n# rhs[0] = -C[0]*(u[1] - u[nx-2])/(2*dx)\n# rhs[nx-1] = -C[nx-1]*(u[1] - u[nx-2])/(2*dx)\n# for i in range(1,nx-1):\n# rhs[i] = -C[i]*(u[i+1] - u[i-1])/(2*dx)\n# return rhs\n \n# elif(Syncflag=='DAsync'):\n# ## Interior point computations ##\n# for pe in range(PE): \n# for i in range(pe*perPE+1,perPE*(pe+1)-1):\n# rhs[i] = -C[i]*(u[i+1] - u[i-1])/(2*dx)\n \n# ## Assigning values to buffer array ##\n# #L=max_delay\n# pstart=np.zeros((L,PE))\n# pend=np.zeros((L,PE))\n\n# pstart[:-1]=pstart_in\n# pend[:-1]=pend_in\n \n# pstart[L-1],pend[L-1]=probability_initial.prob_1D_from_u_1D(u,PE,perPE)\n# ## pend with left_pt & pstart with right_pt ##\n# #Different l use \n# l=int(delay_file.delay_())\n# rhs[0] = -C[0]*(u[1] - pend[L-1-l][PE-1])/(2*dx)\n# l=int(delay_file.delay_())\n# rhs[nx-1] = -C[nx-1]*(pstart[L-1-l][0*PE]- u[nx-2])/(2*dx)\n# #Processor Boundary points\n# for pe in range(PE-1):\n# right_pt = perPE*(pe+1)-1\n# l=int(delay_file.delay_())\n# rhs[right_pt] = -C[right_pt]*(pstart[L-1-l][(right_pt+1)//perPE] - u[right_pt-1])/(2*dx)\n# l=int(delay_file.delay_())\n# left_pt = perPE*(pe+1)\n# rhs[left_pt] = -C[left_pt]*(u[left_pt+1] - pend[L-1-l][(left_pt+1)//perPE - 1])/(2*dx)\n \n# pstart_out=pstart[1:]\n# pend_out=pend[1:]\n \n# return rhs,pstart_out,pend_out\n\n# def euler(u,rhs,dt,nx):\n# # v=np.zeros_like(u)\n# # for i in range(nx):\n# # v[i]=u[i]+dt*rhs[i]\n# u=u+dt*rhs\n# return u" ]
[ [ "numpy.zeros_like" ] ]
pandamax/current-lane-drivable
[ "0727b101cec3d5663aa953209abf1f323b062a4f" ]
[ "mask-rcnn/libraries/mrcnn/visualize.py" ]
[ "\"\"\"\nMask R-CNN\nDisplay and Visualization Functions.\n\nCopyright (c) 2017 Matterport, Inc.\nLicensed under the MIT License (see LICENSE for details)\nWritten by Waleed Abdulla\n\"\"\"\n\nimport os\nimport sys\nimport logging\nimport random\nimport itertools\nimport colorsys\n\nimport numpy as np\nfrom skimage.measure import find_contours\nimport matplotlib.pyplot as plt\nfrom matplotlib import patches, lines\nfrom matplotlib.patches import Polygon\nimport IPython.display\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../\")\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn import utils\n# from PIL import ImageFont\n\n############################################################\n# Visualization\n############################################################\n\ndef display_images(images, titles=None, cols=4, cmap=None, norm=None,\n interpolation=None):\n \"\"\"Display the given set of images, optionally with titles.\n images: list or array of image tensors in HWC format.\n titles: optional. A list of titles to display with each image.\n cols: number of images per row\n cmap: Optional. Color map to use. For example, \"Blues\".\n norm: Optional. A Normalize instance to map values to colors.\n interpolation: Optional. Image interporlation to use for display.\n \"\"\"\n titles = titles if titles is not None else [\"\"] * len(images)\n rows = len(images) // cols + 1\n plt.figure(figsize=(14, 14 * rows // cols))\n i = 1\n for image, title in zip(images, titles):\n plt.subplot(rows, cols, i)\n plt.title(title, fontsize=9)\n plt.axis('off')\n plt.imshow(image.astype(np.uint8), cmap=cmap,\n norm=norm, interpolation=interpolation)\n i += 1\n plt.show()\n\n\ndef random_colors(N, bright=True):\n \"\"\"\n Generate random colors.\n To get visually distinct colors, generate them in HSV space then\n convert to RGB.\n \"\"\"\n brightness = 1.0 if bright else 0.7\n hsv = [(i / N, 1, brightness) for i in range(N)]\n colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))\n random.shuffle(colors)\n return colors\n\n\ndef apply_mask(image, mask, color, alpha=0.5):\n \"\"\"Apply the given mask to the image.\n \"\"\"\n for c in range(3):\n image[:, :, c] = np.where(mask == 1,\n image[:, :, c] *\n (1 - alpha) + alpha * color[c] * 255,\n image[:, :, c])\n return image\n\n\ndef display_instances(image, boxes, masks, class_ids, class_names,\n scores=None, title=\"\",\n figsize=(16, 16), ax=None,\n show_mask=True, show_bbox=True,\n colors=None, captions=None):\n \"\"\"\n boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates.\n masks: [height, width, num_instances]\n class_ids: [num_instances]\n class_names: list of class names of the dataset\n scores: (optional) confidence scores for each box\n title: (optional) Figure title\n show_mask, show_bbox: To show masks and bounding boxes or not\n figsize: (optional) the size of the image\n colors: (optional) An array or colors to use with each object\n captions: (optional) A list of strings to use as captions for each object\n \"\"\"\n # Number of instances\n N = boxes.shape[0]\n if not N:\n print(\"\\n*** No instances to display *** \\n\")\n else:\n assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0]\n\n # If no axis is passed, create one and automatically call show()\n auto_show = False\n if not ax:\n _, ax = plt.subplots(1, figsize=figsize)\n auto_show = True\n\n # Generate random colors\n colors = colors or random_colors(N)\n\n # Show area outside image boundaries.\n height, width = image.shape[:2]\n ax.set_ylim(height + 10, -10)\n ax.set_xlim(-10, width + 10)\n ax.axis('off')\n ax.set_title(title)\n\n masked_image = image.astype(np.uint32).copy()\n for i in range(N):\n color = colors[i]\n\n # Bounding box\n if not np.any(boxes[i]):\n # Skip this instance. Has no bbox. Likely lost in image cropping.\n continue\n y1, x1, y2, x2 = boxes[i]\n if show_bbox:\n p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2,\n alpha=0.7, linestyle=\"solid\",\n edgecolor=color, facecolor='none')\n ax.add_patch(p)\n\n # Label\n if not captions:\n class_id = class_ids[i]\n score = scores[i] if scores is not None else None\n label = class_names[class_id]\n x = random.randint(x1, (x1 + x2) // 2)\n caption = \"{} {:.3f}\".format(label, score) if score else label\n else:\n caption = captions[i]\n plt.savefig('/home/pandamax/result/res50/{}.jpg'.format(random.randint(1, 100)), bbox_inches='tight', pad_inches=-0.5, orientation='landscape')\n ax.text(x1, y1 + 14, caption,\n color='w', size=12, backgroundcolor=\"none\")\n\n # Mask\n mask = masks[:, :, i]\n if show_mask:\n masked_image = apply_mask(masked_image, mask, color)\n\n # Mask Polygon\n # Pad to ensure proper polygons for masks that touch image edges.\n padded_mask = np.zeros(\n (mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8)\n padded_mask[1:-1, 1:-1] = mask\n contours = find_contours(padded_mask, 0.5)\n for verts in contours:\n # Subtract the padding and flip (y, x) to (x, y)\n verts = np.fliplr(verts) - 1\n p = Polygon(verts, facecolor=\"green\", edgecolor='green')\n ax.add_patch(p)\n ax.imshow(masked_image.astype(np.uint8))\n if auto_show:\n plt.show()\n\n\n\ndef display_differences(image,\n gt_box, gt_class_id, gt_mask,\n pred_box, pred_class_id, pred_score, pred_mask,\n class_names, title=\"\", ax=None,\n show_mask=True, show_box=True,\n iou_threshold=0.5, score_threshold=0.5):\n \"\"\"Display ground truth and prediction instances on the same image.\"\"\"\n # Match predictions to ground truth\n gt_match, pred_match, overlaps = utils.compute_matches(\n gt_box, gt_class_id, gt_mask,\n pred_box, pred_class_id, pred_score, pred_mask,\n iou_threshold=iou_threshold, score_threshold=score_threshold)\n # Ground truth = green. Predictions = red\n colors = [(0, 1, 0, .8)] * len(gt_match)\\\n + [(1, 0, 0, 1)] * len(pred_match)\n # Concatenate GT and predictions\n class_ids = np.concatenate([gt_class_id, pred_class_id])\n scores = np.concatenate([np.zeros([len(gt_match)]), pred_score])\n boxes = np.concatenate([gt_box, pred_box])\n masks = np.concatenate([gt_mask, pred_mask], axis=-1)\n # Captions per instance show score/IoU\n captions = [\"\" for m in gt_match] + [\"{:.2f} / {:.2f}\".format(\n pred_score[i],\n (overlaps[i, int(pred_match[i])]\n if pred_match[i] > -1 else overlaps[i].max()))\n for i in range(len(pred_match))]\n # Set title if not provided\n title = title or \"Ground Truth and Detections\\n GT=green, pred=red, captions: score/IoU\"\n # Display\n display_instances(\n image,\n boxes, masks, class_ids,\n class_names, scores, ax=ax,\n show_bbox=show_box, show_mask=show_mask,\n colors=colors, captions=captions,\n title=title)\n\n\ndef draw_rois(image, rois, refined_rois, mask, class_ids, class_names, limit=10):\n \"\"\"\n anchors: [n, (y1, x1, y2, x2)] list of anchors in image coordinates.\n proposals: [n, 4] the same anchors but refined to fit objects better.\n \"\"\"\n masked_image = image.copy()\n\n # Pick random anchors in case there are too many.\n ids = np.arange(rois.shape[0], dtype=np.int32)\n ids = np.random.choice(\n ids, limit, replace=False) if ids.shape[0] > limit else ids\n\n fig, ax = plt.subplots(1, figsize=(12, 12))\n if rois.shape[0] > limit:\n plt.title(\"Showing {} random ROIs out of {}\".format(\n len(ids), rois.shape[0]))\n else:\n plt.title(\"{} ROIs\".format(len(ids)))\n\n # Show area outside image boundaries.\n ax.set_ylim(image.shape[0] + 20, -20)\n ax.set_xlim(-50, image.shape[1] + 20)\n ax.axis('off')\n\n for i, id in enumerate(ids):\n color = np.random.rand(3)\n class_id = class_ids[id]\n # ROI\n y1, x1, y2, x2 = rois[id]\n p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2,\n edgecolor=color if class_id else \"gray\",\n facecolor='none', linestyle=\"dashed\")\n ax.add_patch(p)\n # Refined ROI\n if class_id:\n ry1, rx1, ry2, rx2 = refined_rois[id]\n p = patches.Rectangle((rx1, ry1), rx2 - rx1, ry2 - ry1, linewidth=2,\n edgecolor=color, facecolor='none')\n ax.add_patch(p)\n # Connect the top-left corners of the anchor and proposal for easy visualization\n ax.add_line(lines.Line2D([x1, rx1], [y1, ry1], color=color))\n\n # Label\n label = class_names[class_id]\n ax.text(rx1, ry1 + 8, \"{}\".format(label),\n color='w', size=11, backgroundcolor=\"none\")\n\n # Mask\n m = utils.unmold_mask(mask[id], rois[id]\n [:4].astype(np.int32), image.shape)\n masked_image = apply_mask(masked_image, m, color)\n\n ax.imshow(masked_image)\n\n # Print stats\n print(\"Positive ROIs: \", class_ids[class_ids > 0].shape[0])\n print(\"Negative ROIs: \", class_ids[class_ids == 0].shape[0])\n print(\"Positive Ratio: {:.2f}\".format(\n class_ids[class_ids > 0].shape[0] / class_ids.shape[0]))\n\n\n# TODO: Replace with matplotlib equivalent?\ndef draw_box(image, box, color):\n \"\"\"Draw 3-pixel width bounding boxes on the given image array.\n color: list of 3 int values for RGB.\n \"\"\"\n y1, x1, y2, x2 = box\n image[y1:y1 + 2, x1:x2] = color\n image[y2:y2 + 2, x1:x2] = color\n image[y1:y2, x1:x1 + 2] = color\n image[y1:y2, x2:x2 + 2] = color\n return image\n\n\ndef display_top_masks(image, mask, class_ids, class_names, limit=4):\n \"\"\"Display the given image and the top few class masks.\"\"\"\n to_display = []\n titles = []\n to_display.append(image)\n titles.append(\"H x W={}x{}\".format(image.shape[0], image.shape[1]))\n # Pick top prominent classes in this image\n unique_class_ids = np.unique(class_ids)\n mask_area = [np.sum(mask[:, :, np.where(class_ids == i)[0]])\n for i in unique_class_ids]\n top_ids = [v[0] for v in sorted(zip(unique_class_ids, mask_area),\n key=lambda r: r[1], reverse=True) if v[1] > 0]\n # Generate images and titles\n for i in range(limit):\n class_id = top_ids[i] if i < len(top_ids) else -1\n # Pull masks of instances belonging to the same class.\n m = mask[:, :, np.where(class_ids == class_id)[0]]\n m = np.sum(m * np.arange(1, m.shape[-1] + 1), -1)\n to_display.append(m)\n titles.append(class_names[class_id] if class_id != -1 else \"-\")\n display_images(to_display, titles=titles, cols=limit + 1, cmap=\"Blues_r\")\n\n\ndef plot_precision_recall(AP, precisions, recalls):\n \"\"\"Draw the precision-recall curve.\n\n AP: Average precision at IoU >= 0.5\n precisions: list of precision values\n recalls: list of recall values\n \"\"\"\n # Plot the Precision-Recall curve\n _, ax = plt.subplots(1)\n ax.set_title(\"Precision-Recall Curve. AP@50 = {:.3f}\".format(AP))\n ax.set_ylim(0, 1.1)\n ax.set_xlim(0, 1.1)\n _ = ax.plot(recalls, precisions)\n\n\ndef plot_overlaps(gt_class_ids, pred_class_ids, pred_scores,\n overlaps, class_names, threshold=0.5):\n \"\"\"Draw a grid showing how ground truth objects are classified.\n gt_class_ids: [N] int. Ground truth class IDs\n pred_class_id: [N] int. Predicted class IDs\n pred_scores: [N] float. The probability scores of predicted classes\n overlaps: [pred_boxes, gt_boxes] IoU overlaps of predictins and GT boxes.\n class_names: list of all class names in the dataset\n threshold: Float. The prediction probability required to predict a class\n \"\"\"\n gt_class_ids = gt_class_ids[gt_class_ids != 0]\n pred_class_ids = pred_class_ids[pred_class_ids != 0]\n\n plt.figure(figsize=(12, 10))\n plt.imshow(overlaps, interpolation='nearest', cmap=plt.cm.Blues)\n plt.yticks(np.arange(len(pred_class_ids)),\n [\"{} ({:.2f})\".format(class_names[int(id)], pred_scores[i])\n for i, id in enumerate(pred_class_ids)])\n plt.xticks(np.arange(len(gt_class_ids)),\n [class_names[int(id)] for id in gt_class_ids], rotation=90)\n\n thresh = overlaps.max() / 2.\n for i, j in itertools.product(range(overlaps.shape[0]),\n range(overlaps.shape[1])):\n text = \"\"\n if overlaps[i, j] > threshold:\n text = \"match\" if gt_class_ids[j] == pred_class_ids[i] else \"wrong\"\n color = (\"white\" if overlaps[i, j] > thresh\n else \"black\" if overlaps[i, j] > 0\n else \"grey\")\n plt.text(j, i, \"{:.3f}\\n{}\".format(overlaps[i, j], text),\n horizontalalignment=\"center\", verticalalignment=\"center\",\n fontsize=9, color=color)\n\n plt.tight_layout()\n plt.xlabel(\"Ground Truth\")\n plt.ylabel(\"Predictions\")\n\n\ndef draw_boxes(image, boxes=None, refined_boxes=None,\n masks=None, captions=None, visibilities=None,\n title=\"\", ax=None):\n \"\"\"Draw bounding boxes and segmentation masks with differnt\n customizations.\n\n boxes: [N, (y1, x1, y2, x2, class_id)] in image coordinates.\n refined_boxes: Like boxes, but draw with solid lines to show\n that they're the result of refining 'boxes'.\n masks: [N, height, width]\n captions: List of N titles to display on each box\n visibilities: (optional) List of values of 0, 1, or 2. Determine how\n prominant each bounding box should be.\n title: An optional title to show over the image\n ax: (optional) Matplotlib axis to draw on.\n \"\"\"\n # Number of boxes\n assert boxes is not None or refined_boxes is not None\n N = boxes.shape[0] if boxes is not None else refined_boxes.shape[0]\n\n # Matplotlib Axis\n if not ax:\n _, ax = plt.subplots(1, figsize=(12, 12))\n\n # Generate random colors\n colors = random_colors(N)\n\n # Show area outside image boundaries.\n margin = image.shape[0] // 10\n ax.set_ylim(image.shape[0] + margin, -margin)\n ax.set_xlim(-margin, image.shape[1] + margin)\n ax.axis('off')\n\n ax.set_title(title)\n\n masked_image = image.astype(np.uint32).copy()\n for i in range(N):\n # Box visibility\n visibility = visibilities[i] if visibilities is not None else 1\n if visibility == 0:\n color = \"gray\"\n style = \"dotted\"\n alpha = 0.5\n elif visibility == 1:\n color = colors[i]\n style = \"dotted\"\n alpha = 1\n elif visibility == 2:\n color = colors[i]\n style = \"solid\"\n alpha = 1\n\n # Boxes\n if boxes is not None:\n if not np.any(boxes[i]):\n # Skip this instance. Has no bbox. Likely lost in cropping.\n continue\n y1, x1, y2, x2 = boxes[i]\n p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2,\n alpha=alpha, linestyle=style,\n edgecolor=color, facecolor='none')\n ax.add_patch(p)\n\n # Refined boxes\n if refined_boxes is not None and visibility > 0:\n ry1, rx1, ry2, rx2 = refined_boxes[i].astype(np.int32)\n p = patches.Rectangle((rx1, ry1), rx2 - rx1, ry2 - ry1, linewidth=2,\n edgecolor=color, facecolor='none')\n ax.add_patch(p)\n # Connect the top-left corners of the anchor and proposal\n if boxes is not None:\n ax.add_line(lines.Line2D([x1, rx1], [y1, ry1], color=color))\n\n # Captions\n if captions is not None:\n caption = captions[i]\n # If there are refined boxes, display captions on them\n if refined_boxes is not None:\n y1, x1, y2, x2 = ry1, rx1, ry2, rx2\n x = random.randint(x1, (x1 + x2) // 2)\n ax.text(x1, y1, caption, size=11, verticalalignment='top',\n color='w', backgroundcolor=\"none\",\n bbox={'facecolor': color, 'alpha': 0.5,\n 'pad': 2, 'edgecolor': 'none'})\n\n # Masks\n if masks is not None:\n mask = masks[:, :, i]\n masked_image = apply_mask(masked_image, mask, color)\n # Mask Polygon\n # Pad to ensure proper polygons for masks that touch image edges.\n padded_mask = np.zeros(\n (mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8)\n padded_mask[1:-1, 1:-1] = mask\n contours = find_contours(padded_mask, 0.5)\n for verts in contours:\n # Subtract the padding and flip (y, x) to (x, y)\n verts = np.fliplr(verts) - 1\n p = Polygon(verts, facecolor=\"none\", edgecolor=color)\n ax.add_patch(p)\n ax.imshow(masked_image.astype(np.uint8))\n\n\ndef display_table(table):\n \"\"\"Display values in a table format.\n table: an iterable of rows, and each row is an iterable of values.\n \"\"\"\n html = \"\"\n for row in table:\n row_html = \"\"\n for col in row:\n row_html += \"<td>{:40}</td>\".format(str(col))\n html += \"<tr>\" + row_html + \"</tr>\"\n html = \"<table>\" + html + \"</table>\"\n IPython.display.display(IPython.display.HTML(html))\n\n\ndef display_weight_stats(model):\n \"\"\"Scans all the weights in the model and returns a list of tuples\n that contain stats about each weight.\n \"\"\"\n layers = model.get_trainable_layers()\n table = [[\"WEIGHT NAME\", \"SHAPE\", \"MIN\", \"MAX\", \"STD\"]]\n for l in layers:\n weight_values = l.get_weights() # list of Numpy arrays\n weight_tensors = l.weights # list of TF tensors\n for i, w in enumerate(weight_values):\n weight_name = weight_tensors[i].name\n # Detect problematic layers. Exclude biases of conv layers.\n alert = \"\"\n if w.min() == w.max() and not (l.__class__.__name__ == \"Conv2D\" and i == 1):\n alert += \"<span style='color:red'>*** dead?</span>\"\n if np.abs(w.min()) > 1000 or np.abs(w.max()) > 1000:\n alert += \"<span style='color:red'>*** Overflow?</span>\"\n # Add row\n table.append([\n weight_name + alert,\n str(w.shape),\n \"{:+9.4f}\".format(w.min()),\n \"{:+10.4f}\".format(w.max()),\n \"{:+9.4f}\".format(w.std()),\n ])\n display_table(table)\n" ]
[ [ "matplotlib.pyplot.imshow", "numpy.concatenate", "numpy.any", "numpy.where", "matplotlib.patches.Polygon", "matplotlib.pyplot.tight_layout", "numpy.unique", "numpy.fliplr", "numpy.arange", "matplotlib.pyplot.subplot", "matplotlib.pyplot.axis", "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "numpy.random.choice", "matplotlib.patches.Rectangle", "numpy.random.rand", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "matplotlib.lines.Line2D", "matplotlib.pyplot.subplots", "matplotlib.pyplot.xlabel" ] ]
nicwulab/UK_strain_in_vitro_fitness
[ "743115c37d60877ca520ba0a4d53e4dc3c1734c7" ]
[ "codes/coverage_plot.py" ]
[ "#!/usr/bin/env python\n\nimport sys\nimport glob\nimport os\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib import use as mpl_use\n\nmpl_use(\"agg\")\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(\"SARS-CoV2 coverage\")\n\nplt.rc(\"axes\", labelsize=15)\nplt.rc(\"xtick\", labelsize=15)\nplt.rc(\"ytick\", labelsize=15)\n\n\ndef read_bed(bed):\n \"\"\"\n reading mosdepth output: {prefix}.per-base.bed.gz into pandas dataframe\n \"\"\"\n logger.info(\"Reading: %s\" % bed)\n return (\n pd.read_csv(bed, names=[\"chrom\", \"start\", \"end\", \"read_coverage\"], sep=\"\\t\")\n .assign(samplename=os.path.basename(os.path.dirname(bed)))\n .assign(log_cov=lambda d: d.read_coverage.transform(np.log))\n )\n\n\ndef main(mosdepth_bed_file: str, figure: str):\n \"\"\"\n plotting coverage plot from a mosdepth bed file\n\n :param mosdepth_bed_file: bed file generated from mosdepth (e.g. {prefix}.per-base.bed.gz)\n :param figure: output figure name\n \"\"\"\n df = read_bed(mosdepth_bed_file)\n\n # make figure\n p = sns.FacetGrid(data=df, col_wrap=1, col=\"samplename\")\n p.map(plt.plot, \"end\", \"log_cov\")\n p.set_titles(col_template=\"{col_name}\")\n sns.despine()\n p.set(xlabel=\"Genomic position\", ylabel=\"Read coverage (log)\")\n p.savefig(figure, bbox_inches=\"tight\")\n logger.info(\"Plotted: %s\" % figure)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n sys.exit(\n \"[usage] python %s <mosdepth bed file: {prefix}.per-base.bed.gz> <figurename> \"\n % sys.argv[0]\n )\n main(sys.argv[1], sys.argv[2])\n" ]
[ [ "matplotlib.use", "pandas.read_csv", "matplotlib.pyplot.rc" ] ]
NagisaZj/varibad
[ "df7cda81588c62a2a3bee69e4173228701bd7000", "df7cda81588c62a2a3bee69e4173228701bd7000" ]
[ "config/mujoco/args_metaworld_varibad.py", "config/mujoco/args_mujoco_cheetah_dir_varibad.py" ]
[ "import argparse\n\nimport torch\n\nfrom utils.cli import boolean_argument\n\n\ndef get_args(rest_args):\n parser = argparse.ArgumentParser()\n\n # --- GENERAL ---\n\n # training parameters\n parser.add_argument('--num_frames', type=int, default=1e8, help='number of frames to train')\n parser.add_argument('--max_rollouts_per_task', type=int, default=4)\n\n # variBAD\n parser.add_argument('--exp_label', default='varibad', help='label for the experiment')\n parser.add_argument('--disable_varibad', type=boolean_argument, default=False,\n help='Train policy w/o variBAD architecture')\n\n # env\n parser.add_argument('--env_name', default='metaworld-16', help='environment to train on')\n parser.add_argument('--norm_obs_for_policy', type=boolean_argument, default=True,\n help='normalise env observations (for policy)')\n parser.add_argument('--norm_rew_for_policy', type=boolean_argument, default=True,\n help='normalise env rewards (for policy)')\n parser.add_argument('--normalise_actions', type=boolean_argument, default=False, help='output normalised actions')\n\n # --- POLICY ---\n\n # network\n parser.add_argument('--policy_layers', nargs='+', default=[128, 128])\n parser.add_argument('--policy_activation_function', type=str, default='tanh', help='tanh, relu, leaky-relu')\n\n # algo\n parser.add_argument('--policy', type=str, default='ppo', help='choose: a2c, ppo, sac, optimal, oracle')\n\n # ppo specific\n parser.add_argument('--ppo_num_epochs', type=int, default=2, help='number of epochs per PPO update')\n parser.add_argument('--ppo_num_minibatch', type=int, default=4, help='number of minibatches to split the data')\n parser.add_argument('--ppo_use_huberloss', type=boolean_argument, default=True,\n help='use huber loss instead of MSE')\n parser.add_argument('--ppo_use_clipped_value_loss', type=boolean_argument, default=True,\n help='use huber loss instead of MSE')\n parser.add_argument('--ppo_clip_param', type=float, default=0.1, help='clamp param')\n\n # other hyperparameters\n parser.add_argument('--lr_policy', type=float, default=7e-4, help='learning rate (default: 7e-4)')\n parser.add_argument('--policy_num_steps', type=int, default=200,\n help='number of env steps to do (per process) before updating (for A2C ~ 10, for PPO ~100-200)')\n parser.add_argument('--policy_eps', type=float, default=1e-8, help='optimizer epsilon (1e-8 for ppo, 1e-5 for a2c)')\n parser.add_argument('--policy_init_std', type=float, default=1.0, help='learning rate (default: 7e-4)')\n parser.add_argument('--learn_action_std', type=boolean_argument, default=True)\n parser.add_argument('--policy_value_loss_coef', type=float, default=0.5,\n help='value loss coefficient (default: 0.5)')\n parser.add_argument('--policy_entropy_coef', type=float, default=0.01,\n help='entropy term coefficient (default: 0.01)')\n parser.add_argument('--policy_gamma', type=float, default=0.97, help='discount factor for rewards (default: 0.99)')\n parser.add_argument('--policy_use_gae', type=boolean_argument, default=True,\n help='use generalized advantage estimation')\n parser.add_argument('--policy_tau', type=float, default=0.9, help='gae parameter (default: 0.95)')\n parser.add_argument('--use_proper_time_limits', type=boolean_argument, default=True)\n parser.add_argument('--policy_max_grad_norm', type=float, default=0.5, help='max norm of gradients (default: 0.5)')\n\n # --- VAE ---\n\n # general\n parser.add_argument('--lr_vae', type=float, default=0.001)\n parser.add_argument('--size_vae_buffer', type=int, default=10000,\n help='how many trajectories to keep in VAE buffer')\n parser.add_argument('--vae_buffer_add_thresh', type=float, default=0.8, help='prob of adding a new traj to buffer')\n parser.add_argument('--vae_batch_num_trajs', type=int, default=10)\n parser.add_argument('--vae_batch_num_enc_lens', type=int, default=50)\n parser.add_argument('--num_vae_updates', type=int, default=1,\n help='how many VAE update steps to take per meta-iteration')\n parser.add_argument('--kl_weight', type=float, default=1.0, help='weight for the KL term')\n parser.add_argument('--precollect_len', type=int, default=0,\n help='how many frames to pre-collect before training begins')\n parser.add_argument('--pretrain_len', type=int, default=0,\n help='for how many updates to pre-train the VAE (done with the frames from precollect-len)')\n\n # - encoder\n parser.add_argument('--latent_dim', type=int, default=5, help='dimensionality of latent space')\n parser.add_argument('--aggregator_hidden_size', type=int, default=128,\n help='dimensionality of hidden state of the rnn')\n parser.add_argument('--layers_before_aggregator', nargs='+', type=int, default=[])\n parser.add_argument('--layers_after_aggregator', nargs='+', type=int, default=[])\n parser.add_argument('--state_embedding_size', type=int, default=32)\n parser.add_argument('--action_embedding_size', type=int, default=16)\n parser.add_argument('--reward_embedding_size', type=int, default=16)\n\n # decoder: rewards\n parser.add_argument('--decode_reward', type=boolean_argument, default=True, help='use reward decoder')\n parser.add_argument('--rew_loss_coeff', type=float, default=1.0, help='weight for state loss (vs reward loss)')\n parser.add_argument('--input_prev_state', type=boolean_argument, default=True, help='use reward decoder')\n parser.add_argument('--input_action', type=boolean_argument, default=True, help='use reward decoder')\n parser.add_argument('--reward_decoder_layers', nargs='+', type=int, default=[64, 32])\n parser.add_argument('--rew_pred_type', type=str, default='deterministic',\n help='choose from: bernoulli, gaussian, deterministic')\n parser.add_argument('--multihead_for_reward', type=boolean_argument, default=False,\n help='one head per reward pred (i.e. per state)')\n\n # decoder: state transitions\n parser.add_argument('--decode_state', type=boolean_argument, default=False, help='use state decoder')\n parser.add_argument('--state_loss_coeff', type=float, default=1.0, help='weight for state loss (vs reward loss)')\n\n # decoder: ground-truth task (\"varibad oracle\", after Humplik et al. 2019)\n parser.add_argument('--decode_task', type=boolean_argument, default=False, help='use task decoder')\n parser.add_argument('--task_loss_coeff', type=float, default=1.0, help='weight for task loss (vs other losses)')\n parser.add_argument('--task_decoder_layers', nargs='+', type=int, default=[64, 32])\n parser.add_argument('--task_pred_type', type=str, default='task_description',\n help='choose from: task_id (not implemented), task_description')\n\n # --- ABLATIONS ---\n\n parser.add_argument('--disable_decoder', type=boolean_argument, default=False)\n parser.add_argument('--disable_stochasticity_in_latent', type=boolean_argument, default=False)\n parser.add_argument('--sample_embeddings', type=boolean_argument, default=False,\n help='sample the embedding (otherwise: pass mean)')\n parser.add_argument('--rlloss_through_encoder', type=boolean_argument, default=False,\n help='backprop rl loss through encoder')\n parser.add_argument('--vae_loss_coeff', type=float, default=1.0, help='weight for VAE loss (vs RL loss)')\n parser.add_argument('--kl_to_gauss_prior', type=boolean_argument, default=False)\n parser.add_argument('--learn_prior', type=boolean_argument, default=False)\n parser.add_argument('--decode_only_past', type=boolean_argument, default=False,\n help='whether to decode future observations')\n parser.add_argument('--condition_policy_on_state', type=boolean_argument, default=True,\n help='after the encoder, add the env state to the latent space')\n\n # --- OTHERS ---\n\n # logging, saving, evaluation\n parser.add_argument('--log_interval', type=int, default=25,\n help='log interval, one log per n updates (default: 10)')\n parser.add_argument('--save_interval', type=int, default=500,\n help='save interval, one save per n updates (default: 100)')\n parser.add_argument('--eval_interval', type=int, default=25,\n help='eval interval, one eval per n updates (default: None)')\n parser.add_argument('--vis_interval', type=int, default=500,\n help='visualisation interval, one eval per n updates (default: None)')\n parser.add_argument('--agent_log_dir', default='/tmp/gym/', help='directory to save agent logs (default: /tmp/gym)')\n parser.add_argument('--results_log_dir', default=None, help='directory to save agent logs (default: ./data)')\n\n # general settings\n parser.add_argument('--seed', type=int, default=41, help='random seed (default: 73)')\n parser.add_argument('--deterministic_execution', type=boolean_argument, default=False,\n help='Make code fully deterministic. Expects 1 process and uses deterministic CUDNN')\n parser.add_argument('--num_processes', type=int, default=16,\n help='how many training CPU processes to use (default: 16)')\n args = parser.parse_args(rest_args)\n\n args.cuda = torch.cuda.is_available()\n args.policy_layers = [int(p) for p in args.policy_layers]\n\n return args\n", "import argparse\n\nimport torch\n\nfrom utils.cli import boolean_argument\n\n\ndef get_args(rest_args):\n parser = argparse.ArgumentParser()\n\n # --- GENERAL ---\n\n # training parameters\n parser.add_argument('--num_frames', type=int, default=1e8, help='number of frames to train')\n parser.add_argument('--max_rollouts_per_task', type=int, default=2)\n\n # variBAD\n parser.add_argument('--exp_label', default='varibad', help='label for the experiment')\n parser.add_argument('--disable_varibad', type=boolean_argument, default=False,\n help='Train policy w/o variBAD architecture')\n\n # env\n parser.add_argument('--env_name', default='HalfCheetahDir-v0', help='environment to train on')\n parser.add_argument('--norm_obs_for_policy', type=boolean_argument, default=True,\n help='normalise env observations (for policy)')\n parser.add_argument('--norm_rew_for_policy', type=boolean_argument, default=True,\n help='normalise env rewards (for policy)')\n parser.add_argument('--normalise_actions', type=boolean_argument, default=False, help='output normalised actions')\n\n # --- POLICY ---\n\n # network\n parser.add_argument('--policy_layers', nargs='+', default=[128, 128])\n parser.add_argument('--policy_activation_function', type=str, default='tanh', help='tanh, relu, leaky-relu')\n\n # algo\n parser.add_argument('--policy', type=str, default='ppo', help='choose: a2c, ppo, sac, optimal, oracle')\n\n # ppo specific\n parser.add_argument('--ppo_num_epochs', type=int, default=2, help='number of epochs per PPO update')\n parser.add_argument('--ppo_num_minibatch', type=int, default=4, help='number of minibatches to split the data')\n parser.add_argument('--ppo_use_huberloss', type=boolean_argument, default=True,\n help='use huber loss instead of MSE')\n parser.add_argument('--ppo_use_clipped_value_loss', type=boolean_argument, default=True,\n help='use huber loss instead of MSE')\n parser.add_argument('--ppo_clip_param', type=float, default=0.1, help='clamp param')\n\n # other hyperparameters\n parser.add_argument('--lr_policy', type=float, default=7e-4, help='learning rate (default: 7e-4)')\n parser.add_argument('--policy_num_steps', type=int, default=200,\n help='number of env steps to do (per process) before updating (for A2C ~ 10, for PPO ~100-200)')\n parser.add_argument('--policy_eps', type=float, default=1e-8, help='optimizer epsilon (1e-8 for ppo, 1e-5 for a2c)')\n parser.add_argument('--policy_init_std', type=float, default=1.0, help='learning rate (default: 7e-4)')\n parser.add_argument('--learn_action_std', type=boolean_argument, default=True)\n parser.add_argument('--policy_value_loss_coef', type=float, default=0.5,\n help='value loss coefficient (default: 0.5)')\n parser.add_argument('--policy_entropy_coef', type=float, default=0.01,\n help='entropy term coefficient (default: 0.01)')\n parser.add_argument('--policy_gamma', type=float, default=0.97, help='discount factor for rewards (default: 0.99)')\n parser.add_argument('--policy_use_gae', type=boolean_argument, default=True,\n help='use generalized advantage estimation')\n parser.add_argument('--policy_tau', type=float, default=0.9, help='gae parameter (default: 0.95)')\n parser.add_argument('--use_proper_time_limits', type=boolean_argument, default=True)\n parser.add_argument('--policy_max_grad_norm', type=float, default=0.5, help='max norm of gradients (default: 0.5)')\n\n # --- VAE ---\n\n # general\n parser.add_argument('--lr_vae', type=float, default=0.001)\n parser.add_argument('--size_vae_buffer', type=int, default=10000,\n help='how many trajectories to keep in VAE buffer')\n parser.add_argument('--vae_buffer_add_thresh', type=float, default=0.8, help='prob of adding a new traj to buffer')\n parser.add_argument('--vae_batch_num_trajs', type=int, default=10)\n parser.add_argument('--vae_batch_num_enc_lens', type=int, default=50)\n parser.add_argument('--num_vae_updates', type=int, default=1,\n help='how many VAE update steps to take per meta-iteration')\n parser.add_argument('--kl_weight', type=float, default=0.1, help='weight for the KL term')\n parser.add_argument('--precollect_len', type=int, default=0,\n help='how many frames to pre-collect before training begins')\n parser.add_argument('--pretrain_len', type=int, default=0, help='for how many updates to pre-train the VAE')\n\n # - encoder\n parser.add_argument('--latent_dim', type=int, default=5, help='dimensionality of latent space')\n parser.add_argument('--aggregator_hidden_size', type=int, default=128,\n help='dimensionality of hidden state of the rnn')\n parser.add_argument('--layers_before_aggregator', nargs='+', type=int, default=[])\n parser.add_argument('--layers_after_aggregator', nargs='+', type=int, default=[])\n parser.add_argument('--state_embedding_size', type=int, default=32)\n parser.add_argument('--action_embedding_size', type=int, default=16)\n parser.add_argument('--reward_embedding_size', type=int, default=16)\n\n # decoder: rewards\n parser.add_argument('--decode_reward', type=boolean_argument, default=True, help='use reward decoder')\n parser.add_argument('--rew_loss_coeff', type=float, default=1.0, help='weight for state loss (vs reward loss)')\n parser.add_argument('--input_prev_state', type=boolean_argument, default=True, help='use reward decoder')\n parser.add_argument('--input_action', type=boolean_argument, default=True, help='use reward decoder')\n parser.add_argument('--reward_decoder_layers', nargs='+', type=int, default=[64, 32])\n parser.add_argument('--rew_pred_type', type=str, default='deterministic',\n help='choose from: bernoulli, gaussian, deterministic')\n parser.add_argument('--multihead_for_reward', type=boolean_argument, default=False,\n help='one head per reward pred (i.e. per state)')\n\n # decoder: state transitions\n parser.add_argument('--decode_state', type=boolean_argument, default=False, help='use state decoder')\n parser.add_argument('--state_loss_coeff', type=float, default=1.0, help='weight for state loss (vs reward loss)')\n\n # decoder: ground-truth task (\"varibad oracle\", after Humplik et al. 2019)\n parser.add_argument('--decode_task', type=boolean_argument, default=False, help='use task decoder')\n parser.add_argument('--task_loss_coeff', type=float, default=1.0, help='weight for task loss (vs other losses)')\n parser.add_argument('--task_decoder_layers', nargs='+', type=int, default=[64, 32])\n parser.add_argument('--task_pred_type', type=str, default='task_description',\n help='choose from: task_id (not implemented), task_description')\n\n # --- ABLATIONS ---\n\n parser.add_argument('--disable_decoder', type=boolean_argument, default=False)\n parser.add_argument('--disable_stochasticity_in_latent', type=boolean_argument, default=False)\n parser.add_argument('--sample_embeddings', type=boolean_argument, default=False,\n help='sample the embedding (otherwise: pass mean)')\n parser.add_argument('--rlloss_through_encoder', type=boolean_argument, default=False,\n help='backprop rl loss through encoder')\n parser.add_argument('--vae_loss_coeff', type=float, default=1.0, help='weight for VAE loss (vs RL loss)')\n parser.add_argument('--kl_to_gauss_prior', type=boolean_argument, default=False)\n parser.add_argument('--learn_prior', type=boolean_argument, default=False)\n parser.add_argument('--decode_only_past', type=boolean_argument, default=False,\n help='whether to decode future observations')\n parser.add_argument('--condition_policy_on_state', type=boolean_argument, default=True,\n help='after the encoder, add the env state to the latent space')\n\n # --- OTHERS ---\n\n # logging, saving, evaluation\n parser.add_argument('--log_interval', type=int, default=25,\n help='log interval, one log per n updates (default: 10)')\n parser.add_argument('--save_interval', type=int, default=500,\n help='save interval, one save per n updates (default: 100)')\n parser.add_argument('--eval_interval', type=int, default=25,\n help='eval interval, one eval per n updates (default: None)')\n parser.add_argument('--vis_interval', type=int, default=500,\n help='visualisation interval, one eval per n updates (default: None)')\n parser.add_argument('--agent_log_dir', default='/tmp/gym/', help='directory to save agent logs (default: /tmp/gym)')\n parser.add_argument('--results_log_dir', default=None, help='directory to save agent logs (default: ./data)')\n\n # general settings\n parser.add_argument('--seed', type=int, default=73, help='random seed (default: 73)')\n parser.add_argument('--deterministic_execution', type=boolean_argument, default=False,\n help='Make code fully deterministic. Expects 1 process and uses deterministic CUDNN')\n parser.add_argument('--num_processes', type=int, default=16,\n help='how many training CPU processes to use (default: 16)')\n args = parser.parse_args(rest_args)\n\n args.cuda = torch.cuda.is_available()\n args.policy_layers = [int(p) for p in args.policy_layers]\n\n return args\n" ]
[ [ "torch.cuda.is_available" ], [ "torch.cuda.is_available" ] ]
dsosnoski/irvideo-classification
[ "894e0bf00039fb35e870e682eb62f68e7ec00334" ]
[ "model/trainer_kfold.py" ]
[ "\nimport datetime\nimport json\nimport os\nimport pickle\nimport sys\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom model.frame_sequence import FrameSequence\nfrom model.model_builder import ModelBuilder\nfrom model.training_utils import load_raw_tracks, tracks_by_tag, first_time_model, build_callback, \\\n print_track_information, draw_figures\nfrom support.data_model import CLASSES, TAG_HOTS\n\n\ndef split_training_validation(tag_tracks, validate_frame_counts):\n train_tracks = {}\n validate_tracks = {}\n for tag in tag_tracks.keys():\n if tag in CLASSES:\n tracks = tag_tracks[tag]\n np.random.shuffle(tracks)\n vcount = 0\n train_use = []\n validate_use = []\n for track_info in tracks:\n if vcount < validate_frame_counts[tag]:\n validate_use.append(track_info)\n vcount += track_info.frame_count\n else:\n train_use.append(track_info)\n train_tracks[tag] = train_use\n validate_tracks[tag] = validate_use\n return train_tracks, validate_tracks\n\n\ndef kfold_split(data_directory, fold_count):\n tracks = load_raw_tracks(f'{data_directory}/train_infos.pk')\n tag_tracks = tracks_by_tag(tracks)\n for tag in tag_tracks:\n print(f'{tag} loaded {len(tag_tracks[tag])} tracks')\n fold_tag_tracks = [{} for _ in range(fold_count)]\n for tag in tag_tracks.keys():\n if tag in CLASSES:\n tracks = tag_tracks[tag]\n np.random.shuffle(tracks)\n fold_tracks = [[] for _ in range(fold_count)]\n frame_counts = np.zeros(fold_count)\n for track_info in tracks:\n fold = frame_counts.argmin()\n fold_tracks[fold].append(track_info)\n frame_counts[fold] += track_info.frame_count\n for i in range(fold_count):\n fold_tag_tracks[i][tag] = fold_tracks[i]\n return fold_tag_tracks\n\n\ndef merge_tag_tracks(tag_tracks_list):\n merged_tracks = { c: [] for c in CLASSES }\n for tag_tracks in tag_tracks_list:\n for tag in tag_tracks:\n merged_tracks[tag] += tag_tracks[tag]\n return merged_tracks\n\n\ndef main():\n argv = sys.argv\n with open(argv[1]) as f:\n training_config = json.load(f)\n with open(argv[2]) as f:\n model_config = json.load(f)\n\n os.environ['CUDA_VISIBLE_DEVICES'] = argv[3] if len(argv) > 3 else ''\n\n #check GPU and limit GPU memory growth\n gpu = tf.config.list_physical_devices('GPU')\n print(\"Num GPUs Available: \", len(gpu))\n if len(gpu) > 0:\n tf.config.experimental.set_memory_growth(gpu[0], True)\n\n base_save_path = training_config['base_save_path']\n name = model_config['model_name']\n model_name_suffix = training_config.get('model_name_suffix', '')\n date_string = datetime.datetime.now().strftime('%Y%m%d')\n save_directory = f'{base_save_path}/{name}{model_name_suffix}-{date_string}'\n if not os.path.exists(save_directory):\n os.mkdir(save_directory)\n print(f'saving to {save_directory}')\n epochs_count = training_config['epochs_count']\n\n data_directory = training_config['data_path']\n fold_count = training_config['fold_count']\n split_path = f'{save_directory}/splits.pk'\n if os.path.exists(save_directory):\n with open(split_path, 'rb') as f:\n kfold_tag_tracks = []\n for _ in range(fold_count):\n kfold_tag_tracks.append(pickle.load(f))\n else:\n kfold_tag_tracks = kfold_split(data_directory, fold_count)\n with open(split_path, 'wb') as f:\n for fold in kfold_tag_tracks:\n pickle.dump(fold, f)\n data_path = f'{data_directory}/train_frames.npy'\n batch_size = training_config['batch_size']\n max_frame_load_count = training_config['max_frame_load_count']\n frame_counts = { k: max_frame_load_count for k in CLASSES }\n replace_fraction_per_epoch = training_config['replace_fraction_per_epoch']\n noise_scale = training_config.get('noise_scale')\n rotation_limit = training_config.get('rotation_limit')\n use_flip = training_config.get('use_flip', False)\n input_dims = tuple(training_config['input_dims'])\n model = ModelBuilder.build_model(input_dims, len(CLASSES), None, **model_config)\n first_time_model(model, save_directory, training_config, model_config)\n model_json = model.to_json()\n with open(f'{save_directory}/model.json', 'w') as f:\n f.write(model_json)\n for fold_num in range(fold_count):\n pass_directory = f'{save_directory}/fold{fold_num}'\n if not os.path.exists(pass_directory):\n os.mkdir(pass_directory)\n print(f'\\nTraining fold {fold_num}')\n training_tracks = merge_tag_tracks([kfold_tag_tracks[i] for i in range(fold_count) if i != fold_num])\n validation_tracks = kfold_tag_tracks[fold_num]\n print_track_information(training_tracks, validation_tracks)\n train_sequence = FrameSequence.build_training_sequence(training_tracks, data_path, batch_size, TAG_HOTS, input_dims,\n frame_counts, replace_fraction_per_epoch, noise_scale,\n rotation_limit, use_flip)\n validate_sequence = FrameSequence.build_validation_sequence(validation_tracks, data_path, batch_size, TAG_HOTS, input_dims)\n certainty_loss_weight = training_config.get('certainty_loss_weight')\n model = ModelBuilder.build_model(input_dims, len(CLASSES), certainty_loss_weight, **model_config)\n callbacks = [build_callback(cfg, pass_directory) for cfg in training_config['callbacks']]\n history = model.fit(train_sequence, validation_data=validate_sequence, epochs=epochs_count, callbacks=callbacks)\n model.save(f'{pass_directory}/model-finished.sav')\n draw_figures(history, training_config['plots'], pass_directory)\n train_sequence.clear()\n validate_sequence.clear()\n tf.keras.backend.clear_session()\n\n\nif __name__ == '__main__':\n sys.exit(main())\n" ]
[ [ "tensorflow.config.experimental.set_memory_growth", "numpy.random.shuffle", "tensorflow.keras.backend.clear_session", "tensorflow.config.list_physical_devices", "numpy.zeros" ] ]
likesum/deepFnF
[ "461d93de15a642bda75c7ef15937a01e1c5575e5" ]
[ "test.py" ]
[ "#!/usr/bin/env python3\n\nimport os\nimport argparse\n\nimport utils.np_utils as npu\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.contrib.eager as tfe\n\nimport net\nimport utils.utils as ut\nimport utils.tf_utils as tfu\n\ntf.enable_eager_execution()\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n '--wts', default='wts/model.npz', help='path to trianed model')\nopts = parser.parse_args()\n\n\ndef load_net(fn, model):\n wts = np.load(fn)\n for k, v in wts.items():\n model.weights[k] = tfe.Variable(v)\n\n\ndatapath = 'data/testset'\nmodel_path = opts.wts\n\nmodel = net.Net(ksz=15, num_basis=90, burst_length=2)\n\nprint(\"Restoring model from \" + model_path)\nload_net(model_path, model)\nprint('Done\\n')\n\nfor k in range(4):\n metrics = []\n for c in range(128):\n data = np.load('%s/%d/%d.npz' % (datapath, k, c))\n\n alpha = data['alpha'][None, None, None, None]\n ambient = data['ambient']\n dimmed_ambient, _ = tfu.dim_image(data['ambient'], alpha=alpha)\n dimmed_warped_ambient, _ = tfu.dim_image(\n data['warped_ambient'], alpha=alpha)\n\n # Make the flash brighter by increasing the brightness of the\n # flash-only image.\n flash = data['flash_only'] * ut.FLASH_STRENGTH + dimmed_ambient\n warped_flash = data['warped_flash_only'] * \\\n ut.FLASH_STRENGTH + dimmed_warped_ambient\n\n noisy_ambient = data['noisy_ambient']\n noisy_flash = data['noisy_warped_flash']\n\n noisy = tf.concat([noisy_ambient, noisy_flash], axis=-1)\n noise_std = tfu.estimate_std(\n noisy, data['sig_read'], data['sig_shot'])\n net_input = tf.concat([noisy, noise_std], axis=-1)\n\n denoise = model.forward(net_input)\n denoise = denoise / alpha\n\n ambient = tfu.camera_to_rgb(\n ambient, data['color_matrix'], data['adapt_matrix'])\n denoise = tfu.camera_to_rgb(\n denoise, data['color_matrix'], data['adapt_matrix'])\n\n ambient = np.clip(ambient, 0., 1.).squeeze()\n denoise = np.clip(denoise, 0., 1.).squeeze()\n\n mse = npu.get_mse(denoise, ambient)\n psnr = npu.get_psnr(denoise, ambient)\n ssim = npu.get_ssim(denoise, ambient)\n\n metrics.append([psnr, ssim])\n\n metrics = np.mean(metrics, axis=0).tolist()\n print('\\nLevel %d' % (4 - k) +\n ': PSNR: %.3f, SSIM: %.4f' % tuple(metrics))\n\n" ]
[ [ "tensorflow.enable_eager_execution", "tensorflow.concat", "numpy.clip", "tensorflow.contrib.eager.Variable", "numpy.mean", "numpy.load" ] ]
Templarrr/pandas
[ "e91a840869aa023ac52802145df8c916e6ef907d" ]
[ "pandas/core/generic.py" ]
[ "# pylint: disable=W0231,E1101\nimport collections\nimport functools\nimport warnings\nimport operator\nimport weakref\nimport gc\nimport json\n\nimport numpy as np\nimport pandas as pd\n\nfrom pandas._libs import tslib, properties\nfrom pandas.core.dtypes.common import (\n ensure_int64,\n ensure_object,\n is_scalar,\n is_number,\n is_integer, is_bool,\n is_bool_dtype,\n is_categorical_dtype,\n is_numeric_dtype,\n is_datetime64_any_dtype,\n is_timedelta64_dtype,\n is_datetime64tz_dtype,\n is_list_like,\n is_dict_like,\n is_re_compilable,\n is_period_arraylike,\n is_object_dtype,\n pandas_dtype)\nfrom pandas.core.dtypes.cast import maybe_promote, maybe_upcast_putmask\nfrom pandas.core.dtypes.inference import is_hashable\nfrom pandas.core.dtypes.missing import isna, notna\nfrom pandas.core.dtypes.generic import ABCSeries, ABCPanel, ABCDataFrame\n\nfrom pandas.core.base import PandasObject, SelectionMixin\nfrom pandas.core.index import (Index, MultiIndex, ensure_index,\n InvalidIndexError, RangeIndex)\nimport pandas.core.indexing as indexing\nfrom pandas.core.indexes.datetimes import DatetimeIndex\nfrom pandas.core.indexes.period import PeriodIndex, Period\nfrom pandas.core.internals import BlockManager\nimport pandas.core.algorithms as algos\nimport pandas.core.common as com\nimport pandas.core.missing as missing\nfrom pandas.io.formats.printing import pprint_thing\nfrom pandas.io.formats.format import format_percentiles, DataFrameFormatter\nfrom pandas.tseries.frequencies import to_offset\nfrom pandas import compat\nfrom pandas.compat.numpy import function as nv\nfrom pandas.compat import (map, zip, lzip, lrange, string_types, to_str,\n isidentifier, set_function_name, cPickle as pkl)\nfrom pandas.core.ops import _align_method_FRAME\nimport pandas.core.nanops as nanops\nfrom pandas.util._decorators import (Appender, Substitution,\n deprecate_kwarg)\nfrom pandas.util._validators import validate_bool_kwarg, validate_fillna_kwargs\nfrom pandas.core import config\n\n# goal is to be able to define the docs close to function, while still being\n# able to share\n_shared_docs = dict()\n_shared_doc_kwargs = dict(\n axes='keywords for axes', klass='NDFrame',\n axes_single_arg='int or labels for object',\n args_transpose='axes to permute (int or label for object)',\n optional_by=\"\"\"\n by : str or list of str\n Name or list of names to sort by\"\"\")\n\n\ndef _single_replace(self, to_replace, method, inplace, limit):\n \"\"\"\n Replaces values in a Series using the fill method specified when no\n replacement value is given in the replace method\n \"\"\"\n if self.ndim != 1:\n raise TypeError('cannot replace {0} with method {1} on a {2}'\n .format(to_replace, method, type(self).__name__))\n\n orig_dtype = self.dtype\n result = self if inplace else self.copy()\n fill_f = missing.get_fill_func(method)\n\n mask = missing.mask_missing(result.values, to_replace)\n values = fill_f(result.values, limit=limit, mask=mask)\n\n if values.dtype == orig_dtype and inplace:\n return\n\n result = pd.Series(values, index=self.index,\n dtype=self.dtype).__finalize__(self)\n\n if inplace:\n self._update_inplace(result._data)\n return\n\n return result\n\n\nclass NDFrame(PandasObject, SelectionMixin):\n \"\"\"\n N-dimensional analogue of DataFrame. Store multi-dimensional in a\n size-mutable, labeled data structure\n\n Parameters\n ----------\n data : BlockManager\n axes : list\n copy : boolean, default False\n \"\"\"\n _internal_names = ['_data', '_cacher', '_item_cache', '_cache', '_is_copy',\n '_subtyp', '_name', '_index', '_default_kind',\n '_default_fill_value', '_metadata', '__array_struct__',\n '__array_interface__']\n _internal_names_set = set(_internal_names)\n _accessors = frozenset([])\n _deprecations = frozenset(['as_blocks', 'blocks',\n 'consolidate', 'convert_objects', 'is_copy'])\n _metadata = []\n _is_copy = None\n\n def __init__(self, data, axes=None, copy=False, dtype=None,\n fastpath=False):\n\n if not fastpath:\n if dtype is not None:\n data = data.astype(dtype)\n elif copy:\n data = data.copy()\n\n if axes is not None:\n for i, ax in enumerate(axes):\n data = data.reindex_axis(ax, axis=i)\n\n object.__setattr__(self, '_is_copy', None)\n object.__setattr__(self, '_data', data)\n object.__setattr__(self, '_item_cache', {})\n\n @property\n def is_copy(self):\n warnings.warn(\"Attribute 'is_copy' is deprecated and will be removed \"\n \"in a future version.\", FutureWarning, stacklevel=2)\n return self._is_copy\n\n @is_copy.setter\n def is_copy(self, msg):\n warnings.warn(\"Attribute 'is_copy' is deprecated and will be removed \"\n \"in a future version.\", FutureWarning, stacklevel=2)\n self._is_copy = msg\n\n def _repr_data_resource_(self):\n \"\"\"\n Not a real Jupyter special repr method, but we use the same\n naming convention.\n \"\"\"\n if config.get_option(\"display.html.table_schema\"):\n data = self.head(config.get_option('display.max_rows'))\n payload = json.loads(data.to_json(orient='table'),\n object_pairs_hook=collections.OrderedDict)\n return payload\n\n def _validate_dtype(self, dtype):\n \"\"\" validate the passed dtype \"\"\"\n\n if dtype is not None:\n dtype = pandas_dtype(dtype)\n\n # a compound dtype\n if dtype.kind == 'V':\n raise NotImplementedError(\"compound dtypes are not implemented\"\n \" in the {0} constructor\"\n .format(self.__class__.__name__))\n\n return dtype\n\n def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):\n \"\"\" passed a manager and a axes dict \"\"\"\n for a, axe in axes.items():\n if axe is not None:\n mgr = mgr.reindex_axis(axe,\n axis=self._get_block_manager_axis(a),\n copy=False)\n\n # make a copy if explicitly requested\n if copy:\n mgr = mgr.copy()\n if dtype is not None:\n # avoid further copies if we can\n if len(mgr.blocks) > 1 or mgr.blocks[0].values.dtype != dtype:\n mgr = mgr.astype(dtype=dtype)\n return mgr\n\n # ----------------------------------------------------------------------\n # Construction\n\n @property\n def _constructor(self):\n \"\"\"Used when a manipulation result has the same dimensions as the\n original.\n \"\"\"\n raise com.AbstractMethodError(self)\n\n def __unicode__(self):\n # unicode representation based upon iterating over self\n # (since, by definition, `PandasContainers` are iterable)\n prepr = '[%s]' % ','.join(map(pprint_thing, self))\n return '%s(%s)' % (self.__class__.__name__, prepr)\n\n def _dir_additions(self):\n \"\"\" add the string-like attributes from the info_axis.\n If info_axis is a MultiIndex, it's first level values are used.\n \"\"\"\n additions = {c for c in self._info_axis.unique(level=0)[:100]\n if isinstance(c, string_types) and isidentifier(c)}\n return super(NDFrame, self)._dir_additions().union(additions)\n\n @property\n def _constructor_sliced(self):\n \"\"\"Used when a manipulation result has one lower dimension(s) as the\n original, such as DataFrame single columns slicing.\n \"\"\"\n raise com.AbstractMethodError(self)\n\n @property\n def _constructor_expanddim(self):\n \"\"\"Used when a manipulation result has one higher dimension as the\n original, such as Series.to_frame() and DataFrame.to_panel()\n \"\"\"\n raise NotImplementedError\n\n # ----------------------------------------------------------------------\n # Axis\n\n @classmethod\n def _setup_axes(cls, axes, info_axis=None, stat_axis=None, aliases=None,\n slicers=None, axes_are_reversed=False, build_axes=True,\n ns=None, docs=None):\n \"\"\"Provide axes setup for the major PandasObjects.\n\n Parameters\n ----------\n axes : the names of the axes in order (lowest to highest)\n info_axis_num : the axis of the selector dimension (int)\n stat_axis_num : the number of axis for the default stats (int)\n aliases : other names for a single axis (dict)\n slicers : how axes slice to others (dict)\n axes_are_reversed : boolean whether to treat passed axes as\n reversed (DataFrame)\n build_axes : setup the axis properties (default True)\n \"\"\"\n\n cls._AXIS_ORDERS = axes\n cls._AXIS_NUMBERS = {a: i for i, a in enumerate(axes)}\n cls._AXIS_LEN = len(axes)\n cls._AXIS_ALIASES = aliases or dict()\n cls._AXIS_IALIASES = {v: k for k, v in cls._AXIS_ALIASES.items()}\n cls._AXIS_NAMES = dict(enumerate(axes))\n cls._AXIS_SLICEMAP = slicers or None\n cls._AXIS_REVERSED = axes_are_reversed\n\n # typ\n setattr(cls, '_typ', cls.__name__.lower())\n\n # indexing support\n cls._ix = None\n\n if info_axis is not None:\n cls._info_axis_number = info_axis\n cls._info_axis_name = axes[info_axis]\n\n if stat_axis is not None:\n cls._stat_axis_number = stat_axis\n cls._stat_axis_name = axes[stat_axis]\n\n # setup the actual axis\n if build_axes:\n\n def set_axis(a, i):\n setattr(cls, a, properties.AxisProperty(i, docs.get(a, a)))\n cls._internal_names_set.add(a)\n\n if axes_are_reversed:\n m = cls._AXIS_LEN - 1\n for i, a in cls._AXIS_NAMES.items():\n set_axis(a, m - i)\n else:\n for i, a in cls._AXIS_NAMES.items():\n set_axis(a, i)\n\n # addtl parms\n if isinstance(ns, dict):\n for k, v in ns.items():\n setattr(cls, k, v)\n\n def _construct_axes_dict(self, axes=None, **kwargs):\n \"\"\"Return an axes dictionary for myself.\"\"\"\n d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)}\n d.update(kwargs)\n return d\n\n @staticmethod\n def _construct_axes_dict_from(self, axes, **kwargs):\n \"\"\"Return an axes dictionary for the passed axes.\"\"\"\n d = {a: ax for a, ax in zip(self._AXIS_ORDERS, axes)}\n d.update(kwargs)\n return d\n\n def _construct_axes_dict_for_slice(self, axes=None, **kwargs):\n \"\"\"Return an axes dictionary for myself.\"\"\"\n d = {self._AXIS_SLICEMAP[a]: self._get_axis(a)\n for a in (axes or self._AXIS_ORDERS)}\n d.update(kwargs)\n return d\n\n def _construct_axes_from_arguments(self, args, kwargs, require_all=False):\n \"\"\"Construct and returns axes if supplied in args/kwargs.\n\n If require_all, raise if all axis arguments are not supplied\n return a tuple of (axes, kwargs).\n \"\"\"\n\n # construct the args\n args = list(args)\n for a in self._AXIS_ORDERS:\n\n # if we have an alias for this axis\n alias = self._AXIS_IALIASES.get(a)\n if alias is not None:\n if a in kwargs:\n if alias in kwargs:\n raise TypeError(\"arguments are mutually exclusive \"\n \"for [%s,%s]\" % (a, alias))\n continue\n if alias in kwargs:\n kwargs[a] = kwargs.pop(alias)\n continue\n\n # look for a argument by position\n if a not in kwargs:\n try:\n kwargs[a] = args.pop(0)\n except IndexError:\n if require_all:\n raise TypeError(\"not enough/duplicate arguments \"\n \"specified!\")\n\n axes = {a: kwargs.pop(a, None) for a in self._AXIS_ORDERS}\n return axes, kwargs\n\n @classmethod\n def _from_axes(cls, data, axes, **kwargs):\n # for construction from BlockManager\n if isinstance(data, BlockManager):\n return cls(data, **kwargs)\n else:\n if cls._AXIS_REVERSED:\n axes = axes[::-1]\n d = cls._construct_axes_dict_from(cls, axes, copy=False)\n d.update(kwargs)\n return cls(data, **d)\n\n def _get_axis_number(self, axis):\n axis = self._AXIS_ALIASES.get(axis, axis)\n if is_integer(axis):\n if axis in self._AXIS_NAMES:\n return axis\n else:\n try:\n return self._AXIS_NUMBERS[axis]\n except KeyError:\n pass\n raise ValueError('No axis named {0} for object type {1}'\n .format(axis, type(self)))\n\n def _get_axis_name(self, axis):\n axis = self._AXIS_ALIASES.get(axis, axis)\n if isinstance(axis, string_types):\n if axis in self._AXIS_NUMBERS:\n return axis\n else:\n try:\n return self._AXIS_NAMES[axis]\n except KeyError:\n pass\n raise ValueError('No axis named {0} for object type {1}'\n .format(axis, type(self)))\n\n def _get_axis(self, axis):\n name = self._get_axis_name(axis)\n return getattr(self, name)\n\n def _get_block_manager_axis(self, axis):\n \"\"\"Map the axis to the block_manager axis.\"\"\"\n axis = self._get_axis_number(axis)\n if self._AXIS_REVERSED:\n m = self._AXIS_LEN - 1\n return m - axis\n return axis\n\n def _get_axis_resolvers(self, axis):\n # index or columns\n axis_index = getattr(self, axis)\n d = dict()\n prefix = axis[0]\n\n for i, name in enumerate(axis_index.names):\n if name is not None:\n key = level = name\n else:\n # prefix with 'i' or 'c' depending on the input axis\n # e.g., you must do ilevel_0 for the 0th level of an unnamed\n # multiiindex\n key = '{prefix}level_{i}'.format(prefix=prefix, i=i)\n level = i\n\n level_values = axis_index.get_level_values(level)\n s = level_values.to_series()\n s.index = axis_index\n d[key] = s\n\n # put the index/columns itself in the dict\n if isinstance(axis_index, MultiIndex):\n dindex = axis_index\n else:\n dindex = axis_index.to_series()\n\n d[axis] = dindex\n return d\n\n def _get_index_resolvers(self):\n d = {}\n for axis_name in self._AXIS_ORDERS:\n d.update(self._get_axis_resolvers(axis_name))\n return d\n\n @property\n def _info_axis(self):\n return getattr(self, self._info_axis_name)\n\n @property\n def _stat_axis(self):\n return getattr(self, self._stat_axis_name)\n\n @property\n def shape(self):\n \"\"\"Return a tuple of axis dimensions\"\"\"\n return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS)\n\n @property\n def axes(self):\n \"\"\"Return index label(s) of the internal NDFrame\"\"\"\n # we do it this way because if we have reversed axes, then\n # the block manager shows then reversed\n return [self._get_axis(a) for a in self._AXIS_ORDERS]\n\n @property\n def ndim(self):\n \"\"\"\n Return an int representing the number of axes / array dimensions.\n\n Return 1 if Series. Otherwise return 2 if DataFrame.\n\n See Also\n --------\n ndarray.ndim : Number of array dimensions.\n\n Examples\n --------\n >>> s = pd.Series({'a': 1, 'b': 2, 'c': 3})\n >>> s.ndim\n 1\n\n >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})\n >>> df.ndim\n 2\n \"\"\"\n return self._data.ndim\n\n @property\n def size(self):\n \"\"\"\n Return an int representing the number of elements in this object.\n\n Return the number of rows if Series. Otherwise return the number of\n rows times number of columns if DataFrame.\n\n See Also\n --------\n ndarray.size : Number of elements in the array.\n\n Examples\n --------\n >>> s = pd.Series({'a': 1, 'b': 2, 'c': 3})\n >>> s.size\n 3\n\n >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})\n >>> df.size\n 4\n \"\"\"\n return np.prod(self.shape)\n\n @property\n def _selected_obj(self):\n \"\"\" internal compat with SelectionMixin \"\"\"\n return self\n\n @property\n def _obj_with_exclusions(self):\n \"\"\" internal compat with SelectionMixin \"\"\"\n return self\n\n def _expand_axes(self, key):\n new_axes = []\n for k, ax in zip(key, self.axes):\n if k not in ax:\n if type(k) != ax.dtype.type:\n ax = ax.astype('O')\n new_axes.append(ax.insert(len(ax), k))\n else:\n new_axes.append(ax)\n\n return new_axes\n\n def set_axis(self, labels, axis=0, inplace=None):\n \"\"\"\n Assign desired index to given axis.\n\n Indexes for column or row labels can be changed by assigning\n a list-like or Index.\n\n .. versionchanged:: 0.21.0\n\n The signature is now `labels` and `axis`, consistent with\n the rest of pandas API. Previously, the `axis` and `labels`\n arguments were respectively the first and second positional\n arguments.\n\n Parameters\n ----------\n labels : list-like, Index\n The values for the new index.\n\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to update. The value 0 identifies the rows, and 1\n identifies the columns.\n\n inplace : boolean, default None\n Whether to return a new %(klass)s instance.\n\n .. warning::\n\n ``inplace=None`` currently falls back to to True, but in a\n future version, will default to False. Use inplace=True\n explicitly rather than relying on the default.\n\n Returns\n -------\n renamed : %(klass)s or None\n An object of same type as caller if inplace=False, None otherwise.\n\n See Also\n --------\n pandas.DataFrame.rename_axis : Alter the name of the index or columns.\n\n Examples\n --------\n **Series**\n\n >>> s = pd.Series([1, 2, 3])\n >>> s\n 0 1\n 1 2\n 2 3\n dtype: int64\n\n >>> s.set_axis(['a', 'b', 'c'], axis=0, inplace=False)\n a 1\n b 2\n c 3\n dtype: int64\n\n The original object is not modified.\n\n >>> s\n 0 1\n 1 2\n 2 3\n dtype: int64\n\n **DataFrame**\n\n >>> df = pd.DataFrame({\"A\": [1, 2, 3], \"B\": [4, 5, 6]})\n\n Change the row labels.\n\n >>> df.set_axis(['a', 'b', 'c'], axis='index', inplace=False)\n A B\n a 1 4\n b 2 5\n c 3 6\n\n Change the column labels.\n\n >>> df.set_axis(['I', 'II'], axis='columns', inplace=False)\n I II\n 0 1 4\n 1 2 5\n 2 3 6\n\n Now, update the labels inplace.\n\n >>> df.set_axis(['i', 'ii'], axis='columns', inplace=True)\n >>> df\n i ii\n 0 1 4\n 1 2 5\n 2 3 6\n \"\"\"\n if is_scalar(labels):\n warnings.warn(\n 'set_axis now takes \"labels\" as first argument, and '\n '\"axis\" as named parameter. The old form, with \"axis\" as '\n 'first parameter and \\\"labels\\\" as second, is still supported '\n 'but will be deprecated in a future version of pandas.',\n FutureWarning, stacklevel=2)\n labels, axis = axis, labels\n\n if inplace is None:\n warnings.warn(\n 'set_axis currently defaults to operating inplace.\\nThis '\n 'will change in a future version of pandas, use '\n 'inplace=True to avoid this warning.',\n FutureWarning, stacklevel=2)\n inplace = True\n if inplace:\n setattr(self, self._get_axis_name(axis), labels)\n else:\n obj = self.copy()\n obj.set_axis(labels, axis=axis, inplace=True)\n return obj\n\n def _set_axis(self, axis, labels):\n self._data.set_axis(axis, labels)\n self._clear_item_cache()\n\n _shared_docs['transpose'] = \"\"\"\n Permute the dimensions of the %(klass)s\n\n Parameters\n ----------\n args : %(args_transpose)s\n copy : boolean, default False\n Make a copy of the underlying data. Mixed-dtype data will\n always result in a copy\n\n Examples\n --------\n >>> p.transpose(2, 0, 1)\n >>> p.transpose(2, 0, 1, copy=True)\n\n Returns\n -------\n y : same as input\n \"\"\"\n\n @Appender(_shared_docs['transpose'] % _shared_doc_kwargs)\n def transpose(self, *args, **kwargs):\n\n # construct the args\n axes, kwargs = self._construct_axes_from_arguments(args, kwargs,\n require_all=True)\n axes_names = tuple(self._get_axis_name(axes[a])\n for a in self._AXIS_ORDERS)\n axes_numbers = tuple(self._get_axis_number(axes[a])\n for a in self._AXIS_ORDERS)\n\n # we must have unique axes\n if len(axes) != len(set(axes)):\n raise ValueError('Must specify %s unique axes' % self._AXIS_LEN)\n\n new_axes = self._construct_axes_dict_from(self, [self._get_axis(x)\n for x in axes_names])\n new_values = self.values.transpose(axes_numbers)\n if kwargs.pop('copy', None) or (len(args) and args[-1]):\n new_values = new_values.copy()\n\n nv.validate_transpose_for_generic(self, kwargs)\n return self._constructor(new_values, **new_axes).__finalize__(self)\n\n def swapaxes(self, axis1, axis2, copy=True):\n \"\"\"\n Interchange axes and swap values axes appropriately\n\n Returns\n -------\n y : same as input\n \"\"\"\n i = self._get_axis_number(axis1)\n j = self._get_axis_number(axis2)\n\n if i == j:\n if copy:\n return self.copy()\n return self\n\n mapping = {i: j, j: i}\n\n new_axes = (self._get_axis(mapping.get(k, k))\n for k in range(self._AXIS_LEN))\n new_values = self.values.swapaxes(i, j)\n if copy:\n new_values = new_values.copy()\n\n return self._constructor(new_values, *new_axes).__finalize__(self)\n\n def droplevel(self, level, axis=0):\n \"\"\"Return DataFrame with requested index / column level(s) removed.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n level : int, str, or list-like\n If a string is given, must be the name of a level\n If list-like, elements must be names or positional indexes\n of levels.\n\n axis : {0 or 'index', 1 or 'columns'}, default 0\n\n\n Returns\n -------\n DataFrame.droplevel()\n\n Examples\n --------\n >>> df = pd.DataFrame([\n ...: [1, 2, 3, 4],\n ...: [5, 6, 7, 8],\n ...: [9, 10, 11, 12]\n ...: ]).set_index([0, 1]).rename_axis(['a', 'b'])\n\n >>> df.columns = pd.MultiIndex.from_tuples([\n ...: ('c', 'e'), ('d', 'f')\n ...:], names=['level_1', 'level_2'])\n\n >>> df\n level_1 c d\n level_2 e f\n a b\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n\n >>> df.droplevel('a')\n level_1 c d\n level_2 e f\n b\n 2 3 4\n 6 7 8\n 10 11 12\n\n >>> df.droplevel('level2', axis=1)\n level_1 c d\n a b\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n\n \"\"\"\n labels = self._get_axis(axis)\n new_labels = labels.droplevel(level)\n result = self.set_axis(new_labels, axis=axis, inplace=False)\n return result\n\n def pop(self, item):\n \"\"\"\n Return item and drop from frame. Raise KeyError if not found.\n\n Parameters\n ----------\n item : str\n Column label to be popped\n\n Returns\n -------\n popped : Series\n\n Examples\n --------\n >>> df = pd.DataFrame([('falcon', 'bird', 389.0),\n ... ('parrot', 'bird', 24.0),\n ... ('lion', 'mammal', 80.5),\n ... ('monkey', 'mammal', np.nan)],\n ... columns=('name', 'class', 'max_speed'))\n >>> df\n name class max_speed\n 0 falcon bird 389.0\n 1 parrot bird 24.0\n 2 lion mammal 80.5\n 3 monkey mammal NaN\n\n >>> df.pop('class')\n 0 bird\n 1 bird\n 2 mammal\n 3 mammal\n Name: class, dtype: object\n\n >>> df\n name max_speed\n 0 falcon 389.0\n 1 parrot 24.0\n 2 lion 80.5\n 3 monkey NaN\n \"\"\"\n result = self[item]\n del self[item]\n try:\n result._reset_cacher()\n except AttributeError:\n pass\n\n return result\n\n def squeeze(self, axis=None):\n \"\"\"\n Squeeze 1 dimensional axis objects into scalars.\n\n Series or DataFrames with a single element are squeezed to a scalar.\n DataFrames with a single column or a single row are squeezed to a\n Series. Otherwise the object is unchanged.\n\n This method is most useful when you don't know if your\n object is a Series or DataFrame, but you do know it has just a single\n column. In that case you can safely call `squeeze` to ensure you have a\n Series.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns', None}, default None\n A specific axis to squeeze. By default, all length-1 axes are\n squeezed.\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n DataFrame, Series, or scalar\n The projection after squeezing `axis` or all the axes.\n\n See Also\n --------\n Series.iloc : Integer-location based indexing for selecting scalars\n DataFrame.iloc : Integer-location based indexing for selecting Series\n Series.to_frame : Inverse of DataFrame.squeeze for a\n single-column DataFrame.\n\n Examples\n --------\n >>> primes = pd.Series([2, 3, 5, 7])\n\n Slicing might produce a Series with a single value:\n\n >>> even_primes = primes[primes % 2 == 0]\n >>> even_primes\n 0 2\n dtype: int64\n\n >>> even_primes.squeeze()\n 2\n\n Squeezing objects with more than one value in every axis does nothing:\n\n >>> odd_primes = primes[primes % 2 == 1]\n >>> odd_primes\n 1 3\n 2 5\n 3 7\n dtype: int64\n\n >>> odd_primes.squeeze()\n 1 3\n 2 5\n 3 7\n dtype: int64\n\n Squeezing is even more effective when used with DataFrames.\n\n >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])\n >>> df\n a b\n 0 1 2\n 1 3 4\n\n Slicing a single column will produce a DataFrame with the columns\n having only one value:\n\n >>> df_a = df[['a']]\n >>> df_a\n a\n 0 1\n 1 3\n\n So the columns can be squeezed down, resulting in a Series:\n\n >>> df_a.squeeze('columns')\n 0 1\n 1 3\n Name: a, dtype: int64\n\n Slicing a single row from a single column will produce a single\n scalar DataFrame:\n\n >>> df_0a = df.loc[df.index < 1, ['a']]\n >>> df_0a\n a\n 0 1\n\n Squeezing the rows produces a single scalar Series:\n\n >>> df_0a.squeeze('rows')\n a 1\n Name: 0, dtype: int64\n\n Squeezing all axes wil project directly into a scalar:\n\n >>> df_0a.squeeze()\n 1\n \"\"\"\n axis = (self._AXIS_NAMES if axis is None else\n (self._get_axis_number(axis),))\n try:\n return self.iloc[\n tuple(0 if i in axis and len(a) == 1 else slice(None)\n for i, a in enumerate(self.axes))]\n except Exception:\n return self\n\n def swaplevel(self, i=-2, j=-1, axis=0):\n \"\"\"\n Swap levels i and j in a MultiIndex on a particular axis\n\n Parameters\n ----------\n i, j : int, string (can be mixed)\n Level of index to be swapped. Can pass level name as string.\n\n Returns\n -------\n swapped : same type as caller (new object)\n\n .. versionchanged:: 0.18.1\n\n The indexes ``i`` and ``j`` are now optional, and default to\n the two innermost levels of the index.\n\n \"\"\"\n axis = self._get_axis_number(axis)\n result = self.copy()\n labels = result._data.axes[axis]\n result._data.set_axis(axis, labels.swaplevel(i, j))\n return result\n\n # ----------------------------------------------------------------------\n # Rename\n\n # TODO: define separate funcs for DataFrame, Series and Panel so you can\n # get completion on keyword arguments.\n _shared_docs['rename'] = \"\"\"\n Alter axes input function or functions. Function / dict values must be\n unique (1-to-1). Labels not contained in a dict / Series will be left\n as-is. Extra labels listed don't throw an error. Alternatively, change\n ``Series.name`` with a scalar value (Series only).\n\n Parameters\n ----------\n %(optional_mapper)s\n %(axes)s : scalar, list-like, dict-like or function, optional\n Scalar or list-like will alter the ``Series.name`` attribute,\n and raise on DataFrame or Panel.\n dict-like or functions are transformations to apply to\n that axis' values\n %(optional_axis)s\n copy : boolean, default True\n Also copy underlying data\n inplace : boolean, default False\n Whether to return a new %(klass)s. If True then value of copy is\n ignored.\n level : int or level name, default None\n In case of a MultiIndex, only rename labels in the specified\n level.\n\n Returns\n -------\n renamed : %(klass)s (new object)\n\n See Also\n --------\n pandas.NDFrame.rename_axis\n\n Examples\n --------\n\n >>> s = pd.Series([1, 2, 3])\n >>> s\n 0 1\n 1 2\n 2 3\n dtype: int64\n >>> s.rename(\"my_name\") # scalar, changes Series.name\n 0 1\n 1 2\n 2 3\n Name: my_name, dtype: int64\n >>> s.rename(lambda x: x ** 2) # function, changes labels\n 0 1\n 1 2\n 4 3\n dtype: int64\n >>> s.rename({1: 3, 2: 5}) # mapping, changes labels\n 0 1\n 3 2\n 5 3\n dtype: int64\n\n Since ``DataFrame`` doesn't have a ``.name`` attribute,\n only mapping-type arguments are allowed.\n\n >>> df = pd.DataFrame({\"A\": [1, 2, 3], \"B\": [4, 5, 6]})\n >>> df.rename(2)\n Traceback (most recent call last):\n ...\n TypeError: 'int' object is not callable\n\n ``DataFrame.rename`` supports two calling conventions\n\n * ``(index=index_mapper, columns=columns_mapper, ...)``\n * ``(mapper, axis={'index', 'columns'}, ...)``\n\n We *highly* recommend using keyword arguments to clarify your\n intent.\n\n >>> df.rename(index=str, columns={\"A\": \"a\", \"B\": \"c\"})\n a c\n 0 1 4\n 1 2 5\n 2 3 6\n\n >>> df.rename(index=str, columns={\"A\": \"a\", \"C\": \"c\"})\n a B\n 0 1 4\n 1 2 5\n 2 3 6\n\n Using axis-style parameters\n\n >>> df.rename(str.lower, axis='columns')\n a b\n 0 1 4\n 1 2 5\n 2 3 6\n\n >>> df.rename({1: 2, 2: 4}, axis='index')\n A B\n 0 1 4\n 2 2 5\n 4 3 6\n\n See the :ref:`user guide <basics.rename>` for more.\n \"\"\"\n\n @Appender(_shared_docs['rename'] % dict(axes='axes keywords for this'\n ' object', klass='NDFrame',\n optional_mapper='',\n optional_axis=''))\n def rename(self, *args, **kwargs):\n axes, kwargs = self._construct_axes_from_arguments(args, kwargs)\n copy = kwargs.pop('copy', True)\n inplace = kwargs.pop('inplace', False)\n level = kwargs.pop('level', None)\n axis = kwargs.pop('axis', None)\n if axis is not None:\n # Validate the axis\n self._get_axis_number(axis)\n\n if kwargs:\n raise TypeError('rename() got an unexpected keyword '\n 'argument \"{0}\"'.format(list(kwargs.keys())[0]))\n\n if com.count_not_none(*axes.values()) == 0:\n raise TypeError('must pass an index to rename')\n\n # renamer function if passed a dict\n def _get_rename_function(mapper):\n if isinstance(mapper, (dict, ABCSeries)):\n\n def f(x):\n if x in mapper:\n return mapper[x]\n else:\n return x\n else:\n f = mapper\n\n return f\n\n self._consolidate_inplace()\n result = self if inplace else self.copy(deep=copy)\n\n # start in the axis order to eliminate too many copies\n for axis in lrange(self._AXIS_LEN):\n v = axes.get(self._AXIS_NAMES[axis])\n if v is None:\n continue\n f = _get_rename_function(v)\n\n baxis = self._get_block_manager_axis(axis)\n if level is not None:\n level = self.axes[axis]._get_level_number(level)\n result._data = result._data.rename_axis(f, axis=baxis, copy=copy,\n level=level)\n result._clear_item_cache()\n\n if inplace:\n self._update_inplace(result._data)\n else:\n return result.__finalize__(self)\n\n rename.__doc__ = _shared_docs['rename']\n\n def rename_axis(self, mapper, axis=0, copy=True, inplace=False):\n \"\"\"\n Alter the name of the index or columns.\n\n Parameters\n ----------\n mapper : scalar, list-like, optional\n Value to set as the axis name attribute.\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The index or the name of the axis.\n copy : boolean, default True\n Also copy underlying data.\n inplace : boolean, default False\n Modifies the object directly, instead of creating a new Series\n or DataFrame.\n\n Returns\n -------\n renamed : Series, DataFrame, or None\n The same type as the caller or None if `inplace` is True.\n\n Notes\n -----\n Prior to version 0.21.0, ``rename_axis`` could also be used to change\n the axis *labels* by passing a mapping or scalar. This behavior is\n deprecated and will be removed in a future version. Use ``rename``\n instead.\n\n See Also\n --------\n pandas.Series.rename : Alter Series index labels or name\n pandas.DataFrame.rename : Alter DataFrame index labels or name\n pandas.Index.rename : Set new names on index\n\n Examples\n --------\n **Series**\n\n >>> s = pd.Series([1, 2, 3])\n >>> s.rename_axis(\"foo\")\n foo\n 0 1\n 1 2\n 2 3\n dtype: int64\n\n **DataFrame**\n\n >>> df = pd.DataFrame({\"A\": [1, 2, 3], \"B\": [4, 5, 6]})\n >>> df.rename_axis(\"foo\")\n A B\n foo\n 0 1 4\n 1 2 5\n 2 3 6\n\n >>> df.rename_axis(\"bar\", axis=\"columns\")\n bar A B\n 0 1 4\n 1 2 5\n 2 3 6\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n non_mapper = is_scalar(mapper) or (is_list_like(mapper) and not\n is_dict_like(mapper))\n if non_mapper:\n return self._set_axis_name(mapper, axis=axis, inplace=inplace)\n else:\n msg = (\"Using 'rename_axis' to alter labels is deprecated. \"\n \"Use '.rename' instead\")\n warnings.warn(msg, FutureWarning, stacklevel=2)\n axis = self._get_axis_name(axis)\n d = {'copy': copy, 'inplace': inplace}\n d[axis] = mapper\n return self.rename(**d)\n\n def _set_axis_name(self, name, axis=0, inplace=False):\n \"\"\"\n Alter the name or names of the axis.\n\n Parameters\n ----------\n name : str or list of str\n Name for the Index, or list of names for the MultiIndex\n axis : int or str\n 0 or 'index' for the index; 1 or 'columns' for the columns\n inplace : bool\n whether to modify `self` directly or return a copy\n\n .. versionadded:: 0.21.0\n\n Returns\n -------\n renamed : same type as caller or None if inplace=True\n\n See Also\n --------\n pandas.DataFrame.rename\n pandas.Series.rename\n pandas.Index.rename\n\n Examples\n --------\n >>> df._set_axis_name(\"foo\")\n A\n foo\n 0 1\n 1 2\n 2 3\n >>> df.index = pd.MultiIndex.from_product([['A'], ['a', 'b', 'c']])\n >>> df._set_axis_name([\"bar\", \"baz\"])\n A\n bar baz\n A a 1\n b 2\n c 3\n \"\"\"\n axis = self._get_axis_number(axis)\n idx = self._get_axis(axis).set_names(name)\n\n inplace = validate_bool_kwarg(inplace, 'inplace')\n renamed = self if inplace else self.copy()\n renamed.set_axis(idx, axis=axis, inplace=True)\n if not inplace:\n return renamed\n\n # ----------------------------------------------------------------------\n # Comparisons\n\n def _indexed_same(self, other):\n return all(self._get_axis(a).equals(other._get_axis(a))\n for a in self._AXIS_ORDERS)\n\n def __neg__(self):\n values = com.values_from_object(self)\n if is_bool_dtype(values):\n arr = operator.inv(values)\n elif (is_numeric_dtype(values) or is_timedelta64_dtype(values)\n or is_object_dtype(values)):\n arr = operator.neg(values)\n else:\n raise TypeError(\"Unary negative expects numeric dtype, not {}\"\n .format(values.dtype))\n return self.__array_wrap__(arr)\n\n def __pos__(self):\n values = com.values_from_object(self)\n if (is_bool_dtype(values) or is_period_arraylike(values)):\n arr = values\n elif (is_numeric_dtype(values) or is_timedelta64_dtype(values)\n or is_object_dtype(values)):\n arr = operator.pos(values)\n else:\n raise TypeError(\"Unary plus expects numeric dtype, not {}\"\n .format(values.dtype))\n return self.__array_wrap__(arr)\n\n def __invert__(self):\n try:\n arr = operator.inv(com.values_from_object(self))\n return self.__array_wrap__(arr)\n except Exception:\n\n # inv fails with 0 len\n if not np.prod(self.shape):\n return self\n\n raise\n\n def equals(self, other):\n \"\"\"\n Determines if two NDFrame objects contain the same elements. NaNs in\n the same location are considered equal.\n \"\"\"\n if not isinstance(other, self._constructor):\n return False\n return self._data.equals(other._data)\n\n # -------------------------------------------------------------------------\n # Label or Level Combination Helpers\n #\n # A collection of helper methods for DataFrame/Series operations that\n # accept a combination of column/index labels and levels. All such\n # operations should utilize/extend these methods when possible so that we\n # have consistent precedence and validation logic throughout the library.\n\n def _is_level_reference(self, key, axis=0):\n \"\"\"\n Test whether a key is a level reference for a given axis.\n\n To be considered a level reference, `key` must be a string that:\n - (axis=0): Matches the name of an index level and does NOT match\n a column label.\n - (axis=1): Matches the name of a column level and does NOT match\n an index label.\n\n Parameters\n ----------\n key: str\n Potential level name for the given axis\n axis: int, default 0\n Axis that levels are associated with (0 for index, 1 for columns)\n\n Returns\n -------\n is_level: bool\n \"\"\"\n axis = self._get_axis_number(axis)\n\n if self.ndim > 2:\n raise NotImplementedError(\n \"_is_level_reference is not implemented for {type}\"\n .format(type=type(self)))\n\n return (key is not None and\n is_hashable(key) and\n key in self.axes[axis].names and\n not self._is_label_reference(key, axis=axis))\n\n def _is_label_reference(self, key, axis=0):\n \"\"\"\n Test whether a key is a label reference for a given axis.\n\n To be considered a label reference, `key` must be a string that:\n - (axis=0): Matches a column label\n - (axis=1): Matches an index label\n\n Parameters\n ----------\n key: str\n Potential label name\n axis: int, default 0\n Axis perpendicular to the axis that labels are associated with\n (0 means search for column labels, 1 means search for index labels)\n\n Returns\n -------\n is_label: bool\n \"\"\"\n axis = self._get_axis_number(axis)\n other_axes = [ax for ax in range(self._AXIS_LEN) if ax != axis]\n\n if self.ndim > 2:\n raise NotImplementedError(\n \"_is_label_reference is not implemented for {type}\"\n .format(type=type(self)))\n\n return (key is not None and\n is_hashable(key) and\n any(key in self.axes[ax] for ax in other_axes))\n\n def _is_label_or_level_reference(self, key, axis=0):\n \"\"\"\n Test whether a key is a label or level reference for a given axis.\n\n To be considered either a label or a level reference, `key` must be a\n string that:\n - (axis=0): Matches a column label or an index level\n - (axis=1): Matches an index label or a column level\n\n Parameters\n ----------\n key: str\n Potential label or level name\n axis: int, default 0\n Axis that levels are associated with (0 for index, 1 for columns)\n\n Returns\n -------\n is_label_or_level: bool\n \"\"\"\n\n if self.ndim > 2:\n raise NotImplementedError(\n \"_is_label_or_level_reference is not implemented for {type}\"\n .format(type=type(self)))\n\n return (self._is_level_reference(key, axis=axis) or\n self._is_label_reference(key, axis=axis))\n\n def _check_label_or_level_ambiguity(self, key, axis=0, stacklevel=1):\n \"\"\"\n Check whether `key` matches both a level of the input `axis` and a\n label of the other axis and raise a ``FutureWarning`` if this is the\n case.\n\n Note: This method will be altered to raise an ambiguity exception in\n a future version.\n\n Parameters\n ----------\n key: str or object\n label or level name\n axis: int, default 0\n Axis that levels are associated with (0 for index, 1 for columns)\n stacklevel: int, default 1\n Stack level used when a FutureWarning is raised (see below).\n\n Returns\n -------\n ambiguous: bool\n\n Raises\n ------\n FutureWarning\n if `key` is ambiguous. This will become an ambiguity error in a\n future version\n \"\"\"\n\n axis = self._get_axis_number(axis)\n other_axes = [ax for ax in range(self._AXIS_LEN) if ax != axis]\n\n if self.ndim > 2:\n raise NotImplementedError(\n \"_check_label_or_level_ambiguity is not implemented for {type}\"\n .format(type=type(self)))\n\n if (key is not None and\n is_hashable(key) and\n key in self.axes[axis].names and\n any(key in self.axes[ax] for ax in other_axes)):\n\n # Build an informative and grammatical warning\n level_article, level_type = (('an', 'index')\n if axis == 0 else\n ('a', 'column'))\n\n label_article, label_type = (('a', 'column')\n if axis == 0 else\n ('an', 'index'))\n\n msg = (\"'{key}' is both {level_article} {level_type} level and \"\n \"{label_article} {label_type} label.\\n\"\n \"Defaulting to {label_type}, but this will raise an \"\n \"ambiguity error in a future version\"\n ).format(key=key,\n level_article=level_article,\n level_type=level_type,\n label_article=label_article,\n label_type=label_type)\n\n warnings.warn(msg, FutureWarning, stacklevel=stacklevel + 1)\n return True\n else:\n return False\n\n def _get_label_or_level_values(self, key, axis=0, stacklevel=1):\n \"\"\"\n Return a 1-D array of values associated with `key`, a label or level\n from the given `axis`.\n\n Retrieval logic:\n - (axis=0): Return column values if `key` matches a column label.\n Otherwise return index level values if `key` matches an index\n level.\n - (axis=1): Return row values if `key` matches an index label.\n Otherwise return column level values if 'key' matches a column\n level\n\n Parameters\n ----------\n key: str\n Label or level name.\n axis: int, default 0\n Axis that levels are associated with (0 for index, 1 for columns)\n stacklevel: int, default 1\n Stack level used when a FutureWarning is raised (see below).\n\n Returns\n -------\n values: np.ndarray\n\n Raises\n ------\n KeyError\n if `key` matches neither a label nor a level\n ValueError\n if `key` matches multiple labels\n FutureWarning\n if `key` is ambiguous. This will become an ambiguity error in a\n future version\n \"\"\"\n\n axis = self._get_axis_number(axis)\n other_axes = [ax for ax in range(self._AXIS_LEN) if ax != axis]\n\n if self.ndim > 2:\n raise NotImplementedError(\n \"_get_label_or_level_values is not implemented for {type}\"\n .format(type=type(self)))\n\n if self._is_label_reference(key, axis=axis):\n self._check_label_or_level_ambiguity(key, axis=axis,\n stacklevel=stacklevel + 1)\n values = self.xs(key, axis=other_axes[0])._values\n elif self._is_level_reference(key, axis=axis):\n values = self.axes[axis].get_level_values(key)._values\n else:\n raise KeyError(key)\n\n # Check for duplicates\n if values.ndim > 1:\n\n if other_axes and isinstance(\n self._get_axis(other_axes[0]), MultiIndex):\n multi_message = ('\\n'\n 'For a multi-index, the label must be a '\n 'tuple with elements corresponding to '\n 'each level.')\n else:\n multi_message = ''\n\n label_axis_name = 'column' if axis == 0 else 'index'\n raise ValueError((\"The {label_axis_name} label '{key}' \"\n \"is not unique.{multi_message}\")\n .format(key=key,\n label_axis_name=label_axis_name,\n multi_message=multi_message))\n\n return values\n\n def _drop_labels_or_levels(self, keys, axis=0):\n \"\"\"\n Drop labels and/or levels for the given `axis`.\n\n For each key in `keys`:\n - (axis=0): If key matches a column label then drop the column.\n Otherwise if key matches an index level then drop the level.\n - (axis=1): If key matches an index label then drop the row.\n Otherwise if key matches a column level then drop the level.\n\n Parameters\n ----------\n keys: str or list of str\n labels or levels to drop\n axis: int, default 0\n Axis that levels are associated with (0 for index, 1 for columns)\n\n Returns\n -------\n dropped: DataFrame\n\n Raises\n ------\n ValueError\n if any `keys` match neither a label nor a level\n \"\"\"\n\n axis = self._get_axis_number(axis)\n\n if self.ndim > 2:\n raise NotImplementedError(\n \"_drop_labels_or_levels is not implemented for {type}\"\n .format(type=type(self)))\n\n # Validate keys\n keys = com.maybe_make_list(keys)\n invalid_keys = [k for k in keys if not\n self._is_label_or_level_reference(k, axis=axis)]\n\n if invalid_keys:\n raise ValueError((\"The following keys are not valid labels or \"\n \"levels for axis {axis}: {invalid_keys}\")\n .format(axis=axis,\n invalid_keys=invalid_keys))\n\n # Compute levels and labels to drop\n levels_to_drop = [k for k in keys\n if self._is_level_reference(k, axis=axis)]\n\n labels_to_drop = [k for k in keys\n if not self._is_level_reference(k, axis=axis)]\n\n # Perform copy upfront and then use inplace operations below.\n # This ensures that we always perform exactly one copy.\n # ``copy`` and/or ``inplace`` options could be added in the future.\n dropped = self.copy()\n\n if axis == 0:\n # Handle dropping index levels\n if levels_to_drop:\n dropped.reset_index(levels_to_drop, drop=True, inplace=True)\n\n # Handle dropping columns labels\n if labels_to_drop:\n dropped.drop(labels_to_drop, axis=1, inplace=True)\n else:\n # Handle dropping column levels\n if levels_to_drop:\n if isinstance(dropped.columns, MultiIndex):\n # Drop the specified levels from the MultiIndex\n dropped.columns = dropped.columns.droplevel(levels_to_drop)\n else:\n # Drop the last level of Index by replacing with\n # a RangeIndex\n dropped.columns = RangeIndex(dropped.columns.size)\n\n # Handle dropping index labels\n if labels_to_drop:\n dropped.drop(labels_to_drop, axis=0, inplace=True)\n\n return dropped\n\n # ----------------------------------------------------------------------\n # Iteration\n\n def __hash__(self):\n raise TypeError('{0!r} objects are mutable, thus they cannot be'\n ' hashed'.format(self.__class__.__name__))\n\n def __iter__(self):\n \"\"\"Iterate over infor axis\"\"\"\n return iter(self._info_axis)\n\n # can we get a better explanation of this?\n def keys(self):\n \"\"\"Get the 'info axis' (see Indexing for more)\n\n This is index for Series, columns for DataFrame and major_axis for\n Panel.\n \"\"\"\n return self._info_axis\n\n def iteritems(self):\n \"\"\"Iterate over (label, values) on info axis\n\n This is index for Series, columns for DataFrame, major_axis for Panel,\n and so on.\n \"\"\"\n for h in self._info_axis:\n yield h, self[h]\n\n def __len__(self):\n \"\"\"Returns length of info axis\"\"\"\n return len(self._info_axis)\n\n def __contains__(self, key):\n \"\"\"True if the key is in the info axis\"\"\"\n return key in self._info_axis\n\n @property\n def empty(self):\n \"\"\"\n Indicator whether DataFrame is empty.\n\n True if DataFrame is entirely empty (no items), meaning any of the\n axes are of length 0.\n\n Returns\n -------\n bool\n If DataFrame is empty, return True, if not return False.\n\n Notes\n -----\n If DataFrame contains only NaNs, it is still not considered empty. See\n the example below.\n\n Examples\n --------\n An example of an actual empty DataFrame. Notice the index is empty:\n\n >>> df_empty = pd.DataFrame({'A' : []})\n >>> df_empty\n Empty DataFrame\n Columns: [A]\n Index: []\n >>> df_empty.empty\n True\n\n If we only have NaNs in our DataFrame, it is not considered empty! We\n will need to drop the NaNs to make the DataFrame empty:\n\n >>> df = pd.DataFrame({'A' : [np.nan]})\n >>> df\n A\n 0 NaN\n >>> df.empty\n False\n >>> df.dropna().empty\n True\n\n See also\n --------\n pandas.Series.dropna\n pandas.DataFrame.dropna\n \"\"\"\n return any(len(self._get_axis(a)) == 0 for a in self._AXIS_ORDERS)\n\n def __nonzero__(self):\n raise ValueError(\"The truth value of a {0} is ambiguous. \"\n \"Use a.empty, a.bool(), a.item(), a.any() or a.all().\"\n .format(self.__class__.__name__))\n\n __bool__ = __nonzero__\n\n def bool(self):\n \"\"\"Return the bool of a single element PandasObject.\n\n This must be a boolean scalar value, either True or False. Raise a\n ValueError if the PandasObject does not have exactly 1 element, or that\n element is not boolean\n \"\"\"\n v = self.squeeze()\n if isinstance(v, (bool, np.bool_)):\n return bool(v)\n elif is_scalar(v):\n raise ValueError(\"bool cannot act on a non-boolean single element \"\n \"{0}\".format(self.__class__.__name__))\n\n self.__nonzero__()\n\n def __abs__(self):\n return self.abs()\n\n def __round__(self, decimals=0):\n return self.round(decimals)\n\n # ----------------------------------------------------------------------\n # Array Interface\n\n def __array__(self, dtype=None):\n return com.values_from_object(self)\n\n def __array_wrap__(self, result, context=None):\n d = self._construct_axes_dict(self._AXIS_ORDERS, copy=False)\n return self._constructor(result, **d).__finalize__(self)\n\n # ideally we would define this to avoid the getattr checks, but\n # is slower\n # @property\n # def __array_interface__(self):\n # \"\"\" provide numpy array interface method \"\"\"\n # values = self.values\n # return dict(typestr=values.dtype.str,shape=values.shape,data=values)\n\n def to_dense(self):\n \"\"\"Return dense representation of NDFrame (as opposed to sparse)\"\"\"\n # compat\n return self\n\n # ----------------------------------------------------------------------\n # Picklability\n\n def __getstate__(self):\n meta = {k: getattr(self, k, None) for k in self._metadata}\n return dict(_data=self._data, _typ=self._typ, _metadata=self._metadata,\n **meta)\n\n def __setstate__(self, state):\n\n if isinstance(state, BlockManager):\n self._data = state\n elif isinstance(state, dict):\n typ = state.get('_typ')\n if typ is not None:\n\n # set in the order of internal names\n # to avoid definitional recursion\n # e.g. say fill_value needing _data to be\n # defined\n meta = set(self._internal_names + self._metadata)\n for k in list(meta):\n if k in state:\n v = state[k]\n object.__setattr__(self, k, v)\n\n for k, v in state.items():\n if k not in meta:\n object.__setattr__(self, k, v)\n\n else:\n self._unpickle_series_compat(state)\n elif isinstance(state[0], dict):\n if len(state) == 5:\n self._unpickle_sparse_frame_compat(state)\n else:\n self._unpickle_frame_compat(state)\n elif len(state) == 4:\n self._unpickle_panel_compat(state)\n elif len(state) == 2:\n self._unpickle_series_compat(state)\n else: # pragma: no cover\n # old pickling format, for compatibility\n self._unpickle_matrix_compat(state)\n\n self._item_cache = {}\n\n # ----------------------------------------------------------------------\n # IO\n\n def _repr_latex_(self):\n \"\"\"\n Returns a LaTeX representation for a particular object.\n Mainly for use with nbconvert (jupyter notebook conversion to pdf).\n \"\"\"\n if config.get_option('display.latex.repr'):\n return self.to_latex()\n else:\n return None\n\n # ----------------------------------------------------------------------\n # I/O Methods\n\n _shared_docs['to_excel'] = \"\"\"\n Write %(klass)s to an excel sheet.\n\n To write a single %(klass)s to an excel .xlsx file it is only necessary to\n specify a target file name. To write to multiple sheets it is necessary to\n create an `ExcelWriter` object with a target file name, and specify a sheet\n in the file to write to. Multiple sheets may be written to by\n specifying unique `sheet_name`. With all data written to the file it is\n necessary to save the changes. Note that creating an ExcelWriter object\n with a file name that already exists will result in the contents of the\n existing file being erased.\n\n Parameters\n ----------\n excel_writer : string or ExcelWriter object\n File path or existing ExcelWriter.\n sheet_name : string, default 'Sheet1'\n Name of sheet which will contain DataFrame.\n na_rep : string, default ''\n Missing data representation.\n float_format : string, optional\n Format string for floating point numbers. For example\n ``float_format=\"%%.2f\"`` will format 0.1234 to 0.12.\n columns : sequence or list of string, optional\n Columns to write.\n header : boolean or list of string, default True\n Write out the column names. If a list of strings is given it is\n assumed to be aliases for the column names.\n index : boolean, default True\n Write row names (index).\n index_label : string or sequence, optional\n Column label for index column(s) if desired. If not specified, and\n `header` and `index` are True, then the index names are used. A\n sequence should be given if the DataFrame uses MultiIndex.\n startrow : integer, default 0\n Upper left cell row to dump data frame.\n startcol : integer, default 0\n Upper left cell column to dump data frame.\n engine : string, optional\n Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this\n via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and\n ``io.excel.xlsm.writer``.\n merge_cells : boolean, default True\n Write MultiIndex and Hierarchical Rows as merged cells.\n encoding : string, optional\n Encoding of the resulting excel file. Only necessary for xlwt,\n other writers support unicode natively.\n inf_rep : string, default 'inf'\n Representation for infinity (there is no native representation for\n infinity in Excel).\n verbose : boolean, default True\n Display more information in the error logs.\n freeze_panes : tuple of integer (length 2), optional\n Specifies the one-based bottommost row and rightmost column that\n is to be frozen.\n\n .. versionadded:: 0.20.0.\n\n Notes\n -----\n For compatibility with :meth:`~DataFrame.to_csv`,\n to_excel serializes lists and dicts to strings before writing.\n\n Once a workbook has been saved it is not possible write further data\n without rewriting the whole workbook.\n\n See Also\n --------\n pandas.read_excel\n pandas.ExcelWriter\n\n Examples\n --------\n\n Create, write to and save a workbook:\n\n >>> df1 = pd.DataFrame([['a', 'b'], ['c', 'd']],\n ... index=['row 1', 'row 2'],\n ... columns=['col 1', 'col 2'])\n >>> df1.to_excel(\"output.xlsx\")\n\n To specify the sheet name:\n\n >>> df1.to_excel(\"output.xlsx\", sheet_name='Sheet_name_1')\n\n If you wish to write to more than one sheet in the workbook, it is\n necessary to specify an ExcelWriter object:\n\n >>> writer = pd.ExcelWriter('output2.xlsx', engine='xlsxwriter')\n >>> df1.to_excel(writer, sheet_name='Sheet1')\n >>> df2 = df1.copy()\n >>> df2.to_excel(writer, sheet_name='Sheet2')\n >>> writer.save()\n \"\"\"\n\n def to_json(self, path_or_buf=None, orient=None, date_format=None,\n double_precision=10, force_ascii=True, date_unit='ms',\n default_handler=None, lines=False, compression='infer',\n index=True):\n \"\"\"\n Convert the object to a JSON string.\n\n Note NaN's and None will be converted to null and datetime objects\n will be converted to UNIX timestamps.\n\n Parameters\n ----------\n path_or_buf : string or file handle, optional\n File path or object. If not specified, the result is returned as\n a string.\n orient : string\n Indication of expected JSON string format.\n\n * Series\n\n - default is 'index'\n - allowed values are: {'split','records','index'}\n\n * DataFrame\n\n - default is 'columns'\n - allowed values are:\n {'split','records','index','columns','values'}\n\n * The format of the JSON string\n\n - 'split' : dict like {'index' -> [index],\n 'columns' -> [columns], 'data' -> [values]}\n - 'records' : list like\n [{column -> value}, ... , {column -> value}]\n - 'index' : dict like {index -> {column -> value}}\n - 'columns' : dict like {column -> {index -> value}}\n - 'values' : just the values array\n - 'table' : dict like {'schema': {schema}, 'data': {data}}\n describing the data, and the data component is\n like ``orient='records'``.\n\n .. versionchanged:: 0.20.0\n\n date_format : {None, 'epoch', 'iso'}\n Type of date conversion. 'epoch' = epoch milliseconds,\n 'iso' = ISO8601. The default depends on the `orient`. For\n ``orient='table'``, the default is 'iso'. For all other orients,\n the default is 'epoch'.\n double_precision : int, default 10\n The number of decimal places to use when encoding\n floating point values.\n force_ascii : boolean, default True\n Force encoded string to be ASCII.\n date_unit : string, default 'ms' (milliseconds)\n The time unit to encode to, governs timestamp and ISO8601\n precision. One of 's', 'ms', 'us', 'ns' for second, millisecond,\n microsecond, and nanosecond respectively.\n default_handler : callable, default None\n Handler to call if object cannot otherwise be converted to a\n suitable format for JSON. Should receive a single argument which is\n the object to convert and return a serialisable object.\n lines : boolean, default False\n If 'orient' is 'records' write out line delimited json format. Will\n throw ValueError if incorrect 'orient' since others are not list\n like.\n\n .. versionadded:: 0.19.0\n compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None},\n default 'infer'\n A string representing the compression to use in the output file,\n only used when the first argument is a filename.\n\n .. versionadded:: 0.21.0\n .. versionchanged:: 0.24.0\n 'infer' option added and set to default\n index : boolean, default True\n Whether to include the index values in the JSON string. Not\n including the index (``index=False``) is only supported when\n orient is 'split' or 'table'.\n\n .. versionadded:: 0.23.0\n\n See Also\n --------\n pandas.read_json\n\n Examples\n --------\n\n >>> df = pd.DataFrame([['a', 'b'], ['c', 'd']],\n ... index=['row 1', 'row 2'],\n ... columns=['col 1', 'col 2'])\n >>> df.to_json(orient='split')\n '{\"columns\":[\"col 1\",\"col 2\"],\n \"index\":[\"row 1\",\"row 2\"],\n \"data\":[[\"a\",\"b\"],[\"c\",\"d\"]]}'\n\n Encoding/decoding a Dataframe using ``'records'`` formatted JSON.\n Note that index labels are not preserved with this encoding.\n\n >>> df.to_json(orient='records')\n '[{\"col 1\":\"a\",\"col 2\":\"b\"},{\"col 1\":\"c\",\"col 2\":\"d\"}]'\n\n Encoding/decoding a Dataframe using ``'index'`` formatted JSON:\n\n >>> df.to_json(orient='index')\n '{\"row 1\":{\"col 1\":\"a\",\"col 2\":\"b\"},\"row 2\":{\"col 1\":\"c\",\"col 2\":\"d\"}}'\n\n Encoding/decoding a Dataframe using ``'columns'`` formatted JSON:\n\n >>> df.to_json(orient='columns')\n '{\"col 1\":{\"row 1\":\"a\",\"row 2\":\"c\"},\"col 2\":{\"row 1\":\"b\",\"row 2\":\"d\"}}'\n\n Encoding/decoding a Dataframe using ``'values'`` formatted JSON:\n\n >>> df.to_json(orient='values')\n '[[\"a\",\"b\"],[\"c\",\"d\"]]'\n\n Encoding with Table Schema\n\n >>> df.to_json(orient='table')\n '{\"schema\": {\"fields\": [{\"name\": \"index\", \"type\": \"string\"},\n {\"name\": \"col 1\", \"type\": \"string\"},\n {\"name\": \"col 2\", \"type\": \"string\"}],\n \"primaryKey\": \"index\",\n \"pandas_version\": \"0.20.0\"},\n \"data\": [{\"index\": \"row 1\", \"col 1\": \"a\", \"col 2\": \"b\"},\n {\"index\": \"row 2\", \"col 1\": \"c\", \"col 2\": \"d\"}]}'\n \"\"\"\n\n from pandas.io import json\n if date_format is None and orient == 'table':\n date_format = 'iso'\n elif date_format is None:\n date_format = 'epoch'\n return json.to_json(path_or_buf=path_or_buf, obj=self, orient=orient,\n date_format=date_format,\n double_precision=double_precision,\n force_ascii=force_ascii, date_unit=date_unit,\n default_handler=default_handler,\n lines=lines, compression=compression,\n index=index)\n\n def to_hdf(self, path_or_buf, key, **kwargs):\n \"\"\"\n Write the contained data to an HDF5 file using HDFStore.\n\n Hierarchical Data Format (HDF) is self-describing, allowing an\n application to interpret the structure and contents of a file with\n no outside information. One HDF file can hold a mix of related objects\n which can be accessed as a group or as individual objects.\n\n In order to add another DataFrame or Series to an existing HDF file\n please use append mode and a different a key.\n\n For more information see the :ref:`user guide <io.hdf5>`.\n\n Parameters\n ----------\n path_or_buf : str or pandas.HDFStore\n File path or HDFStore object.\n key : str\n Identifier for the group in the store.\n mode : {'a', 'w', 'r+'}, default 'a'\n Mode to open file:\n\n - 'w': write, a new file is created (an existing file with\n the same name would be deleted).\n - 'a': append, an existing file is opened for reading and\n writing, and if the file does not exist it is created.\n - 'r+': similar to 'a', but the file must already exist.\n format : {'fixed', 'table'}, default 'fixed'\n Possible values:\n\n - 'fixed': Fixed format. Fast writing/reading. Not-appendable,\n nor searchable.\n - 'table': Table format. Write as a PyTables Table structure\n which may perform worse but allow more flexible operations\n like searching / selecting subsets of the data.\n append : bool, default False\n For Table formats, append the input data to the existing.\n data_columns : list of columns or True, optional\n List of columns to create as indexed data columns for on-disk\n queries, or True to use all columns. By default only the axes\n of the object are indexed. See :ref:`io.hdf5-query-data-columns`.\n Applicable only to format='table'.\n complevel : {0-9}, optional\n Specifies a compression level for data.\n A value of 0 disables compression.\n complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib'\n Specifies the compression library to be used.\n As of v0.20.2 these additional compressors for Blosc are supported\n (default if no compressor specified: 'blosc:blosclz'):\n {'blosc:blosclz', 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy',\n 'blosc:zlib', 'blosc:zstd'}.\n Specifying a compression library which is not available issues\n a ValueError.\n fletcher32 : bool, default False\n If applying compression use the fletcher32 checksum.\n dropna : bool, default False\n If true, ALL nan rows will not be written to store.\n errors : str, default 'strict'\n Specifies how encoding and decoding errors are to be handled.\n See the errors argument for :func:`open` for a full list\n of options.\n\n See Also\n --------\n DataFrame.read_hdf : Read from HDF file.\n DataFrame.to_parquet : Write a DataFrame to the binary parquet format.\n DataFrame.to_sql : Write to a sql table.\n DataFrame.to_feather : Write out feather-format for DataFrames.\n DataFrame.to_csv : Write out to a csv file.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},\n ... index=['a', 'b', 'c'])\n >>> df.to_hdf('data.h5', key='df', mode='w')\n\n We can add another object to the same file:\n\n >>> s = pd.Series([1, 2, 3, 4])\n >>> s.to_hdf('data.h5', key='s')\n\n Reading from HDF file:\n\n >>> pd.read_hdf('data.h5', 'df')\n A B\n a 1 4\n b 2 5\n c 3 6\n >>> pd.read_hdf('data.h5', 's')\n 0 1\n 1 2\n 2 3\n 3 4\n dtype: int64\n\n Deleting file with data:\n\n >>> import os\n >>> os.remove('data.h5')\n\n \"\"\"\n from pandas.io import pytables\n return pytables.to_hdf(path_or_buf, key, self, **kwargs)\n\n def to_msgpack(self, path_or_buf=None, encoding='utf-8', **kwargs):\n \"\"\"\n msgpack (serialize) object to input file path\n\n THIS IS AN EXPERIMENTAL LIBRARY and the storage format\n may not be stable until a future release.\n\n Parameters\n ----------\n path : string File path, buffer-like, or None\n if None, return generated string\n append : boolean whether to append to an existing msgpack\n (default is False)\n compress : type of compressor (zlib or blosc), default to None (no\n compression)\n \"\"\"\n\n from pandas.io import packers\n return packers.to_msgpack(path_or_buf, self, encoding=encoding,\n **kwargs)\n\n def to_sql(self, name, con, schema=None, if_exists='fail', index=True,\n index_label=None, chunksize=None, dtype=None):\n \"\"\"\n Write records stored in a DataFrame to a SQL database.\n\n Databases supported by SQLAlchemy [1]_ are supported. Tables can be\n newly created, appended to, or overwritten.\n\n Parameters\n ----------\n name : string\n Name of SQL table.\n con : sqlalchemy.engine.Engine or sqlite3.Connection\n Using SQLAlchemy makes it possible to use any DB supported by that\n library. Legacy support is provided for sqlite3.Connection objects.\n schema : string, optional\n Specify the schema (if database flavor supports this). If None, use\n default schema.\n if_exists : {'fail', 'replace', 'append'}, default 'fail'\n How to behave if the table already exists.\n\n * fail: Raise a ValueError.\n * replace: Drop the table before inserting new values.\n * append: Insert new values to the existing table.\n\n index : boolean, default True\n Write DataFrame index as a column. Uses `index_label` as the column\n name in the table.\n index_label : string or sequence, default None\n Column label for index column(s). If None is given (default) and\n `index` is True, then the index names are used.\n A sequence should be given if the DataFrame uses MultiIndex.\n chunksize : int, optional\n Rows will be written in batches of this size at a time. By default,\n all rows will be written at once.\n dtype : dict, optional\n Specifying the datatype for columns. The keys should be the column\n names and the values should be the SQLAlchemy types or strings for\n the sqlite3 legacy mode.\n\n Raises\n ------\n ValueError\n When the table already exists and `if_exists` is 'fail' (the\n default).\n\n See Also\n --------\n pandas.read_sql : read a DataFrame from a table\n\n References\n ----------\n .. [1] http://docs.sqlalchemy.org\n .. [2] https://www.python.org/dev/peps/pep-0249/\n\n Examples\n --------\n\n Create an in-memory SQLite database.\n\n >>> from sqlalchemy import create_engine\n >>> engine = create_engine('sqlite://', echo=False)\n\n Create a table from scratch with 3 rows.\n\n >>> df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']})\n >>> df\n name\n 0 User 1\n 1 User 2\n 2 User 3\n\n >>> df.to_sql('users', con=engine)\n >>> engine.execute(\"SELECT * FROM users\").fetchall()\n [(0, 'User 1'), (1, 'User 2'), (2, 'User 3')]\n\n >>> df1 = pd.DataFrame({'name' : ['User 4', 'User 5']})\n >>> df1.to_sql('users', con=engine, if_exists='append')\n >>> engine.execute(\"SELECT * FROM users\").fetchall()\n [(0, 'User 1'), (1, 'User 2'), (2, 'User 3'),\n (0, 'User 4'), (1, 'User 5')]\n\n Overwrite the table with just ``df1``.\n\n >>> df1.to_sql('users', con=engine, if_exists='replace',\n ... index_label='id')\n >>> engine.execute(\"SELECT * FROM users\").fetchall()\n [(0, 'User 4'), (1, 'User 5')]\n\n Specify the dtype (especially useful for integers with missing values).\n Notice that while pandas is forced to store the data as floating point,\n the database supports nullable integers. When fetching the data with\n Python, we get back integer scalars.\n\n >>> df = pd.DataFrame({\"A\": [1, None, 2]})\n >>> df\n A\n 0 1.0\n 1 NaN\n 2 2.0\n\n >>> from sqlalchemy.types import Integer\n >>> df.to_sql('integers', con=engine, index=False,\n ... dtype={\"A\": Integer()})\n\n >>> engine.execute(\"SELECT * FROM integers\").fetchall()\n [(1,), (None,), (2,)]\n \"\"\"\n from pandas.io import sql\n sql.to_sql(self, name, con, schema=schema, if_exists=if_exists,\n index=index, index_label=index_label, chunksize=chunksize,\n dtype=dtype)\n\n def to_pickle(self, path, compression='infer',\n protocol=pkl.HIGHEST_PROTOCOL):\n \"\"\"\n Pickle (serialize) object to file.\n\n Parameters\n ----------\n path : str\n File path where the pickled object will be stored.\n compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, \\\n default 'infer'\n A string representing the compression to use in the output file. By\n default, infers from the file extension in specified path.\n\n .. versionadded:: 0.20.0\n protocol : int\n Int which indicates which protocol should be used by the pickler,\n default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible\n values for this parameter depend on the version of Python. For\n Python 2.x, possible values are 0, 1, 2. For Python>=3.0, 3 is a\n valid value. For Python >= 3.4, 4 is a valid value. A negative\n value for the protocol parameter is equivalent to setting its value\n to HIGHEST_PROTOCOL.\n\n .. [1] https://docs.python.org/3/library/pickle.html\n .. versionadded:: 0.21.0\n\n See Also\n --------\n read_pickle : Load pickled pandas object (or any object) from file.\n DataFrame.to_hdf : Write DataFrame to an HDF5 file.\n DataFrame.to_sql : Write DataFrame to a SQL database.\n DataFrame.to_parquet : Write a DataFrame to the binary parquet format.\n\n Examples\n --------\n >>> original_df = pd.DataFrame({\"foo\": range(5), \"bar\": range(5, 10)})\n >>> original_df\n foo bar\n 0 0 5\n 1 1 6\n 2 2 7\n 3 3 8\n 4 4 9\n >>> original_df.to_pickle(\"./dummy.pkl\")\n\n >>> unpickled_df = pd.read_pickle(\"./dummy.pkl\")\n >>> unpickled_df\n foo bar\n 0 0 5\n 1 1 6\n 2 2 7\n 3 3 8\n 4 4 9\n\n >>> import os\n >>> os.remove(\"./dummy.pkl\")\n \"\"\"\n from pandas.io.pickle import to_pickle\n return to_pickle(self, path, compression=compression,\n protocol=protocol)\n\n def to_clipboard(self, excel=True, sep=None, **kwargs):\n r\"\"\"\n Copy object to the system clipboard.\n\n Write a text representation of object to the system clipboard.\n This can be pasted into Excel, for example.\n\n Parameters\n ----------\n excel : bool, default True\n - True, use the provided separator, writing in a csv format for\n allowing easy pasting into excel.\n - False, write a string representation of the object to the\n clipboard.\n\n sep : str, default ``'\\t'``\n Field delimiter.\n **kwargs\n These parameters will be passed to DataFrame.to_csv.\n\n See Also\n --------\n DataFrame.to_csv : Write a DataFrame to a comma-separated values\n (csv) file.\n read_clipboard : Read text from clipboard and pass to read_table.\n\n Notes\n -----\n Requirements for your platform.\n\n - Linux : `xclip`, or `xsel` (with `gtk` or `PyQt4` modules)\n - Windows : none\n - OS X : none\n\n Examples\n --------\n Copy the contents of a DataFrame to the clipboard.\n\n >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C'])\n >>> df.to_clipboard(sep=',')\n ... # Wrote the following to the system clipboard:\n ... # ,A,B,C\n ... # 0,1,2,3\n ... # 1,4,5,6\n\n We can omit the the index by passing the keyword `index` and setting\n it to false.\n\n >>> df.to_clipboard(sep=',', index=False)\n ... # Wrote the following to the system clipboard:\n ... # A,B,C\n ... # 1,2,3\n ... # 4,5,6\n \"\"\"\n from pandas.io import clipboards\n clipboards.to_clipboard(self, excel=excel, sep=sep, **kwargs)\n\n def to_xarray(self):\n \"\"\"\n Return an xarray object from the pandas object.\n\n Returns\n -------\n a DataArray for a Series\n a Dataset for a DataFrame\n a DataArray for higher dims\n\n Examples\n --------\n >>> df = pd.DataFrame({'A' : [1, 1, 2],\n 'B' : ['foo', 'bar', 'foo'],\n 'C' : np.arange(4.,7)})\n >>> df\n A B C\n 0 1 foo 4.0\n 1 1 bar 5.0\n 2 2 foo 6.0\n\n >>> df.to_xarray()\n <xarray.Dataset>\n Dimensions: (index: 3)\n Coordinates:\n * index (index) int64 0 1 2\n Data variables:\n A (index) int64 1 1 2\n B (index) object 'foo' 'bar' 'foo'\n C (index) float64 4.0 5.0 6.0\n\n >>> df = pd.DataFrame({'A' : [1, 1, 2],\n 'B' : ['foo', 'bar', 'foo'],\n 'C' : np.arange(4.,7)}\n ).set_index(['B','A'])\n >>> df\n C\n B A\n foo 1 4.0\n bar 1 5.0\n foo 2 6.0\n\n >>> df.to_xarray()\n <xarray.Dataset>\n Dimensions: (A: 2, B: 2)\n Coordinates:\n * B (B) object 'bar' 'foo'\n * A (A) int64 1 2\n Data variables:\n C (B, A) float64 5.0 nan 4.0 6.0\n\n >>> p = pd.Panel(np.arange(24).reshape(4,3,2),\n items=list('ABCD'),\n major_axis=pd.date_range('20130101', periods=3),\n minor_axis=['first', 'second'])\n >>> p\n <class 'pandas.core.panel.Panel'>\n Dimensions: 4 (items) x 3 (major_axis) x 2 (minor_axis)\n Items axis: A to D\n Major_axis axis: 2013-01-01 00:00:00 to 2013-01-03 00:00:00\n Minor_axis axis: first to second\n\n >>> p.to_xarray()\n <xarray.DataArray (items: 4, major_axis: 3, minor_axis: 2)>\n array([[[ 0, 1],\n [ 2, 3],\n [ 4, 5]],\n [[ 6, 7],\n [ 8, 9],\n [10, 11]],\n [[12, 13],\n [14, 15],\n [16, 17]],\n [[18, 19],\n [20, 21],\n [22, 23]]])\n Coordinates:\n * items (items) object 'A' 'B' 'C' 'D'\n * major_axis (major_axis) datetime64[ns] 2013-01-01 2013-01-02 2013-01-03 # noqa\n * minor_axis (minor_axis) object 'first' 'second'\n\n Notes\n -----\n See the `xarray docs <http://xarray.pydata.org/en/stable/>`__\n \"\"\"\n\n try:\n import xarray\n except ImportError:\n # Give a nice error message\n raise ImportError(\"the xarray library is not installed\\n\"\n \"you can install via conda\\n\"\n \"conda install xarray\\n\"\n \"or via pip\\n\"\n \"pip install xarray\\n\")\n\n if self.ndim == 1:\n return xarray.DataArray.from_series(self)\n elif self.ndim == 2:\n return xarray.Dataset.from_dataframe(self)\n\n # > 2 dims\n coords = [(a, self._get_axis(a)) for a in self._AXIS_ORDERS]\n return xarray.DataArray(self,\n coords=coords,\n )\n\n _shared_docs['to_latex'] = r\"\"\"\n Render an object to a tabular environment table. You can splice\n this into a LaTeX document. Requires \\\\usepackage{booktabs}.\n\n .. versionchanged:: 0.20.2\n Added to Series\n\n `to_latex`-specific options:\n\n bold_rows : boolean, default False\n Make the row labels bold in the output\n column_format : str, default None\n The columns format as specified in `LaTeX table format\n <https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g 'rcl' for 3\n columns\n longtable : boolean, default will be read from the pandas config module\n Default: False.\n Use a longtable environment instead of tabular. Requires adding\n a \\\\usepackage{longtable} to your LaTeX preamble.\n escape : boolean, default will be read from the pandas config module\n Default: True.\n When set to False prevents from escaping latex special\n characters in column names.\n encoding : str, default None\n A string representing the encoding to use in the output file,\n defaults to 'ascii' on Python 2 and 'utf-8' on Python 3.\n decimal : string, default '.'\n Character recognized as decimal separator, e.g. ',' in Europe.\n\n .. versionadded:: 0.18.0\n\n multicolumn : boolean, default True\n Use \\multicolumn to enhance MultiIndex columns.\n The default will be read from the config module.\n\n .. versionadded:: 0.20.0\n\n multicolumn_format : str, default 'l'\n The alignment for multicolumns, similar to `column_format`\n The default will be read from the config module.\n\n .. versionadded:: 0.20.0\n\n multirow : boolean, default False\n Use \\multirow to enhance MultiIndex rows.\n Requires adding a \\\\usepackage{multirow} to your LaTeX preamble.\n Will print centered labels (instead of top-aligned)\n across the contained rows, separating groups via clines.\n The default will be read from the pandas config module.\n\n .. versionadded:: 0.20.0\n \"\"\"\n\n @Substitution(header='Write out the column names. If a list of strings '\n 'is given, it is assumed to be aliases for the '\n 'column names.')\n @Appender(_shared_docs['to_latex'] % _shared_doc_kwargs)\n def to_latex(self, buf=None, columns=None, col_space=None, header=True,\n index=True, na_rep='NaN', formatters=None, float_format=None,\n sparsify=None, index_names=True, bold_rows=False,\n column_format=None, longtable=None, escape=None,\n encoding=None, decimal='.', multicolumn=None,\n multicolumn_format=None, multirow=None):\n # Get defaults from the pandas config\n if self.ndim == 1:\n self = self.to_frame()\n if longtable is None:\n longtable = config.get_option(\"display.latex.longtable\")\n if escape is None:\n escape = config.get_option(\"display.latex.escape\")\n if multicolumn is None:\n multicolumn = config.get_option(\"display.latex.multicolumn\")\n if multicolumn_format is None:\n multicolumn_format = config.get_option(\n \"display.latex.multicolumn_format\")\n if multirow is None:\n multirow = config.get_option(\"display.latex.multirow\")\n\n formatter = DataFrameFormatter(self, buf=buf, columns=columns,\n col_space=col_space, na_rep=na_rep,\n header=header, index=index,\n formatters=formatters,\n float_format=float_format,\n bold_rows=bold_rows,\n sparsify=sparsify,\n index_names=index_names,\n escape=escape, decimal=decimal)\n formatter.to_latex(column_format=column_format, longtable=longtable,\n encoding=encoding, multicolumn=multicolumn,\n multicolumn_format=multicolumn_format,\n multirow=multirow)\n\n if buf is None:\n return formatter.buf.getvalue()\n\n # ----------------------------------------------------------------------\n # Fancy Indexing\n\n @classmethod\n def _create_indexer(cls, name, indexer):\n \"\"\"Create an indexer like _name in the class.\"\"\"\n if getattr(cls, name, None) is None:\n _indexer = functools.partial(indexer, name)\n setattr(cls, name, property(_indexer, doc=indexer.__doc__))\n\n def get(self, key, default=None):\n \"\"\"\n Get item from object for given key (DataFrame column, Panel slice,\n etc.). Returns default value if not found.\n\n Parameters\n ----------\n key : object\n\n Returns\n -------\n value : same type as items contained in object\n \"\"\"\n try:\n return self[key]\n except (KeyError, ValueError, IndexError):\n return default\n\n def __getitem__(self, item):\n return self._get_item_cache(item)\n\n def _get_item_cache(self, item):\n \"\"\"Return the cached item, item represents a label indexer.\"\"\"\n cache = self._item_cache\n res = cache.get(item)\n if res is None:\n values = self._data.get(item)\n res = self._box_item_values(item, values)\n cache[item] = res\n res._set_as_cached(item, self)\n\n # for a chain\n res._is_copy = self._is_copy\n return res\n\n def _set_as_cached(self, item, cacher):\n \"\"\"Set the _cacher attribute on the calling object with a weakref to\n cacher.\n \"\"\"\n self._cacher = (item, weakref.ref(cacher))\n\n def _reset_cacher(self):\n \"\"\"Reset the cacher.\"\"\"\n if hasattr(self, '_cacher'):\n del self._cacher\n\n def _iget_item_cache(self, item):\n \"\"\"Return the cached item, item represents a positional indexer.\"\"\"\n ax = self._info_axis\n if ax.is_unique:\n lower = self._get_item_cache(ax[item])\n else:\n lower = self._take(item, axis=self._info_axis_number)\n return lower\n\n def _box_item_values(self, key, values):\n raise com.AbstractMethodError(self)\n\n def _maybe_cache_changed(self, item, value):\n \"\"\"The object has called back to us saying maybe it has changed.\n \"\"\"\n self._data.set(item, value, check=False)\n\n @property\n def _is_cached(self):\n \"\"\"Return boolean indicating if self is cached or not.\"\"\"\n return getattr(self, '_cacher', None) is not None\n\n def _get_cacher(self):\n \"\"\"return my cacher or None\"\"\"\n cacher = getattr(self, '_cacher', None)\n if cacher is not None:\n cacher = cacher[1]()\n return cacher\n\n @property\n def _is_view(self):\n \"\"\"Return boolean indicating if self is view of another array \"\"\"\n return self._data.is_view\n\n def _maybe_update_cacher(self, clear=False, verify_is_copy=True):\n \"\"\"\n See if we need to update our parent cacher if clear, then clear our\n cache.\n\n Parameters\n ----------\n clear : boolean, default False\n clear the item cache\n verify_is_copy : boolean, default True\n provide is_copy checks\n\n \"\"\"\n\n cacher = getattr(self, '_cacher', None)\n if cacher is not None:\n ref = cacher[1]()\n\n # we are trying to reference a dead referant, hence\n # a copy\n if ref is None:\n del self._cacher\n else:\n try:\n ref._maybe_cache_changed(cacher[0], self)\n except Exception:\n pass\n\n if verify_is_copy:\n self._check_setitem_copy(stacklevel=5, t='referant')\n\n if clear:\n self._clear_item_cache()\n\n def _clear_item_cache(self, i=None):\n if i is not None:\n self._item_cache.pop(i, None)\n else:\n self._item_cache.clear()\n\n def _slice(self, slobj, axis=0, kind=None):\n \"\"\"\n Construct a slice of this container.\n\n kind parameter is maintained for compatibility with Series slicing.\n \"\"\"\n axis = self._get_block_manager_axis(axis)\n result = self._constructor(self._data.get_slice(slobj, axis=axis))\n result = result.__finalize__(self)\n\n # this could be a view\n # but only in a single-dtyped view slicable case\n is_copy = axis != 0 or result._is_view\n result._set_is_copy(self, copy=is_copy)\n return result\n\n def _set_item(self, key, value):\n self._data.set(key, value)\n self._clear_item_cache()\n\n def _set_is_copy(self, ref=None, copy=True):\n if not copy:\n self._is_copy = None\n else:\n if ref is not None:\n self._is_copy = weakref.ref(ref)\n else:\n self._is_copy = None\n\n def _check_is_chained_assignment_possible(self):\n \"\"\"\n Check if we are a view, have a cacher, and are of mixed type.\n If so, then force a setitem_copy check.\n\n Should be called just near setting a value\n\n Will return a boolean if it we are a view and are cached, but a\n single-dtype meaning that the cacher should be updated following\n setting.\n \"\"\"\n if self._is_view and self._is_cached:\n ref = self._get_cacher()\n if ref is not None and ref._is_mixed_type:\n self._check_setitem_copy(stacklevel=4, t='referant',\n force=True)\n return True\n elif self._is_copy:\n self._check_setitem_copy(stacklevel=4, t='referant')\n return False\n\n def _check_setitem_copy(self, stacklevel=4, t='setting', force=False):\n \"\"\"\n\n Parameters\n ----------\n stacklevel : integer, default 4\n the level to show of the stack when the error is output\n t : string, the type of setting error\n force : boolean, default False\n if True, then force showing an error\n\n validate if we are doing a settitem on a chained copy.\n\n If you call this function, be sure to set the stacklevel such that the\n user will see the error *at the level of setting*\n\n It is technically possible to figure out that we are setting on\n a copy even WITH a multi-dtyped pandas object. In other words, some\n blocks may be views while other are not. Currently _is_view will ALWAYS\n return False for multi-blocks to avoid having to handle this case.\n\n df = DataFrame(np.arange(0,9), columns=['count'])\n df['group'] = 'b'\n\n # This technically need not raise SettingWithCopy if both are view\n # (which is not # generally guaranteed but is usually True. However,\n # this is in general not a good practice and we recommend using .loc.\n df.iloc[0:5]['group'] = 'a'\n\n \"\"\"\n\n if force or self._is_copy:\n\n value = config.get_option('mode.chained_assignment')\n if value is None:\n return\n\n # see if the copy is not actually referred; if so, then dissolve\n # the copy weakref\n try:\n gc.collect(2)\n if not gc.get_referents(self._is_copy()):\n self._is_copy = None\n return\n except Exception:\n pass\n\n # we might be a false positive\n try:\n if self._is_copy().shape == self.shape:\n self._is_copy = None\n return\n except Exception:\n pass\n\n # a custom message\n if isinstance(self._is_copy, string_types):\n t = self._is_copy\n\n elif t == 'referant':\n t = (\"\\n\"\n \"A value is trying to be set on a copy of a slice from a \"\n \"DataFrame\\n\\n\"\n \"See the caveats in the documentation: \"\n \"http://pandas.pydata.org/pandas-docs/stable/\"\n \"indexing.html#indexing-view-versus-copy\"\n )\n\n else:\n t = (\"\\n\"\n \"A value is trying to be set on a copy of a slice from a \"\n \"DataFrame.\\n\"\n \"Try using .loc[row_indexer,col_indexer] = value \"\n \"instead\\n\\nSee the caveats in the documentation: \"\n \"http://pandas.pydata.org/pandas-docs/stable/\"\n \"indexing.html#indexing-view-versus-copy\"\n )\n\n if value == 'raise':\n raise com.SettingWithCopyError(t)\n elif value == 'warn':\n warnings.warn(t, com.SettingWithCopyWarning,\n stacklevel=stacklevel)\n\n def __delitem__(self, key):\n \"\"\"\n Delete item\n \"\"\"\n deleted = False\n\n maybe_shortcut = False\n if hasattr(self, 'columns') and isinstance(self.columns, MultiIndex):\n try:\n maybe_shortcut = key not in self.columns._engine\n except TypeError:\n pass\n\n if maybe_shortcut:\n # Allow shorthand to delete all columns whose first len(key)\n # elements match key:\n if not isinstance(key, tuple):\n key = (key, )\n for col in self.columns:\n if isinstance(col, tuple) and col[:len(key)] == key:\n del self[col]\n deleted = True\n if not deleted:\n # If the above loop ran and didn't delete anything because\n # there was no match, this call should raise the appropriate\n # exception:\n self._data.delete(key)\n\n # delete from the caches\n try:\n del self._item_cache[key]\n except KeyError:\n pass\n\n _shared_docs['_take'] = \"\"\"\n Return the elements in the given *positional* indices along an axis.\n\n This means that we are not indexing according to actual values in\n the index attribute of the object. We are indexing according to the\n actual position of the element in the object.\n\n This is the internal version of ``.take()`` and will contain a wider\n selection of parameters useful for internal use but not as suitable\n for public usage.\n\n Parameters\n ----------\n indices : array-like\n An array of ints indicating which positions to take.\n axis : int, default 0\n The axis on which to select elements. \"0\" means that we are\n selecting rows, \"1\" means that we are selecting columns, etc.\n is_copy : bool, default True\n Whether to return a copy of the original object or not.\n\n Returns\n -------\n taken : same type as caller\n An array-like containing the elements taken from the object.\n\n See Also\n --------\n numpy.ndarray.take\n numpy.take\n \"\"\"\n\n @Appender(_shared_docs['_take'])\n def _take(self, indices, axis=0, is_copy=True):\n self._consolidate_inplace()\n\n new_data = self._data.take(indices,\n axis=self._get_block_manager_axis(axis),\n verify=True)\n result = self._constructor(new_data).__finalize__(self)\n\n # Maybe set copy if we didn't actually change the index.\n if is_copy:\n if not result._get_axis(axis).equals(self._get_axis(axis)):\n result._set_is_copy(self)\n\n return result\n\n _shared_docs['take'] = \"\"\"\n Return the elements in the given *positional* indices along an axis.\n\n This means that we are not indexing according to actual values in\n the index attribute of the object. We are indexing according to the\n actual position of the element in the object.\n\n Parameters\n ----------\n indices : array-like\n An array of ints indicating which positions to take.\n axis : {0 or 'index', 1 or 'columns', None}, default 0\n The axis on which to select elements. ``0`` means that we are\n selecting rows, ``1`` means that we are selecting columns.\n convert : bool, default True\n Whether to convert negative indices into positive ones.\n For example, ``-1`` would map to the ``len(axis) - 1``.\n The conversions are similar to the behavior of indexing a\n regular Python list.\n\n .. deprecated:: 0.21.0\n In the future, negative indices will always be converted.\n\n is_copy : bool, default True\n Whether to return a copy of the original object or not.\n **kwargs\n For compatibility with :meth:`numpy.take`. Has no effect on the\n output.\n\n Returns\n -------\n taken : same type as caller\n An array-like containing the elements taken from the object.\n\n See Also\n --------\n DataFrame.loc : Select a subset of a DataFrame by labels.\n DataFrame.iloc : Select a subset of a DataFrame by positions.\n numpy.take : Take elements from an array along an axis.\n\n Examples\n --------\n >>> df = pd.DataFrame([('falcon', 'bird', 389.0),\n ... ('parrot', 'bird', 24.0),\n ... ('lion', 'mammal', 80.5),\n ... ('monkey', 'mammal', np.nan)],\n ... columns=['name', 'class', 'max_speed'],\n ... index=[0, 2, 3, 1])\n >>> df\n name class max_speed\n 0 falcon bird 389.0\n 2 parrot bird 24.0\n 3 lion mammal 80.5\n 1 monkey mammal NaN\n\n Take elements at positions 0 and 3 along the axis 0 (default).\n\n Note how the actual indices selected (0 and 1) do not correspond to\n our selected indices 0 and 3. That's because we are selecting the 0th\n and 3rd rows, not rows whose indices equal 0 and 3.\n\n >>> df.take([0, 3])\n name class max_speed\n 0 falcon bird 389.0\n 1 monkey mammal NaN\n\n Take elements at indices 1 and 2 along the axis 1 (column selection).\n\n >>> df.take([1, 2], axis=1)\n class max_speed\n 0 bird 389.0\n 2 bird 24.0\n 3 mammal 80.5\n 1 mammal NaN\n\n We may take elements using negative integers for positive indices,\n starting from the end of the object, just like with Python lists.\n\n >>> df.take([-1, -2])\n name class max_speed\n 1 monkey mammal NaN\n 3 lion mammal 80.5\n \"\"\"\n\n @Appender(_shared_docs['take'])\n def take(self, indices, axis=0, convert=None, is_copy=True, **kwargs):\n if convert is not None:\n msg = (\"The 'convert' parameter is deprecated \"\n \"and will be removed in a future version.\")\n warnings.warn(msg, FutureWarning, stacklevel=2)\n\n nv.validate_take(tuple(), kwargs)\n return self._take(indices, axis=axis, is_copy=is_copy)\n\n def xs(self, key, axis=0, level=None, drop_level=True):\n \"\"\"\n Returns a cross-section (row(s) or column(s)) from the\n Series/DataFrame. Defaults to cross-section on the rows (axis=0).\n\n Parameters\n ----------\n key : object\n Some label contained in the index, or partially in a MultiIndex\n axis : int, default 0\n Axis to retrieve cross-section on\n level : object, defaults to first n levels (n=1 or len(key))\n In case of a key partially contained in a MultiIndex, indicate\n which levels are used. Levels can be referred by label or position.\n drop_level : boolean, default True\n If False, returns object with same levels as self.\n\n Examples\n --------\n >>> df\n A B C\n a 4 5 2\n b 4 0 9\n c 9 7 3\n >>> df.xs('a')\n A 4\n B 5\n C 2\n Name: a\n >>> df.xs('C', axis=1)\n a 2\n b 9\n c 3\n Name: C\n\n >>> df\n A B C D\n first second third\n bar one 1 4 1 8 9\n two 1 7 5 5 0\n baz one 1 6 6 8 0\n three 2 5 3 5 3\n >>> df.xs(('baz', 'three'))\n A B C D\n third\n 2 5 3 5 3\n >>> df.xs('one', level=1)\n A B C D\n first third\n bar 1 4 1 8 9\n baz 1 6 6 8 0\n >>> df.xs(('baz', 2), level=[0, 'third'])\n A B C D\n second\n three 5 3 5 3\n\n Returns\n -------\n xs : Series or DataFrame\n\n Notes\n -----\n xs is only for getting, not setting values.\n\n MultiIndex Slicers is a generic way to get/set values on any level or\n levels. It is a superset of xs functionality, see\n :ref:`MultiIndex Slicers <advanced.mi_slicers>`\n\n \"\"\"\n axis = self._get_axis_number(axis)\n labels = self._get_axis(axis)\n if level is not None:\n loc, new_ax = labels.get_loc_level(key, level=level,\n drop_level=drop_level)\n\n # create the tuple of the indexer\n indexer = [slice(None)] * self.ndim\n indexer[axis] = loc\n indexer = tuple(indexer)\n\n result = self.iloc[indexer]\n setattr(result, result._get_axis_name(axis), new_ax)\n return result\n\n if axis == 1:\n return self[key]\n\n self._consolidate_inplace()\n\n index = self.index\n if isinstance(index, MultiIndex):\n loc, new_index = self.index.get_loc_level(key,\n drop_level=drop_level)\n else:\n loc = self.index.get_loc(key)\n\n if isinstance(loc, np.ndarray):\n if loc.dtype == np.bool_:\n inds, = loc.nonzero()\n return self._take(inds, axis=axis)\n else:\n return self._take(loc, axis=axis)\n\n if not is_scalar(loc):\n new_index = self.index[loc]\n\n if is_scalar(loc):\n new_values = self._data.fast_xs(loc)\n\n # may need to box a datelike-scalar\n #\n # if we encounter an array-like and we only have 1 dim\n # that means that their are list/ndarrays inside the Series!\n # so just return them (GH 6394)\n if not is_list_like(new_values) or self.ndim == 1:\n return com.maybe_box_datetimelike(new_values)\n\n result = self._constructor_sliced(\n new_values, index=self.columns,\n name=self.index[loc], dtype=new_values.dtype)\n\n else:\n result = self.iloc[loc]\n result.index = new_index\n\n # this could be a view\n # but only in a single-dtyped view slicable case\n result._set_is_copy(self, copy=not result._is_view)\n return result\n\n _xs = xs\n\n def select(self, crit, axis=0):\n \"\"\"Return data corresponding to axis labels matching criteria\n\n .. deprecated:: 0.21.0\n Use df.loc[df.index.map(crit)] to select via labels\n\n Parameters\n ----------\n crit : function\n To be called on each index (label). Should return True or False\n axis : int\n\n Returns\n -------\n selection : same type as caller\n \"\"\"\n warnings.warn(\"'select' is deprecated and will be removed in a \"\n \"future release. You can use \"\n \".loc[labels.map(crit)] as a replacement\",\n FutureWarning, stacklevel=2)\n\n axis = self._get_axis_number(axis)\n axis_name = self._get_axis_name(axis)\n axis_values = self._get_axis(axis)\n\n if len(axis_values) > 0:\n new_axis = axis_values[\n np.asarray([bool(crit(label)) for label in axis_values])]\n else:\n new_axis = axis_values\n\n return self.reindex(**{axis_name: new_axis})\n\n def reindex_like(self, other, method=None, copy=True, limit=None,\n tolerance=None):\n \"\"\"Return an object with matching indices to myself.\n\n Parameters\n ----------\n other : Object\n method : string or None\n copy : boolean, default True\n limit : int, default None\n Maximum number of consecutive labels to fill for inexact matches.\n tolerance : optional\n Maximum distance between labels of the other object and this\n object for inexact matches. Can be list-like.\n\n .. versionadded:: 0.21.0 (list-like tolerance)\n\n Notes\n -----\n Like calling s.reindex(index=other.index, columns=other.columns,\n method=...)\n\n Returns\n -------\n reindexed : same as input\n \"\"\"\n d = other._construct_axes_dict(axes=self._AXIS_ORDERS, method=method,\n copy=copy, limit=limit,\n tolerance=tolerance)\n\n return self.reindex(**d)\n\n def drop(self, labels=None, axis=0, index=None, columns=None, level=None,\n inplace=False, errors='raise'):\n\n inplace = validate_bool_kwarg(inplace, 'inplace')\n\n if labels is not None:\n if index is not None or columns is not None:\n raise ValueError(\"Cannot specify both 'labels' and \"\n \"'index'/'columns'\")\n axis_name = self._get_axis_name(axis)\n axes = {axis_name: labels}\n elif index is not None or columns is not None:\n axes, _ = self._construct_axes_from_arguments((index, columns), {})\n else:\n raise ValueError(\"Need to specify at least one of 'labels', \"\n \"'index' or 'columns'\")\n\n obj = self\n\n for axis, labels in axes.items():\n if labels is not None:\n obj = obj._drop_axis(labels, axis, level=level, errors=errors)\n\n if inplace:\n self._update_inplace(obj)\n else:\n return obj\n\n def _drop_axis(self, labels, axis, level=None, errors='raise'):\n \"\"\"\n Drop labels from specified axis. Used in the ``drop`` method\n internally.\n\n Parameters\n ----------\n labels : single label or list-like\n axis : int or axis name\n level : int or level name, default None\n For MultiIndex\n errors : {'ignore', 'raise'}, default 'raise'\n If 'ignore', suppress error and existing labels are dropped.\n\n \"\"\"\n axis = self._get_axis_number(axis)\n axis_name = self._get_axis_name(axis)\n axis = self._get_axis(axis)\n\n if axis.is_unique:\n if level is not None:\n if not isinstance(axis, MultiIndex):\n raise AssertionError('axis must be a MultiIndex')\n new_axis = axis.drop(labels, level=level, errors=errors)\n else:\n new_axis = axis.drop(labels, errors=errors)\n result = self.reindex(**{axis_name: new_axis})\n\n # Case for non-unique axis\n else:\n labels = ensure_object(com.index_labels_to_array(labels))\n if level is not None:\n if not isinstance(axis, MultiIndex):\n raise AssertionError('axis must be a MultiIndex')\n indexer = ~axis.get_level_values(level).isin(labels)\n\n # GH 18561 MultiIndex.drop should raise if label is absent\n if errors == 'raise' and indexer.all():\n raise KeyError('{} not found in axis'.format(labels))\n else:\n indexer = ~axis.isin(labels)\n # Check if label doesn't exist along axis\n labels_missing = (axis.get_indexer_for(labels) == -1).any()\n if errors == 'raise' and labels_missing:\n raise KeyError('{} not found in axis'.format(labels))\n\n slicer = [slice(None)] * self.ndim\n slicer[self._get_axis_number(axis_name)] = indexer\n\n result = self.loc[tuple(slicer)]\n\n return result\n\n def _update_inplace(self, result, verify_is_copy=True):\n \"\"\"\n Replace self internals with result.\n\n Parameters\n ----------\n verify_is_copy : boolean, default True\n provide is_copy checks\n\n \"\"\"\n # NOTE: This does *not* call __finalize__ and that's an explicit\n # decision that we may revisit in the future.\n\n self._reset_cache()\n self._clear_item_cache()\n self._data = getattr(result, '_data', result)\n self._maybe_update_cacher(verify_is_copy=verify_is_copy)\n\n def add_prefix(self, prefix):\n \"\"\"\n Prefix labels with string `prefix`.\n\n For Series, the row labels are prefixed.\n For DataFrame, the column labels are prefixed.\n\n Parameters\n ----------\n prefix : str\n The string to add before each label.\n\n Returns\n -------\n Series or DataFrame\n New Series or DataFrame with updated labels.\n\n See Also\n --------\n Series.add_suffix: Suffix row labels with string `suffix`.\n DataFrame.add_suffix: Suffix column labels with string `suffix`.\n\n Examples\n --------\n >>> s = pd.Series([1, 2, 3, 4])\n >>> s\n 0 1\n 1 2\n 2 3\n 3 4\n dtype: int64\n\n >>> s.add_prefix('item_')\n item_0 1\n item_1 2\n item_2 3\n item_3 4\n dtype: int64\n\n >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})\n >>> df\n A B\n 0 1 3\n 1 2 4\n 2 3 5\n 3 4 6\n\n >>> df.add_prefix('col_')\n col_A col_B\n 0 1 3\n 1 2 4\n 2 3 5\n 3 4 6\n \"\"\"\n new_data = self._data.add_prefix(prefix)\n return self._constructor(new_data).__finalize__(self)\n\n def add_suffix(self, suffix):\n \"\"\"\n Suffix labels with string `suffix`.\n\n For Series, the row labels are suffixed.\n For DataFrame, the column labels are suffixed.\n\n Parameters\n ----------\n suffix : str\n The string to add after each label.\n\n Returns\n -------\n Series or DataFrame\n New Series or DataFrame with updated labels.\n\n See Also\n --------\n Series.add_prefix: Prefix row labels with string `prefix`.\n DataFrame.add_prefix: Prefix column labels with string `prefix`.\n\n Examples\n --------\n >>> s = pd.Series([1, 2, 3, 4])\n >>> s\n 0 1\n 1 2\n 2 3\n 3 4\n dtype: int64\n\n >>> s.add_suffix('_item')\n 0_item 1\n 1_item 2\n 2_item 3\n 3_item 4\n dtype: int64\n\n >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})\n >>> df\n A B\n 0 1 3\n 1 2 4\n 2 3 5\n 3 4 6\n\n >>> df.add_suffix('_col')\n A_col B_col\n 0 1 3\n 1 2 4\n 2 3 5\n 3 4 6\n \"\"\"\n new_data = self._data.add_suffix(suffix)\n return self._constructor(new_data).__finalize__(self)\n\n _shared_docs['sort_values'] = \"\"\"\n Sort by the values along either axis\n\n Parameters\n ----------%(optional_by)s\n axis : %(axes_single_arg)s, default 0\n Axis to be sorted\n ascending : bool or list of bool, default True\n Sort ascending vs. descending. Specify list for multiple sort\n orders. If this is a list of bools, must match the length of\n the by.\n inplace : bool, default False\n if True, perform operation in-place\n kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'\n Choice of sorting algorithm. See also ndarray.np.sort for more\n information. `mergesort` is the only stable algorithm. For\n DataFrames, this option is only applied when sorting on a single\n column or label.\n na_position : {'first', 'last'}, default 'last'\n `first` puts NaNs at the beginning, `last` puts NaNs at the end\n\n Returns\n -------\n sorted_obj : %(klass)s\n\n Examples\n --------\n >>> df = pd.DataFrame({\n ... 'col1' : ['A', 'A', 'B', np.nan, 'D', 'C'],\n ... 'col2' : [2, 1, 9, 8, 7, 4],\n ... 'col3': [0, 1, 9, 4, 2, 3],\n ... })\n >>> df\n col1 col2 col3\n 0 A 2 0\n 1 A 1 1\n 2 B 9 9\n 3 NaN 8 4\n 4 D 7 2\n 5 C 4 3\n\n Sort by col1\n\n >>> df.sort_values(by=['col1'])\n col1 col2 col3\n 0 A 2 0\n 1 A 1 1\n 2 B 9 9\n 5 C 4 3\n 4 D 7 2\n 3 NaN 8 4\n\n Sort by multiple columns\n\n >>> df.sort_values(by=['col1', 'col2'])\n col1 col2 col3\n 1 A 1 1\n 0 A 2 0\n 2 B 9 9\n 5 C 4 3\n 4 D 7 2\n 3 NaN 8 4\n\n Sort Descending\n\n >>> df.sort_values(by='col1', ascending=False)\n col1 col2 col3\n 4 D 7 2\n 5 C 4 3\n 2 B 9 9\n 0 A 2 0\n 1 A 1 1\n 3 NaN 8 4\n\n Putting NAs first\n\n >>> df.sort_values(by='col1', ascending=False, na_position='first')\n col1 col2 col3\n 3 NaN 8 4\n 4 D 7 2\n 5 C 4 3\n 2 B 9 9\n 0 A 2 0\n 1 A 1 1\n \"\"\"\n\n def sort_values(self, by=None, axis=0, ascending=True, inplace=False,\n kind='quicksort', na_position='last'):\n \"\"\"\n NOT IMPLEMENTED: do not call this method, as sorting values is not\n supported for Panel objects and will raise an error.\n \"\"\"\n raise NotImplementedError(\"sort_values has not been implemented \"\n \"on Panel or Panel4D objects.\")\n\n _shared_docs['sort_index'] = \"\"\"\n Sort object by labels (along an axis)\n\n Parameters\n ----------\n axis : %(axes)s to direct sorting\n level : int or level name or list of ints or list of level names\n if not None, sort on values in specified index level(s)\n ascending : boolean, default True\n Sort ascending vs. descending\n inplace : bool, default False\n if True, perform operation in-place\n kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'\n Choice of sorting algorithm. See also ndarray.np.sort for more\n information. `mergesort` is the only stable algorithm. For\n DataFrames, this option is only applied when sorting on a single\n column or label.\n na_position : {'first', 'last'}, default 'last'\n `first` puts NaNs at the beginning, `last` puts NaNs at the end.\n Not implemented for MultiIndex.\n sort_remaining : bool, default True\n if true and sorting by level and index is multilevel, sort by other\n levels too (in order) after sorting by specified level\n\n Returns\n -------\n sorted_obj : %(klass)s\n \"\"\"\n\n @Appender(_shared_docs['sort_index'] % dict(axes=\"axes\", klass=\"NDFrame\"))\n def sort_index(self, axis=0, level=None, ascending=True, inplace=False,\n kind='quicksort', na_position='last', sort_remaining=True):\n inplace = validate_bool_kwarg(inplace, 'inplace')\n axis = self._get_axis_number(axis)\n axis_name = self._get_axis_name(axis)\n labels = self._get_axis(axis)\n\n if level is not None:\n raise NotImplementedError(\"level is not implemented\")\n if inplace:\n raise NotImplementedError(\"inplace is not implemented\")\n\n sort_index = labels.argsort()\n if not ascending:\n sort_index = sort_index[::-1]\n\n new_axis = labels.take(sort_index)\n return self.reindex(**{axis_name: new_axis})\n\n _shared_docs['reindex'] = \"\"\"\n Conform %(klass)s to new index with optional filling logic, placing\n NA/NaN in locations having no value in the previous index. A new object\n is produced unless the new index is equivalent to the current one and\n copy=False\n\n Parameters\n ----------\n %(optional_labels)s\n %(axes)s : array-like, optional (should be specified using keywords)\n New labels / index to conform to. Preferably an Index object to\n avoid duplicating data\n %(optional_axis)s\n method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}, optional\n method to use for filling holes in reindexed DataFrame.\n Please note: this is only applicable to DataFrames/Series with a\n monotonically increasing/decreasing index.\n\n * default: don't fill gaps\n * pad / ffill: propagate last valid observation forward to next\n valid\n * backfill / bfill: use next valid observation to fill gap\n * nearest: use nearest valid observations to fill gap\n\n copy : boolean, default True\n Return a new object, even if the passed indexes are the same\n level : int or name\n Broadcast across a level, matching Index values on the\n passed MultiIndex level\n fill_value : scalar, default np.NaN\n Value to use for missing values. Defaults to NaN, but can be any\n \"compatible\" value\n limit : int, default None\n Maximum number of consecutive elements to forward or backward fill\n tolerance : optional\n Maximum distance between original and new labels for inexact\n matches. The values of the index at the matching locations most\n satisfy the equation ``abs(index[indexer] - target) <= tolerance``.\n\n Tolerance may be a scalar value, which applies the same tolerance\n to all values, or list-like, which applies variable tolerance per\n element. List-like includes list, tuple, array, Series, and must be\n the same size as the index and its dtype must exactly match the\n index's type.\n\n .. versionadded:: 0.21.0 (list-like tolerance)\n\n Examples\n --------\n\n ``DataFrame.reindex`` supports two calling conventions\n\n * ``(index=index_labels, columns=column_labels, ...)``\n * ``(labels, axis={'index', 'columns'}, ...)``\n\n We *highly* recommend using keyword arguments to clarify your\n intent.\n\n Create a dataframe with some fictional data.\n\n >>> index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror']\n >>> df = pd.DataFrame({\n ... 'http_status': [200,200,404,404,301],\n ... 'response_time': [0.04, 0.02, 0.07, 0.08, 1.0]},\n ... index=index)\n >>> df\n http_status response_time\n Firefox 200 0.04\n Chrome 200 0.02\n Safari 404 0.07\n IE10 404 0.08\n Konqueror 301 1.00\n\n Create a new index and reindex the dataframe. By default\n values in the new index that do not have corresponding\n records in the dataframe are assigned ``NaN``.\n\n >>> new_index= ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10',\n ... 'Chrome']\n >>> df.reindex(new_index)\n http_status response_time\n Safari 404.0 0.07\n Iceweasel NaN NaN\n Comodo Dragon NaN NaN\n IE10 404.0 0.08\n Chrome 200.0 0.02\n\n We can fill in the missing values by passing a value to\n the keyword ``fill_value``. Because the index is not monotonically\n increasing or decreasing, we cannot use arguments to the keyword\n ``method`` to fill the ``NaN`` values.\n\n >>> df.reindex(new_index, fill_value=0)\n http_status response_time\n Safari 404 0.07\n Iceweasel 0 0.00\n Comodo Dragon 0 0.00\n IE10 404 0.08\n Chrome 200 0.02\n\n >>> df.reindex(new_index, fill_value='missing')\n http_status response_time\n Safari 404 0.07\n Iceweasel missing missing\n Comodo Dragon missing missing\n IE10 404 0.08\n Chrome 200 0.02\n\n We can also reindex the columns.\n\n >>> df.reindex(columns=['http_status', 'user_agent'])\n http_status user_agent\n Firefox 200 NaN\n Chrome 200 NaN\n Safari 404 NaN\n IE10 404 NaN\n Konqueror 301 NaN\n\n Or we can use \"axis-style\" keyword arguments\n\n >>> df.reindex(['http_status', 'user_agent'], axis=\"columns\")\n http_status user_agent\n Firefox 200 NaN\n Chrome 200 NaN\n Safari 404 NaN\n IE10 404 NaN\n Konqueror 301 NaN\n\n To further illustrate the filling functionality in\n ``reindex``, we will create a dataframe with a\n monotonically increasing index (for example, a sequence\n of dates).\n\n >>> date_index = pd.date_range('1/1/2010', periods=6, freq='D')\n >>> df2 = pd.DataFrame({\"prices\": [100, 101, np.nan, 100, 89, 88]},\n ... index=date_index)\n >>> df2\n prices\n 2010-01-01 100\n 2010-01-02 101\n 2010-01-03 NaN\n 2010-01-04 100\n 2010-01-05 89\n 2010-01-06 88\n\n Suppose we decide to expand the dataframe to cover a wider\n date range.\n\n >>> date_index2 = pd.date_range('12/29/2009', periods=10, freq='D')\n >>> df2.reindex(date_index2)\n prices\n 2009-12-29 NaN\n 2009-12-30 NaN\n 2009-12-31 NaN\n 2010-01-01 100\n 2010-01-02 101\n 2010-01-03 NaN\n 2010-01-04 100\n 2010-01-05 89\n 2010-01-06 88\n 2010-01-07 NaN\n\n The index entries that did not have a value in the original data frame\n (for example, '2009-12-29') are by default filled with ``NaN``.\n If desired, we can fill in the missing values using one of several\n options.\n\n For example, to back-propagate the last valid value to fill the ``NaN``\n values, pass ``bfill`` as an argument to the ``method`` keyword.\n\n >>> df2.reindex(date_index2, method='bfill')\n prices\n 2009-12-29 100\n 2009-12-30 100\n 2009-12-31 100\n 2010-01-01 100\n 2010-01-02 101\n 2010-01-03 NaN\n 2010-01-04 100\n 2010-01-05 89\n 2010-01-06 88\n 2010-01-07 NaN\n\n Please note that the ``NaN`` value present in the original dataframe\n (at index value 2010-01-03) will not be filled by any of the\n value propagation schemes. This is because filling while reindexing\n does not look at dataframe values, but only compares the original and\n desired indexes. If you do want to fill in the ``NaN`` values present\n in the original dataframe, use the ``fillna()`` method.\n\n See the :ref:`user guide <basics.reindexing>` for more.\n\n Returns\n -------\n reindexed : %(klass)s\n \"\"\"\n\n # TODO: Decide if we care about having different examples for different\n # kinds\n\n @Appender(_shared_docs['reindex'] % dict(axes=\"axes\", klass=\"NDFrame\",\n optional_labels=\"\",\n optional_axis=\"\"))\n def reindex(self, *args, **kwargs):\n\n # construct the args\n axes, kwargs = self._construct_axes_from_arguments(args, kwargs)\n method = missing.clean_reindex_fill_method(kwargs.pop('method', None))\n level = kwargs.pop('level', None)\n copy = kwargs.pop('copy', True)\n limit = kwargs.pop('limit', None)\n tolerance = kwargs.pop('tolerance', None)\n fill_value = kwargs.pop('fill_value', None)\n\n # Series.reindex doesn't use / need the axis kwarg\n # We pop and ignore it here, to make writing Series/Frame generic code\n # easier\n kwargs.pop(\"axis\", None)\n\n if kwargs:\n raise TypeError('reindex() got an unexpected keyword '\n 'argument \"{0}\"'.format(list(kwargs.keys())[0]))\n\n self._consolidate_inplace()\n\n # if all axes that are requested to reindex are equal, then only copy\n # if indicated must have index names equal here as well as values\n if all(self._get_axis(axis).identical(ax)\n for axis, ax in axes.items() if ax is not None):\n if copy:\n return self.copy()\n return self\n\n # check if we are a multi reindex\n if self._needs_reindex_multi(axes, method, level):\n try:\n return self._reindex_multi(axes, copy, fill_value)\n except Exception:\n pass\n\n # perform the reindex on the axes\n return self._reindex_axes(axes, level, limit, tolerance, method,\n fill_value, copy).__finalize__(self)\n\n def _reindex_axes(self, axes, level, limit, tolerance, method, fill_value,\n copy):\n \"\"\"Perform the reindex for all the axes.\"\"\"\n obj = self\n for a in self._AXIS_ORDERS:\n labels = axes[a]\n if labels is None:\n continue\n\n ax = self._get_axis(a)\n new_index, indexer = ax.reindex(labels, level=level, limit=limit,\n tolerance=tolerance, method=method)\n\n axis = self._get_axis_number(a)\n obj = obj._reindex_with_indexers({axis: [new_index, indexer]},\n fill_value=fill_value,\n copy=copy, allow_dups=False)\n\n return obj\n\n def _needs_reindex_multi(self, axes, method, level):\n \"\"\"Check if we do need a multi reindex.\"\"\"\n return ((com.count_not_none(*axes.values()) == self._AXIS_LEN) and\n method is None and level is None and not self._is_mixed_type)\n\n def _reindex_multi(self, axes, copy, fill_value):\n return NotImplemented\n\n _shared_docs[\n 'reindex_axis'] = (\"\"\"Conform input object to new index with optional\n filling logic, placing NA/NaN in locations having no value in the\n previous index. A new object is produced unless the new index is\n equivalent to the current one and copy=False\n\n Parameters\n ----------\n labels : array-like\n New labels / index to conform to. Preferably an Index object to\n avoid duplicating data\n axis : %(axes_single_arg)s\n method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}, optional\n Method to use for filling holes in reindexed DataFrame:\n\n * default: don't fill gaps\n * pad / ffill: propagate last valid observation forward to next\n valid\n * backfill / bfill: use next valid observation to fill gap\n * nearest: use nearest valid observations to fill gap\n\n copy : boolean, default True\n Return a new object, even if the passed indexes are the same\n level : int or name\n Broadcast across a level, matching Index values on the\n passed MultiIndex level\n limit : int, default None\n Maximum number of consecutive elements to forward or backward fill\n tolerance : optional\n Maximum distance between original and new labels for inexact\n matches. The values of the index at the matching locations most\n satisfy the equation ``abs(index[indexer] - target) <= tolerance``.\n\n Tolerance may be a scalar value, which applies the same tolerance\n to all values, or list-like, which applies variable tolerance per\n element. List-like includes list, tuple, array, Series, and must be\n the same size as the index and its dtype must exactly match the\n index's type.\n\n .. versionadded:: 0.21.0 (list-like tolerance)\n\n Examples\n --------\n >>> df.reindex_axis(['A', 'B', 'C'], axis=1)\n\n See Also\n --------\n reindex, reindex_like\n\n Returns\n -------\n reindexed : %(klass)s\n \"\"\")\n\n @Appender(_shared_docs['reindex_axis'] % _shared_doc_kwargs)\n def reindex_axis(self, labels, axis=0, method=None, level=None, copy=True,\n limit=None, fill_value=None):\n msg = (\"'.reindex_axis' is deprecated and will be removed in a future \"\n \"version. Use '.reindex' instead.\")\n self._consolidate_inplace()\n\n axis_name = self._get_axis_name(axis)\n axis_values = self._get_axis(axis_name)\n method = missing.clean_reindex_fill_method(method)\n warnings.warn(msg, FutureWarning, stacklevel=3)\n new_index, indexer = axis_values.reindex(labels, method, level,\n limit=limit)\n return self._reindex_with_indexers({axis: [new_index, indexer]},\n fill_value=fill_value, copy=copy)\n\n def _reindex_with_indexers(self, reindexers, fill_value=None, copy=False,\n allow_dups=False):\n \"\"\"allow_dups indicates an internal call here \"\"\"\n\n # reindex doing multiple operations on different axes if indicated\n new_data = self._data\n for axis in sorted(reindexers.keys()):\n index, indexer = reindexers[axis]\n baxis = self._get_block_manager_axis(axis)\n\n if index is None:\n continue\n\n index = ensure_index(index)\n if indexer is not None:\n indexer = ensure_int64(indexer)\n\n # TODO: speed up on homogeneous DataFrame objects\n new_data = new_data.reindex_indexer(index, indexer, axis=baxis,\n fill_value=fill_value,\n allow_dups=allow_dups,\n copy=copy)\n\n if copy and new_data is self._data:\n new_data = new_data.copy()\n\n return self._constructor(new_data).__finalize__(self)\n\n def _reindex_axis(self, new_index, fill_method, axis, copy):\n new_data = self._data.reindex_axis(new_index, axis=axis,\n method=fill_method, copy=copy)\n\n if new_data is self._data and not copy:\n return self\n else:\n return self._constructor(new_data).__finalize__(self)\n\n def filter(self, items=None, like=None, regex=None, axis=None):\n \"\"\"\n Subset rows or columns of dataframe according to labels in\n the specified index.\n\n Note that this routine does not filter a dataframe on its\n contents. The filter is applied to the labels of the index.\n\n Parameters\n ----------\n items : list-like\n List of axis to restrict to (must not all be present).\n like : string\n Keep axis where \"arg in col == True\".\n regex : string (regular expression)\n Keep axis with re.search(regex, col) == True.\n axis : int or string axis name\n The axis to filter on. By default this is the info axis,\n 'index' for Series, 'columns' for DataFrame.\n\n Returns\n -------\n same type as input object\n\n Examples\n --------\n >>> df = pd.DataFrame(np.array(([1,2,3], [4,5,6])),\n ... index=['mouse', 'rabbit'],\n ... columns=['one', 'two', 'three'])\n\n >>> # select columns by name\n >>> df.filter(items=['one', 'three'])\n one three\n mouse 1 3\n rabbit 4 6\n\n >>> # select columns by regular expression\n >>> df.filter(regex='e$', axis=1)\n one three\n mouse 1 3\n rabbit 4 6\n\n >>> # select rows containing 'bbi'\n >>> df.filter(like='bbi', axis=0)\n one two three\n rabbit 4 5 6\n\n See Also\n --------\n pandas.DataFrame.loc\n\n Notes\n -----\n The ``items``, ``like``, and ``regex`` parameters are\n enforced to be mutually exclusive.\n\n ``axis`` defaults to the info axis that is used when indexing\n with ``[]``.\n \"\"\"\n import re\n\n nkw = com.count_not_none(items, like, regex)\n if nkw > 1:\n raise TypeError('Keyword arguments `items`, `like`, or `regex` '\n 'are mutually exclusive')\n\n if axis is None:\n axis = self._info_axis_name\n labels = self._get_axis(axis)\n\n if items is not None:\n name = self._get_axis_name(axis)\n return self.reindex(\n **{name: [r for r in items if r in labels]})\n elif like:\n def f(x):\n return like in to_str(x)\n values = labels.map(f)\n return self.loc(axis=axis)[values]\n elif regex:\n def f(x):\n return matcher.search(to_str(x)) is not None\n matcher = re.compile(regex)\n values = labels.map(f)\n return self.loc(axis=axis)[values]\n else:\n raise TypeError('Must pass either `items`, `like`, or `regex`')\n\n def head(self, n=5):\n \"\"\"\n Return the first `n` rows.\n\n This function returns the first `n` rows for the object based\n on position. It is useful for quickly testing if your object\n has the right type of data in it.\n\n Parameters\n ----------\n n : int, default 5\n Number of rows to select.\n\n Returns\n -------\n obj_head : same type as caller\n The first `n` rows of the caller object.\n\n See Also\n --------\n pandas.DataFrame.tail: Returns the last `n` rows.\n\n Examples\n --------\n >>> df = pd.DataFrame({'animal':['alligator', 'bee', 'falcon', 'lion',\n ... 'monkey', 'parrot', 'shark', 'whale', 'zebra']})\n >>> df\n animal\n 0 alligator\n 1 bee\n 2 falcon\n 3 lion\n 4 monkey\n 5 parrot\n 6 shark\n 7 whale\n 8 zebra\n\n Viewing the first 5 lines\n\n >>> df.head()\n animal\n 0 alligator\n 1 bee\n 2 falcon\n 3 lion\n 4 monkey\n\n Viewing the first `n` lines (three in this case)\n\n >>> df.head(3)\n animal\n 0 alligator\n 1 bee\n 2 falcon\n \"\"\"\n\n return self.iloc[:n]\n\n def tail(self, n=5):\n \"\"\"\n Return the last `n` rows.\n\n This function returns last `n` rows from the object based on\n position. It is useful for quickly verifying data, for example,\n after sorting or appending rows.\n\n Parameters\n ----------\n n : int, default 5\n Number of rows to select.\n\n Returns\n -------\n type of caller\n The last `n` rows of the caller object.\n\n See Also\n --------\n pandas.DataFrame.head : The first `n` rows of the caller object.\n\n Examples\n --------\n >>> df = pd.DataFrame({'animal':['alligator', 'bee', 'falcon', 'lion',\n ... 'monkey', 'parrot', 'shark', 'whale', 'zebra']})\n >>> df\n animal\n 0 alligator\n 1 bee\n 2 falcon\n 3 lion\n 4 monkey\n 5 parrot\n 6 shark\n 7 whale\n 8 zebra\n\n Viewing the last 5 lines\n\n >>> df.tail()\n animal\n 4 monkey\n 5 parrot\n 6 shark\n 7 whale\n 8 zebra\n\n Viewing the last `n` lines (three in this case)\n\n >>> df.tail(3)\n animal\n 6 shark\n 7 whale\n 8 zebra\n \"\"\"\n\n if n == 0:\n return self.iloc[0:0]\n return self.iloc[-n:]\n\n def sample(self, n=None, frac=None, replace=False, weights=None,\n random_state=None, axis=None):\n \"\"\"\n Return a random sample of items from an axis of object.\n\n You can use `random_state` for reproducibility.\n\n Parameters\n ----------\n n : int, optional\n Number of items from axis to return. Cannot be used with `frac`.\n Default = 1 if `frac` = None.\n frac : float, optional\n Fraction of axis items to return. Cannot be used with `n`.\n replace : boolean, optional\n Sample with or without replacement. Default = False.\n weights : str or ndarray-like, optional\n Default 'None' results in equal probability weighting.\n If passed a Series, will align with target object on index. Index\n values in weights not found in sampled object will be ignored and\n index values in sampled object not in weights will be assigned\n weights of zero.\n If called on a DataFrame, will accept the name of a column\n when axis = 0.\n Unless weights are a Series, weights must be same length as axis\n being sampled.\n If weights do not sum to 1, they will be normalized to sum to 1.\n Missing values in the weights column will be treated as zero.\n inf and -inf values not allowed.\n random_state : int or numpy.random.RandomState, optional\n Seed for the random number generator (if int), or numpy RandomState\n object.\n axis : int or string, optional\n Axis to sample. Accepts axis number or name. Default is stat axis\n for given data type (0 for Series and DataFrames, 1 for Panels).\n\n Returns\n -------\n A new object of same type as caller.\n\n Examples\n --------\n Generate an example ``Series`` and ``DataFrame``:\n\n >>> s = pd.Series(np.random.randn(50))\n >>> s.head()\n 0 -0.038497\n 1 1.820773\n 2 -0.972766\n 3 -1.598270\n 4 -1.095526\n dtype: float64\n >>> df = pd.DataFrame(np.random.randn(50, 4), columns=list('ABCD'))\n >>> df.head()\n A B C D\n 0 0.016443 -2.318952 -0.566372 -1.028078\n 1 -1.051921 0.438836 0.658280 -0.175797\n 2 -1.243569 -0.364626 -0.215065 0.057736\n 3 1.768216 0.404512 -0.385604 -1.457834\n 4 1.072446 -1.137172 0.314194 -0.046661\n\n Next extract a random sample from both of these objects...\n\n 3 random elements from the ``Series``:\n\n >>> s.sample(n=3)\n 27 -0.994689\n 55 -1.049016\n 67 -0.224565\n dtype: float64\n\n And a random 10% of the ``DataFrame`` with replacement:\n\n >>> df.sample(frac=0.1, replace=True)\n A B C D\n 35 1.981780 0.142106 1.817165 -0.290805\n 49 -1.336199 -0.448634 -0.789640 0.217116\n 40 0.823173 -0.078816 1.009536 1.015108\n 15 1.421154 -0.055301 -1.922594 -0.019696\n 6 -0.148339 0.832938 1.787600 -1.383767\n\n You can use `random state` for reproducibility:\n\n >>> df.sample(random_state=1)\n A B C D\n 37 -2.027662 0.103611 0.237496 -0.165867\n 43 -0.259323 -0.583426 1.516140 -0.479118\n 12 -1.686325 -0.579510 0.985195 -0.460286\n 8 1.167946 0.429082 1.215742 -1.636041\n 9 1.197475 -0.864188 1.554031 -1.505264\n \"\"\"\n\n if axis is None:\n axis = self._stat_axis_number\n\n axis = self._get_axis_number(axis)\n axis_length = self.shape[axis]\n\n # Process random_state argument\n rs = com.random_state(random_state)\n\n # Check weights for compliance\n if weights is not None:\n\n # If a series, align with frame\n if isinstance(weights, pd.Series):\n weights = weights.reindex(self.axes[axis])\n\n # Strings acceptable if a dataframe and axis = 0\n if isinstance(weights, string_types):\n if isinstance(self, pd.DataFrame):\n if axis == 0:\n try:\n weights = self[weights]\n except KeyError:\n raise KeyError(\"String passed to weights not a \"\n \"valid column\")\n else:\n raise ValueError(\"Strings can only be passed to \"\n \"weights when sampling from rows on \"\n \"a DataFrame\")\n else:\n raise ValueError(\"Strings cannot be passed as weights \"\n \"when sampling from a Series or Panel.\")\n\n weights = pd.Series(weights, dtype='float64')\n\n if len(weights) != axis_length:\n raise ValueError(\"Weights and axis to be sampled must be of \"\n \"same length\")\n\n if (weights == np.inf).any() or (weights == -np.inf).any():\n raise ValueError(\"weight vector may not include `inf` values\")\n\n if (weights < 0).any():\n raise ValueError(\"weight vector many not include negative \"\n \"values\")\n\n # If has nan, set to zero.\n weights = weights.fillna(0)\n\n # Renormalize if don't sum to 1\n if weights.sum() != 1:\n if weights.sum() != 0:\n weights = weights / weights.sum()\n else:\n raise ValueError(\"Invalid weights: weights sum to zero\")\n\n weights = weights.values\n\n # If no frac or n, default to n=1.\n if n is None and frac is None:\n n = 1\n elif n is not None and frac is None and n % 1 != 0:\n raise ValueError(\"Only integers accepted as `n` values\")\n elif n is None and frac is not None:\n n = int(round(frac * axis_length))\n elif n is not None and frac is not None:\n raise ValueError('Please enter a value for `frac` OR `n`, not '\n 'both')\n\n # Check for negative sizes\n if n < 0:\n raise ValueError(\"A negative number of rows requested. Please \"\n \"provide positive value.\")\n\n locs = rs.choice(axis_length, size=n, replace=replace, p=weights)\n return self.take(locs, axis=axis, is_copy=False)\n\n _shared_docs['pipe'] = (r\"\"\"\n Apply func(self, \\*args, \\*\\*kwargs)\n\n Parameters\n ----------\n func : function\n function to apply to the %(klass)s.\n ``args``, and ``kwargs`` are passed into ``func``.\n Alternatively a ``(callable, data_keyword)`` tuple where\n ``data_keyword`` is a string indicating the keyword of\n ``callable`` that expects the %(klass)s.\n args : iterable, optional\n positional arguments passed into ``func``.\n kwargs : mapping, optional\n a dictionary of keyword arguments passed into ``func``.\n\n Returns\n -------\n object : the return type of ``func``.\n\n Notes\n -----\n\n Use ``.pipe`` when chaining together functions that expect\n Series, DataFrames or GroupBy objects. Instead of writing\n\n >>> f(g(h(df), arg1=a), arg2=b, arg3=c)\n\n You can write\n\n >>> (df.pipe(h)\n ... .pipe(g, arg1=a)\n ... .pipe(f, arg2=b, arg3=c)\n ... )\n\n If you have a function that takes the data as (say) the second\n argument, pass a tuple indicating which keyword expects the\n data. For example, suppose ``f`` takes its data as ``arg2``:\n\n >>> (df.pipe(h)\n ... .pipe(g, arg1=a)\n ... .pipe((f, 'arg2'), arg1=a, arg3=c)\n ... )\n\n See Also\n --------\n pandas.DataFrame.apply\n pandas.DataFrame.applymap\n pandas.Series.map\n \"\"\")\n\n @Appender(_shared_docs['pipe'] % _shared_doc_kwargs)\n def pipe(self, func, *args, **kwargs):\n return com._pipe(self, func, *args, **kwargs)\n\n _shared_docs['aggregate'] = (\"\"\"\n Aggregate using one or more operations over the specified axis.\n\n %(versionadded)s\n\n Parameters\n ----------\n func : function, string, dictionary, or list of string/functions\n Function to use for aggregating the data. If a function, must either\n work when passed a %(klass)s or when passed to %(klass)s.apply. For\n a DataFrame, can pass a dict, if the keys are DataFrame column names.\n\n Accepted combinations are:\n\n - string function name.\n - function.\n - list of functions.\n - dict of column names -> functions (or list of functions).\n\n %(axis)s\n *args\n Positional arguments to pass to `func`.\n **kwargs\n Keyword arguments to pass to `func`.\n\n Returns\n -------\n aggregated : %(klass)s\n\n Notes\n -----\n `agg` is an alias for `aggregate`. Use the alias.\n\n A passed user-defined-function will be passed a Series for evaluation.\n \"\"\")\n\n _shared_docs['transform'] = (\"\"\"\n Call function producing a like-indexed %(klass)s\n and return a %(klass)s with the transformed values\n\n .. versionadded:: 0.20.0\n\n Parameters\n ----------\n func : callable, string, dictionary, or list of string/callables\n To apply to column\n\n Accepted Combinations are:\n\n - string function name\n - function\n - list of functions\n - dict of column names -> functions (or list of functions)\n\n Returns\n -------\n transformed : %(klass)s\n\n Examples\n --------\n >>> df = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C'],\n ... index=pd.date_range('1/1/2000', periods=10))\n df.iloc[3:7] = np.nan\n\n >>> df.transform(lambda x: (x - x.mean()) / x.std())\n A B C\n 2000-01-01 0.579457 1.236184 0.123424\n 2000-01-02 0.370357 -0.605875 -1.231325\n 2000-01-03 1.455756 -0.277446 0.288967\n 2000-01-04 NaN NaN NaN\n 2000-01-05 NaN NaN NaN\n 2000-01-06 NaN NaN NaN\n 2000-01-07 NaN NaN NaN\n 2000-01-08 -0.498658 1.274522 1.642524\n 2000-01-09 -0.540524 -1.012676 -0.828968\n 2000-01-10 -1.366388 -0.614710 0.005378\n\n See also\n --------\n pandas.%(klass)s.aggregate\n pandas.%(klass)s.apply\n \"\"\")\n\n # ----------------------------------------------------------------------\n # Attribute access\n\n def __finalize__(self, other, method=None, **kwargs):\n \"\"\"\n Propagate metadata from other to self.\n\n Parameters\n ----------\n other : the object from which to get the attributes that we are going\n to propagate\n method : optional, a passed method name ; possibly to take different\n types of propagation actions based on this\n\n \"\"\"\n if isinstance(other, NDFrame):\n for name in self._metadata:\n object.__setattr__(self, name, getattr(other, name, None))\n return self\n\n def __getattr__(self, name):\n \"\"\"After regular attribute access, try looking up the name\n This allows simpler access to columns for interactive use.\n \"\"\"\n\n # Note: obj.x will always call obj.__getattribute__('x') prior to\n # calling obj.__getattr__('x').\n\n if (name in self._internal_names_set or name in self._metadata or\n name in self._accessors):\n return object.__getattribute__(self, name)\n else:\n if self._info_axis._can_hold_identifiers_and_holds_name(name):\n return self[name]\n return object.__getattribute__(self, name)\n\n def __setattr__(self, name, value):\n \"\"\"After regular attribute access, try setting the name\n This allows simpler access to columns for interactive use.\n \"\"\"\n\n # first try regular attribute access via __getattribute__, so that\n # e.g. ``obj.x`` and ``obj.x = 4`` will always reference/modify\n # the same attribute.\n\n try:\n object.__getattribute__(self, name)\n return object.__setattr__(self, name, value)\n except AttributeError:\n pass\n\n # if this fails, go on to more involved attribute setting\n # (note that this matches __getattr__, above).\n if name in self._internal_names_set:\n object.__setattr__(self, name, value)\n elif name in self._metadata:\n object.__setattr__(self, name, value)\n else:\n try:\n existing = getattr(self, name)\n if isinstance(existing, Index):\n object.__setattr__(self, name, value)\n elif name in self._info_axis:\n self[name] = value\n else:\n object.__setattr__(self, name, value)\n except (AttributeError, TypeError):\n if isinstance(self, ABCDataFrame) and (is_list_like(value)):\n warnings.warn(\"Pandas doesn't allow columns to be \"\n \"created via a new attribute name - see \"\n \"https://pandas.pydata.org/pandas-docs/\"\n \"stable/indexing.html#attribute-access\",\n stacklevel=2)\n object.__setattr__(self, name, value)\n\n # ----------------------------------------------------------------------\n # Getting and setting elements\n\n # ----------------------------------------------------------------------\n # Consolidation of internals\n\n def _protect_consolidate(self, f):\n \"\"\"Consolidate _data -- if the blocks have changed, then clear the\n cache\n \"\"\"\n blocks_before = len(self._data.blocks)\n result = f()\n if len(self._data.blocks) != blocks_before:\n self._clear_item_cache()\n return result\n\n def _consolidate_inplace(self):\n \"\"\"Consolidate data in place and return None\"\"\"\n\n def f():\n self._data = self._data.consolidate()\n\n self._protect_consolidate(f)\n\n def _consolidate(self, inplace=False):\n \"\"\"\n Compute NDFrame with \"consolidated\" internals (data of each dtype\n grouped together in a single ndarray).\n\n Parameters\n ----------\n inplace : boolean, default False\n If False return new object, otherwise modify existing object\n\n Returns\n -------\n consolidated : same type as caller\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n if inplace:\n self._consolidate_inplace()\n else:\n f = lambda: self._data.consolidate()\n cons_data = self._protect_consolidate(f)\n return self._constructor(cons_data).__finalize__(self)\n\n def consolidate(self, inplace=False):\n \"\"\"Compute NDFrame with \"consolidated\" internals (data of each dtype\n grouped together in a single ndarray).\n\n .. deprecated:: 0.20.0\n Consolidate will be an internal implementation only.\n \"\"\"\n # 15483\n warnings.warn(\"consolidate is deprecated and will be removed in a \"\n \"future release.\", FutureWarning, stacklevel=2)\n return self._consolidate(inplace)\n\n @property\n def _is_mixed_type(self):\n f = lambda: self._data.is_mixed_type\n return self._protect_consolidate(f)\n\n @property\n def _is_numeric_mixed_type(self):\n f = lambda: self._data.is_numeric_mixed_type\n return self._protect_consolidate(f)\n\n @property\n def _is_datelike_mixed_type(self):\n f = lambda: self._data.is_datelike_mixed_type\n return self._protect_consolidate(f)\n\n def _check_inplace_setting(self, value):\n \"\"\" check whether we allow in-place setting with this type of value \"\"\"\n\n if self._is_mixed_type:\n if not self._is_numeric_mixed_type:\n\n # allow an actual np.nan thru\n try:\n if np.isnan(value):\n return True\n except Exception:\n pass\n\n raise TypeError('Cannot do inplace boolean setting on '\n 'mixed-types with a non np.nan value')\n\n return True\n\n def _get_numeric_data(self):\n return self._constructor(\n self._data.get_numeric_data()).__finalize__(self)\n\n def _get_bool_data(self):\n return self._constructor(self._data.get_bool_data()).__finalize__(self)\n\n # ----------------------------------------------------------------------\n # Internal Interface Methods\n\n def as_matrix(self, columns=None):\n \"\"\"Convert the frame to its Numpy-array representation.\n\n .. deprecated:: 0.23.0\n Use :meth:`DataFrame.values` instead.\n\n Parameters\n ----------\n columns: list, optional, default:None\n If None, return all columns, otherwise, returns specified columns.\n\n Returns\n -------\n values : ndarray\n If the caller is heterogeneous and contains booleans or objects,\n the result will be of dtype=object. See Notes.\n\n\n Notes\n -----\n Return is NOT a Numpy-matrix, rather, a Numpy-array.\n\n The dtype will be a lower-common-denominator dtype (implicit\n upcasting); that is to say if the dtypes (even of numeric types)\n are mixed, the one that accommodates all will be chosen. Use this\n with care if you are not dealing with the blocks.\n\n e.g. If the dtypes are float16 and float32, dtype will be upcast to\n float32. If dtypes are int32 and uint8, dtype will be upcase to\n int32. By numpy.find_common_type convention, mixing int64 and uint64\n will result in a float64 dtype.\n\n This method is provided for backwards compatibility. Generally,\n it is recommended to use '.values'.\n\n See Also\n --------\n pandas.DataFrame.values\n \"\"\"\n warnings.warn(\"Method .as_matrix will be removed in a future version. \"\n \"Use .values instead.\", FutureWarning, stacklevel=2)\n self._consolidate_inplace()\n return self._data.as_array(transpose=self._AXIS_REVERSED,\n items=columns)\n\n @property\n def values(self):\n \"\"\"\n Return a Numpy representation of the DataFrame.\n\n Only the values in the DataFrame will be returned, the axes labels\n will be removed.\n\n Returns\n -------\n numpy.ndarray\n The values of the DataFrame.\n\n Examples\n --------\n A DataFrame where all columns are the same type (e.g., int64) results\n in an array of the same type.\n\n >>> df = pd.DataFrame({'age': [ 3, 29],\n ... 'height': [94, 170],\n ... 'weight': [31, 115]})\n >>> df\n age height weight\n 0 3 94 31\n 1 29 170 115\n >>> df.dtypes\n age int64\n height int64\n weight int64\n dtype: object\n >>> df.values\n array([[ 3, 94, 31],\n [ 29, 170, 115]], dtype=int64)\n\n A DataFrame with mixed type columns(e.g., str/object, int64, float32)\n results in an ndarray of the broadest type that accommodates these\n mixed types (e.g., object).\n\n >>> df2 = pd.DataFrame([('parrot', 24.0, 'second'),\n ... ('lion', 80.5, 1),\n ... ('monkey', np.nan, None)],\n ... columns=('name', 'max_speed', 'rank'))\n >>> df2.dtypes\n name object\n max_speed float64\n rank object\n dtype: object\n >>> df2.values\n array([['parrot', 24.0, 'second'],\n ['lion', 80.5, 1],\n ['monkey', nan, None]], dtype=object)\n\n Notes\n -----\n The dtype will be a lower-common-denominator dtype (implicit\n upcasting); that is to say if the dtypes (even of numeric types)\n are mixed, the one that accommodates all will be chosen. Use this\n with care if you are not dealing with the blocks.\n\n e.g. If the dtypes are float16 and float32, dtype will be upcast to\n float32. If dtypes are int32 and uint8, dtype will be upcast to\n int32. By :func:`numpy.find_common_type` convention, mixing int64\n and uint64 will result in a float64 dtype.\n\n See Also\n --------\n pandas.DataFrame.index : Retrieve the index labels\n pandas.DataFrame.columns : Retrieving the column names\n \"\"\"\n self._consolidate_inplace()\n return self._data.as_array(transpose=self._AXIS_REVERSED)\n\n @property\n def _values(self):\n \"\"\"internal implementation\"\"\"\n return self.values\n\n @property\n def _get_values(self):\n # compat\n return self.values\n\n def get_values(self):\n \"\"\"\n Return an ndarray after converting sparse values to dense.\n\n This is the same as ``.values`` for non-sparse data. For sparse\n data contained in a `pandas.SparseArray`, the data are first\n converted to a dense representation.\n\n Returns\n -------\n numpy.ndarray\n Numpy representation of DataFrame\n\n See Also\n --------\n values : Numpy representation of DataFrame.\n pandas.SparseArray : Container for sparse data.\n\n Examples\n --------\n >>> df = pd.DataFrame({'a': [1, 2], 'b': [True, False],\n ... 'c': [1.0, 2.0]})\n >>> df\n a b c\n 0 1 True 1.0\n 1 2 False 2.0\n\n >>> df.get_values()\n array([[1, True, 1.0], [2, False, 2.0]], dtype=object)\n\n >>> df = pd.DataFrame({\"a\": pd.SparseArray([1, None, None]),\n ... \"c\": [1.0, 2.0, 3.0]})\n >>> df\n a c\n 0 1.0 1.0\n 1 NaN 2.0\n 2 NaN 3.0\n\n >>> df.get_values()\n array([[ 1., 1.],\n [nan, 2.],\n [nan, 3.]])\n \"\"\"\n return self.values\n\n def get_dtype_counts(self):\n \"\"\"\n Return counts of unique dtypes in this object.\n\n Returns\n -------\n dtype : Series\n Series with the count of columns with each dtype.\n\n See Also\n --------\n dtypes : Return the dtypes in this object.\n\n Examples\n --------\n >>> a = [['a', 1, 1.0], ['b', 2, 2.0], ['c', 3, 3.0]]\n >>> df = pd.DataFrame(a, columns=['str', 'int', 'float'])\n >>> df\n str int float\n 0 a 1 1.0\n 1 b 2 2.0\n 2 c 3 3.0\n\n >>> df.get_dtype_counts()\n float64 1\n int64 1\n object 1\n dtype: int64\n \"\"\"\n from pandas import Series\n return Series(self._data.get_dtype_counts())\n\n def get_ftype_counts(self):\n \"\"\"\n Return counts of unique ftypes in this object.\n\n .. deprecated:: 0.23.0\n\n This is useful for SparseDataFrame or for DataFrames containing\n sparse arrays.\n\n Returns\n -------\n dtype : Series\n Series with the count of columns with each type and\n sparsity (dense/sparse)\n\n See Also\n --------\n ftypes : Return ftypes (indication of sparse/dense and dtype) in\n this object.\n\n Examples\n --------\n >>> a = [['a', 1, 1.0], ['b', 2, 2.0], ['c', 3, 3.0]]\n >>> df = pd.DataFrame(a, columns=['str', 'int', 'float'])\n >>> df\n str int float\n 0 a 1 1.0\n 1 b 2 2.0\n 2 c 3 3.0\n\n >>> df.get_ftype_counts()\n float64:dense 1\n int64:dense 1\n object:dense 1\n dtype: int64\n \"\"\"\n warnings.warn(\"get_ftype_counts is deprecated and will \"\n \"be removed in a future version\",\n FutureWarning, stacklevel=2)\n\n from pandas import Series\n return Series(self._data.get_ftype_counts())\n\n @property\n def dtypes(self):\n \"\"\"\n Return the dtypes in the DataFrame.\n\n This returns a Series with the data type of each column.\n The result's index is the original DataFrame's columns. Columns\n with mixed types are stored with the ``object`` dtype. See\n :ref:`the User Guide <basics.dtypes>` for more.\n\n Returns\n -------\n pandas.Series\n The data type of each column.\n\n See Also\n --------\n pandas.DataFrame.ftypes : dtype and sparsity information.\n\n Examples\n --------\n >>> df = pd.DataFrame({'float': [1.0],\n ... 'int': [1],\n ... 'datetime': [pd.Timestamp('20180310')],\n ... 'string': ['foo']})\n >>> df.dtypes\n float float64\n int int64\n datetime datetime64[ns]\n string object\n dtype: object\n \"\"\"\n from pandas import Series\n return Series(self._data.get_dtypes(), index=self._info_axis,\n dtype=np.object_)\n\n @property\n def ftypes(self):\n \"\"\"\n Return the ftypes (indication of sparse/dense and dtype) in DataFrame.\n\n This returns a Series with the data type of each column.\n The result's index is the original DataFrame's columns. Columns\n with mixed types are stored with the ``object`` dtype. See\n :ref:`the User Guide <basics.dtypes>` for more.\n\n Returns\n -------\n pandas.Series\n The data type and indication of sparse/dense of each column.\n\n See Also\n --------\n pandas.DataFrame.dtypes: Series with just dtype information.\n pandas.SparseDataFrame : Container for sparse tabular data.\n\n Notes\n -----\n Sparse data should have the same dtypes as its dense representation.\n\n Examples\n --------\n >>> arr = np.random.RandomState(0).randn(100, 4)\n >>> arr[arr < .8] = np.nan\n >>> pd.DataFrame(arr).ftypes\n 0 float64:dense\n 1 float64:dense\n 2 float64:dense\n 3 float64:dense\n dtype: object\n\n >>> pd.SparseDataFrame(arr).ftypes\n 0 float64:sparse\n 1 float64:sparse\n 2 float64:sparse\n 3 float64:sparse\n dtype: object\n \"\"\"\n from pandas import Series\n return Series(self._data.get_ftypes(), index=self._info_axis,\n dtype=np.object_)\n\n def as_blocks(self, copy=True):\n \"\"\"\n Convert the frame to a dict of dtype -> Constructor Types that each has\n a homogeneous dtype.\n\n .. deprecated:: 0.21.0\n\n NOTE: the dtypes of the blocks WILL BE PRESERVED HERE (unlike in\n as_matrix)\n\n Parameters\n ----------\n copy : boolean, default True\n\n Returns\n -------\n values : a dict of dtype -> Constructor Types\n \"\"\"\n warnings.warn(\"as_blocks is deprecated and will \"\n \"be removed in a future version\",\n FutureWarning, stacklevel=2)\n return self._to_dict_of_blocks(copy=copy)\n\n @property\n def blocks(self):\n \"\"\"\n Internal property, property synonym for as_blocks()\n\n .. deprecated:: 0.21.0\n \"\"\"\n return self.as_blocks()\n\n def _to_dict_of_blocks(self, copy=True):\n \"\"\"\n Return a dict of dtype -> Constructor Types that\n each is a homogeneous dtype.\n\n Internal ONLY\n \"\"\"\n return {k: self._constructor(v).__finalize__(self)\n for k, v, in self._data.to_dict(copy=copy).items()}\n\n @deprecate_kwarg(old_arg_name='raise_on_error', new_arg_name='errors',\n mapping={True: 'raise', False: 'ignore'})\n def astype(self, dtype, copy=True, errors='raise', **kwargs):\n \"\"\"\n Cast a pandas object to a specified dtype ``dtype``.\n\n Parameters\n ----------\n dtype : data type, or dict of column name -> data type\n Use a numpy.dtype or Python type to cast entire pandas object to\n the same type. Alternatively, use {col: dtype, ...}, where col is a\n column label and dtype is a numpy.dtype or Python type to cast one\n or more of the DataFrame's columns to column-specific types.\n copy : bool, default True.\n Return a copy when ``copy=True`` (be very careful setting\n ``copy=False`` as changes to values then may propagate to other\n pandas objects).\n errors : {'raise', 'ignore'}, default 'raise'.\n Control raising of exceptions on invalid data for provided dtype.\n\n - ``raise`` : allow exceptions to be raised\n - ``ignore`` : suppress exceptions. On error return original object\n\n .. versionadded:: 0.20.0\n\n raise_on_error : raise on invalid input\n .. deprecated:: 0.20.0\n Use ``errors`` instead\n kwargs : keyword arguments to pass on to the constructor\n\n Returns\n -------\n casted : same type as caller\n\n Examples\n --------\n >>> ser = pd.Series([1, 2], dtype='int32')\n >>> ser\n 0 1\n 1 2\n dtype: int32\n >>> ser.astype('int64')\n 0 1\n 1 2\n dtype: int64\n\n Convert to categorical type:\n\n >>> ser.astype('category')\n 0 1\n 1 2\n dtype: category\n Categories (2, int64): [1, 2]\n\n Convert to ordered categorical type with custom ordering:\n\n >>> ser.astype('category', ordered=True, categories=[2, 1])\n 0 1\n 1 2\n dtype: category\n Categories (2, int64): [2 < 1]\n\n Note that using ``copy=False`` and changing data on a new\n pandas object may propagate changes:\n\n >>> s1 = pd.Series([1,2])\n >>> s2 = s1.astype('int64', copy=False)\n >>> s2[0] = 10\n >>> s1 # note that s1[0] has changed too\n 0 10\n 1 2\n dtype: int64\n\n See also\n --------\n pandas.to_datetime : Convert argument to datetime.\n pandas.to_timedelta : Convert argument to timedelta.\n pandas.to_numeric : Convert argument to a numeric type.\n numpy.ndarray.astype : Cast a numpy array to a specified type.\n \"\"\"\n if is_dict_like(dtype):\n if self.ndim == 1: # i.e. Series\n if len(dtype) > 1 or self.name not in dtype:\n raise KeyError('Only the Series name can be used for '\n 'the key in Series dtype mappings.')\n new_type = dtype[self.name]\n return self.astype(new_type, copy, errors, **kwargs)\n elif self.ndim > 2:\n raise NotImplementedError(\n 'astype() only accepts a dtype arg of type dict when '\n 'invoked on Series and DataFrames. A single dtype must be '\n 'specified when invoked on a Panel.'\n )\n for col_name in dtype.keys():\n if col_name not in self:\n raise KeyError('Only a column name can be used for the '\n 'key in a dtype mappings argument.')\n results = []\n for col_name, col in self.iteritems():\n if col_name in dtype:\n results.append(col.astype(dtype[col_name], copy=copy))\n else:\n results.append(results.append(col.copy() if copy else col))\n\n elif is_categorical_dtype(dtype) and self.ndim > 1:\n # GH 18099: columnwise conversion to categorical\n results = (self[col].astype(dtype, copy=copy) for col in self)\n\n else:\n # else, only a single dtype is given\n new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors,\n **kwargs)\n return self._constructor(new_data).__finalize__(self)\n\n # GH 19920: retain column metadata after concat\n result = pd.concat(results, axis=1, copy=False)\n result.columns = self.columns\n return result\n\n def copy(self, deep=True):\n \"\"\"\n Make a copy of this object's indices and data.\n\n When ``deep=True`` (default), a new object will be created with a\n copy of the calling object's data and indices. Modifications to\n the data or indices of the copy will not be reflected in the\n original object (see notes below).\n\n When ``deep=False``, a new object will be created without copying\n the calling object's data or index (only references to the data\n and index are copied). Any changes to the data of the original\n will be reflected in the shallow copy (and vice versa).\n\n Parameters\n ----------\n deep : bool, default True\n Make a deep copy, including a copy of the data and the indices.\n With ``deep=False`` neither the indices nor the data are copied.\n\n Returns\n -------\n copy : Series, DataFrame or Panel\n Object type matches caller.\n\n Notes\n -----\n When ``deep=True``, data is copied but actual Python objects\n will not be copied recursively, only the reference to the object.\n This is in contrast to `copy.deepcopy` in the Standard Library,\n which recursively copies object data (see examples below).\n\n While ``Index`` objects are copied when ``deep=True``, the underlying\n numpy array is not copied for performance reasons. Since ``Index`` is\n immutable, the underlying data can be safely shared and a copy\n is not needed.\n\n Examples\n --------\n >>> s = pd.Series([1, 2], index=[\"a\", \"b\"])\n >>> s\n a 1\n b 2\n dtype: int64\n\n >>> s_copy = s.copy()\n >>> s_copy\n a 1\n b 2\n dtype: int64\n\n **Shallow copy versus default (deep) copy:**\n\n >>> s = pd.Series([1, 2], index=[\"a\", \"b\"])\n >>> deep = s.copy()\n >>> shallow = s.copy(deep=False)\n\n Shallow copy shares data and index with original.\n\n >>> s is shallow\n False\n >>> s.values is shallow.values and s.index is shallow.index\n True\n\n Deep copy has own copy of data and index.\n\n >>> s is deep\n False\n >>> s.values is deep.values or s.index is deep.index\n False\n\n Updates to the data shared by shallow copy and original is reflected\n in both; deep copy remains unchanged.\n\n >>> s[0] = 3\n >>> shallow[1] = 4\n >>> s\n a 3\n b 4\n dtype: int64\n >>> shallow\n a 3\n b 4\n dtype: int64\n >>> deep\n a 1\n b 2\n dtype: int64\n\n Note that when copying an object containing Python objects, a deep copy\n will copy the data, but will not do so recursively. Updating a nested\n data object will be reflected in the deep copy.\n\n >>> s = pd.Series([[1, 2], [3, 4]])\n >>> deep = s.copy()\n >>> s[0][0] = 10\n >>> s\n 0 [10, 2]\n 1 [3, 4]\n dtype: object\n >>> deep\n 0 [10, 2]\n 1 [3, 4]\n dtype: object\n \"\"\"\n data = self._data.copy(deep=deep)\n return self._constructor(data).__finalize__(self)\n\n def __copy__(self, deep=True):\n return self.copy(deep=deep)\n\n def __deepcopy__(self, memo=None):\n \"\"\"\n Parameters\n ----------\n memo, default None\n Standard signature. Unused\n \"\"\"\n if memo is None:\n memo = {}\n return self.copy(deep=True)\n\n def _convert(self, datetime=False, numeric=False, timedelta=False,\n coerce=False, copy=True):\n \"\"\"\n Attempt to infer better dtype for object columns\n\n Parameters\n ----------\n datetime : boolean, default False\n If True, convert to date where possible.\n numeric : boolean, default False\n If True, attempt to convert to numbers (including strings), with\n unconvertible values becoming NaN.\n timedelta : boolean, default False\n If True, convert to timedelta where possible.\n coerce : boolean, default False\n If True, force conversion with unconvertible values converted to\n nulls (NaN or NaT)\n copy : boolean, default True\n If True, return a copy even if no copy is necessary (e.g. no\n conversion was done). Note: This is meant for internal use, and\n should not be confused with inplace.\n\n Returns\n -------\n converted : same as input object\n \"\"\"\n return self._constructor(\n self._data.convert(datetime=datetime, numeric=numeric,\n timedelta=timedelta, coerce=coerce,\n copy=copy)).__finalize__(self)\n\n def convert_objects(self, convert_dates=True, convert_numeric=False,\n convert_timedeltas=True, copy=True):\n \"\"\"Attempt to infer better dtype for object columns.\n\n .. deprecated:: 0.21.0\n\n Parameters\n ----------\n convert_dates : boolean, default True\n If True, convert to date where possible. If 'coerce', force\n conversion, with unconvertible values becoming NaT.\n convert_numeric : boolean, default False\n If True, attempt to coerce to numbers (including strings), with\n unconvertible values becoming NaN.\n convert_timedeltas : boolean, default True\n If True, convert to timedelta where possible. If 'coerce', force\n conversion, with unconvertible values becoming NaT.\n copy : boolean, default True\n If True, return a copy even if no copy is necessary (e.g. no\n conversion was done). Note: This is meant for internal use, and\n should not be confused with inplace.\n\n See Also\n --------\n pandas.to_datetime : Convert argument to datetime.\n pandas.to_timedelta : Convert argument to timedelta.\n pandas.to_numeric : Convert argument to numeric type.\n\n Returns\n -------\n converted : same as input object\n \"\"\"\n msg = (\"convert_objects is deprecated. To re-infer data dtypes for \"\n \"object columns, use {klass}.infer_objects()\\nFor all \"\n \"other conversions use the data-type specific converters \"\n \"pd.to_datetime, pd.to_timedelta and pd.to_numeric.\"\n ).format(klass=self.__class__.__name__)\n warnings.warn(msg, FutureWarning, stacklevel=2)\n\n return self._constructor(\n self._data.convert(convert_dates=convert_dates,\n convert_numeric=convert_numeric,\n convert_timedeltas=convert_timedeltas,\n copy=copy)).__finalize__(self)\n\n def infer_objects(self):\n \"\"\"\n Attempt to infer better dtypes for object columns.\n\n Attempts soft conversion of object-dtyped\n columns, leaving non-object and unconvertible\n columns unchanged. The inference rules are the\n same as during normal Series/DataFrame construction.\n\n .. versionadded:: 0.21.0\n\n See Also\n --------\n pandas.to_datetime : Convert argument to datetime.\n pandas.to_timedelta : Convert argument to timedelta.\n pandas.to_numeric : Convert argument to numeric type.\n\n Returns\n -------\n converted : same type as input object\n\n Examples\n --------\n >>> df = pd.DataFrame({\"A\": [\"a\", 1, 2, 3]})\n >>> df = df.iloc[1:]\n >>> df\n A\n 1 1\n 2 2\n 3 3\n\n >>> df.dtypes\n A object\n dtype: object\n\n >>> df.infer_objects().dtypes\n A int64\n dtype: object\n \"\"\"\n # numeric=False necessary to only soft convert;\n # python objects will still be converted to\n # native numpy numeric types\n return self._constructor(\n self._data.convert(datetime=True, numeric=False,\n timedelta=True, coerce=False,\n copy=True)).__finalize__(self)\n\n # ----------------------------------------------------------------------\n # Filling NA's\n\n def fillna(self, value=None, method=None, axis=None, inplace=False,\n limit=None, downcast=None):\n \"\"\"\n Fill NA/NaN values using the specified method\n\n Parameters\n ----------\n value : scalar, dict, Series, or DataFrame\n Value to use to fill holes (e.g. 0), alternately a\n dict/Series/DataFrame of values specifying which value to use for\n each index (for a Series) or column (for a DataFrame). (values not\n in the dict/Series/DataFrame will not be filled). This value cannot\n be a list.\n method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None\n Method to use for filling holes in reindexed Series\n pad / ffill: propagate last valid observation forward to next valid\n backfill / bfill: use NEXT valid observation to fill gap\n axis : %(axes_single_arg)s\n inplace : boolean, default False\n If True, fill in place. Note: this will modify any\n other views on this object, (e.g. a no-copy slice for a column in a\n DataFrame).\n limit : int, default None\n If method is specified, this is the maximum number of consecutive\n NaN values to forward/backward fill. In other words, if there is\n a gap with more than this number of consecutive NaNs, it will only\n be partially filled. If method is not specified, this is the\n maximum number of entries along the entire axis where NaNs will be\n filled. Must be greater than 0 if not None.\n downcast : dict, default is None\n a dict of item->dtype of what to downcast if possible,\n or the string 'infer' which will try to downcast to an appropriate\n equal type (e.g. float64 to int64 if possible)\n\n See Also\n --------\n interpolate : Fill NaN values using interpolation.\n reindex, asfreq\n\n Returns\n -------\n filled : %(klass)s\n\n Examples\n --------\n >>> df = pd.DataFrame([[np.nan, 2, np.nan, 0],\n ... [3, 4, np.nan, 1],\n ... [np.nan, np.nan, np.nan, 5],\n ... [np.nan, 3, np.nan, 4]],\n ... columns=list('ABCD'))\n >>> df\n A B C D\n 0 NaN 2.0 NaN 0\n 1 3.0 4.0 NaN 1\n 2 NaN NaN NaN 5\n 3 NaN 3.0 NaN 4\n\n Replace all NaN elements with 0s.\n\n >>> df.fillna(0)\n A B C D\n 0 0.0 2.0 0.0 0\n 1 3.0 4.0 0.0 1\n 2 0.0 0.0 0.0 5\n 3 0.0 3.0 0.0 4\n\n We can also propagate non-null values forward or backward.\n\n >>> df.fillna(method='ffill')\n A B C D\n 0 NaN 2.0 NaN 0\n 1 3.0 4.0 NaN 1\n 2 3.0 4.0 NaN 5\n 3 3.0 3.0 NaN 4\n\n Replace all NaN elements in column 'A', 'B', 'C', and 'D', with 0, 1,\n 2, and 3 respectively.\n\n >>> values = {'A': 0, 'B': 1, 'C': 2, 'D': 3}\n >>> df.fillna(value=values)\n A B C D\n 0 0.0 2.0 2.0 0\n 1 3.0 4.0 2.0 1\n 2 0.0 1.0 2.0 5\n 3 0.0 3.0 2.0 4\n\n Only replace the first NaN element.\n\n >>> df.fillna(value=values, limit=1)\n A B C D\n 0 0.0 2.0 2.0 0\n 1 3.0 4.0 NaN 1\n 2 NaN 1.0 NaN 5\n 3 NaN 3.0 NaN 4\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n value, method = validate_fillna_kwargs(value, method)\n\n self._consolidate_inplace()\n\n # set the default here, so functions examining the signaure\n # can detect if something was set (e.g. in groupby) (GH9221)\n if axis is None:\n axis = 0\n axis = self._get_axis_number(axis)\n\n from pandas import DataFrame\n if value is None:\n\n if self._is_mixed_type and axis == 1:\n if inplace:\n raise NotImplementedError()\n result = self.T.fillna(method=method, limit=limit).T\n\n # need to downcast here because of all of the transposes\n result._data = result._data.downcast()\n\n return result\n\n # > 3d\n if self.ndim > 3:\n raise NotImplementedError('Cannot fillna with a method for > '\n '3dims')\n\n # 3d\n elif self.ndim == 3:\n # fill in 2d chunks\n result = {col: s.fillna(method=method, value=value)\n for col, s in self.iteritems()}\n new_obj = self._constructor.\\\n from_dict(result).__finalize__(self)\n new_data = new_obj._data\n\n else:\n # 2d or less\n new_data = self._data.interpolate(method=method, axis=axis,\n limit=limit, inplace=inplace,\n coerce=True,\n downcast=downcast)\n else:\n if len(self._get_axis(axis)) == 0:\n return self\n\n if self.ndim == 1:\n if isinstance(value, (dict, ABCSeries)):\n from pandas import Series\n value = Series(value)\n elif not is_list_like(value):\n pass\n else:\n raise TypeError('\"value\" parameter must be a scalar, dict '\n 'or Series, but you passed a '\n '\"{0}\"'.format(type(value).__name__))\n\n new_data = self._data.fillna(value=value, limit=limit,\n inplace=inplace,\n downcast=downcast)\n\n elif isinstance(value, (dict, ABCSeries)):\n if axis == 1:\n raise NotImplementedError('Currently only can fill '\n 'with dict/Series column '\n 'by column')\n\n result = self if inplace else self.copy()\n for k, v in compat.iteritems(value):\n if k not in result:\n continue\n obj = result[k]\n obj.fillna(v, limit=limit, inplace=True, downcast=downcast)\n return result if not inplace else None\n\n elif not is_list_like(value):\n new_data = self._data.fillna(value=value, limit=limit,\n inplace=inplace,\n downcast=downcast)\n elif isinstance(value, DataFrame) and self.ndim == 2:\n new_data = self.where(self.notna(), value)\n else:\n raise ValueError(\"invalid fill value with a %s\" % type(value))\n\n if inplace:\n self._update_inplace(new_data)\n else:\n return self._constructor(new_data).__finalize__(self)\n\n def ffill(self, axis=None, inplace=False, limit=None, downcast=None):\n \"\"\"\n Synonym for :meth:`DataFrame.fillna(method='ffill') <DataFrame.fillna>`\n \"\"\"\n return self.fillna(method='ffill', axis=axis, inplace=inplace,\n limit=limit, downcast=downcast)\n\n def bfill(self, axis=None, inplace=False, limit=None, downcast=None):\n \"\"\"\n Synonym for :meth:`DataFrame.fillna(method='bfill') <DataFrame.fillna>`\n \"\"\"\n return self.fillna(method='bfill', axis=axis, inplace=inplace,\n limit=limit, downcast=downcast)\n\n _shared_docs['replace'] = (\"\"\"\n Replace values given in `to_replace` with `value`.\n\n Values of the %(klass)s are replaced with other values dynamically.\n This differs from updating with ``.loc`` or ``.iloc``, which require\n you to specify a location to update with some value.\n\n Parameters\n ----------\n to_replace : str, regex, list, dict, Series, int, float, or None\n How to find the values that will be replaced.\n\n * numeric, str or regex:\n\n - numeric: numeric values equal to `to_replace` will be\n replaced with `value`\n - str: string exactly matching `to_replace` will be replaced\n with `value`\n - regex: regexs matching `to_replace` will be replaced with\n `value`\n\n * list of str, regex, or numeric:\n\n - First, if `to_replace` and `value` are both lists, they\n **must** be the same length.\n - Second, if ``regex=True`` then all of the strings in **both**\n lists will be interpreted as regexs otherwise they will match\n directly. This doesn't matter much for `value` since there\n are only a few possible substitution regexes you can use.\n - str, regex and numeric rules apply as above.\n\n * dict:\n\n - Dicts can be used to specify different replacement values\n for different existing values. For example,\n ``{'a': 'b', 'y': 'z'}`` replaces the value 'a' with 'b' and\n 'y' with 'z'. To use a dict in this way the `value`\n parameter should be `None`.\n - For a DataFrame a dict can specify that different values\n should be replaced in different columns. For example,\n ``{'a': 1, 'b': 'z'}`` looks for the value 1 in column 'a'\n and the value 'z' in column 'b' and replaces these values\n with whatever is specified in `value`. The `value` parameter\n should not be ``None`` in this case. You can treat this as a\n special case of passing two lists except that you are\n specifying the column to search in.\n - For a DataFrame nested dictionaries, e.g.,\n ``{'a': {'b': np.nan}}``, are read as follows: look in column\n 'a' for the value 'b' and replace it with NaN. The `value`\n parameter should be ``None`` to use a nested dict in this\n way. You can nest regular expressions as well. Note that\n column names (the top-level dictionary keys in a nested\n dictionary) **cannot** be regular expressions.\n\n * None:\n\n - This means that the `regex` argument must be a string,\n compiled regular expression, or list, dict, ndarray or\n Series of such elements. If `value` is also ``None`` then\n this **must** be a nested dictionary or Series.\n\n See the examples section for examples of each of these.\n value : scalar, dict, list, str, regex, default None\n Value to replace any values matching `to_replace` with.\n For a DataFrame a dict of values can be used to specify which\n value to use for each column (columns not in the dict will not be\n filled). Regular expressions, strings and lists or dicts of such\n objects are also allowed.\n inplace : boolean, default False\n If True, in place. Note: this will modify any\n other views on this object (e.g. a column from a DataFrame).\n Returns the caller if this is True.\n limit : int, default None\n Maximum size gap to forward or backward fill.\n regex : bool or same types as `to_replace`, default False\n Whether to interpret `to_replace` and/or `value` as regular\n expressions. If this is ``True`` then `to_replace` *must* be a\n string. Alternatively, this could be a regular expression or a\n list, dict, or array of regular expressions in which case\n `to_replace` must be ``None``.\n method : {'pad', 'ffill', 'bfill', `None`}\n The method to use when for replacement, when `to_replace` is a\n scalar, list or tuple and `value` is ``None``.\n\n .. versionchanged:: 0.23.0\n Added to DataFrame.\n\n See Also\n --------\n %(klass)s.fillna : Fill NA values\n %(klass)s.where : Replace values based on boolean condition\n Series.str.replace : Simple string replacement.\n\n Returns\n -------\n %(klass)s\n Object after replacement.\n\n Raises\n ------\n AssertionError\n * If `regex` is not a ``bool`` and `to_replace` is not\n ``None``.\n TypeError\n * If `to_replace` is a ``dict`` and `value` is not a ``list``,\n ``dict``, ``ndarray``, or ``Series``\n * If `to_replace` is ``None`` and `regex` is not compilable\n into a regular expression or is a list, dict, ndarray, or\n Series.\n * When replacing multiple ``bool`` or ``datetime64`` objects and\n the arguments to `to_replace` does not match the type of the\n value being replaced\n ValueError\n * If a ``list`` or an ``ndarray`` is passed to `to_replace` and\n `value` but they are not the same length.\n\n Notes\n -----\n * Regex substitution is performed under the hood with ``re.sub``. The\n rules for substitution for ``re.sub`` are the same.\n * Regular expressions will only substitute on strings, meaning you\n cannot provide, for example, a regular expression matching floating\n point numbers and expect the columns in your frame that have a\n numeric dtype to be matched. However, if those floating point\n numbers *are* strings, then you can do this.\n * This method has *a lot* of options. You are encouraged to experiment\n and play with this method to gain intuition about how it works.\n * When dict is used as the `to_replace` value, it is like\n key(s) in the dict are the to_replace part and\n value(s) in the dict are the value parameter.\n\n Examples\n --------\n\n **Scalar `to_replace` and `value`**\n\n >>> s = pd.Series([0, 1, 2, 3, 4])\n >>> s.replace(0, 5)\n 0 5\n 1 1\n 2 2\n 3 3\n 4 4\n dtype: int64\n\n >>> df = pd.DataFrame({'A': [0, 1, 2, 3, 4],\n ... 'B': [5, 6, 7, 8, 9],\n ... 'C': ['a', 'b', 'c', 'd', 'e']})\n >>> df.replace(0, 5)\n A B C\n 0 5 5 a\n 1 1 6 b\n 2 2 7 c\n 3 3 8 d\n 4 4 9 e\n\n **List-like `to_replace`**\n\n >>> df.replace([0, 1, 2, 3], 4)\n A B C\n 0 4 5 a\n 1 4 6 b\n 2 4 7 c\n 3 4 8 d\n 4 4 9 e\n\n >>> df.replace([0, 1, 2, 3], [4, 3, 2, 1])\n A B C\n 0 4 5 a\n 1 3 6 b\n 2 2 7 c\n 3 1 8 d\n 4 4 9 e\n\n >>> s.replace([1, 2], method='bfill')\n 0 0\n 1 3\n 2 3\n 3 3\n 4 4\n dtype: int64\n\n **dict-like `to_replace`**\n\n >>> df.replace({0: 10, 1: 100})\n A B C\n 0 10 5 a\n 1 100 6 b\n 2 2 7 c\n 3 3 8 d\n 4 4 9 e\n\n >>> df.replace({'A': 0, 'B': 5}, 100)\n A B C\n 0 100 100 a\n 1 1 6 b\n 2 2 7 c\n 3 3 8 d\n 4 4 9 e\n\n >>> df.replace({'A': {0: 100, 4: 400}})\n A B C\n 0 100 5 a\n 1 1 6 b\n 2 2 7 c\n 3 3 8 d\n 4 400 9 e\n\n **Regular expression `to_replace`**\n\n >>> df = pd.DataFrame({'A': ['bat', 'foo', 'bait'],\n ... 'B': ['abc', 'bar', 'xyz']})\n >>> df.replace(to_replace=r'^ba.$', value='new', regex=True)\n A B\n 0 new abc\n 1 foo new\n 2 bait xyz\n\n >>> df.replace({'A': r'^ba.$'}, {'A': 'new'}, regex=True)\n A B\n 0 new abc\n 1 foo bar\n 2 bait xyz\n\n >>> df.replace(regex=r'^ba.$', value='new')\n A B\n 0 new abc\n 1 foo new\n 2 bait xyz\n\n >>> df.replace(regex={r'^ba.$':'new', 'foo':'xyz'})\n A B\n 0 new abc\n 1 xyz new\n 2 bait xyz\n\n >>> df.replace(regex=[r'^ba.$', 'foo'], value='new')\n A B\n 0 new abc\n 1 new new\n 2 bait xyz\n\n Note that when replacing multiple ``bool`` or ``datetime64`` objects,\n the data types in the `to_replace` parameter must match the data\n type of the value being replaced:\n\n >>> df = pd.DataFrame({'A': [True, False, True],\n ... 'B': [False, True, False]})\n >>> df.replace({'a string': 'new value', True: False}) # raises\n Traceback (most recent call last):\n ...\n TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str'\n\n This raises a ``TypeError`` because one of the ``dict`` keys is not of\n the correct type for replacement.\n\n Compare the behavior of ``s.replace({'a': None})`` and\n ``s.replace('a', None)`` to understand the peculiarities\n of the `to_replace` parameter:\n\n >>> s = pd.Series([10, 'a', 'a', 'b', 'a'])\n\n When one uses a dict as the `to_replace` value, it is like the\n value(s) in the dict are equal to the `value` parameter.\n ``s.replace({'a': None})`` is equivalent to\n ``s.replace(to_replace={'a': None}, value=None, method=None)``:\n\n >>> s.replace({'a': None})\n 0 10\n 1 None\n 2 None\n 3 b\n 4 None\n dtype: object\n\n When ``value=None`` and `to_replace` is a scalar, list or\n tuple, `replace` uses the method parameter (default 'pad') to do the\n replacement. So this is why the 'a' values are being replaced by 10\n in rows 1 and 2 and 'b' in row 4 in this case.\n The command ``s.replace('a', None)`` is actually equivalent to\n ``s.replace(to_replace='a', value=None, method='pad')``:\n\n >>> s.replace('a', None)\n 0 10\n 1 10\n 2 10\n 3 b\n 4 b\n dtype: object\n \"\"\")\n\n @Appender(_shared_docs['replace'] % _shared_doc_kwargs)\n def replace(self, to_replace=None, value=None, inplace=False, limit=None,\n regex=False, method='pad'):\n inplace = validate_bool_kwarg(inplace, 'inplace')\n if not is_bool(regex) and to_replace is not None:\n raise AssertionError(\"'to_replace' must be 'None' if 'regex' is \"\n \"not a bool\")\n\n self._consolidate_inplace()\n\n if value is None:\n # passing a single value that is scalar like\n # when value is None (GH5319), for compat\n if not is_dict_like(to_replace) and not is_dict_like(regex):\n to_replace = [to_replace]\n\n if isinstance(to_replace, (tuple, list)):\n if isinstance(self, pd.DataFrame):\n return self.apply(_single_replace,\n args=(to_replace, method, inplace,\n limit))\n return _single_replace(self, to_replace, method, inplace,\n limit)\n\n if not is_dict_like(to_replace):\n if not is_dict_like(regex):\n raise TypeError('If \"to_replace\" and \"value\" are both None'\n ' and \"to_replace\" is not a list, then '\n 'regex must be a mapping')\n to_replace = regex\n regex = True\n\n items = list(compat.iteritems(to_replace))\n keys, values = lzip(*items) or ([], [])\n\n are_mappings = [is_dict_like(v) for v in values]\n\n if any(are_mappings):\n if not all(are_mappings):\n raise TypeError(\"If a nested mapping is passed, all values\"\n \" of the top level mapping must be \"\n \"mappings\")\n # passed a nested dict/Series\n to_rep_dict = {}\n value_dict = {}\n\n for k, v in items:\n keys, values = lzip(*v.items()) or ([], [])\n if set(keys) & set(values):\n raise ValueError(\"Replacement not allowed with \"\n \"overlapping keys and values\")\n to_rep_dict[k] = list(keys)\n value_dict[k] = list(values)\n\n to_replace, value = to_rep_dict, value_dict\n else:\n to_replace, value = keys, values\n\n return self.replace(to_replace, value, inplace=inplace,\n limit=limit, regex=regex)\n else:\n\n # need a non-zero len on all axes\n for a in self._AXIS_ORDERS:\n if not len(self._get_axis(a)):\n return self\n\n new_data = self._data\n if is_dict_like(to_replace):\n if is_dict_like(value): # {'A' : NA} -> {'A' : 0}\n res = self if inplace else self.copy()\n for c, src in compat.iteritems(to_replace):\n if c in value and c in self:\n # object conversion is handled in\n # series.replace which is called recursivelly\n res[c] = res[c].replace(to_replace=src,\n value=value[c],\n inplace=False,\n regex=regex)\n return None if inplace else res\n\n # {'A': NA} -> 0\n elif not is_list_like(value):\n keys = [(k, src) for k, src in compat.iteritems(to_replace)\n if k in self]\n keys_len = len(keys) - 1\n for i, (k, src) in enumerate(keys):\n convert = i == keys_len\n new_data = new_data.replace(to_replace=src,\n value=value,\n filter=[k],\n inplace=inplace,\n regex=regex,\n convert=convert)\n else:\n raise TypeError('value argument must be scalar, dict, or '\n 'Series')\n\n elif is_list_like(to_replace): # [NA, ''] -> [0, 'missing']\n if is_list_like(value):\n if len(to_replace) != len(value):\n raise ValueError('Replacement lists must match '\n 'in length. Expecting %d got %d ' %\n (len(to_replace), len(value)))\n\n new_data = self._data.replace_list(src_list=to_replace,\n dest_list=value,\n inplace=inplace,\n regex=regex)\n\n else: # [NA, ''] -> 0\n new_data = self._data.replace(to_replace=to_replace,\n value=value, inplace=inplace,\n regex=regex)\n elif to_replace is None:\n if not (is_re_compilable(regex) or\n is_list_like(regex) or is_dict_like(regex)):\n raise TypeError(\"'regex' must be a string or a compiled \"\n \"regular expression or a list or dict of \"\n \"strings or regular expressions, you \"\n \"passed a\"\n \" {0!r}\".format(type(regex).__name__))\n return self.replace(regex, value, inplace=inplace, limit=limit,\n regex=True)\n else:\n\n # dest iterable dict-like\n if is_dict_like(value): # NA -> {'A' : 0, 'B' : -1}\n new_data = self._data\n\n for k, v in compat.iteritems(value):\n if k in self:\n new_data = new_data.replace(to_replace=to_replace,\n value=v, filter=[k],\n inplace=inplace,\n regex=regex)\n\n elif not is_list_like(value): # NA -> 0\n new_data = self._data.replace(to_replace=to_replace,\n value=value, inplace=inplace,\n regex=regex)\n else:\n msg = ('Invalid \"to_replace\" type: '\n '{0!r}').format(type(to_replace).__name__)\n raise TypeError(msg) # pragma: no cover\n\n if inplace:\n self._update_inplace(new_data)\n else:\n return self._constructor(new_data).__finalize__(self)\n\n _shared_docs['interpolate'] = \"\"\"\n Please note that only ``method='linear'`` is supported for\n DataFrames/Series with a MultiIndex.\n\n Parameters\n ----------\n method : {'linear', 'time', 'index', 'values', 'nearest', 'zero',\n 'slinear', 'quadratic', 'cubic', 'barycentric', 'krogh',\n 'polynomial', 'spline', 'piecewise_polynomial',\n 'from_derivatives', 'pchip', 'akima'}\n\n * 'linear': ignore the index and treat the values as equally\n spaced. This is the only method supported on MultiIndexes.\n default\n * 'time': interpolation works on daily and higher resolution\n data to interpolate given length of interval\n * 'index', 'values': use the actual numerical values of the index\n * 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',\n 'barycentric', 'polynomial' is passed to\n :class:`scipy.interpolate.interp1d`. Both 'polynomial' and\n 'spline' require that you also specify an `order` (int),\n e.g. ``df.interpolate(method='polynomial', order=4)``.\n These use the actual numerical values of the index.\n * 'krogh', 'piecewise_polynomial', 'spline', 'pchip' and 'akima'\n are all wrappers around the scipy interpolation methods of\n similar names. These use the actual numerical values of the\n index. For more information on their behavior, see the\n `scipy documentation\n <http://docs.scipy.org/doc/scipy/reference/interpolate.html#univariate-interpolation>`__\n and `tutorial documentation\n <http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html>`__\n * 'from_derivatives' refers to\n :meth:`scipy.interpolate.BPoly.from_derivatives` which\n replaces 'piecewise_polynomial' interpolation method in\n scipy 0.18\n\n .. versionadded:: 0.18.1\n\n Added support for the 'akima' method.\n Added interpolate method 'from_derivatives' which replaces\n 'piecewise_polynomial' in scipy 0.18; backwards-compatible with\n scipy < 0.18\n\n axis : {0, 1}, default 0\n * 0: fill column-by-column\n * 1: fill row-by-row\n limit : int, default None.\n Maximum number of consecutive NaNs to fill. Must be greater than 0.\n limit_direction : {'forward', 'backward', 'both'}, default 'forward'\n limit_area : {'inside', 'outside'}, default None\n * None: (default) no fill restriction\n * 'inside' Only fill NaNs surrounded by valid values (interpolate).\n * 'outside' Only fill NaNs outside valid values (extrapolate).\n\n If limit is specified, consecutive NaNs will be filled in this\n direction.\n\n .. versionadded:: 0.21.0\n inplace : bool, default False\n Update the NDFrame in place if possible.\n downcast : optional, 'infer' or None, defaults to None\n Downcast dtypes if possible.\n kwargs : keyword arguments to pass on to the interpolating function.\n\n Returns\n -------\n Series or DataFrame of same shape interpolated at the NaNs\n\n See Also\n --------\n reindex, replace, fillna\n\n Examples\n --------\n\n Filling in NaNs\n\n >>> s = pd.Series([0, 1, np.nan, 3])\n >>> s.interpolate()\n 0 0\n 1 1\n 2 2\n 3 3\n dtype: float64\n\n \"\"\"\n\n @Appender(_shared_docs['interpolate'] % _shared_doc_kwargs)\n def interpolate(self, method='linear', axis=0, limit=None, inplace=False,\n limit_direction='forward', limit_area=None,\n downcast=None, **kwargs):\n \"\"\"\n Interpolate values according to different methods.\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n\n if self.ndim > 2:\n raise NotImplementedError(\"Interpolate has not been implemented \"\n \"on Panel and Panel 4D objects.\")\n\n if axis == 0:\n ax = self._info_axis_name\n _maybe_transposed_self = self\n elif axis == 1:\n _maybe_transposed_self = self.T\n ax = 1\n else:\n _maybe_transposed_self = self\n ax = _maybe_transposed_self._get_axis_number(ax)\n\n if _maybe_transposed_self.ndim == 2:\n alt_ax = 1 - ax\n else:\n alt_ax = ax\n\n if (isinstance(_maybe_transposed_self.index, MultiIndex) and\n method != 'linear'):\n raise ValueError(\"Only `method=linear` interpolation is supported \"\n \"on MultiIndexes.\")\n\n if _maybe_transposed_self._data.get_dtype_counts().get(\n 'object') == len(_maybe_transposed_self.T):\n raise TypeError(\"Cannot interpolate with all NaNs.\")\n\n # create/use the index\n if method == 'linear':\n # prior default\n index = np.arange(len(_maybe_transposed_self._get_axis(alt_ax)))\n else:\n index = _maybe_transposed_self._get_axis(alt_ax)\n\n if isna(index).any():\n raise NotImplementedError(\"Interpolation with NaNs in the index \"\n \"has not been implemented. Try filling \"\n \"those NaNs before interpolating.\")\n data = _maybe_transposed_self._data\n new_data = data.interpolate(method=method, axis=ax, index=index,\n values=_maybe_transposed_self, limit=limit,\n limit_direction=limit_direction,\n limit_area=limit_area,\n inplace=inplace, downcast=downcast,\n **kwargs)\n\n if inplace:\n if axis == 1:\n new_data = self._constructor(new_data).T._data\n self._update_inplace(new_data)\n else:\n res = self._constructor(new_data).__finalize__(self)\n if axis == 1:\n res = res.T\n return res\n\n # ----------------------------------------------------------------------\n # Timeseries methods Methods\n\n def asof(self, where, subset=None):\n \"\"\"\n The last row without any NaN is taken (or the last row without\n NaN considering only the subset of columns in the case of a DataFrame)\n\n .. versionadded:: 0.19.0 For DataFrame\n\n If there is no good value, NaN is returned for a Series\n a Series of NaN values for a DataFrame\n\n Parameters\n ----------\n where : date or array of dates\n subset : string or list of strings, default None\n if not None use these columns for NaN propagation\n\n Notes\n -----\n Dates are assumed to be sorted\n Raises if this is not the case\n\n Returns\n -------\n where is scalar\n\n - value or NaN if input is Series\n - Series if input is DataFrame\n\n where is Index: same shape object as input\n\n See Also\n --------\n merge_asof\n\n \"\"\"\n\n if isinstance(where, compat.string_types):\n from pandas import to_datetime\n where = to_datetime(where)\n\n if not self.index.is_monotonic:\n raise ValueError(\"asof requires a sorted index\")\n\n is_series = isinstance(self, ABCSeries)\n if is_series:\n if subset is not None:\n raise ValueError(\"subset is not valid for Series\")\n elif self.ndim > 2:\n raise NotImplementedError(\"asof is not implemented \"\n \"for {type}\".format(type=type(self)))\n else:\n if subset is None:\n subset = self.columns\n if not is_list_like(subset):\n subset = [subset]\n\n is_list = is_list_like(where)\n if not is_list:\n start = self.index[0]\n if isinstance(self.index, PeriodIndex):\n where = Period(where, freq=self.index.freq).ordinal\n start = start.ordinal\n\n if where < start:\n if not is_series:\n from pandas import Series\n return Series(index=self.columns, name=where)\n return np.nan\n\n # It's always much faster to use a *while* loop here for\n # Series than pre-computing all the NAs. However a\n # *while* loop is extremely expensive for DataFrame\n # so we later pre-compute all the NAs and use the same\n # code path whether *where* is a scalar or list.\n # See PR: https://github.com/pandas-dev/pandas/pull/14476\n if is_series:\n loc = self.index.searchsorted(where, side='right')\n if loc > 0:\n loc -= 1\n\n values = self._values\n while loc > 0 and isna(values[loc]):\n loc -= 1\n return values[loc]\n\n if not isinstance(where, Index):\n where = Index(where) if is_list else Index([where])\n\n nulls = self.isna() if is_series else self[subset].isna().any(1)\n if nulls.all():\n if is_series:\n return self._constructor(np.nan, index=where, name=self.name)\n elif is_list:\n from pandas import DataFrame\n return DataFrame(np.nan, index=where, columns=self.columns)\n else:\n from pandas import Series\n return Series(np.nan, index=self.columns, name=where[0])\n\n locs = self.index.asof_locs(where, ~(nulls.values))\n\n # mask the missing\n missing = locs == -1\n data = self.take(locs, is_copy=False)\n data.index = where\n data.loc[missing] = np.nan\n return data if is_list else data.iloc[-1]\n\n # ----------------------------------------------------------------------\n # Action Methods\n\n _shared_docs['isna'] = \"\"\"\n Detect missing values.\n\n Return a boolean same-sized object indicating if the values are NA.\n NA values, such as None or :attr:`numpy.NaN`, gets mapped to True\n values.\n Everything else gets mapped to False values. Characters such as empty\n strings ``''`` or :attr:`numpy.inf` are not considered NA values\n (unless you set ``pandas.options.mode.use_inf_as_na = True``).\n\n Returns\n -------\n %(klass)s\n Mask of bool values for each element in %(klass)s that\n indicates whether an element is not an NA value.\n\n See Also\n --------\n %(klass)s.isnull : alias of isna\n %(klass)s.notna : boolean inverse of isna\n %(klass)s.dropna : omit axes labels with missing values\n isna : top-level isna\n\n Examples\n --------\n Show which entries in a DataFrame are NA.\n\n >>> df = pd.DataFrame({'age': [5, 6, np.NaN],\n ... 'born': [pd.NaT, pd.Timestamp('1939-05-27'),\n ... pd.Timestamp('1940-04-25')],\n ... 'name': ['Alfred', 'Batman', ''],\n ... 'toy': [None, 'Batmobile', 'Joker']})\n >>> df\n age born name toy\n 0 5.0 NaT Alfred None\n 1 6.0 1939-05-27 Batman Batmobile\n 2 NaN 1940-04-25 Joker\n\n >>> df.isna()\n age born name toy\n 0 False True False True\n 1 False False False False\n 2 True False False False\n\n Show which entries in a Series are NA.\n\n >>> ser = pd.Series([5, 6, np.NaN])\n >>> ser\n 0 5.0\n 1 6.0\n 2 NaN\n dtype: float64\n\n >>> ser.isna()\n 0 False\n 1 False\n 2 True\n dtype: bool\n \"\"\"\n\n @Appender(_shared_docs['isna'] % _shared_doc_kwargs)\n def isna(self):\n return isna(self).__finalize__(self)\n\n @Appender(_shared_docs['isna'] % _shared_doc_kwargs)\n def isnull(self):\n return isna(self).__finalize__(self)\n\n _shared_docs['notna'] = \"\"\"\n Detect existing (non-missing) values.\n\n Return a boolean same-sized object indicating if the values are not NA.\n Non-missing values get mapped to True. Characters such as empty\n strings ``''`` or :attr:`numpy.inf` are not considered NA values\n (unless you set ``pandas.options.mode.use_inf_as_na = True``).\n NA values, such as None or :attr:`numpy.NaN`, get mapped to False\n values.\n\n Returns\n -------\n %(klass)s\n Mask of bool values for each element in %(klass)s that\n indicates whether an element is not an NA value.\n\n See Also\n --------\n %(klass)s.notnull : alias of notna\n %(klass)s.isna : boolean inverse of notna\n %(klass)s.dropna : omit axes labels with missing values\n notna : top-level notna\n\n Examples\n --------\n Show which entries in a DataFrame are not NA.\n\n >>> df = pd.DataFrame({'age': [5, 6, np.NaN],\n ... 'born': [pd.NaT, pd.Timestamp('1939-05-27'),\n ... pd.Timestamp('1940-04-25')],\n ... 'name': ['Alfred', 'Batman', ''],\n ... 'toy': [None, 'Batmobile', 'Joker']})\n >>> df\n age born name toy\n 0 5.0 NaT Alfred None\n 1 6.0 1939-05-27 Batman Batmobile\n 2 NaN 1940-04-25 Joker\n\n >>> df.notna()\n age born name toy\n 0 True False True False\n 1 True True True True\n 2 False True True True\n\n Show which entries in a Series are not NA.\n\n >>> ser = pd.Series([5, 6, np.NaN])\n >>> ser\n 0 5.0\n 1 6.0\n 2 NaN\n dtype: float64\n\n >>> ser.notna()\n 0 True\n 1 True\n 2 False\n dtype: bool\n \"\"\"\n\n @Appender(_shared_docs['notna'] % _shared_doc_kwargs)\n def notna(self):\n return notna(self).__finalize__(self)\n\n @Appender(_shared_docs['notna'] % _shared_doc_kwargs)\n def notnull(self):\n return notna(self).__finalize__(self)\n\n def _clip_with_scalar(self, lower, upper, inplace=False):\n if ((lower is not None and np.any(isna(lower))) or\n (upper is not None and np.any(isna(upper)))):\n raise ValueError(\"Cannot use an NA value as a clip threshold\")\n\n result = self.values\n mask = isna(result)\n\n with np.errstate(all='ignore'):\n if upper is not None:\n result = np.where(result >= upper, upper, result)\n if lower is not None:\n result = np.where(result <= lower, lower, result)\n if np.any(mask):\n result[mask] = np.nan\n\n axes_dict = self._construct_axes_dict()\n result = self._constructor(result, **axes_dict).__finalize__(self)\n\n if inplace:\n self._update_inplace(result)\n else:\n return result\n\n def _clip_with_one_bound(self, threshold, method, axis, inplace):\n\n inplace = validate_bool_kwarg(inplace, 'inplace')\n if axis is not None:\n axis = self._get_axis_number(axis)\n\n # method is self.le for upper bound and self.ge for lower bound\n if is_scalar(threshold) and is_number(threshold):\n if method.__name__ == 'le':\n return self._clip_with_scalar(None, threshold, inplace=inplace)\n return self._clip_with_scalar(threshold, None, inplace=inplace)\n\n subset = method(threshold, axis=axis) | isna(self)\n\n # GH #15390\n # In order for where method to work, the threshold must\n # be transformed to NDFrame from other array like structure.\n if (not isinstance(threshold, ABCSeries)) and is_list_like(threshold):\n if isinstance(self, ABCSeries):\n threshold = pd.Series(threshold, index=self.index)\n else:\n threshold = _align_method_FRAME(self, np.asarray(threshold),\n axis)\n return self.where(subset, threshold, axis=axis, inplace=inplace)\n\n def clip(self, lower=None, upper=None, axis=None, inplace=False,\n *args, **kwargs):\n \"\"\"\n Trim values at input threshold(s).\n\n Assigns values outside boundary to boundary values. Thresholds\n can be singular values or array like, and in the latter case\n the clipping is performed element-wise in the specified axis.\n\n Parameters\n ----------\n lower : float or array_like, default None\n Minimum threshold value. All values below this\n threshold will be set to it.\n upper : float or array_like, default None\n Maximum threshold value. All values above this\n threshold will be set to it.\n axis : int or string axis name, optional\n Align object with lower and upper along the given axis.\n inplace : boolean, default False\n Whether to perform the operation in place on the data.\n\n .. versionadded:: 0.21.0\n *args, **kwargs\n Additional keywords have no effect but might be accepted\n for compatibility with numpy.\n\n See Also\n --------\n clip_lower : Clip values below specified threshold(s).\n clip_upper : Clip values above specified threshold(s).\n\n Returns\n -------\n Series or DataFrame\n Same type as calling object with the values outside the\n clip boundaries replaced\n\n Examples\n --------\n >>> data = {'col_0': [9, -3, 0, -1, 5], 'col_1': [-2, -7, 6, 8, -5]}\n >>> df = pd.DataFrame(data)\n >>> df\n col_0 col_1\n 0 9 -2\n 1 -3 -7\n 2 0 6\n 3 -1 8\n 4 5 -5\n\n Clips per column using lower and upper thresholds:\n\n >>> df.clip(-4, 6)\n col_0 col_1\n 0 6 -2\n 1 -3 -4\n 2 0 6\n 3 -1 6\n 4 5 -4\n\n Clips using specific lower and upper thresholds per column element:\n\n >>> t = pd.Series([2, -4, -1, 6, 3])\n >>> t\n 0 2\n 1 -4\n 2 -1\n 3 6\n 4 3\n dtype: int64\n\n >>> df.clip(t, t + 4, axis=0)\n col_0 col_1\n 0 6 2\n 1 -3 -4\n 2 0 3\n 3 6 8\n 4 5 3\n \"\"\"\n if isinstance(self, ABCPanel):\n raise NotImplementedError(\"clip is not supported yet for panels\")\n\n inplace = validate_bool_kwarg(inplace, 'inplace')\n\n axis = nv.validate_clip_with_axis(axis, args, kwargs)\n if axis is not None:\n axis = self._get_axis_number(axis)\n\n # GH 17276\n # numpy doesn't like NaN as a clip value\n # so ignore\n # GH 19992\n # numpy doesn't drop a list-like bound containing NaN\n if not is_list_like(lower) and np.any(pd.isnull(lower)):\n lower = None\n if not is_list_like(upper) and np.any(pd.isnull(upper)):\n upper = None\n\n # GH 2747 (arguments were reversed)\n if lower is not None and upper is not None:\n if is_scalar(lower) and is_scalar(upper):\n lower, upper = min(lower, upper), max(lower, upper)\n\n # fast-path for scalars\n if ((lower is None or (is_scalar(lower) and is_number(lower))) and\n (upper is None or (is_scalar(upper) and is_number(upper)))):\n return self._clip_with_scalar(lower, upper, inplace=inplace)\n\n result = self\n if lower is not None:\n result = result.clip_lower(lower, axis, inplace=inplace)\n if upper is not None:\n if inplace:\n result = self\n result = result.clip_upper(upper, axis, inplace=inplace)\n\n return result\n\n def clip_upper(self, threshold, axis=None, inplace=False):\n \"\"\"\n Trim values above a given threshold.\n\n Elements above the `threshold` will be changed to match the\n `threshold` value(s). Threshold can be a single value or an array,\n in the latter case it performs the truncation element-wise.\n\n Parameters\n ----------\n threshold : numeric or array-like\n Maximum value allowed. All values above threshold will be set to\n this value.\n\n * float : every value is compared to `threshold`.\n * array-like : The shape of `threshold` should match the object\n it's compared to. When `self` is a Series, `threshold` should be\n the length. When `self` is a DataFrame, `threshold` should 2-D\n and the same shape as `self` for ``axis=None``, or 1-D and the\n same length as the axis being compared.\n\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Align object with `threshold` along the given axis.\n inplace : boolean, default False\n Whether to perform the operation in place on the data.\n\n .. versionadded:: 0.21.0\n\n Returns\n -------\n clipped\n Original data with values trimmed.\n\n See Also\n --------\n DataFrame.clip : General purpose method to trim DataFrame values to\n given threshold(s)\n DataFrame.clip_lower : Trim DataFrame values below given\n threshold(s)\n Series.clip : General purpose method to trim Series values to given\n threshold(s)\n Series.clip_lower : Trim Series values below given threshold(s)\n\n Examples\n --------\n >>> s = pd.Series([1, 2, 3, 4, 5])\n >>> s\n 0 1\n 1 2\n 2 3\n 3 4\n 4 5\n dtype: int64\n\n >>> s.clip_upper(3)\n 0 1\n 1 2\n 2 3\n 3 3\n 4 3\n dtype: int64\n\n >>> t = [5, 4, 3, 2, 1]\n >>> t\n [5, 4, 3, 2, 1]\n\n >>> s.clip_upper(t)\n 0 1\n 1 2\n 2 3\n 3 2\n 4 1\n dtype: int64\n \"\"\"\n return self._clip_with_one_bound(threshold, method=self.le,\n axis=axis, inplace=inplace)\n\n def clip_lower(self, threshold, axis=None, inplace=False):\n \"\"\"\n Trim values below a given threshold.\n\n Elements below the `threshold` will be changed to match the\n `threshold` value(s). Threshold can be a single value or an array,\n in the latter case it performs the truncation element-wise.\n\n Parameters\n ----------\n threshold : numeric or array-like\n Minimum value allowed. All values below threshold will be set to\n this value.\n\n * float : every value is compared to `threshold`.\n * array-like : The shape of `threshold` should match the object\n it's compared to. When `self` is a Series, `threshold` should be\n the length. When `self` is a DataFrame, `threshold` should 2-D\n and the same shape as `self` for ``axis=None``, or 1-D and the\n same length as the axis being compared.\n\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Align `self` with `threshold` along the given axis.\n\n inplace : boolean, default False\n Whether to perform the operation in place on the data.\n\n .. versionadded:: 0.21.0\n\n Returns\n -------\n clipped\n Original data with values trimmed.\n\n See Also\n --------\n DataFrame.clip : General purpose method to trim DataFrame values to\n given threshold(s)\n DataFrame.clip_upper : Trim DataFrame values above given\n threshold(s)\n Series.clip : General purpose method to trim Series values to given\n threshold(s)\n Series.clip_upper : Trim Series values above given threshold(s)\n\n Examples\n --------\n\n Series single threshold clipping:\n\n >>> s = pd.Series([5, 6, 7, 8, 9])\n >>> s.clip_lower(8)\n 0 8\n 1 8\n 2 8\n 3 8\n 4 9\n dtype: int64\n\n Series clipping element-wise using an array of thresholds. `threshold`\n should be the same length as the Series.\n\n >>> elemwise_thresholds = [4, 8, 7, 2, 5]\n >>> s.clip_lower(elemwise_thresholds)\n 0 5\n 1 8\n 2 7\n 3 8\n 4 9\n dtype: int64\n\n DataFrames can be compared to a scalar.\n\n >>> df = pd.DataFrame({\"A\": [1, 3, 5], \"B\": [2, 4, 6]})\n >>> df\n A B\n 0 1 2\n 1 3 4\n 2 5 6\n\n >>> df.clip_lower(3)\n A B\n 0 3 3\n 1 3 4\n 2 5 6\n\n Or to an array of values. By default, `threshold` should be the same\n shape as the DataFrame.\n\n >>> df.clip_lower(np.array([[3, 4], [2, 2], [6, 2]]))\n A B\n 0 3 4\n 1 3 4\n 2 6 6\n\n Control how `threshold` is broadcast with `axis`. In this case\n `threshold` should be the same length as the axis specified by\n `axis`.\n\n >>> df.clip_lower([3, 3, 5], axis='index')\n A B\n 0 3 3\n 1 3 4\n 2 5 6\n\n >>> df.clip_lower([4, 5], axis='columns')\n A B\n 0 4 5\n 1 4 5\n 2 5 6\n \"\"\"\n return self._clip_with_one_bound(threshold, method=self.ge,\n axis=axis, inplace=inplace)\n\n def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,\n group_keys=True, squeeze=False, observed=False, **kwargs):\n \"\"\"\n Group series using mapper (dict or key function, apply given function\n to group, return result as series) or by a series of columns.\n\n Parameters\n ----------\n by : mapping, function, label, or list of labels\n Used to determine the groups for the groupby.\n If ``by`` is a function, it's called on each value of the object's\n index. If a dict or Series is passed, the Series or dict VALUES\n will be used to determine the groups (the Series' values are first\n aligned; see ``.align()`` method). If an ndarray is passed, the\n values are used as-is determine the groups. A label or list of\n labels may be passed to group by the columns in ``self``. Notice\n that a tuple is interpreted a (single) key.\n axis : int, default 0\n level : int, level name, or sequence of such, default None\n If the axis is a MultiIndex (hierarchical), group by a particular\n level or levels\n as_index : boolean, default True\n For aggregated output, return object with group labels as the\n index. Only relevant for DataFrame input. as_index=False is\n effectively \"SQL-style\" grouped output\n sort : boolean, default True\n Sort group keys. Get better performance by turning this off.\n Note this does not influence the order of observations within each\n group. groupby preserves the order of rows within each group.\n group_keys : boolean, default True\n When calling apply, add group keys to index to identify pieces\n squeeze : boolean, default False\n reduce the dimensionality of the return type if possible,\n otherwise return a consistent type\n observed : boolean, default False\n This only applies if any of the groupers are Categoricals\n If True: only show observed values for categorical groupers.\n If False: show all values for categorical groupers.\n\n .. versionadded:: 0.23.0\n\n Returns\n -------\n GroupBy object\n\n Examples\n --------\n DataFrame results\n\n >>> data.groupby(func, axis=0).mean()\n >>> data.groupby(['col1', 'col2'])['col3'].mean()\n\n DataFrame with hierarchical index\n\n >>> data.groupby(['col1', 'col2']).mean()\n\n Notes\n -----\n See the `user guide\n <http://pandas.pydata.org/pandas-docs/stable/groupby.html>`_ for more.\n\n See also\n --------\n resample : Convenience method for frequency conversion and resampling\n of time series.\n \"\"\"\n from pandas.core.groupby.groupby import groupby\n\n if level is None and by is None:\n raise TypeError(\"You have to supply one of 'by' and 'level'\")\n axis = self._get_axis_number(axis)\n return groupby(self, by=by, axis=axis, level=level, as_index=as_index,\n sort=sort, group_keys=group_keys, squeeze=squeeze,\n observed=observed, **kwargs)\n\n def asfreq(self, freq, method=None, how=None, normalize=False,\n fill_value=None):\n \"\"\"\n Convert TimeSeries to specified frequency.\n\n Optionally provide filling method to pad/backfill missing values.\n\n Returns the original data conformed to a new index with the specified\n frequency. ``resample`` is more appropriate if an operation, such as\n summarization, is necessary to represent the data at the new frequency.\n\n Parameters\n ----------\n freq : DateOffset object, or string\n method : {'backfill'/'bfill', 'pad'/'ffill'}, default None\n Method to use for filling holes in reindexed Series (note this\n does not fill NaNs that already were present):\n\n * 'pad' / 'ffill': propagate last valid observation forward to next\n valid\n * 'backfill' / 'bfill': use NEXT valid observation to fill\n how : {'start', 'end'}, default end\n For PeriodIndex only, see PeriodIndex.asfreq\n normalize : bool, default False\n Whether to reset output index to midnight\n fill_value: scalar, optional\n Value to use for missing values, applied during upsampling (note\n this does not fill NaNs that already were present).\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n converted : same type as caller\n\n Examples\n --------\n\n Start by creating a series with 4 one minute timestamps.\n\n >>> index = pd.date_range('1/1/2000', periods=4, freq='T')\n >>> series = pd.Series([0.0, None, 2.0, 3.0], index=index)\n >>> df = pd.DataFrame({'s':series})\n >>> df\n s\n 2000-01-01 00:00:00 0.0\n 2000-01-01 00:01:00 NaN\n 2000-01-01 00:02:00 2.0\n 2000-01-01 00:03:00 3.0\n\n Upsample the series into 30 second bins.\n\n >>> df.asfreq(freq='30S')\n s\n 2000-01-01 00:00:00 0.0\n 2000-01-01 00:00:30 NaN\n 2000-01-01 00:01:00 NaN\n 2000-01-01 00:01:30 NaN\n 2000-01-01 00:02:00 2.0\n 2000-01-01 00:02:30 NaN\n 2000-01-01 00:03:00 3.0\n\n Upsample again, providing a ``fill value``.\n\n >>> df.asfreq(freq='30S', fill_value=9.0)\n s\n 2000-01-01 00:00:00 0.0\n 2000-01-01 00:00:30 9.0\n 2000-01-01 00:01:00 NaN\n 2000-01-01 00:01:30 9.0\n 2000-01-01 00:02:00 2.0\n 2000-01-01 00:02:30 9.0\n 2000-01-01 00:03:00 3.0\n\n Upsample again, providing a ``method``.\n\n >>> df.asfreq(freq='30S', method='bfill')\n s\n 2000-01-01 00:00:00 0.0\n 2000-01-01 00:00:30 NaN\n 2000-01-01 00:01:00 NaN\n 2000-01-01 00:01:30 2.0\n 2000-01-01 00:02:00 2.0\n 2000-01-01 00:02:30 3.0\n 2000-01-01 00:03:00 3.0\n\n See Also\n --------\n reindex\n\n Notes\n -----\n To learn more about the frequency strings, please see `this link\n <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.\n \"\"\"\n from pandas.core.resample import asfreq\n return asfreq(self, freq, method=method, how=how, normalize=normalize,\n fill_value=fill_value)\n\n def at_time(self, time, asof=False):\n \"\"\"\n Select values at particular time of day (e.g. 9:30AM).\n\n Raises\n ------\n TypeError\n If the index is not a :class:`DatetimeIndex`\n\n Parameters\n ----------\n time : datetime.time or string\n\n Returns\n -------\n values_at_time : same type as caller\n\n Examples\n --------\n >>> i = pd.date_range('2018-04-09', periods=4, freq='12H')\n >>> ts = pd.DataFrame({'A': [1,2,3,4]}, index=i)\n >>> ts\n A\n 2018-04-09 00:00:00 1\n 2018-04-09 12:00:00 2\n 2018-04-10 00:00:00 3\n 2018-04-10 12:00:00 4\n\n >>> ts.at_time('12:00')\n A\n 2018-04-09 12:00:00 2\n 2018-04-10 12:00:00 4\n\n See Also\n --------\n between_time : Select values between particular times of the day\n first : Select initial periods of time series based on a date offset\n last : Select final periods of time series based on a date offset\n DatetimeIndex.indexer_at_time : Get just the index locations for\n values at particular time of the day\n \"\"\"\n try:\n indexer = self.index.indexer_at_time(time, asof=asof)\n return self._take(indexer)\n except AttributeError:\n raise TypeError('Index must be DatetimeIndex')\n\n def between_time(self, start_time, end_time, include_start=True,\n include_end=True):\n \"\"\"\n Select values between particular times of the day (e.g., 9:00-9:30 AM).\n\n By setting ``start_time`` to be later than ``end_time``,\n you can get the times that are *not* between the two times.\n\n Raises\n ------\n TypeError\n If the index is not a :class:`DatetimeIndex`\n\n Parameters\n ----------\n start_time : datetime.time or string\n end_time : datetime.time or string\n include_start : boolean, default True\n include_end : boolean, default True\n\n Returns\n -------\n values_between_time : same type as caller\n\n Examples\n --------\n >>> i = pd.date_range('2018-04-09', periods=4, freq='1D20min')\n >>> ts = pd.DataFrame({'A': [1,2,3,4]}, index=i)\n >>> ts\n A\n 2018-04-09 00:00:00 1\n 2018-04-10 00:20:00 2\n 2018-04-11 00:40:00 3\n 2018-04-12 01:00:00 4\n\n >>> ts.between_time('0:15', '0:45')\n A\n 2018-04-10 00:20:00 2\n 2018-04-11 00:40:00 3\n\n You get the times that are *not* between two times by setting\n ``start_time`` later than ``end_time``:\n\n >>> ts.between_time('0:45', '0:15')\n A\n 2018-04-09 00:00:00 1\n 2018-04-12 01:00:00 4\n\n See Also\n --------\n at_time : Select values at a particular time of the day\n first : Select initial periods of time series based on a date offset\n last : Select final periods of time series based on a date offset\n DatetimeIndex.indexer_between_time : Get just the index locations for\n values between particular times of the day\n \"\"\"\n try:\n indexer = self.index.indexer_between_time(\n start_time, end_time, include_start=include_start,\n include_end=include_end)\n return self._take(indexer)\n except AttributeError:\n raise TypeError('Index must be DatetimeIndex')\n\n def resample(self, rule, how=None, axis=0, fill_method=None, closed=None,\n label=None, convention='start', kind=None, loffset=None,\n limit=None, base=0, on=None, level=None):\n \"\"\"\n Convenience method for frequency conversion and resampling of time\n series. Object must have a datetime-like index (DatetimeIndex,\n PeriodIndex, or TimedeltaIndex), or pass datetime-like values\n to the on or level keyword.\n\n Parameters\n ----------\n rule : string\n the offset string or object representing target conversion\n axis : int, optional, default 0\n closed : {'right', 'left'}\n Which side of bin interval is closed. The default is 'left'\n for all frequency offsets except for 'M', 'A', 'Q', 'BM',\n 'BA', 'BQ', and 'W' which all have a default of 'right'.\n label : {'right', 'left'}\n Which bin edge label to label bucket with. The default is 'left'\n for all frequency offsets except for 'M', 'A', 'Q', 'BM',\n 'BA', 'BQ', and 'W' which all have a default of 'right'.\n convention : {'start', 'end', 's', 'e'}\n For PeriodIndex only, controls whether to use the start or end of\n `rule`\n kind: {'timestamp', 'period'}, optional\n Pass 'timestamp' to convert the resulting index to a\n ``DateTimeIndex`` or 'period' to convert it to a ``PeriodIndex``.\n By default the input representation is retained.\n loffset : timedelta\n Adjust the resampled time labels\n base : int, default 0\n For frequencies that evenly subdivide 1 day, the \"origin\" of the\n aggregated intervals. For example, for '5min' frequency, base could\n range from 0 through 4. Defaults to 0\n on : string, optional\n For a DataFrame, column to use instead of index for resampling.\n Column must be datetime-like.\n\n .. versionadded:: 0.19.0\n\n level : string or int, optional\n For a MultiIndex, level (name or number) to use for\n resampling. Level must be datetime-like.\n\n .. versionadded:: 0.19.0\n\n Returns\n -------\n Resampler object\n\n Notes\n -----\n See the `user guide\n <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#resampling>`_\n for more.\n\n To learn more about the offset strings, please see `this link\n <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.\n\n Examples\n --------\n\n Start by creating a series with 9 one minute timestamps.\n\n >>> index = pd.date_range('1/1/2000', periods=9, freq='T')\n >>> series = pd.Series(range(9), index=index)\n >>> series\n 2000-01-01 00:00:00 0\n 2000-01-01 00:01:00 1\n 2000-01-01 00:02:00 2\n 2000-01-01 00:03:00 3\n 2000-01-01 00:04:00 4\n 2000-01-01 00:05:00 5\n 2000-01-01 00:06:00 6\n 2000-01-01 00:07:00 7\n 2000-01-01 00:08:00 8\n Freq: T, dtype: int64\n\n Downsample the series into 3 minute bins and sum the values\n of the timestamps falling into a bin.\n\n >>> series.resample('3T').sum()\n 2000-01-01 00:00:00 3\n 2000-01-01 00:03:00 12\n 2000-01-01 00:06:00 21\n Freq: 3T, dtype: int64\n\n Downsample the series into 3 minute bins as above, but label each\n bin using the right edge instead of the left. Please note that the\n value in the bucket used as the label is not included in the bucket,\n which it labels. For example, in the original series the\n bucket ``2000-01-01 00:03:00`` contains the value 3, but the summed\n value in the resampled bucket with the label ``2000-01-01 00:03:00``\n does not include 3 (if it did, the summed value would be 6, not 3).\n To include this value close the right side of the bin interval as\n illustrated in the example below this one.\n\n >>> series.resample('3T', label='right').sum()\n 2000-01-01 00:03:00 3\n 2000-01-01 00:06:00 12\n 2000-01-01 00:09:00 21\n Freq: 3T, dtype: int64\n\n Downsample the series into 3 minute bins as above, but close the right\n side of the bin interval.\n\n >>> series.resample('3T', label='right', closed='right').sum()\n 2000-01-01 00:00:00 0\n 2000-01-01 00:03:00 6\n 2000-01-01 00:06:00 15\n 2000-01-01 00:09:00 15\n Freq: 3T, dtype: int64\n\n Upsample the series into 30 second bins.\n\n >>> series.resample('30S').asfreq()[0:5] #select first 5 rows\n 2000-01-01 00:00:00 0.0\n 2000-01-01 00:00:30 NaN\n 2000-01-01 00:01:00 1.0\n 2000-01-01 00:01:30 NaN\n 2000-01-01 00:02:00 2.0\n Freq: 30S, dtype: float64\n\n Upsample the series into 30 second bins and fill the ``NaN``\n values using the ``pad`` method.\n\n >>> series.resample('30S').pad()[0:5]\n 2000-01-01 00:00:00 0\n 2000-01-01 00:00:30 0\n 2000-01-01 00:01:00 1\n 2000-01-01 00:01:30 1\n 2000-01-01 00:02:00 2\n Freq: 30S, dtype: int64\n\n Upsample the series into 30 second bins and fill the\n ``NaN`` values using the ``bfill`` method.\n\n >>> series.resample('30S').bfill()[0:5]\n 2000-01-01 00:00:00 0\n 2000-01-01 00:00:30 1\n 2000-01-01 00:01:00 1\n 2000-01-01 00:01:30 2\n 2000-01-01 00:02:00 2\n Freq: 30S, dtype: int64\n\n Pass a custom function via ``apply``\n\n >>> def custom_resampler(array_like):\n ... return np.sum(array_like)+5\n\n >>> series.resample('3T').apply(custom_resampler)\n 2000-01-01 00:00:00 8\n 2000-01-01 00:03:00 17\n 2000-01-01 00:06:00 26\n Freq: 3T, dtype: int64\n\n For a Series with a PeriodIndex, the keyword `convention` can be\n used to control whether to use the start or end of `rule`.\n\n >>> s = pd.Series([1, 2], index=pd.period_range('2012-01-01',\n freq='A',\n periods=2))\n >>> s\n 2012 1\n 2013 2\n Freq: A-DEC, dtype: int64\n\n Resample by month using 'start' `convention`. Values are assigned to\n the first month of the period.\n\n >>> s.resample('M', convention='start').asfreq().head()\n 2012-01 1.0\n 2012-02 NaN\n 2012-03 NaN\n 2012-04 NaN\n 2012-05 NaN\n Freq: M, dtype: float64\n\n Resample by month using 'end' `convention`. Values are assigned to\n the last month of the period.\n\n >>> s.resample('M', convention='end').asfreq()\n 2012-12 1.0\n 2013-01 NaN\n 2013-02 NaN\n 2013-03 NaN\n 2013-04 NaN\n 2013-05 NaN\n 2013-06 NaN\n 2013-07 NaN\n 2013-08 NaN\n 2013-09 NaN\n 2013-10 NaN\n 2013-11 NaN\n 2013-12 2.0\n Freq: M, dtype: float64\n\n For DataFrame objects, the keyword ``on`` can be used to specify the\n column instead of the index for resampling.\n\n >>> df = pd.DataFrame(data=9*[range(4)], columns=['a', 'b', 'c', 'd'])\n >>> df['time'] = pd.date_range('1/1/2000', periods=9, freq='T')\n >>> df.resample('3T', on='time').sum()\n a b c d\n time\n 2000-01-01 00:00:00 0 3 6 9\n 2000-01-01 00:03:00 0 3 6 9\n 2000-01-01 00:06:00 0 3 6 9\n\n For a DataFrame with MultiIndex, the keyword ``level`` can be used to\n specify on level the resampling needs to take place.\n\n >>> time = pd.date_range('1/1/2000', periods=5, freq='T')\n >>> df2 = pd.DataFrame(data=10*[range(4)],\n columns=['a', 'b', 'c', 'd'],\n index=pd.MultiIndex.from_product([time, [1, 2]])\n )\n >>> df2.resample('3T', level=0).sum()\n a b c d\n 2000-01-01 00:00:00 0 6 12 18\n 2000-01-01 00:03:00 0 4 8 12\n\n See also\n --------\n groupby : Group by mapping, function, label, or list of labels.\n \"\"\"\n from pandas.core.resample import (resample,\n _maybe_process_deprecations)\n axis = self._get_axis_number(axis)\n r = resample(self, freq=rule, label=label, closed=closed,\n axis=axis, kind=kind, loffset=loffset,\n convention=convention,\n base=base, key=on, level=level)\n return _maybe_process_deprecations(r,\n how=how,\n fill_method=fill_method,\n limit=limit)\n\n def first(self, offset):\n \"\"\"\n Convenience method for subsetting initial periods of time series data\n based on a date offset.\n\n Raises\n ------\n TypeError\n If the index is not a :class:`DatetimeIndex`\n\n Parameters\n ----------\n offset : string, DateOffset, dateutil.relativedelta\n\n Examples\n --------\n >>> i = pd.date_range('2018-04-09', periods=4, freq='2D')\n >>> ts = pd.DataFrame({'A': [1,2,3,4]}, index=i)\n >>> ts\n A\n 2018-04-09 1\n 2018-04-11 2\n 2018-04-13 3\n 2018-04-15 4\n\n Get the rows for the first 3 days:\n\n >>> ts.first('3D')\n A\n 2018-04-09 1\n 2018-04-11 2\n\n Notice the data for 3 first calender days were returned, not the first\n 3 days observed in the dataset, and therefore data for 2018-04-13 was\n not returned.\n\n Returns\n -------\n subset : same type as caller\n\n See Also\n --------\n last : Select final periods of time series based on a date offset\n at_time : Select values at a particular time of the day\n between_time : Select values between particular times of the day\n \"\"\"\n if not isinstance(self.index, DatetimeIndex):\n raise TypeError(\"'first' only supports a DatetimeIndex index\")\n\n if len(self.index) == 0:\n return self\n\n offset = to_offset(offset)\n end_date = end = self.index[0] + offset\n\n # Tick-like, e.g. 3 weeks\n if not offset.isAnchored() and hasattr(offset, '_inc'):\n if end_date in self.index:\n end = self.index.searchsorted(end_date, side='left')\n return self.iloc[:end]\n\n return self.loc[:end]\n\n def last(self, offset):\n \"\"\"\n Convenience method for subsetting final periods of time series data\n based on a date offset.\n\n Raises\n ------\n TypeError\n If the index is not a :class:`DatetimeIndex`\n\n Parameters\n ----------\n offset : string, DateOffset, dateutil.relativedelta\n\n Examples\n --------\n >>> i = pd.date_range('2018-04-09', periods=4, freq='2D')\n >>> ts = pd.DataFrame({'A': [1,2,3,4]}, index=i)\n >>> ts\n A\n 2018-04-09 1\n 2018-04-11 2\n 2018-04-13 3\n 2018-04-15 4\n\n Get the rows for the last 3 days:\n\n >>> ts.last('3D')\n A\n 2018-04-13 3\n 2018-04-15 4\n\n Notice the data for 3 last calender days were returned, not the last\n 3 observed days in the dataset, and therefore data for 2018-04-11 was\n not returned.\n\n Returns\n -------\n subset : same type as caller\n\n See Also\n --------\n first : Select initial periods of time series based on a date offset\n at_time : Select values at a particular time of the day\n between_time : Select values between particular times of the day\n \"\"\"\n if not isinstance(self.index, DatetimeIndex):\n raise TypeError(\"'last' only supports a DatetimeIndex index\")\n\n if len(self.index) == 0:\n return self\n\n offset = to_offset(offset)\n\n start_date = self.index[-1] - offset\n start = self.index.searchsorted(start_date, side='right')\n return self.iloc[start:]\n\n def rank(self, axis=0, method='average', numeric_only=None,\n na_option='keep', ascending=True, pct=False):\n \"\"\"\n Compute numerical data ranks (1 through n) along axis. Equal values are\n assigned a rank that is the average of the ranks of those values\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n index to direct ranking\n method : {'average', 'min', 'max', 'first', 'dense'}\n * average: average rank of group\n * min: lowest rank in group\n * max: highest rank in group\n * first: ranks assigned in order they appear in the array\n * dense: like 'min', but rank always increases by 1 between groups\n numeric_only : boolean, default None\n Include only float, int, boolean data. Valid only for DataFrame or\n Panel objects\n na_option : {'keep', 'top', 'bottom'}\n * keep: leave NA values where they are\n * top: smallest rank if ascending\n * bottom: smallest rank if descending\n ascending : boolean, default True\n False for ranks by high (1) to low (N)\n pct : boolean, default False\n Computes percentage rank of data\n\n Returns\n -------\n ranks : same type as caller\n \"\"\"\n axis = self._get_axis_number(axis)\n\n if self.ndim > 2:\n msg = \"rank does not make sense when ndim > 2\"\n raise NotImplementedError(msg)\n\n if na_option not in {'keep', 'top', 'bottom'}:\n msg = \"na_option must be one of 'keep', 'top', or 'bottom'\"\n raise ValueError(msg)\n\n def ranker(data):\n ranks = algos.rank(data.values, axis=axis, method=method,\n ascending=ascending, na_option=na_option,\n pct=pct)\n ranks = self._constructor(ranks, **data._construct_axes_dict())\n return ranks.__finalize__(self)\n\n # if numeric_only is None, and we can't get anything, we try with\n # numeric_only=True\n if numeric_only is None:\n try:\n return ranker(self)\n except TypeError:\n numeric_only = True\n\n if numeric_only:\n data = self._get_numeric_data()\n else:\n data = self\n\n return ranker(data)\n\n _shared_docs['align'] = (\"\"\"\n Align two objects on their axes with the\n specified join method for each axis Index\n\n Parameters\n ----------\n other : DataFrame or Series\n join : {'outer', 'inner', 'left', 'right'}, default 'outer'\n axis : allowed axis of the other object, default None\n Align on index (0), columns (1), or both (None)\n level : int or level name, default None\n Broadcast across a level, matching Index values on the\n passed MultiIndex level\n copy : boolean, default True\n Always returns new objects. If copy=False and no reindexing is\n required then original objects are returned.\n fill_value : scalar, default np.NaN\n Value to use for missing values. Defaults to NaN, but can be any\n \"compatible\" value\n method : str, default None\n limit : int, default None\n fill_axis : %(axes_single_arg)s, default 0\n Filling axis, method and limit\n broadcast_axis : %(axes_single_arg)s, default None\n Broadcast values along this axis, if aligning two objects of\n different dimensions\n\n Returns\n -------\n (left, right) : (%(klass)s, type of other)\n Aligned objects\n \"\"\")\n\n @Appender(_shared_docs['align'] % _shared_doc_kwargs)\n def align(self, other, join='outer', axis=None, level=None, copy=True,\n fill_value=None, method=None, limit=None, fill_axis=0,\n broadcast_axis=None):\n from pandas import DataFrame, Series\n method = missing.clean_fill_method(method)\n\n if broadcast_axis == 1 and self.ndim != other.ndim:\n if isinstance(self, Series):\n # this means other is a DataFrame, and we need to broadcast\n # self\n cons = self._constructor_expanddim\n df = cons({c: self for c in other.columns},\n **other._construct_axes_dict())\n return df._align_frame(other, join=join, axis=axis,\n level=level, copy=copy,\n fill_value=fill_value, method=method,\n limit=limit, fill_axis=fill_axis)\n elif isinstance(other, Series):\n # this means self is a DataFrame, and we need to broadcast\n # other\n cons = other._constructor_expanddim\n df = cons({c: other for c in self.columns},\n **self._construct_axes_dict())\n return self._align_frame(df, join=join, axis=axis, level=level,\n copy=copy, fill_value=fill_value,\n method=method, limit=limit,\n fill_axis=fill_axis)\n\n if axis is not None:\n axis = self._get_axis_number(axis)\n if isinstance(other, DataFrame):\n return self._align_frame(other, join=join, axis=axis, level=level,\n copy=copy, fill_value=fill_value,\n method=method, limit=limit,\n fill_axis=fill_axis)\n elif isinstance(other, Series):\n return self._align_series(other, join=join, axis=axis, level=level,\n copy=copy, fill_value=fill_value,\n method=method, limit=limit,\n fill_axis=fill_axis)\n else: # pragma: no cover\n raise TypeError('unsupported type: %s' % type(other))\n\n def _align_frame(self, other, join='outer', axis=None, level=None,\n copy=True, fill_value=None, method=None, limit=None,\n fill_axis=0):\n # defaults\n join_index, join_columns = None, None\n ilidx, iridx = None, None\n clidx, cridx = None, None\n\n is_series = isinstance(self, ABCSeries)\n\n if axis is None or axis == 0:\n if not self.index.equals(other.index):\n join_index, ilidx, iridx = self.index.join(\n other.index, how=join, level=level, return_indexers=True)\n\n if axis is None or axis == 1:\n if not is_series and not self.columns.equals(other.columns):\n join_columns, clidx, cridx = self.columns.join(\n other.columns, how=join, level=level, return_indexers=True)\n\n if is_series:\n reindexers = {0: [join_index, ilidx]}\n else:\n reindexers = {0: [join_index, ilidx], 1: [join_columns, clidx]}\n\n left = self._reindex_with_indexers(reindexers, copy=copy,\n fill_value=fill_value,\n allow_dups=True)\n # other must be always DataFrame\n right = other._reindex_with_indexers({0: [join_index, iridx],\n 1: [join_columns, cridx]},\n copy=copy, fill_value=fill_value,\n allow_dups=True)\n\n if method is not None:\n left = left.fillna(axis=fill_axis, method=method, limit=limit)\n right = right.fillna(axis=fill_axis, method=method, limit=limit)\n\n # if DatetimeIndex have different tz, convert to UTC\n if is_datetime64tz_dtype(left.index):\n if left.index.tz != right.index.tz:\n if join_index is not None:\n left.index = join_index\n right.index = join_index\n\n return left.__finalize__(self), right.__finalize__(other)\n\n def _align_series(self, other, join='outer', axis=None, level=None,\n copy=True, fill_value=None, method=None, limit=None,\n fill_axis=0):\n\n is_series = isinstance(self, ABCSeries)\n\n # series/series compat, other must always be a Series\n if is_series:\n if axis:\n raise ValueError('cannot align series to a series other than '\n 'axis 0')\n\n # equal\n if self.index.equals(other.index):\n join_index, lidx, ridx = None, None, None\n else:\n join_index, lidx, ridx = self.index.join(other.index, how=join,\n level=level,\n return_indexers=True)\n\n left = self._reindex_indexer(join_index, lidx, copy)\n right = other._reindex_indexer(join_index, ridx, copy)\n\n else:\n # one has > 1 ndim\n fdata = self._data\n if axis == 0:\n join_index = self.index\n lidx, ridx = None, None\n if not self.index.equals(other.index):\n join_index, lidx, ridx = self.index.join(\n other.index, how=join, level=level,\n return_indexers=True)\n\n if lidx is not None:\n fdata = fdata.reindex_indexer(join_index, lidx, axis=1)\n\n elif axis == 1:\n join_index = self.columns\n lidx, ridx = None, None\n if not self.columns.equals(other.index):\n join_index, lidx, ridx = self.columns.join(\n other.index, how=join, level=level,\n return_indexers=True)\n\n if lidx is not None:\n fdata = fdata.reindex_indexer(join_index, lidx, axis=0)\n else:\n raise ValueError('Must specify axis=0 or 1')\n\n if copy and fdata is self._data:\n fdata = fdata.copy()\n\n left = self._constructor(fdata)\n\n if ridx is None:\n right = other\n else:\n right = other.reindex(join_index, level=level)\n\n # fill\n fill_na = notna(fill_value) or (method is not None)\n if fill_na:\n left = left.fillna(fill_value, method=method, limit=limit,\n axis=fill_axis)\n right = right.fillna(fill_value, method=method, limit=limit)\n\n # if DatetimeIndex have different tz, convert to UTC\n if is_series or (not is_series and axis == 0):\n if is_datetime64tz_dtype(left.index):\n if left.index.tz != right.index.tz:\n if join_index is not None:\n left.index = join_index\n right.index = join_index\n\n return left.__finalize__(self), right.__finalize__(other)\n\n def _where(self, cond, other=np.nan, inplace=False, axis=None, level=None,\n errors='raise', try_cast=False):\n \"\"\"\n Equivalent to public method `where`, except that `other` is not\n applied as a function even if callable. Used in __setitem__.\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n\n # align the cond to same shape as myself\n cond = com.apply_if_callable(cond, self)\n if isinstance(cond, NDFrame):\n cond, _ = cond.align(self, join='right', broadcast_axis=1)\n else:\n if not hasattr(cond, 'shape'):\n cond = np.asanyarray(cond)\n if cond.shape != self.shape:\n raise ValueError('Array conditional must be same shape as '\n 'self')\n cond = self._constructor(cond, **self._construct_axes_dict())\n\n # make sure we are boolean\n fill_value = True if inplace else False\n cond = cond.fillna(fill_value)\n\n msg = \"Boolean array expected for the condition, not {dtype}\"\n\n if not isinstance(cond, pd.DataFrame):\n # This is a single-dimensional object.\n if not is_bool_dtype(cond):\n raise ValueError(msg.format(dtype=cond.dtype))\n else:\n for dt in cond.dtypes:\n if not is_bool_dtype(dt):\n raise ValueError(msg.format(dtype=dt))\n\n cond = -cond if inplace else cond\n\n # try to align with other\n try_quick = True\n if hasattr(other, 'align'):\n\n # align with me\n if other.ndim <= self.ndim:\n\n _, other = self.align(other, join='left', axis=axis,\n level=level, fill_value=np.nan)\n\n # if we are NOT aligned, raise as we cannot where index\n if (axis is None and\n not all(other._get_axis(i).equals(ax)\n for i, ax in enumerate(self.axes))):\n raise InvalidIndexError\n\n # slice me out of the other\n else:\n raise NotImplementedError(\"cannot align with a higher \"\n \"dimensional NDFrame\")\n\n if isinstance(other, np.ndarray):\n\n if other.shape != self.shape:\n\n if self.ndim == 1:\n\n icond = cond.values\n\n # GH 2745 / GH 4192\n # treat like a scalar\n if len(other) == 1:\n other = np.array(other[0])\n\n # GH 3235\n # match True cond to other\n elif len(cond[icond]) == len(other):\n\n # try to not change dtype at first (if try_quick)\n if try_quick:\n\n try:\n new_other = com.values_from_object(self)\n new_other = new_other.copy()\n new_other[icond] = other\n other = new_other\n except Exception:\n try_quick = False\n\n # let's create a new (if we failed at the above\n # or not try_quick\n if not try_quick:\n\n dtype, fill_value = maybe_promote(other.dtype)\n new_other = np.empty(len(icond), dtype=dtype)\n new_other.fill(fill_value)\n maybe_upcast_putmask(new_other, icond, other)\n other = new_other\n\n else:\n raise ValueError('Length of replacements must equal '\n 'series length')\n\n else:\n raise ValueError('other must be the same shape as self '\n 'when an ndarray')\n\n # we are the same shape, so create an actual object for alignment\n else:\n other = self._constructor(other, **self._construct_axes_dict())\n\n if axis is None:\n axis = 0\n\n if self.ndim == getattr(other, 'ndim', 0):\n align = True\n else:\n align = (self._get_axis_number(axis) == 1)\n\n block_axis = self._get_block_manager_axis(axis)\n\n if inplace:\n # we may have different type blocks come out of putmask, so\n # reconstruct the block manager\n\n self._check_inplace_setting(other)\n new_data = self._data.putmask(mask=cond, new=other, align=align,\n inplace=True, axis=block_axis,\n transpose=self._AXIS_REVERSED)\n self._update_inplace(new_data)\n\n else:\n new_data = self._data.where(other=other, cond=cond, align=align,\n errors=errors,\n try_cast=try_cast, axis=block_axis,\n transpose=self._AXIS_REVERSED)\n\n return self._constructor(new_data).__finalize__(self)\n\n _shared_docs['where'] = (\"\"\"\n Replace values where the condition is %(cond_rev)s.\n\n Parameters\n ----------\n cond : boolean %(klass)s, array-like, or callable\n Where `cond` is %(cond)s, keep the original value. Where\n %(cond_rev)s, replace with corresponding value from `other`.\n If `cond` is callable, it is computed on the %(klass)s and\n should return boolean %(klass)s or array. The callable must\n not change input %(klass)s (though pandas doesn't check it).\n\n .. versionadded:: 0.18.1\n A callable can be used as cond.\n\n other : scalar, %(klass)s, or callable\n Entries where `cond` is %(cond_rev)s are replaced with\n corresponding value from `other`.\n If other is callable, it is computed on the %(klass)s and\n should return scalar or %(klass)s. The callable must not\n change input %(klass)s (though pandas doesn't check it).\n\n .. versionadded:: 0.18.1\n A callable can be used as other.\n\n inplace : boolean, default False\n Whether to perform the operation in place on the data.\n axis : int, default None\n Alignment axis if needed.\n level : int, default None\n Alignment level if needed.\n errors : str, {'raise', 'ignore'}, default `raise`\n Note that currently this parameter won't affect\n the results and will always coerce to a suitable dtype.\n\n - `raise` : allow exceptions to be raised.\n - `ignore` : suppress exceptions. On error return original object.\n\n try_cast : boolean, default False\n Try to cast the result back to the input type (if possible).\n raise_on_error : boolean, default True\n Whether to raise on invalid data types (e.g. trying to where on\n strings).\n\n .. deprecated:: 0.21.0\n\n Use `errors`.\n\n Returns\n -------\n wh : same type as caller\n\n Notes\n -----\n The %(name)s method is an application of the if-then idiom. For each\n element in the calling DataFrame, if ``cond`` is ``%(cond)s`` the\n element is used; otherwise the corresponding element from the DataFrame\n ``other`` is used.\n\n The signature for :func:`DataFrame.where` differs from\n :func:`numpy.where`. Roughly ``df1.where(m, df2)`` is equivalent to\n ``np.where(m, df1, df2)``.\n\n For further details and examples see the ``%(name)s`` documentation in\n :ref:`indexing <indexing.where_mask>`.\n\n See Also\n --------\n :func:`DataFrame.%(name_other)s` : Return an object of same shape as\n self\n\n Examples\n --------\n >>> s = pd.Series(range(5))\n >>> s.where(s > 0)\n 0 NaN\n 1 1.0\n 2 2.0\n 3 3.0\n 4 4.0\n dtype: float64\n\n >>> s.mask(s > 0)\n 0 0.0\n 1 NaN\n 2 NaN\n 3 NaN\n 4 NaN\n dtype: float64\n\n >>> s.where(s > 1, 10)\n 0 10\n 1 10\n 2 2\n 3 3\n 4 4\n dtype: int64\n\n >>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B'])\n >>> m = df %% 3 == 0\n >>> df.where(m, -df)\n A B\n 0 0 -1\n 1 -2 3\n 2 -4 -5\n 3 6 -7\n 4 -8 9\n >>> df.where(m, -df) == np.where(m, df, -df)\n A B\n 0 True True\n 1 True True\n 2 True True\n 3 True True\n 4 True True\n >>> df.where(m, -df) == df.mask(~m, -df)\n A B\n 0 True True\n 1 True True\n 2 True True\n 3 True True\n 4 True True\n \"\"\")\n\n @Appender(_shared_docs['where'] % dict(_shared_doc_kwargs, cond=\"True\",\n cond_rev=\"False\", name='where',\n name_other='mask'))\n def where(self, cond, other=np.nan, inplace=False, axis=None, level=None,\n errors='raise', try_cast=False, raise_on_error=None):\n\n if raise_on_error is not None:\n warnings.warn(\n \"raise_on_error is deprecated in \"\n \"favor of errors='raise|ignore'\",\n FutureWarning, stacklevel=2)\n\n if raise_on_error:\n errors = 'raise'\n else:\n errors = 'ignore'\n\n other = com.apply_if_callable(other, self)\n return self._where(cond, other, inplace, axis, level,\n errors=errors, try_cast=try_cast)\n\n @Appender(_shared_docs['where'] % dict(_shared_doc_kwargs, cond=\"False\",\n cond_rev=\"True\", name='mask',\n name_other='where'))\n def mask(self, cond, other=np.nan, inplace=False, axis=None, level=None,\n errors='raise', try_cast=False, raise_on_error=None):\n\n if raise_on_error is not None:\n warnings.warn(\n \"raise_on_error is deprecated in \"\n \"favor of errors='raise|ignore'\",\n FutureWarning, stacklevel=2)\n\n if raise_on_error:\n errors = 'raise'\n else:\n errors = 'ignore'\n\n inplace = validate_bool_kwarg(inplace, 'inplace')\n cond = com.apply_if_callable(cond, self)\n\n # see gh-21891\n if not hasattr(cond, \"__invert__\"):\n cond = np.array(cond)\n\n return self.where(~cond, other=other, inplace=inplace, axis=axis,\n level=level, try_cast=try_cast,\n errors=errors)\n\n _shared_docs['shift'] = (\"\"\"\n Shift index by desired number of periods with an optional time freq\n\n Parameters\n ----------\n periods : int\n Number of periods to move, can be positive or negative\n freq : DateOffset, timedelta, or time rule string, optional\n Increment to use from the tseries module or time rule (e.g. 'EOM').\n See Notes.\n axis : %(axes_single_arg)s\n\n Notes\n -----\n If freq is specified then the index values are shifted but the data\n is not realigned. That is, use freq if you would like to extend the\n index when shifting and preserve the original data.\n\n Returns\n -------\n shifted : %(klass)s\n \"\"\")\n\n @Appender(_shared_docs['shift'] % _shared_doc_kwargs)\n def shift(self, periods=1, freq=None, axis=0):\n if periods == 0:\n return self\n\n block_axis = self._get_block_manager_axis(axis)\n if freq is None:\n new_data = self._data.shift(periods=periods, axis=block_axis)\n else:\n return self.tshift(periods, freq)\n\n return self._constructor(new_data).__finalize__(self)\n\n def slice_shift(self, periods=1, axis=0):\n \"\"\"\n Equivalent to `shift` without copying data. The shifted data will\n not include the dropped periods and the shifted axis will be smaller\n than the original.\n\n Parameters\n ----------\n periods : int\n Number of periods to move, can be positive or negative\n\n Notes\n -----\n While the `slice_shift` is faster than `shift`, you may pay for it\n later during alignment.\n\n Returns\n -------\n shifted : same type as caller\n \"\"\"\n if periods == 0:\n return self\n\n if periods > 0:\n vslicer = slice(None, -periods)\n islicer = slice(periods, None)\n else:\n vslicer = slice(-periods, None)\n islicer = slice(None, periods)\n\n new_obj = self._slice(vslicer, axis=axis)\n shifted_axis = self._get_axis(axis)[islicer]\n new_obj.set_axis(shifted_axis, axis=axis, inplace=True)\n\n return new_obj.__finalize__(self)\n\n def tshift(self, periods=1, freq=None, axis=0):\n \"\"\"\n Shift the time index, using the index's frequency if available.\n\n Parameters\n ----------\n periods : int\n Number of periods to move, can be positive or negative\n freq : DateOffset, timedelta, or time rule string, default None\n Increment to use from the tseries module or time rule (e.g. 'EOM')\n axis : int or basestring\n Corresponds to the axis that contains the Index\n\n Notes\n -----\n If freq is not specified then tries to use the freq or inferred_freq\n attributes of the index. If neither of those attributes exist, a\n ValueError is thrown\n\n Returns\n -------\n shifted : NDFrame\n \"\"\"\n\n index = self._get_axis(axis)\n if freq is None:\n freq = getattr(index, 'freq', None)\n\n if freq is None:\n freq = getattr(index, 'inferred_freq', None)\n\n if freq is None:\n msg = 'Freq was not given and was not set in the index'\n raise ValueError(msg)\n\n if periods == 0:\n return self\n\n if isinstance(freq, string_types):\n freq = to_offset(freq)\n\n block_axis = self._get_block_manager_axis(axis)\n if isinstance(index, PeriodIndex):\n orig_freq = to_offset(index.freq)\n if freq == orig_freq:\n new_data = self._data.copy()\n new_data.axes[block_axis] = index.shift(periods)\n else:\n msg = ('Given freq %s does not match PeriodIndex freq %s' %\n (freq.rule_code, orig_freq.rule_code))\n raise ValueError(msg)\n else:\n new_data = self._data.copy()\n new_data.axes[block_axis] = index.shift(periods, freq)\n\n return self._constructor(new_data).__finalize__(self)\n\n def truncate(self, before=None, after=None, axis=None, copy=True):\n \"\"\"\n Truncate a Series or DataFrame before and after some index value.\n\n This is a useful shorthand for boolean indexing based on index\n values above or below certain thresholds.\n\n Parameters\n ----------\n before : date, string, int\n Truncate all rows before this index value.\n after : date, string, int\n Truncate all rows after this index value.\n axis : {0 or 'index', 1 or 'columns'}, optional\n Axis to truncate. Truncates the index (rows) by default.\n copy : boolean, default is True,\n Return a copy of the truncated section.\n\n Returns\n -------\n type of caller\n The truncated Series or DataFrame.\n\n See Also\n --------\n DataFrame.loc : Select a subset of a DataFrame by label.\n DataFrame.iloc : Select a subset of a DataFrame by position.\n\n Notes\n -----\n If the index being truncated contains only datetime values,\n `before` and `after` may be specified as strings instead of\n Timestamps.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': ['a', 'b', 'c', 'd', 'e'],\n ... 'B': ['f', 'g', 'h', 'i', 'j'],\n ... 'C': ['k', 'l', 'm', 'n', 'o']},\n ... index=[1, 2, 3, 4, 5])\n >>> df\n A B C\n 1 a f k\n 2 b g l\n 3 c h m\n 4 d i n\n 5 e j o\n\n >>> df.truncate(before=2, after=4)\n A B C\n 2 b g l\n 3 c h m\n 4 d i n\n\n The columns of a DataFrame can be truncated.\n\n >>> df.truncate(before=\"A\", after=\"B\", axis=\"columns\")\n A B\n 1 a f\n 2 b g\n 3 c h\n 4 d i\n 5 e j\n\n For Series, only rows can be truncated.\n\n >>> df['A'].truncate(before=2, after=4)\n 2 b\n 3 c\n 4 d\n Name: A, dtype: object\n\n The index values in ``truncate`` can be datetimes or string\n dates.\n\n >>> dates = pd.date_range('2016-01-01', '2016-02-01', freq='s')\n >>> df = pd.DataFrame(index=dates, data={'A': 1})\n >>> df.tail()\n A\n 2016-01-31 23:59:56 1\n 2016-01-31 23:59:57 1\n 2016-01-31 23:59:58 1\n 2016-01-31 23:59:59 1\n 2016-02-01 00:00:00 1\n\n >>> df.truncate(before=pd.Timestamp('2016-01-05'),\n ... after=pd.Timestamp('2016-01-10')).tail()\n A\n 2016-01-09 23:59:56 1\n 2016-01-09 23:59:57 1\n 2016-01-09 23:59:58 1\n 2016-01-09 23:59:59 1\n 2016-01-10 00:00:00 1\n\n Because the index is a DatetimeIndex containing only dates, we can\n specify `before` and `after` as strings. They will be coerced to\n Timestamps before truncation.\n\n >>> df.truncate('2016-01-05', '2016-01-10').tail()\n A\n 2016-01-09 23:59:56 1\n 2016-01-09 23:59:57 1\n 2016-01-09 23:59:58 1\n 2016-01-09 23:59:59 1\n 2016-01-10 00:00:00 1\n\n Note that ``truncate`` assumes a 0 value for any unspecified time\n component (midnight). This differs from partial string slicing, which\n returns any partially matching dates.\n\n >>> df.loc['2016-01-05':'2016-01-10', :].tail()\n A\n 2016-01-10 23:59:55 1\n 2016-01-10 23:59:56 1\n 2016-01-10 23:59:57 1\n 2016-01-10 23:59:58 1\n 2016-01-10 23:59:59 1\n \"\"\"\n\n if axis is None:\n axis = self._stat_axis_number\n axis = self._get_axis_number(axis)\n ax = self._get_axis(axis)\n\n # GH 17935\n # Check that index is sorted\n if not ax.is_monotonic_increasing and not ax.is_monotonic_decreasing:\n raise ValueError(\"truncate requires a sorted index\")\n\n # if we have a date index, convert to dates, otherwise\n # treat like a slice\n if ax.is_all_dates:\n from pandas.core.tools.datetimes import to_datetime\n before = to_datetime(before)\n after = to_datetime(after)\n\n if before is not None and after is not None:\n if before > after:\n raise ValueError('Truncate: %s must be after %s' %\n (after, before))\n\n slicer = [slice(None, None)] * self._AXIS_LEN\n slicer[axis] = slice(before, after)\n result = self.loc[tuple(slicer)]\n\n if isinstance(ax, MultiIndex):\n setattr(result, self._get_axis_name(axis),\n ax.truncate(before, after))\n\n if copy:\n result = result.copy()\n\n return result\n\n def tz_convert(self, tz, axis=0, level=None, copy=True):\n \"\"\"\n Convert tz-aware axis to target time zone.\n\n Parameters\n ----------\n tz : string or pytz.timezone object\n axis : the axis to convert\n level : int, str, default None\n If axis ia a MultiIndex, convert a specific level. Otherwise\n must be None\n copy : boolean, default True\n Also make a copy of the underlying data\n\n Returns\n -------\n\n Raises\n ------\n TypeError\n If the axis is tz-naive.\n \"\"\"\n axis = self._get_axis_number(axis)\n ax = self._get_axis(axis)\n\n def _tz_convert(ax, tz):\n if not hasattr(ax, 'tz_convert'):\n if len(ax) > 0:\n ax_name = self._get_axis_name(axis)\n raise TypeError('%s is not a valid DatetimeIndex or '\n 'PeriodIndex' % ax_name)\n else:\n ax = DatetimeIndex([], tz=tz)\n else:\n ax = ax.tz_convert(tz)\n return ax\n\n # if a level is given it must be a MultiIndex level or\n # equivalent to the axis name\n if isinstance(ax, MultiIndex):\n level = ax._get_level_number(level)\n new_level = _tz_convert(ax.levels[level], tz)\n ax = ax.set_levels(new_level, level=level)\n else:\n if level not in (None, 0, ax.name):\n raise ValueError(\"The level {0} is not valid\".format(level))\n ax = _tz_convert(ax, tz)\n\n result = self._constructor(self._data, copy=copy)\n result.set_axis(ax, axis=axis, inplace=True)\n return result.__finalize__(self)\n\n def tz_localize(self, tz, axis=0, level=None, copy=True,\n ambiguous='raise'):\n \"\"\"\n Localize tz-naive TimeSeries to target time zone.\n\n Parameters\n ----------\n tz : string or pytz.timezone object\n axis : the axis to localize\n level : int, str, default None\n If axis ia a MultiIndex, localize a specific level. Otherwise\n must be None\n copy : boolean, default True\n Also make a copy of the underlying data\n ambiguous : 'infer', bool-ndarray, 'NaT', default 'raise'\n - 'infer' will attempt to infer fall dst-transition hours based on\n order\n - bool-ndarray where True signifies a DST time, False designates\n a non-DST time (note that this flag is only applicable for\n ambiguous times)\n - 'NaT' will return NaT where there are ambiguous times\n - 'raise' will raise an AmbiguousTimeError if there are ambiguous\n times\n\n Returns\n -------\n\n Raises\n ------\n TypeError\n If the TimeSeries is tz-aware and tz is not None.\n \"\"\"\n axis = self._get_axis_number(axis)\n ax = self._get_axis(axis)\n\n def _tz_localize(ax, tz, ambiguous):\n if not hasattr(ax, 'tz_localize'):\n if len(ax) > 0:\n ax_name = self._get_axis_name(axis)\n raise TypeError('%s is not a valid DatetimeIndex or '\n 'PeriodIndex' % ax_name)\n else:\n ax = DatetimeIndex([], tz=tz)\n else:\n ax = ax.tz_localize(tz, ambiguous=ambiguous)\n return ax\n\n # if a level is given it must be a MultiIndex level or\n # equivalent to the axis name\n if isinstance(ax, MultiIndex):\n level = ax._get_level_number(level)\n new_level = _tz_localize(ax.levels[level], tz, ambiguous)\n ax = ax.set_levels(new_level, level=level)\n else:\n if level not in (None, 0, ax.name):\n raise ValueError(\"The level {0} is not valid\".format(level))\n ax = _tz_localize(ax, tz, ambiguous)\n\n result = self._constructor(self._data, copy=copy)\n result.set_axis(ax, axis=axis, inplace=True)\n return result.__finalize__(self)\n\n # ----------------------------------------------------------------------\n # Numeric Methods\n def abs(self):\n \"\"\"\n Return a Series/DataFrame with absolute numeric value of each element.\n\n This function only applies to elements that are all numeric.\n\n Returns\n -------\n abs\n Series/DataFrame containing the absolute value of each element.\n\n Notes\n -----\n For ``complex`` inputs, ``1.2 + 1j``, the absolute value is\n :math:`\\\\sqrt{ a^2 + b^2 }`.\n\n Examples\n --------\n Absolute numeric values in a Series.\n\n >>> s = pd.Series([-1.10, 2, -3.33, 4])\n >>> s.abs()\n 0 1.10\n 1 2.00\n 2 3.33\n 3 4.00\n dtype: float64\n\n Absolute numeric values in a Series with complex numbers.\n\n >>> s = pd.Series([1.2 + 1j])\n >>> s.abs()\n 0 1.56205\n dtype: float64\n\n Absolute numeric values in a Series with a Timedelta element.\n\n >>> s = pd.Series([pd.Timedelta('1 days')])\n >>> s.abs()\n 0 1 days\n dtype: timedelta64[ns]\n\n Select rows with data closest to certain value using argsort (from\n `StackOverflow <https://stackoverflow.com/a/17758115>`__).\n\n >>> df = pd.DataFrame({\n ... 'a': [4, 5, 6, 7],\n ... 'b': [10, 20, 30, 40],\n ... 'c': [100, 50, -30, -50]\n ... })\n >>> df\n a b c\n 0 4 10 100\n 1 5 20 50\n 2 6 30 -30\n 3 7 40 -50\n >>> df.loc[(df.c - 43).abs().argsort()]\n a b c\n 1 5 20 50\n 0 4 10 100\n 2 6 30 -30\n 3 7 40 -50\n\n See Also\n --------\n numpy.absolute : calculate the absolute value element-wise.\n \"\"\"\n return np.abs(self)\n\n def describe(self, percentiles=None, include=None, exclude=None):\n \"\"\"\n Generate descriptive statistics that summarize the central tendency,\n dispersion and shape of a dataset's distribution, excluding\n ``NaN`` values.\n\n Analyzes both numeric and object series, as well\n as ``DataFrame`` column sets of mixed data types. The output\n will vary depending on what is provided. Refer to the notes\n below for more detail.\n\n Parameters\n ----------\n percentiles : list-like of numbers, optional\n The percentiles to include in the output. All should\n fall between 0 and 1. The default is\n ``[.25, .5, .75]``, which returns the 25th, 50th, and\n 75th percentiles.\n include : 'all', list-like of dtypes or None (default), optional\n A white list of data types to include in the result. Ignored\n for ``Series``. Here are the options:\n\n - 'all' : All columns of the input will be included in the output.\n - A list-like of dtypes : Limits the results to the\n provided data types.\n To limit the result to numeric types submit\n ``numpy.number``. To limit it instead to object columns submit\n the ``numpy.object`` data type. Strings\n can also be used in the style of\n ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To\n select pandas categorical columns, use ``'category'``\n - None (default) : The result will include all numeric columns.\n exclude : list-like of dtypes or None (default), optional,\n A black list of data types to omit from the result. Ignored\n for ``Series``. Here are the options:\n\n - A list-like of dtypes : Excludes the provided data types\n from the result. To exclude numeric types submit\n ``numpy.number``. To exclude object columns submit the data\n type ``numpy.object``. Strings can also be used in the style of\n ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To\n exclude pandas categorical columns, use ``'category'``\n - None (default) : The result will exclude nothing.\n\n Returns\n -------\n Series or DataFrame\n Summary statistics of the Series or Dataframe provided.\n\n See Also\n --------\n DataFrame.count: Count number of non-NA/null observations.\n DataFrame.max: Maximum of the values in the object.\n DataFrame.min: Minimum of the values in the object.\n DataFrame.mean: Mean of the values.\n DataFrame.std: Standard deviation of the obersvations.\n DataFrame.select_dtypes: Subset of a DataFrame including/excluding\n columns based on their dtype.\n\n Notes\n -----\n For numeric data, the result's index will include ``count``,\n ``mean``, ``std``, ``min``, ``max`` as well as lower, ``50`` and\n upper percentiles. By default the lower percentile is ``25`` and the\n upper percentile is ``75``. The ``50`` percentile is the\n same as the median.\n\n For object data (e.g. strings or timestamps), the result's index\n will include ``count``, ``unique``, ``top``, and ``freq``. The ``top``\n is the most common value. The ``freq`` is the most common value's\n frequency. Timestamps also include the ``first`` and ``last`` items.\n\n If multiple object values have the highest count, then the\n ``count`` and ``top`` results will be arbitrarily chosen from\n among those with the highest count.\n\n For mixed data types provided via a ``DataFrame``, the default is to\n return only an analysis of numeric columns. If the dataframe consists\n only of object and categorical data without any numeric columns, the\n default is to return an analysis of both the object and categorical\n columns. If ``include='all'`` is provided as an option, the result\n will include a union of attributes of each type.\n\n The `include` and `exclude` parameters can be used to limit\n which columns in a ``DataFrame`` are analyzed for the output.\n The parameters are ignored when analyzing a ``Series``.\n\n Examples\n --------\n Describing a numeric ``Series``.\n\n >>> s = pd.Series([1, 2, 3])\n >>> s.describe()\n count 3.0\n mean 2.0\n std 1.0\n min 1.0\n 25% 1.5\n 50% 2.0\n 75% 2.5\n max 3.0\n dtype: float64\n\n Describing a categorical ``Series``.\n\n >>> s = pd.Series(['a', 'a', 'b', 'c'])\n >>> s.describe()\n count 4\n unique 3\n top a\n freq 2\n dtype: object\n\n Describing a timestamp ``Series``.\n\n >>> s = pd.Series([\n ... np.datetime64(\"2000-01-01\"),\n ... np.datetime64(\"2010-01-01\"),\n ... np.datetime64(\"2010-01-01\")\n ... ])\n >>> s.describe()\n count 3\n unique 2\n top 2010-01-01 00:00:00\n freq 2\n first 2000-01-01 00:00:00\n last 2010-01-01 00:00:00\n dtype: object\n\n Describing a ``DataFrame``. By default only numeric fields\n are returned.\n\n >>> df = pd.DataFrame({'categorical': pd.Categorical(['d','e','f']),\n ... 'numeric': [1, 2, 3],\n ... 'object': ['a', 'b', 'c']\n ... })\n >>> df.describe()\n numeric\n count 3.0\n mean 2.0\n std 1.0\n min 1.0\n 25% 1.5\n 50% 2.0\n 75% 2.5\n max 3.0\n\n Describing all columns of a ``DataFrame`` regardless of data type.\n\n >>> df.describe(include='all')\n categorical numeric object\n count 3 3.0 3\n unique 3 NaN 3\n top f NaN c\n freq 1 NaN 1\n mean NaN 2.0 NaN\n std NaN 1.0 NaN\n min NaN 1.0 NaN\n 25% NaN 1.5 NaN\n 50% NaN 2.0 NaN\n 75% NaN 2.5 NaN\n max NaN 3.0 NaN\n\n Describing a column from a ``DataFrame`` by accessing it as\n an attribute.\n\n >>> df.numeric.describe()\n count 3.0\n mean 2.0\n std 1.0\n min 1.0\n 25% 1.5\n 50% 2.0\n 75% 2.5\n max 3.0\n Name: numeric, dtype: float64\n\n Including only numeric columns in a ``DataFrame`` description.\n\n >>> df.describe(include=[np.number])\n numeric\n count 3.0\n mean 2.0\n std 1.0\n min 1.0\n 25% 1.5\n 50% 2.0\n 75% 2.5\n max 3.0\n\n Including only string columns in a ``DataFrame`` description.\n\n >>> df.describe(include=[np.object])\n object\n count 3\n unique 3\n top c\n freq 1\n\n Including only categorical columns from a ``DataFrame`` description.\n\n >>> df.describe(include=['category'])\n categorical\n count 3\n unique 3\n top f\n freq 1\n\n Excluding numeric columns from a ``DataFrame`` description.\n\n >>> df.describe(exclude=[np.number])\n categorical object\n count 3 3\n unique 3 3\n top f c\n freq 1 1\n\n Excluding object columns from a ``DataFrame`` description.\n\n >>> df.describe(exclude=[np.object])\n categorical numeric\n count 3 3.0\n unique 3 NaN\n top f NaN\n freq 1 NaN\n mean NaN 2.0\n std NaN 1.0\n min NaN 1.0\n 25% NaN 1.5\n 50% NaN 2.0\n 75% NaN 2.5\n max NaN 3.0\n \"\"\"\n if self.ndim >= 3:\n msg = \"describe is not implemented on Panel objects.\"\n raise NotImplementedError(msg)\n elif self.ndim == 2 and self.columns.size == 0:\n raise ValueError(\"Cannot describe a DataFrame without columns\")\n\n if percentiles is not None:\n # explicit conversion of `percentiles` to list\n percentiles = list(percentiles)\n\n # get them all to be in [0, 1]\n self._check_percentile(percentiles)\n\n # median should always be included\n if 0.5 not in percentiles:\n percentiles.append(0.5)\n percentiles = np.asarray(percentiles)\n else:\n percentiles = np.array([0.25, 0.5, 0.75])\n\n # sort and check for duplicates\n unique_pcts = np.unique(percentiles)\n if len(unique_pcts) < len(percentiles):\n raise ValueError(\"percentiles cannot contain duplicates\")\n percentiles = unique_pcts\n\n formatted_percentiles = format_percentiles(percentiles)\n\n def describe_numeric_1d(series):\n stat_index = (['count', 'mean', 'std', 'min'] +\n formatted_percentiles + ['max'])\n d = ([series.count(), series.mean(), series.std(), series.min()] +\n series.quantile(percentiles).tolist() + [series.max()])\n return pd.Series(d, index=stat_index, name=series.name)\n\n def describe_categorical_1d(data):\n names = ['count', 'unique']\n objcounts = data.value_counts()\n count_unique = len(objcounts[objcounts != 0])\n result = [data.count(), count_unique]\n if result[1] > 0:\n top, freq = objcounts.index[0], objcounts.iloc[0]\n\n if is_datetime64_any_dtype(data):\n tz = data.dt.tz\n asint = data.dropna().values.view('i8')\n names += ['top', 'freq', 'first', 'last']\n result += [tslib.Timestamp(top, tz=tz), freq,\n tslib.Timestamp(asint.min(), tz=tz),\n tslib.Timestamp(asint.max(), tz=tz)]\n else:\n names += ['top', 'freq']\n result += [top, freq]\n\n return pd.Series(result, index=names, name=data.name)\n\n def describe_1d(data):\n if is_bool_dtype(data):\n return describe_categorical_1d(data)\n elif is_numeric_dtype(data):\n return describe_numeric_1d(data)\n elif is_timedelta64_dtype(data):\n return describe_numeric_1d(data)\n else:\n return describe_categorical_1d(data)\n\n if self.ndim == 1:\n return describe_1d(self)\n elif (include is None) and (exclude is None):\n # when some numerics are found, keep only numerics\n data = self.select_dtypes(include=[np.number])\n if len(data.columns) == 0:\n data = self\n elif include == 'all':\n if exclude is not None:\n msg = \"exclude must be None when include is 'all'\"\n raise ValueError(msg)\n data = self\n else:\n data = self.select_dtypes(include=include, exclude=exclude)\n\n ldesc = [describe_1d(s) for _, s in data.iteritems()]\n # set a convenient order for rows\n names = []\n ldesc_indexes = sorted((x.index for x in ldesc), key=len)\n for idxnames in ldesc_indexes:\n for name in idxnames:\n if name not in names:\n names.append(name)\n\n d = pd.concat(ldesc, join_axes=pd.Index([names]), axis=1)\n d.columns = data.columns.copy()\n return d\n\n def _check_percentile(self, q):\n \"\"\"Validate percentiles (used by describe and quantile).\"\"\"\n\n msg = (\"percentiles should all be in the interval [0, 1]. \"\n \"Try {0} instead.\")\n q = np.asarray(q)\n if q.ndim == 0:\n if not 0 <= q <= 1:\n raise ValueError(msg.format(q / 100.0))\n else:\n if not all(0 <= qs <= 1 for qs in q):\n raise ValueError(msg.format(q / 100.0))\n return q\n\n _shared_docs['pct_change'] = \"\"\"\n Percentage change between the current and a prior element.\n\n Computes the percentage change from the immediately previous row by\n default. This is useful in comparing the percentage of change in a time\n series of elements.\n\n Parameters\n ----------\n periods : int, default 1\n Periods to shift for forming percent change.\n fill_method : str, default 'pad'\n How to handle NAs before computing percent changes.\n limit : int, default None\n The number of consecutive NAs to fill before stopping.\n freq : DateOffset, timedelta, or offset alias string, optional\n Increment to use from time series API (e.g. 'M' or BDay()).\n **kwargs\n Additional keyword arguments are passed into\n `DataFrame.shift` or `Series.shift`.\n\n Returns\n -------\n chg : Series or DataFrame\n The same type as the calling object.\n\n See Also\n --------\n Series.diff : Compute the difference of two elements in a Series.\n DataFrame.diff : Compute the difference of two elements in a DataFrame.\n Series.shift : Shift the index by some number of periods.\n DataFrame.shift : Shift the index by some number of periods.\n\n Examples\n --------\n **Series**\n\n >>> s = pd.Series([90, 91, 85])\n >>> s\n 0 90\n 1 91\n 2 85\n dtype: int64\n\n >>> s.pct_change()\n 0 NaN\n 1 0.011111\n 2 -0.065934\n dtype: float64\n\n >>> s.pct_change(periods=2)\n 0 NaN\n 1 NaN\n 2 -0.055556\n dtype: float64\n\n See the percentage change in a Series where filling NAs with last\n valid observation forward to next valid.\n\n >>> s = pd.Series([90, 91, None, 85])\n >>> s\n 0 90.0\n 1 91.0\n 2 NaN\n 3 85.0\n dtype: float64\n\n >>> s.pct_change(fill_method='ffill')\n 0 NaN\n 1 0.011111\n 2 0.000000\n 3 -0.065934\n dtype: float64\n\n **DataFrame**\n\n Percentage change in French franc, Deutsche Mark, and Italian lira from\n 1980-01-01 to 1980-03-01.\n\n >>> df = pd.DataFrame({\n ... 'FR': [4.0405, 4.0963, 4.3149],\n ... 'GR': [1.7246, 1.7482, 1.8519],\n ... 'IT': [804.74, 810.01, 860.13]},\n ... index=['1980-01-01', '1980-02-01', '1980-03-01'])\n >>> df\n FR GR IT\n 1980-01-01 4.0405 1.7246 804.74\n 1980-02-01 4.0963 1.7482 810.01\n 1980-03-01 4.3149 1.8519 860.13\n\n >>> df.pct_change()\n FR GR IT\n 1980-01-01 NaN NaN NaN\n 1980-02-01 0.013810 0.013684 0.006549\n 1980-03-01 0.053365 0.059318 0.061876\n\n Percentage of change in GOOG and APPL stock volume. Shows computing\n the percentage change between columns.\n\n >>> df = pd.DataFrame({\n ... '2016': [1769950, 30586265],\n ... '2015': [1500923, 40912316],\n ... '2014': [1371819, 41403351]},\n ... index=['GOOG', 'APPL'])\n >>> df\n 2016 2015 2014\n GOOG 1769950 1500923 1371819\n APPL 30586265 40912316 41403351\n\n >>> df.pct_change(axis='columns')\n 2016 2015 2014\n GOOG NaN -0.151997 -0.086016\n APPL NaN 0.337604 0.012002\n \"\"\"\n\n @Appender(_shared_docs['pct_change'] % _shared_doc_kwargs)\n def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None,\n **kwargs):\n # TODO: Not sure if above is correct - need someone to confirm.\n axis = self._get_axis_number(kwargs.pop('axis', self._stat_axis_name))\n if fill_method is None:\n data = self\n else:\n data = self.fillna(method=fill_method, limit=limit, axis=axis)\n\n rs = (data.div(data.shift(periods=periods, freq=freq, axis=axis,\n **kwargs)) - 1)\n rs = rs.reindex_like(data)\n if freq is None:\n mask = isna(com.values_from_object(data))\n np.putmask(rs.values, mask, np.nan)\n return rs\n\n def _agg_by_level(self, name, axis=0, level=0, skipna=True, **kwargs):\n if axis is None:\n raise ValueError(\"Must specify 'axis' when aggregating by level.\")\n grouped = self.groupby(level=level, axis=axis, sort=False)\n if hasattr(grouped, name) and skipna:\n return getattr(grouped, name)(**kwargs)\n axis = self._get_axis_number(axis)\n method = getattr(type(self), name)\n applyf = lambda x: method(x, axis=axis, skipna=skipna, **kwargs)\n return grouped.aggregate(applyf)\n\n @classmethod\n def _add_numeric_operations(cls):\n \"\"\"Add the operations to the cls; evaluate the doc strings again\"\"\"\n\n axis_descr, name, name2 = _doc_parms(cls)\n\n cls.any = _make_logical_function(\n cls, 'any', name, name2, axis_descr,\n _any_desc, nanops.nanany, _any_examples, _any_see_also)\n cls.all = _make_logical_function(\n cls, 'all', name, name2, axis_descr, _all_doc,\n nanops.nanall, _all_examples, _all_see_also)\n\n @Substitution(outname='mad',\n desc=\"Return the mean absolute deviation of the values \"\n \"for the requested axis\",\n name1=name, name2=name2, axis_descr=axis_descr,\n min_count='', examples='')\n @Appender(_num_doc)\n def mad(self, axis=None, skipna=None, level=None):\n if skipna is None:\n skipna = True\n if axis is None:\n axis = self._stat_axis_number\n if level is not None:\n return self._agg_by_level('mad', axis=axis, level=level,\n skipna=skipna)\n\n data = self._get_numeric_data()\n if axis == 0:\n demeaned = data - data.mean(axis=0)\n else:\n demeaned = data.sub(data.mean(axis=1), axis=0)\n return np.abs(demeaned).mean(axis=axis, skipna=skipna)\n\n cls.mad = mad\n\n cls.sem = _make_stat_function_ddof(\n cls, 'sem', name, name2, axis_descr,\n \"Return unbiased standard error of the mean over requested \"\n \"axis.\\n\\nNormalized by N-1 by default. This can be changed \"\n \"using the ddof argument\",\n nanops.nansem)\n cls.var = _make_stat_function_ddof(\n cls, 'var', name, name2, axis_descr,\n \"Return unbiased variance over requested axis.\\n\\nNormalized by \"\n \"N-1 by default. This can be changed using the ddof argument\",\n nanops.nanvar)\n cls.std = _make_stat_function_ddof(\n cls, 'std', name, name2, axis_descr,\n \"Return sample standard deviation over requested axis.\"\n \"\\n\\nNormalized by N-1 by default. This can be changed using the \"\n \"ddof argument\",\n nanops.nanstd)\n\n @Substitution(outname='compounded',\n desc=\"Return the compound percentage of the values for \"\n \"the requested axis\", name1=name, name2=name2,\n axis_descr=axis_descr,\n min_count='', examples='')\n @Appender(_num_doc)\n def compound(self, axis=None, skipna=None, level=None):\n if skipna is None:\n skipna = True\n return (1 + self).prod(axis=axis, skipna=skipna, level=level) - 1\n\n cls.compound = compound\n\n cls.cummin = _make_cum_function(\n cls, 'cummin', name, name2, axis_descr, \"minimum\",\n lambda y, axis: np.minimum.accumulate(y, axis), \"min\",\n np.inf, np.nan, _cummin_examples)\n cls.cumsum = _make_cum_function(\n cls, 'cumsum', name, name2, axis_descr, \"sum\",\n lambda y, axis: y.cumsum(axis), \"sum\", 0.,\n np.nan, _cumsum_examples)\n cls.cumprod = _make_cum_function(\n cls, 'cumprod', name, name2, axis_descr, \"product\",\n lambda y, axis: y.cumprod(axis), \"prod\", 1.,\n np.nan, _cumprod_examples)\n cls.cummax = _make_cum_function(\n cls, 'cummax', name, name2, axis_descr, \"maximum\",\n lambda y, axis: np.maximum.accumulate(y, axis), \"max\",\n -np.inf, np.nan, _cummax_examples)\n\n cls.sum = _make_min_count_stat_function(\n cls, 'sum', name, name2, axis_descr,\n 'Return the sum of the values for the requested axis',\n nanops.nansum, _sum_examples)\n cls.mean = _make_stat_function(\n cls, 'mean', name, name2, axis_descr,\n 'Return the mean of the values for the requested axis',\n nanops.nanmean)\n cls.skew = _make_stat_function(\n cls, 'skew', name, name2, axis_descr,\n 'Return unbiased skew over requested axis\\nNormalized by N-1',\n nanops.nanskew)\n cls.kurt = _make_stat_function(\n cls, 'kurt', name, name2, axis_descr,\n \"Return unbiased kurtosis over requested axis using Fisher's \"\n \"definition of\\nkurtosis (kurtosis of normal == 0.0). Normalized \"\n \"by N-1\\n\",\n nanops.nankurt)\n cls.kurtosis = cls.kurt\n cls.prod = _make_min_count_stat_function(\n cls, 'prod', name, name2, axis_descr,\n 'Return the product of the values for the requested axis',\n nanops.nanprod, _prod_examples)\n cls.product = cls.prod\n cls.median = _make_stat_function(\n cls, 'median', name, name2, axis_descr,\n 'Return the median of the values for the requested axis',\n nanops.nanmedian)\n cls.max = _make_stat_function(\n cls, 'max', name, name2, axis_descr,\n \"\"\"This method returns the maximum of the values in the object.\n If you want the *index* of the maximum, use ``idxmax``. This is\n the equivalent of the ``numpy.ndarray`` method ``argmax``.\"\"\",\n nanops.nanmax)\n cls.min = _make_stat_function(\n cls, 'min', name, name2, axis_descr,\n \"\"\"This method returns the minimum of the values in the object.\n If you want the *index* of the minimum, use ``idxmin``. This is\n the equivalent of the ``numpy.ndarray`` method ``argmin``.\"\"\",\n nanops.nanmin)\n\n @classmethod\n def _add_series_only_operations(cls):\n \"\"\"Add the series only operations to the cls; evaluate the doc\n strings again.\n \"\"\"\n\n axis_descr, name, name2 = _doc_parms(cls)\n\n def nanptp(values, axis=0, skipna=True):\n nmax = nanops.nanmax(values, axis, skipna)\n nmin = nanops.nanmin(values, axis, skipna)\n warnings.warn(\"Method .ptp is deprecated and will be removed \"\n \"in a future version. Use numpy.ptp instead.\",\n FutureWarning, stacklevel=4)\n return nmax - nmin\n\n cls.ptp = _make_stat_function(\n cls, 'ptp', name, name2, axis_descr,\n \"\"\"\n Returns the difference between the maximum value and the\n minimum value in the object. This is the equivalent of the\n ``numpy.ndarray`` method ``ptp``.\n\n .. deprecated:: 0.24.0\n Use numpy.ptp instead\n \"\"\",\n nanptp)\n\n @classmethod\n def _add_series_or_dataframe_operations(cls):\n \"\"\"Add the series or dataframe only operations to the cls; evaluate\n the doc strings again.\n \"\"\"\n\n from pandas.core import window as rwindow\n\n @Appender(rwindow.rolling.__doc__)\n def rolling(self, window, min_periods=None, center=False,\n win_type=None, on=None, axis=0, closed=None):\n axis = self._get_axis_number(axis)\n return rwindow.rolling(self, window=window,\n min_periods=min_periods,\n center=center, win_type=win_type,\n on=on, axis=axis, closed=closed)\n\n cls.rolling = rolling\n\n @Appender(rwindow.expanding.__doc__)\n def expanding(self, min_periods=1, center=False, axis=0):\n axis = self._get_axis_number(axis)\n return rwindow.expanding(self, min_periods=min_periods,\n center=center, axis=axis)\n\n cls.expanding = expanding\n\n @Appender(rwindow.ewm.__doc__)\n def ewm(self, com=None, span=None, halflife=None, alpha=None,\n min_periods=0, adjust=True, ignore_na=False,\n axis=0):\n axis = self._get_axis_number(axis)\n return rwindow.ewm(self, com=com, span=span, halflife=halflife,\n alpha=alpha, min_periods=min_periods,\n adjust=adjust, ignore_na=ignore_na, axis=axis)\n\n cls.ewm = ewm\n\n @Appender(_shared_docs['transform'] % _shared_doc_kwargs)\n def transform(self, func, *args, **kwargs):\n result = self.agg(func, *args, **kwargs)\n if is_scalar(result) or len(result) != len(self):\n raise ValueError(\"transforms cannot produce \"\n \"aggregated results\")\n\n return result\n\n # ----------------------------------------------------------------------\n # Misc methods\n\n _shared_docs['valid_index'] = \"\"\"\n Return index for %(position)s non-NA/null value.\n\n Notes\n --------\n If all elements are non-NA/null, returns None.\n Also returns None for empty %(klass)s.\n\n Returns\n --------\n scalar : type of index\n \"\"\"\n\n def _find_valid_index(self, how):\n \"\"\"Retrieves the index of the first valid value.\n\n Parameters\n ----------\n how : {'first', 'last'}\n Use this parameter to change between the first or last valid index.\n\n Returns\n -------\n idx_first_valid : type of index\n \"\"\"\n assert how in ['first', 'last']\n\n if len(self) == 0: # early stop\n return None\n is_valid = ~self.isna()\n\n if self.ndim == 2:\n is_valid = is_valid.any(1) # reduce axis 1\n\n if how == 'first':\n idxpos = is_valid.values[::].argmax()\n\n if how == 'last':\n idxpos = len(self) - 1 - is_valid.values[::-1].argmax()\n\n chk_notna = is_valid.iat[idxpos]\n idx = self.index[idxpos]\n\n if not chk_notna:\n return None\n return idx\n\n @Appender(_shared_docs['valid_index'] % {'position': 'first',\n 'klass': 'NDFrame'})\n def first_valid_index(self):\n return self._find_valid_index('first')\n\n @Appender(_shared_docs['valid_index'] % {'position': 'last',\n 'klass': 'NDFrame'})\n def last_valid_index(self):\n return self._find_valid_index('last')\n\n\ndef _doc_parms(cls):\n \"\"\"Return a tuple of the doc parms.\"\"\"\n axis_descr = \"{%s}\" % ', '.join([\"{0} ({1})\".format(a, i)\n for i, a in enumerate(cls._AXIS_ORDERS)])\n name = (cls._constructor_sliced.__name__\n if cls._AXIS_LEN > 1 else 'scalar')\n name2 = cls.__name__\n return axis_descr, name, name2\n\n\n_num_doc = \"\"\"\n\n%(desc)s\n\nParameters\n----------\naxis : %(axis_descr)s\nskipna : boolean, default True\n Exclude NA/null values when computing the result.\nlevel : int or level name, default None\n If the axis is a MultiIndex (hierarchical), count along a\n particular level, collapsing into a %(name1)s\nnumeric_only : boolean, default None\n Include only float, int, boolean columns. If None, will attempt to use\n everything, then use only numeric data. Not implemented for Series.\n%(min_count)s\\\n\nReturns\n-------\n%(outname)s : %(name1)s or %(name2)s (if level specified)\n\n%(examples)s\"\"\"\n\n_num_ddof_doc = \"\"\"\n\n%(desc)s\n\nParameters\n----------\naxis : %(axis_descr)s\nskipna : boolean, default True\n Exclude NA/null values. If an entire row/column is NA, the result\n will be NA\nlevel : int or level name, default None\n If the axis is a MultiIndex (hierarchical), count along a\n particular level, collapsing into a %(name1)s\nddof : int, default 1\n Delta Degrees of Freedom. The divisor used in calculations is N - ddof,\n where N represents the number of elements.\nnumeric_only : boolean, default None\n Include only float, int, boolean columns. If None, will attempt to use\n everything, then use only numeric data. Not implemented for Series.\n\nReturns\n-------\n%(outname)s : %(name1)s or %(name2)s (if level specified)\\n\"\"\"\n\n_bool_doc = \"\"\"\n%(desc)s\n\nParameters\n----------\naxis : {0 or 'index', 1 or 'columns', None}, default 0\n Indicate which axis or axes should be reduced.\n\n * 0 / 'index' : reduce the index, return a Series whose index is the\n original column labels.\n * 1 / 'columns' : reduce the columns, return a Series whose index is the\n original index.\n * None : reduce all axes, return a scalar.\n\nskipna : boolean, default True\n Exclude NA/null values. If an entire row/column is NA, the result\n will be NA.\nlevel : int or level name, default None\n If the axis is a MultiIndex (hierarchical), count along a\n particular level, collapsing into a %(name1)s.\nbool_only : boolean, default None\n Include only boolean columns. If None, will attempt to use everything,\n then use only boolean data. Not implemented for Series.\n**kwargs : any, default None\n Additional keywords have no effect but might be accepted for\n compatibility with NumPy.\n\nReturns\n-------\n%(outname)s : %(name1)s or %(name2)s (if level specified)\n\n%(see_also)s\n%(examples)s\"\"\"\n\n_all_doc = \"\"\"\\\nReturn whether all elements are True, potentially over an axis.\n\nReturns True if all elements within a series or along a Dataframe\naxis are non-zero, not-empty or not-False.\"\"\"\n\n_all_examples = \"\"\"\\\nExamples\n--------\nSeries\n\n>>> pd.Series([True, True]).all()\nTrue\n>>> pd.Series([True, False]).all()\nFalse\n\nDataFrames\n\nCreate a dataframe from a dictionary.\n\n>>> df = pd.DataFrame({'col1': [True, True], 'col2': [True, False]})\n>>> df\n col1 col2\n0 True True\n1 True False\n\nDefault behaviour checks if column-wise values all return True.\n\n>>> df.all()\ncol1 True\ncol2 False\ndtype: bool\n\nSpecify ``axis='columns'`` to check if row-wise values all return True.\n\n>>> df.all(axis='columns')\n0 True\n1 False\ndtype: bool\n\nOr ``axis=None`` for whether every value is True.\n\n>>> df.all(axis=None)\nFalse\n\"\"\"\n\n_all_see_also = \"\"\"\\\nSee also\n--------\npandas.Series.all : Return True if all elements are True\npandas.DataFrame.any : Return True if one (or more) elements are True\n\"\"\"\n\n_cnum_doc = \"\"\"\nReturn cumulative %(desc)s over a DataFrame or Series axis.\n\nReturns a DataFrame or Series of the same size containing the cumulative\n%(desc)s.\n\nParameters\n----------\naxis : {0 or 'index', 1 or 'columns'}, default 0\n The index or the name of the axis. 0 is equivalent to None or 'index'.\nskipna : boolean, default True\n Exclude NA/null values. If an entire row/column is NA, the result\n will be NA.\n*args, **kwargs :\n Additional keywords have no effect but might be accepted for\n compatibility with NumPy.\n\nReturns\n-------\n%(outname)s : %(name1)s or %(name2)s\\n\n%(examples)s\nSee also\n--------\npandas.core.window.Expanding.%(accum_func_name)s : Similar functionality\n but ignores ``NaN`` values.\n%(name2)s.%(accum_func_name)s : Return the %(desc)s over\n %(name2)s axis.\n%(name2)s.cummax : Return cumulative maximum over %(name2)s axis.\n%(name2)s.cummin : Return cumulative minimum over %(name2)s axis.\n%(name2)s.cumsum : Return cumulative sum over %(name2)s axis.\n%(name2)s.cumprod : Return cumulative product over %(name2)s axis.\n\"\"\"\n\n_cummin_examples = \"\"\"\\\nExamples\n--------\n**Series**\n\n>>> s = pd.Series([2, np.nan, 5, -1, 0])\n>>> s\n0 2.0\n1 NaN\n2 5.0\n3 -1.0\n4 0.0\ndtype: float64\n\nBy default, NA values are ignored.\n\n>>> s.cummin()\n0 2.0\n1 NaN\n2 2.0\n3 -1.0\n4 -1.0\ndtype: float64\n\nTo include NA values in the operation, use ``skipna=False``\n\n>>> s.cummin(skipna=False)\n0 2.0\n1 NaN\n2 NaN\n3 NaN\n4 NaN\ndtype: float64\n\n**DataFrame**\n\n>>> df = pd.DataFrame([[2.0, 1.0],\n... [3.0, np.nan],\n... [1.0, 0.0]],\n... columns=list('AB'))\n>>> df\n A B\n0 2.0 1.0\n1 3.0 NaN\n2 1.0 0.0\n\nBy default, iterates over rows and finds the minimum\nin each column. This is equivalent to ``axis=None`` or ``axis='index'``.\n\n>>> df.cummin()\n A B\n0 2.0 1.0\n1 2.0 NaN\n2 1.0 0.0\n\nTo iterate over columns and find the minimum in each row,\nuse ``axis=1``\n\n>>> df.cummin(axis=1)\n A B\n0 2.0 1.0\n1 3.0 NaN\n2 1.0 0.0\n\"\"\"\n\n_cumsum_examples = \"\"\"\\\nExamples\n--------\n**Series**\n\n>>> s = pd.Series([2, np.nan, 5, -1, 0])\n>>> s\n0 2.0\n1 NaN\n2 5.0\n3 -1.0\n4 0.0\ndtype: float64\n\nBy default, NA values are ignored.\n\n>>> s.cumsum()\n0 2.0\n1 NaN\n2 7.0\n3 6.0\n4 6.0\ndtype: float64\n\nTo include NA values in the operation, use ``skipna=False``\n\n>>> s.cumsum(skipna=False)\n0 2.0\n1 NaN\n2 NaN\n3 NaN\n4 NaN\ndtype: float64\n\n**DataFrame**\n\n>>> df = pd.DataFrame([[2.0, 1.0],\n... [3.0, np.nan],\n... [1.0, 0.0]],\n... columns=list('AB'))\n>>> df\n A B\n0 2.0 1.0\n1 3.0 NaN\n2 1.0 0.0\n\nBy default, iterates over rows and finds the sum\nin each column. This is equivalent to ``axis=None`` or ``axis='index'``.\n\n>>> df.cumsum()\n A B\n0 2.0 1.0\n1 5.0 NaN\n2 6.0 1.0\n\nTo iterate over columns and find the sum in each row,\nuse ``axis=1``\n\n>>> df.cumsum(axis=1)\n A B\n0 2.0 3.0\n1 3.0 NaN\n2 1.0 1.0\n\"\"\"\n\n_cumprod_examples = \"\"\"\\\nExamples\n--------\n**Series**\n\n>>> s = pd.Series([2, np.nan, 5, -1, 0])\n>>> s\n0 2.0\n1 NaN\n2 5.0\n3 -1.0\n4 0.0\ndtype: float64\n\nBy default, NA values are ignored.\n\n>>> s.cumprod()\n0 2.0\n1 NaN\n2 10.0\n3 -10.0\n4 -0.0\ndtype: float64\n\nTo include NA values in the operation, use ``skipna=False``\n\n>>> s.cumprod(skipna=False)\n0 2.0\n1 NaN\n2 NaN\n3 NaN\n4 NaN\ndtype: float64\n\n**DataFrame**\n\n>>> df = pd.DataFrame([[2.0, 1.0],\n... [3.0, np.nan],\n... [1.0, 0.0]],\n... columns=list('AB'))\n>>> df\n A B\n0 2.0 1.0\n1 3.0 NaN\n2 1.0 0.0\n\nBy default, iterates over rows and finds the product\nin each column. This is equivalent to ``axis=None`` or ``axis='index'``.\n\n>>> df.cumprod()\n A B\n0 2.0 1.0\n1 6.0 NaN\n2 6.0 0.0\n\nTo iterate over columns and find the product in each row,\nuse ``axis=1``\n\n>>> df.cumprod(axis=1)\n A B\n0 2.0 2.0\n1 3.0 NaN\n2 1.0 0.0\n\"\"\"\n\n_cummax_examples = \"\"\"\\\nExamples\n--------\n**Series**\n\n>>> s = pd.Series([2, np.nan, 5, -1, 0])\n>>> s\n0 2.0\n1 NaN\n2 5.0\n3 -1.0\n4 0.0\ndtype: float64\n\nBy default, NA values are ignored.\n\n>>> s.cummax()\n0 2.0\n1 NaN\n2 5.0\n3 5.0\n4 5.0\ndtype: float64\n\nTo include NA values in the operation, use ``skipna=False``\n\n>>> s.cummax(skipna=False)\n0 2.0\n1 NaN\n2 NaN\n3 NaN\n4 NaN\ndtype: float64\n\n**DataFrame**\n\n>>> df = pd.DataFrame([[2.0, 1.0],\n... [3.0, np.nan],\n... [1.0, 0.0]],\n... columns=list('AB'))\n>>> df\n A B\n0 2.0 1.0\n1 3.0 NaN\n2 1.0 0.0\n\nBy default, iterates over rows and finds the maximum\nin each column. This is equivalent to ``axis=None`` or ``axis='index'``.\n\n>>> df.cummax()\n A B\n0 2.0 1.0\n1 3.0 NaN\n2 3.0 1.0\n\nTo iterate over columns and find the maximum in each row,\nuse ``axis=1``\n\n>>> df.cummax(axis=1)\n A B\n0 2.0 2.0\n1 3.0 NaN\n2 1.0 1.0\n\"\"\"\n\n_any_see_also = \"\"\"\\\nSee Also\n--------\nnumpy.any : Numpy version of this method.\nSeries.any : Return whether any element is True.\nSeries.all : Return whether all elements are True.\nDataFrame.any : Return whether any element is True over requested axis.\nDataFrame.all : Return whether all elements are True over requested axis.\n\"\"\"\n\n_any_desc = \"\"\"\\\nReturn whether any element is True over requested axis.\n\nUnlike :meth:`DataFrame.all`, this performs an *or* operation. If any of the\nvalues along the specified axis is True, this will return True.\"\"\"\n\n_any_examples = \"\"\"\\\nExamples\n--------\n**Series**\n\nFor Series input, the output is a scalar indicating whether any element\nis True.\n\n>>> pd.Series([True, False]).any()\nTrue\n\n**DataFrame**\n\nWhether each column contains at least one True element (the default).\n\n>>> df = pd.DataFrame({\"A\": [1, 2], \"B\": [0, 2], \"C\": [0, 0]})\n>>> df\n A B C\n0 1 0 0\n1 2 2 0\n\n>>> df.any()\nA True\nB True\nC False\ndtype: bool\n\nAggregating over the columns.\n\n>>> df = pd.DataFrame({\"A\": [True, False], \"B\": [1, 2]})\n>>> df\n A B\n0 True 1\n1 False 2\n\n>>> df.any(axis='columns')\n0 True\n1 True\ndtype: bool\n\n>>> df = pd.DataFrame({\"A\": [True, False], \"B\": [1, 0]})\n>>> df\n A B\n0 True 1\n1 False 0\n\n>>> df.any(axis='columns')\n0 True\n1 False\ndtype: bool\n\nAggregating over the entire DataFrame with ``axis=None``.\n\n>>> df.any(axis=None)\nTrue\n\n`any` for an empty DataFrame is an empty Series.\n\n>>> pd.DataFrame([]).any()\nSeries([], dtype: bool)\n\"\"\"\n\n_sum_examples = \"\"\"\\\nExamples\n--------\nBy default, the sum of an empty or all-NA Series is ``0``.\n\n>>> pd.Series([]).sum() # min_count=0 is the default\n0.0\n\nThis can be controlled with the ``min_count`` parameter. For example, if\nyou'd like the sum of an empty series to be NaN, pass ``min_count=1``.\n\n>>> pd.Series([]).sum(min_count=1)\nnan\n\nThanks to the ``skipna`` parameter, ``min_count`` handles all-NA and\nempty series identically.\n\n>>> pd.Series([np.nan]).sum()\n0.0\n\n>>> pd.Series([np.nan]).sum(min_count=1)\nnan\n\"\"\"\n\n_prod_examples = \"\"\"\\\nExamples\n--------\nBy default, the product of an empty or all-NA Series is ``1``\n\n>>> pd.Series([]).prod()\n1.0\n\nThis can be controlled with the ``min_count`` parameter\n\n>>> pd.Series([]).prod(min_count=1)\nnan\n\nThanks to the ``skipna`` parameter, ``min_count`` handles all-NA and\nempty series identically.\n\n>>> pd.Series([np.nan]).prod()\n1.0\n\n>>> pd.Series([np.nan]).prod(min_count=1)\nnan\n\"\"\"\n\n\n_min_count_stub = \"\"\"\\\nmin_count : int, default 0\n The required number of valid values to perform the operation. If fewer than\n ``min_count`` non-NA values are present the result will be NA.\n\n .. versionadded :: 0.22.0\n\n Added with the default being 0. This means the sum of an all-NA\n or empty Series is 0, and the product of an all-NA or empty\n Series is 1.\n\"\"\"\n\n\ndef _make_min_count_stat_function(cls, name, name1, name2, axis_descr, desc,\n f, examples):\n @Substitution(outname=name, desc=desc, name1=name1, name2=name2,\n axis_descr=axis_descr, min_count=_min_count_stub,\n examples=examples)\n @Appender(_num_doc)\n def stat_func(self, axis=None, skipna=None, level=None, numeric_only=None,\n min_count=0,\n **kwargs):\n nv.validate_stat_func(tuple(), kwargs, fname=name)\n if skipna is None:\n skipna = True\n if axis is None:\n axis = self._stat_axis_number\n if level is not None:\n return self._agg_by_level(name, axis=axis, level=level,\n skipna=skipna, min_count=min_count)\n return self._reduce(f, name, axis=axis, skipna=skipna,\n numeric_only=numeric_only, min_count=min_count)\n\n return set_function_name(stat_func, name, cls)\n\n\ndef _make_stat_function(cls, name, name1, name2, axis_descr, desc, f):\n @Substitution(outname=name, desc=desc, name1=name1, name2=name2,\n axis_descr=axis_descr, min_count='', examples='')\n @Appender(_num_doc)\n def stat_func(self, axis=None, skipna=None, level=None, numeric_only=None,\n **kwargs):\n nv.validate_stat_func(tuple(), kwargs, fname=name)\n if skipna is None:\n skipna = True\n if axis is None:\n axis = self._stat_axis_number\n if level is not None:\n return self._agg_by_level(name, axis=axis, level=level,\n skipna=skipna)\n return self._reduce(f, name, axis=axis, skipna=skipna,\n numeric_only=numeric_only)\n\n return set_function_name(stat_func, name, cls)\n\n\ndef _make_stat_function_ddof(cls, name, name1, name2, axis_descr, desc, f):\n @Substitution(outname=name, desc=desc, name1=name1, name2=name2,\n axis_descr=axis_descr)\n @Appender(_num_ddof_doc)\n def stat_func(self, axis=None, skipna=None, level=None, ddof=1,\n numeric_only=None, **kwargs):\n nv.validate_stat_ddof_func(tuple(), kwargs, fname=name)\n if skipna is None:\n skipna = True\n if axis is None:\n axis = self._stat_axis_number\n if level is not None:\n return self._agg_by_level(name, axis=axis, level=level,\n skipna=skipna, ddof=ddof)\n return self._reduce(f, name, axis=axis, numeric_only=numeric_only,\n skipna=skipna, ddof=ddof)\n\n return set_function_name(stat_func, name, cls)\n\n\ndef _make_cum_function(cls, name, name1, name2, axis_descr, desc,\n accum_func, accum_func_name, mask_a, mask_b, examples):\n @Substitution(outname=name, desc=desc, name1=name1, name2=name2,\n axis_descr=axis_descr, accum_func_name=accum_func_name,\n examples=examples)\n @Appender(_cnum_doc)\n def cum_func(self, axis=None, skipna=True, *args, **kwargs):\n skipna = nv.validate_cum_func_with_skipna(skipna, args, kwargs, name)\n if axis is None:\n axis = self._stat_axis_number\n else:\n axis = self._get_axis_number(axis)\n\n y = com.values_from_object(self).copy()\n\n if (skipna and\n issubclass(y.dtype.type, (np.datetime64, np.timedelta64))):\n result = accum_func(y, axis)\n mask = isna(self)\n np.putmask(result, mask, tslib.iNaT)\n elif skipna and not issubclass(y.dtype.type, (np.integer, np.bool_)):\n mask = isna(self)\n np.putmask(y, mask, mask_a)\n result = accum_func(y, axis)\n np.putmask(result, mask, mask_b)\n else:\n result = accum_func(y, axis)\n\n d = self._construct_axes_dict()\n d['copy'] = False\n return self._constructor(result, **d).__finalize__(self)\n\n return set_function_name(cum_func, name, cls)\n\n\ndef _make_logical_function(cls, name, name1, name2, axis_descr, desc, f,\n examples, see_also):\n @Substitution(outname=name, desc=desc, name1=name1, name2=name2,\n axis_descr=axis_descr, examples=examples, see_also=see_also)\n @Appender(_bool_doc)\n def logical_func(self, axis=0, bool_only=None, skipna=True, level=None,\n **kwargs):\n nv.validate_logical_func(tuple(), kwargs, fname=name)\n if level is not None:\n if bool_only is not None:\n raise NotImplementedError(\"Option bool_only is not \"\n \"implemented with option level.\")\n return self._agg_by_level(name, axis=axis, level=level,\n skipna=skipna)\n return self._reduce(f, name, axis=axis, skipna=skipna,\n numeric_only=bool_only, filter_type='bool')\n\n return set_function_name(logical_func, name, cls)\n\n\n# install the indexes\nfor _name, _indexer in indexing.get_indexers_list():\n NDFrame._create_indexer(_name, _indexer)\n" ]
[ [ "pandas.tseries.frequencies.to_offset", "pandas.util._validators.validate_bool_kwarg", "pandas.core.common.AbstractMethodError", "pandas.core.dtypes.inference.is_hashable", "pandas.core.missing.clean_reindex_fill_method", "pandas.core.nanops.nanmin", "pandas.compat.lzip", "numpy.where", "numpy.unique", "numpy.asanyarray", "pandas.core.common._pipe", "pandas.core.dtypes.common.is_categorical_dtype", "pandas.core.dtypes.common.is_re_compilable", "pandas.concat", "pandas.core.dtypes.common.is_list_like", "pandas.compat.numpy.function.validate_cum_func_with_skipna", "pandas.io.pickle.to_pickle", "numpy.array", "pandas.core.dtypes.common.is_period_arraylike", "pandas.io.formats.format.DataFrameFormatter", "pandas.core.dtypes.common.is_bool_dtype", "pandas.core.groupby.groupby.groupby", "pandas.core.dtypes.missing.isna", "pandas.io.sql.to_sql", "pandas.Series", "numpy.asarray", "pandas.io.json.to_json", "pandas.core.dtypes.common.is_datetime64tz_dtype", "pandas.core.common.SettingWithCopyError", "pandas.core.index.ensure_index", "numpy.putmask", "pandas.core.common.maybe_box_datetimelike", "numpy.errstate", "pandas.compat.isidentifier", "pandas.core.resample.resample", "pandas.core.common.random_state", "pandas.core.dtypes.common.is_integer", "pandas.core.index.Index", "pandas.core.indexes.datetimes.DatetimeIndex", "pandas.util._decorators.deprecate_kwarg", "pandas.core.dtypes.missing.notna", "pandas.DataFrame", "pandas.compat.map", "pandas.compat.iteritems", "pandas.core.window.expanding", "pandas.core.common.values_from_object", "pandas.io.pytables.to_hdf", "pandas.util._decorators.Substitution", "pandas.core.dtypes.common.is_numeric_dtype", "pandas.Index", "pandas.core.dtypes.common.is_number", "pandas._libs.tslib.Timestamp", "pandas.core.dtypes.common.ensure_int64", "pandas.core.dtypes.common.is_dict_like", "pandas.core.index.RangeIndex", "pandas.util._decorators.Appender", "pandas.core.window.ewm", "pandas.core.dtypes.common.pandas_dtype", "pandas.core.dtypes.common.is_timedelta64_dtype", "pandas.core.window.rolling", "numpy.isnan", "pandas.core.algorithms.rank", "pandas.core.missing.mask_missing", "pandas.compat.to_str", "pandas.core.missing.get_fill_func", "pandas.core.dtypes.common.is_bool", "pandas.core.missing.clean_fill_method", "pandas.isnull", "pandas.core.dtypes.common.is_scalar", "pandas.io.formats.format.format_percentiles", "pandas.util._validators.validate_fillna_kwargs", "pandas.compat.zip", "pandas.core.resample.asfreq", "pandas.compat.numpy.function.validate_clip_with_axis", "pandas.core.nanops.nanmax", "pandas.core.dtypes.cast.maybe_upcast_putmask", "numpy.minimum.accumulate", "pandas.core.indexes.period.Period", "numpy.any", "pandas.core.config.get_option", "pandas.core.indexing.get_indexers_list", "pandas.io.packers.to_msgpack", "pandas.io.clipboards.to_clipboard", "pandas.compat.set_function_name", "pandas.core.dtypes.common.is_datetime64_any_dtype", "pandas.compat.numpy.function.validate_transpose_for_generic", "pandas.core.dtypes.cast.maybe_promote", "pandas.core.tools.datetimes.to_datetime", "pandas.core.common.maybe_make_list", "pandas.core.common.count_not_none", "numpy.abs", "pandas.core.resample._maybe_process_deprecations", "pandas.core.dtypes.common.is_object_dtype", "pandas.core.common.apply_if_callable", "numpy.prod", "numpy.maximum.accumulate", "pandas.core.common.index_labels_to_array", "pandas.compat.lrange" ] ]
ajaykumaar/Food-therapy
[ "cbba734ed9eca32caceae5ac937cac487459f38a" ]
[ "app.py" ]
[ "from flask import *\nimport pymongo \nfrom pymongo import MongoClient\nimport joblib\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\nconnection_url = 'mongodb+srv://ajaykumaar:[email protected]/food-therapy?retryWrites=true&w=majority'\napp=Flask(__name__)\nclient = pymongo.MongoClient(connection_url) \n\nDatabase = client.get_database('food-therapy') \ntable = Database.confessions\n\ndef predict(model,tags):\n tag_l=[]\n tag_l.append(tags)\n max_len = 20 \n trunc_type = \"post\" \n padding_type = \"post\" \n\n file_path='static/tokenizer.sav'\n tokenizer=joblib.load(file_path)\n new_seq = tokenizer.texts_to_sequences(tag_l)\n padded = pad_sequences(new_seq, maxlen =max_len,\n padding = padding_type,\n truncating=trunc_type)\n return model.predict(padded)\n\ndef get_food(num):\n if num == 1:\n return ['Chocolates','Ice cream',' Sandwich']\n elif num == 2:\n return ['Biscuits','Fries','Chocolates']\n elif num == 3:\n return ['Pizza','Briyani','Noodles']\n elif num == 4:\n return ['Mac and Cheese','Fried chicken','Candy']\n elif num == 5:\n return ['Briyani','Ice cream','Chocolates']\n elif num == 6:\n return ['Coffee','Fruits','Hot chocolate']\n elif num == 7:\n return ['Briyani','Ice cream','Chocolates']\n elif num == 8:\n return ['Chocolates','Water','Paani poori']\n\n\[email protected]('/')\ndef home():\n return render_template('home.html')\n\[email protected]('/lament', methods=['POST', 'GET'])\ndef lament():\n return render_template('form.html')\n\[email protected]('/save', methods=['POST', 'GET'])\ndef save():\n name=request.form.get('name')\n confession=request.form.get('confession')\n tags=request.form.get('tags')\n\n file_path='static/foodtherapy_model.sav'\n model=joblib.load(file_path)\n preds=predict(model,str(tags))\n foods=get_food(int(preds))\n\n table.insert_one({\"Name\":name, \"Confession\":confession, \"Tags\":tags})\n\n return render_template('food.html',foods=foods)\n\nif __name__ == \"__main__\":\n app.run(debug=True)" ]
[ [ "tensorflow.keras.preprocessing.sequence.pad_sequences" ] ]
jcalcant/Programming-a-self-driving-car
[ "cb11d65d7b67298c93d6640edae71a06aa91da7c" ]
[ "ros/src/waypoint_updater/waypoint_updater.py" ]
[ "#!/usr/bin/env python\n\nimport rospy\nfrom geometry_msgs.msg import PoseStamped\nfrom styx_msgs.msg import Lane, Waypoint\nfrom scipy.spatial import KDTree\nfrom std_msgs.msg import Int32\n\nimport math\nimport numpy as np\n\n'''\nThis node will publish waypoints from the car's current position to some `x` distance ahead.\n\nAs mentioned in the doc, you should ideally first implement a version which does not care\nabout traffic lights or obstacles.\n\nOnce you have created dbw_node, you will update this node to use the status of traffic lights too.\n\nPlease note that our simulator also provides the exact location of traffic lights and their\ncurrent status in `/vehicle/traffic_lights` message. You can use this message to build this node\nas well as to verify your TL classifier.\n\nTODO (for Yousuf and Aaron): Stopline location for each traffic light.\n'''\n\nLOOKAHEAD_WPS = 50 # Number of waypoints we will publish. You can change this number\nMAX_DECEL = 0.5\n\nclass WaypointUpdater(object):\n def __init__(self):\n rospy.init_node('waypoint_updater')\n\n rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb)\n rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb)\n\n # TODO: Add a subscriber for /traffic_waypoint and /obstacle_waypoint below\n rospy.Subscriber('/traffic_waypoint', Int32, self.traffic_cb)\n\n self.final_waypoints_pub = rospy.Publisher('final_waypoints', Lane, queue_size=1)\n\n # TODO: Add other member variables you need below\n self.pose = None\n self.base_waypoints = None\n self.waypoints_2d = None\n self.waypoint_tree = None\n self.stopline_wp_idx = -1\n \n self.loop()\n \n \n def loop(self):\n rate = rospy.Rate(50) # 50 hz\n while not rospy.is_shutdown():\n if self.pose and self.base_waypoints and self.waypoint_tree:\n #get closest waypoint\n #closest_waypoint_idx = self.get_closest_waypoint_idx()\n self.publish_waypoints() #closest_waypoint_idx\n rate.sleep()\n \n def get_closest_waypoint_idx(self):\n x = self.pose.pose.position.x\n y = self.pose.pose.position.y\n closest_idx = self.waypoint_tree.query([x,y],1)[1] # first 1 is for getting 1 closest item,the next 1 is for getting the index from the query\n \n #check if closest is ahead or behind of the vehicle\n closest_coord = self.waypoints_2d[closest_idx]\n prev_coord = self.waypoints_2d[closest_idx-1]\n \n #Equation for hyperplane through closest coords\n cl_vect = np.array(closest_coord)\n prev_vect = np.array(prev_coord)\n pos_vect = np.array([x,y])\n \n val = np.dot(cl_vect - prev_vect, pos_vect - cl_vect)\n \n if (val > 0): # if closest_idx is behind the car, then we take the next idx\n closest_idx = (closest_idx + 1) % len(self.waypoints_2d)\n return closest_idx\n \n def publish_waypoints(self):\n final_lane = self.generate_lane()\n self.final_waypoints_pub.publish(final_lane)\n \n #lane = Lane()\n #lane.header = self.base_waypoints.header\n #lane.waypoints = self.base_waypoints.waypoints[closest_idx : closest_idx + LOOKAHEAD_WPS]\n #self.final_waypoints_pub.publish(lane)\n \n def generate_lane(self):\n lane = Lane()\n closest_idx = self.get_closest_waypoint_idx()\n farthest_idx = closest_idx + LOOKAHEAD_WPS\n base_waypoints = self.base_waypoints.waypoints[closest_idx : farthest_idx]\n \n if (self.stopline_wp_idx == -1) or (self.stopline_wp_idx >= farthest_idx): #we didn't detect any traffic light that we are concerned about\n lane.waypoints = base_waypoints\n else: #otherwise, decelerate\n lane.waypoints = self.decelerate_waypoints(base_waypoints,closest_idx)\n \n return lane\n \n def decelerate_waypoints(self,waypoints,closest_idx):\n temp = []\n for i,wp in enumerate(waypoints):\n p = Waypoint()\n p.pose = wp.pose\n \n stop_idx = max(self.stopline_wp_idx - closest_idx -2, 0) # two waypoints back from line so front of the car stops at the line\n dist = self.distance(waypoints, i, stop_idx)\n vel = math.sqrt(2 * MAX_DECEL * dist)\n if vel < 1.0:\n vel = 0.0\n \n p.twist.twist.linear.x = min(vel,wp.twist.twist.linear.x) #keep the speed limit\n temp.append(p)\n \n return temp\n\n\n def pose_cb(self, msg):\n # TODO: Implement\n self.pose = msg\n\n def waypoints_cb(self, waypoints):\n # TODO: Implement\n self.base_waypoints = waypoints\n if not self.waypoints_2d:\n self.waypoints_2d = [[waypoint.pose.pose.position.x, waypoint.pose.pose.position.y] for waypoint in waypoints.waypoints]\n self.waypoint_tree = KDTree(self.waypoints_2d) # data structure for getting closest point within a set of points\n\n def traffic_cb(self, msg):\n # TODO: Callback for /traffic_waypoint message. Implement\n self.stopline_wp_idx = msg.data\n\n def obstacle_cb(self, msg):\n # TODO: Callback for /obstacle_waypoint message. We will implement it later\n pass\n\n def get_waypoint_velocity(self, waypoint):\n return waypoint.twist.twist.linear.x\n\n def set_waypoint_velocity(self, waypoints, waypoint, velocity):\n waypoints[waypoint].twist.twist.linear.x = velocity\n\n def distance(self, waypoints, wp1, wp2):\n dist = 0\n dl = lambda a, b: math.sqrt((a.x-b.x)**2 + (a.y-b.y)**2 + (a.z-b.z)**2)\n for i in range(wp1, wp2+1):\n dist += dl(waypoints[wp1].pose.pose.position, waypoints[i].pose.pose.position)\n wp1 = i\n return dist\n\n\nif __name__ == '__main__':\n try:\n WaypointUpdater()\n except rospy.ROSInterruptException:\n rospy.logerr('Could not start waypoint updater node.')\n" ]
[ [ "numpy.dot", "numpy.array", "scipy.spatial.KDTree" ] ]
fermi-lat/extendedArchive
[ "d68b2e6e6699d68d157eb4d25cf64d935055445f" ]
[ "build_archive.py" ]
[ "from __future__ import absolute_import, division, print_function\nimport os\nimport re\nimport yaml\nimport argparse\nimport xml.etree.cElementTree as ElementTree\nimport numpy as np\nfrom astropy.table import Table, Column\nfrom astropy.coordinates import SkyCoord\n\n\ndef path_to_xmlpath(path):\n if path is None:\n return path\n\n return re.sub(r'\\$([a-zA-Z\\_]+)', r'$(\\1)', path)\n\n\ndef mkdir(dir):\n if not os.path.exists(dir):\n os.makedirs(dir)\n return dir\n\n\ndef prettify_xml(elem):\n \"\"\"Return a pretty-printed XML string for the Element.\n \"\"\"\n from xml.dom import minidom\n rough_string = ElementTree.tostring(elem, 'utf-8')\n reparsed = minidom.parseString(rough_string)\n return reparsed.toprettyxml(indent=\" \")\n\n\ndef isstr(s):\n \"\"\"String instance testing method that works under both Python 2.X\n and 3.X. Returns true if the input is a string.\"\"\"\n\n try:\n return isinstance(s, basestring)\n except NameError:\n return isinstance(s, str)\n\n\ndef to_xml(xmlfile, name, src_dict):\n\n params = src_dict['Spectral_Parameters']\n spatial_type = src_dict['Spatial_Function']\n spectral_type = src_dict['Spectral_Function']\n defaults = {\n 'Prefactor': {'scale': 1, 'name': 'Prefactor', 'free': 0, 'min': 1, 'max': 1},\n 'RA': {'scale': 1, 'name': 'RA', 'free': 0, 'min': 0, 'max': 360},\n 'DEC': {'scale': 1, 'name': 'DEC', 'free': 0, 'min': -90, 'max': 90},\n 'Radius': {'scale': 1, 'name': 'Radius', 'free': 0, 'min': 0, 'max': 10},\n 'Sigma': {'scale': 1, 'name': 'Sigma', 'free': 0, 'min': 0, 'max': 10},\n }\n\n if spatial_type == 'RadialDisk':\n params_spat = {'RA': defaults['RA'].copy(), 'DEC': defaults['DEC'].copy(),\n 'Radius': defaults['Radius'].copy()}\n params_spat['Radius']['value'] = np.sqrt(src_dict['Model_SemiMajor'] *\n src_dict['Model_SemiMinor'])\n params_spat['RA']['value'] = src_dict['RAJ2000']\n params_spat['DEC']['value'] = src_dict['DEJ2000']\n elif spatial_type == 'RadialGaussian':\n params_spat = {'RA': defaults['RA'].copy(), 'DEC': defaults['DEC'].copy(),\n 'Sigma': defaults['Sigma'].copy()}\n params_spat['Sigma']['value'] = np.sqrt(src_dict['Model_SemiMajor'] *\n src_dict['Model_SemiMinor'])\n params_spat['Sigma']['value'] /= 1.5095921854516636\n params_spat['RA']['value'] = src_dict['RAJ2000']\n params_spat['DEC']['value'] = src_dict['DEJ2000']\n else:\n params_spat = { 'Prefactor' : defaults['Prefactor'] }\n\n root = ElementTree.Element('source_library')\n root.set('title', 'source_library')\n\n source_element = create_xml_element(root, 'source',\n dict(name=name,\n type='DiffuseSource'))\n\n #filename = utils.path_to_xmlpath(self.filefunction)\n spec = create_xml_element(source_element, 'spectrum',\n dict(type=src_dict['Spectral_Function']))\n\n attrib = dict(type=spatial_type)\n if spatial_type == 'SpatialMap':\n attrib['file'] = path_to_xmlpath(src_dict['Spatial_Filename'])\n attrib['map_based_integral'] = 'true'\n \n spat = create_xml_element(source_element, 'spatialModel', attrib)\n\n for k, v in params.items():\n create_xml_element(spec, 'parameter', v)\n\n for k, v in params_spat.items():\n create_xml_element(spat, 'parameter', v)\n\n output_file = open(xmlfile, 'w')\n output_file.write(prettify_xml(root))\n\n\ndef create_xml_element(root, name, attrib):\n el = ElementTree.SubElement(root, name)\n for k, v in attrib.items():\n\n if isinstance(v, bool):\n el.set(k, str(int(v)))\n elif isstr(v):\n el.set(k, v)\n elif np.isfinite(v):\n el.set(k, str(v))\n\n return el\n\n\ndef set_coordinates(src_dict):\n\n has_cel = 'RAJ2000' in src_dict and 'DEJ2000' in src_dict\n has_gal = 'GLON' in src_dict and 'GLAT' in src_dict\n\n if not has_gal and not has_gal:\n raise Exception()\n\n if not has_gal:\n skydir = SkyCoord(src_dict['RAJ2000'], src_dict['RAJ2000'],\n unit='deg', frame='icrs')\n skydir = skydir.transform_to('galactic')\n src_dict['GLAT'] = skydir.b.deg\n src_dict['GLON'] = skydir.l.deg\n\n\ndef main():\n\n usage = \"usage: %(prog)s [archive file]\"\n description = \"Build the extended archive from the master archive YAML file.\"\n parser = argparse.ArgumentParser(usage=usage, description=description)\n\n parser.add_argument('--outdir', default=None, required=True)\n\n parser.add_argument('masterfile',\n help='Extended archive master YAML file.')\n\n args = parser.parse_args()\n \n npar_max = 10\n o = yaml.load(open(args.masterfile))\n cols = [Column(name='Source_Name', dtype='S40'),\n Column(name='RAJ2000', dtype=float, unit='deg'),\n Column(name='DEJ2000', dtype=float, unit='deg'),\n Column(name='GLON', dtype=float, unit='deg'),\n Column(name='GLAT', dtype=float, unit='deg'),\n Column(name='Photon_Flux', dtype=float, unit='ph / (cm2 s)'),\n Column(name='Energy_Flux', dtype=float, unit='erg / (cm2 s)'),\n Column(name='Model_Form', dtype='S40'),\n Column(name='Model_SemiMajor', dtype=float, unit='deg'),\n Column(name='Model_SemiMinor', dtype=float, unit='deg'),\n Column(name='Model_PosAng', dtype=float, unit='deg'),\n Column(name='Spatial_Function', dtype='S40'),\n Column(name='Spectral_Function', dtype='S40'),\n Column(name='Spectral_Filename', dtype='S40'),\n Column(name='Name_1FGL', dtype='S18'),\n Column(name='Name_2FGL', dtype='S18'),\n Column(name='Name_3FGL', dtype='S18'),\n Column(name='Spatial_Filename', dtype='S50'),\n Column(name='Spectral_Param_Name', dtype='S40', shape=(npar_max,)),\n Column(name='Spectral_Param_Value',\n dtype=float, shape=(npar_max,)),\n Column(name='Spectral_Param_Error',\n dtype=float, shape=(npar_max,)),\n Column(name='Spectral_Param_Scale',\n dtype=float, shape=(npar_max,)),\n ]\n\n tab = Table(cols)\n\n mkdir(args.outdir)\n xmldir = os.path.join(args.outdir, 'XML')\n mkdir(xmldir)\n\n for k, v in o.items():\n \n set_coordinates(v)\n row = {c: v.get(c, None) for c in tab.columns}\n\n params = v.get('Spectral_Parameters')\n param_names = params.keys()\n npars = len(param_names)\n row['Spectral_Param_Name'] = param_names + [''] * (npar_max - npars)\n row['Spectral_Param_Value'] = [\n float(params[k]['value']) for k in param_names] + [np.nan] * (npar_max - npars)\n row['Spectral_Param_Error'] = [\n float(params[k]['error']) if 'error' in params[k] else np.nan for k in param_names] + [np.nan] * (npar_max - npars)\n row['Spectral_Param_Scale'] = [\n float(params[k]['scale']) for k in param_names] + [np.nan] * (npar_max - npars)\n row = [row[c] for c in tab.columns]\n\n tab.add_row(row)\n xmlpath = os.path.join(xmldir, v['Source_Name'].replace(' ', '') + '.xml')\n to_xml(xmlpath, v['Source_Name'], v)\n\n tab.write(os.path.join(args.outdir,\n 'LAT_extended_sources.fits'), overwrite=True)\n\n # TODO: Generate region file\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.sqrt", "numpy.isfinite" ] ]
jjerry-k/BentoML
[ "1efd77c609b3fc2e153436c57db9b3707608c894" ]
[ "bentoml/_internal/frameworks/tensorflow.py" ]
[ "import os\nimport re\nimport uuid\nimport typing as t\nimport logging\nimport pathlib\nimport functools\nfrom typing import TYPE_CHECKING\nfrom distutils.dir_util import copy_tree\n\nfrom simple_di import inject\nfrom simple_di import Provide\n\nfrom bentoml import Tag\nfrom bentoml import Model\nfrom bentoml import Runner\nfrom bentoml.exceptions import BentoMLException\nfrom bentoml.exceptions import MissingDependencyException\n\nfrom ..types import PathType\nfrom ..runner.utils import Params\nfrom ..utils.tensorflow import get_arg_names\nfrom ..utils.tensorflow import get_tf_version\nfrom ..utils.tensorflow import cast_tensor_by_spec\nfrom ..utils.tensorflow import get_input_signatures\nfrom ..utils.tensorflow import get_restored_functions\nfrom ..utils.tensorflow import pretty_format_restored_model\nfrom ..configuration.containers import BentoMLContainer\n\nif TYPE_CHECKING:\n import numpy as np\n import tensorflow.keras as keras\n\n from ..models import ModelStore\n\ntry:\n import tensorflow as tf\n from tensorflow.python.client import device_lib\nexcept ImportError: # pragma: no cover\n raise MissingDependencyException(\n \"\"\"\\\n `tensorflow` is required in order to use `bentoml.tensorflow`.\n Instruction: `pip install tensorflow`\n \"\"\"\n )\n\ntry:\n import tensorflow.python.training.tracking.tracking as tracking\nexcept ImportError: # pragma: no cover\n import tensorflow_core.python.training.tracking.tracking as tracking\n\ntry:\n import importlib.metadata as importlib_metadata\nexcept ImportError:\n import importlib_metadata\n\n_tf_version = get_tf_version()\nlogger = logging.getLogger(__name__)\nTF2 = _tf_version.startswith(\"2\")\n\nMODULE_NAME = \"bentoml.tensorflow\"\n\ntry:\n import tensorflow_hub as hub\n from tensorflow_hub import resolve\n from tensorflow_hub import native_module\nexcept ImportError: # pragma: no cover\n logger.warning(\n \"\"\"\\\n If you want to use `bentoml.tensorflow.import_from_tfhub(),\n make sure to `pip install --upgrade tensorflow_hub` before using.\n \"\"\"\n )\n hub = None\n resolve, native_module = None, None\n\ntry:\n _tfhub_version = importlib_metadata.version(\"tensorflow_hub\")\nexcept importlib_metadata.PackageNotFoundError:\n _tfhub_version = None\n\n\ndef _clean_name(name: str) -> str: # pragma: no cover\n return re.sub(r\"\\W|^(?=\\d)-\", \"_\", name)\n\n\nAUTOTRACKABLE_CALLABLE_WARNING: str = \"\"\"\nImporting SavedModels from TensorFlow 1.x. `outputs = imported(inputs)`\n will not be supported by BentoML due to `tensorflow` API.\\n\nSee https://www.tensorflow.org/api_docs/python/tf/saved_model/load for\n more details.\n\"\"\"\n\nTF_FUNCTION_WARNING: str = \"\"\"\nDue to TensorFlow's internal mechanism, only methods\n wrapped under `@tf.function` decorator and the Keras default function\n `__call__(inputs, training=False)` can be restored after a save & load.\\n\nYou can test the restored model object via `bentoml.tensorflow.load(path)`\n\"\"\"\n\nKERAS_MODEL_WARNING: str = \"\"\"\nBentoML detected that {name} is being used to pack a Keras API\n based model. In order to get optimal serving performance, we recommend\n to wrap your keras model `call()` methods with `@tf.function` decorator.\n\"\"\"\n\n\ndef _is_gpu_available() -> bool:\n try:\n return len(tf.config.list_physical_devices(\"GPU\")) > 0\n except AttributeError:\n return tf.test.is_gpu_available() # type: ignore\n\n\nclass _tf_function_wrapper: # pragma: no cover\n def __init__(\n self,\n origin_func: t.Callable[..., t.Any],\n arg_names: t.Optional[t.List[str]] = None,\n arg_specs: t.Optional[t.List[t.Any]] = None,\n kwarg_specs: t.Optional[t.Dict[str, t.Any]] = None,\n ) -> None:\n self.origin_func = origin_func\n self.arg_names = arg_names\n self.arg_specs = arg_specs\n self.kwarg_specs = {k: v for k, v in zip(arg_names or [], arg_specs or [])}\n self.kwarg_specs.update(kwarg_specs or {})\n\n def __call__(self, *args: str, **kwargs: str) -> t.Any:\n if self.arg_specs is None and self.kwarg_specs is None:\n return self.origin_func(*args, **kwargs)\n\n for k in kwargs:\n if k not in self.kwarg_specs:\n raise TypeError(f\"Function got an unexpected keyword argument {k}\")\n\n arg_keys = {k for k, _ in zip(self.arg_names, args)} # type: ignore[arg-type]\n _ambiguous_keys = arg_keys & set(kwargs) # type: t.Set[str]\n if _ambiguous_keys:\n raise TypeError(f\"got two values for arguments '{_ambiguous_keys}'\")\n\n # INFO:\n # how signature with kwargs works?\n # https://github.com/tensorflow/tensorflow/blob/v2.0.0/tensorflow/python/eager/function.py#L1519\n transformed_args: t.Tuple[t.Any, ...] = tuple(\n cast_tensor_by_spec(arg, spec) for arg, spec in zip(args, self.arg_specs) # type: ignore[arg-type] # noqa\n )\n\n transformed_kwargs = {\n k: cast_tensor_by_spec(arg, self.kwarg_specs[k])\n for k, arg in kwargs.items()\n }\n return self.origin_func(*transformed_args, **transformed_kwargs)\n\n def __getattr__(self, k: t.Any) -> t.Any:\n return getattr(self.origin_func, k)\n\n @classmethod\n def hook_loaded_model(cls, loaded_model: t.Any) -> None:\n funcs = get_restored_functions(loaded_model)\n for k, func in funcs.items():\n arg_names = get_arg_names(func)\n sigs = get_input_signatures(func)\n if not sigs:\n continue\n arg_specs, kwarg_specs = sigs[0]\n setattr(\n loaded_model,\n k,\n cls(\n func,\n arg_names=arg_names,\n arg_specs=arg_specs,\n kwarg_specs=kwarg_specs,\n ),\n )\n\n\ndef _load_tf_saved_model(path: str) -> t.Union[\"tracking.AutoTrackable\", t.Any]:\n if TF2:\n return tf.saved_model.load(path)\n else:\n loaded = tf.compat.v2.saved_model.load(path)\n if isinstance(loaded, tracking.AutoTrackable) and not hasattr(\n loaded, \"__call__\"\n ):\n logger.warning(AUTOTRACKABLE_CALLABLE_WARNING)\n return loaded\n\n\n@inject\ndef load(\n tag: Tag,\n tfhub_tags: t.Optional[t.List[str]] = None,\n tfhub_options: t.Optional[t.Any] = None,\n load_as_wrapper: t.Optional[bool] = None,\n model_store: \"ModelStore\" = Provide[BentoMLContainer.model_store],\n) -> t.Any: # returns tf.sessions or keras models\n \"\"\"\n Load a model from BentoML local modelstore with given name.\n\n Args:\n tag (:code:`Union[str, Tag]`):\n Tag of a saved model in BentoML local modelstore.\n tfhub_tags (:code:`str`, `optional`, defaults to `None`):\n A set of strings specifying the graph variant to use, if loading from a v1 module.\n tfhub_options (:code:`tensorflow.saved_model.SaveOptions`, `optional`, default to :code:`None`):\n :code:`tensorflow.saved_model.LoadOptions` object that specifies options for loading. This\n argument can only be used from TensorFlow 2.3 onwards.\n load_as_wrapper (`bool`, `optional`, default to :code:`True`):\n Load the given weight that is saved from tfhub as either `hub.KerasLayer` or `hub.Module`.\n The latter only applies for TF1.\n model_store (:mod:`~bentoml._internal.models.store.ModelStore`, default to :mod:`BentoMLContainer.model_store`):\n BentoML modelstore, provided by DI Container.\n\n Returns:\n :obj:`SavedModel`: an instance of :obj:`SavedModel` format from BentoML modelstore.\n\n Examples:\n\n .. tabs::\n\n .. code-tab:: tensorflow_v1\n\n import bentoml\n\n # load a model back into memory\n model = bentoml.tensorflow.load(\"my_tensorflow_model\")\n\n .. code-tab:: tensorflow_v2\n\n import bentoml\n\n # load a model back into memory\n model = bentoml.tensorflow.load(\"my_tensorflow_model\")\n\n \"\"\" # noqa: LN001\n model = model_store.get(tag)\n if model.info.module not in (MODULE_NAME, __name__):\n raise BentoMLException(\n f\"Model {tag} was saved with module {model.info.module}, failed loading with {MODULE_NAME}.\"\n )\n if model.info.context[\"import_from_tfhub\"]:\n assert load_as_wrapper is not None, (\n \"You have to specified `load_as_wrapper=True | False`\"\n \" to load a `tensorflow_hub` module. If True is chosen,\"\n \" then BentoML will return either an instance of `hub.KerasLayer`\"\n \" or `hub.Module` depending on your TF version. For most usecase,\"\n \" we recommend to keep `load_as_wrapper=True`. If you wish to extend\"\n \" the functionalities of the given model, set `load_as_wrapper=False`\"\n \" will return a SavedModel object.\"\n )\n assert all(\n i is not None for i in [hub, resolve, native_module]\n ), MissingDependencyException(\n \"`tensorflow_hub` is required to load a tfhub module.\"\n )\n module_path = model.path_of(model.info.options[\"local_path\"])\n if load_as_wrapper:\n assert hub is not None\n wrapper_class = hub.KerasLayer if TF2 else hub.Module\n return wrapper_class(module_path)\n # In case users want to load as a SavedModel file object.\n # https://github.com/tensorflow/hub/blob/master/tensorflow_hub/module_v2.py#L93\n is_hub_module_v1 = tf.io.gfile.exists(\n native_module.get_module_proto_path(module_path)\n )\n if tfhub_tags is None and is_hub_module_v1:\n tfhub_tags = []\n\n if tfhub_options is not None:\n if not isinstance(tfhub_options, tf.saved_model.SaveOptions):\n raise BentoMLException(\n f\"`tfhub_options` has to be of type `tf.saved_model.SaveOptions`, got {type(tfhub_options)} instead.\"\n )\n if not hasattr(getattr(tf, \"saved_model\", None), \"LoadOptions\"):\n raise NotImplementedError(\n \"options are not supported for TF < 2.3.x,\"\n f\" Current version: {_tf_version}\"\n )\n # tf.compat.v1.saved_model.load_v2() is TF2 tf.saved_model.load() before TF2\n obj = tf.compat.v1.saved_model.load_v2(\n module_path, tags=tfhub_tags, options=tfhub_options\n )\n else:\n obj = tf.compat.v1.saved_model.load_v2(module_path, tags=tfhub_tags)\n obj._is_hub_module_v1 = (\n is_hub_module_v1 # pylint: disable=protected-access # noqa\n )\n return obj\n else:\n tf_model = _load_tf_saved_model(model.path)\n _tf_function_wrapper.hook_loaded_model(tf_model)\n logger.warning(TF_FUNCTION_WARNING)\n # pretty format loaded model\n logger.info(pretty_format_restored_model(tf_model))\n if hasattr(tf_model, \"keras_api\"):\n logger.warning(KERAS_MODEL_WARNING.format(name=MODULE_NAME))\n return tf_model\n\n\n@inject\ndef import_from_tfhub(\n identifier: t.Union[str, \"hub.Module\", \"hub.KerasLayer\"],\n name: t.Optional[str] = None,\n metadata: t.Optional[t.Dict[str, t.Any]] = None,\n model_store: \"ModelStore\" = Provide[BentoMLContainer.model_store],\n) -> Tag:\n \"\"\"\n Import a model from `Tensorflow Hub <https://tfhub.dev/>`_ to BentoML modelstore.\n\n Args:\n identifier (:code:`Union[str, tensorflow_hub.Module, tensorflow_hub.KerasLayer]`): Identifier accepts\n two type of inputs:\n - if `type` of :code:`identifier` either of type :code:`tensorflow_hub.Module` (**legacy** `tensorflow_hub`) or :code:`tensorflow_hub.KerasLayer` (`tensorflow_hub`), then we will save the given model to a :code:`SavedModel` format.\n - if `type` of :code:`identifier` is a :obj:`str`, we assume that this is the URI retrieved from Tensorflow Hub. We then clean the given URI, and get a local copy of a given model to BentoML modelstore. name (:code:`str`, `optional`, defaults to `None`): An optional name for the model. If :code:`identifier` is a :obj:`str`, then name can be autogenerated from the given URI.\n metadata (:code:`Dict[str, Any]`, `optional`, default to :code:`None`):\n Custom metadata for given model.\n model_store (:mod:`~bentoml._internal.models.store.ModelStore`, default to :mod:`BentoMLContainer.model_store`):\n BentoML modelstore, provided by DI Container.\n\n Returns:\n :obj:`~bentoml._internal.types.Tag`: A :obj:`~bentoml._internal.types.Tag` object that can be used to retrieve the model with :func:`bentoml.tensorflow.load`:\n\n Example for importing a model from Tensorflow Hub:\n\n .. code-block:: python\n\n import tensorflow_text as text # noqa # pylint: disable\n import bentoml\n\n tag = bentoml.tensorflow.import_from_tfhub(\"https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3\")\n\n # load model back with `load`:\n model = bentoml.tensorflow.load(tag, load_as_wrapper=True)\n\n Example for importing a custom Tensorflow Hub model:\n\n .. tabs::\n\n .. code-tab:: tensorflow_v1\n\n import tensorflow as tf\n import tensorflow_hub as hub\n import bentoml\n\n # Simple toy Tensorflow Hub model\n def _plus_one_model_tf1():\n def plus_one():\n x = tf.compat.v1.placeholder(dtype=tf.float32, name=\"x\")\n y = x + 1\n hub.add_signature(inputs=x, outputs=y)\n\n spec = hub.create_module_spec(plus_one)\n with tf.compat.v1.get_default_graph().as_default():\n module = hub.Module(spec, trainable=True)\n return module\n\n model = _plus_one_model_tf1()\n\n # retrieve the given tag:\n tag = bentoml.tensorflow.import_from_tfhub(model)\n\n .. code-tab:: tensorflow_v2\n\n import tensorflow as tf\n import tensorflow_hub as hub\n import bentoml\n\n def _plus_one_model_tf2():\n obj = tf.train.Checkpoint()\n\n @tf.function(input_signature=[tf.TensorSpec(None, dtype=tf.float32)])\n def plus_one(x):\n return x + 1\n\n obj.__call__ = plus_one\n return obj\n\n # then save the given model to BentoML modelstore:\n model = _plus_one_model_tf2()\n tag = bentoml.tensorflow.import_from_tfhub(model)\n \"\"\" # noqa\n context: t.Dict[str, t.Any] = {\n \"framework_name\": \"tensorflow\",\n \"pip_dependencies\": [\n f\"tensorflow=={_tf_version}\",\n f\"tensorflow_hub=={_tfhub_version}\",\n ],\n \"import_from_tfhub\": True,\n }\n if name is None:\n if isinstance(identifier, str):\n if identifier.startswith((\"http://\", \"https://\")):\n name = _clean_name(identifier.split(\"/\", maxsplit=3)[-1])\n else:\n name = _clean_name(identifier.split(\"/\")[-1])\n else:\n name = f\"{identifier.__class__.__name__}_{uuid.uuid4().hex[:5].upper()}\"\n _model = Model.create(\n name,\n module=MODULE_NAME,\n options=None,\n context=context,\n metadata=metadata,\n )\n if isinstance(identifier, str):\n os.environ[\"TFHUB_CACHE_DIR\"] = _model.path\n fpath = resolve(identifier)\n folder = fpath.split(\"/\")[-1]\n _model.info.options = {\"model\": identifier, \"local_path\": folder}\n else:\n if hasattr(identifier, \"export\"):\n # hub.Module.export()\n with tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph()) as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n identifier.export(_model.path, sess)\n else:\n tf.saved_model.save(identifier, _model.path)\n _model.info.options = {\n \"model\": identifier.__class__.__name__,\n \"local_path\": \".\",\n }\n\n _model.save(model_store)\n return _model.tag\n\n\n@inject\ndef save(\n name: str,\n model: t.Union[\"keras.Model\", \"tf.Module\", PathType],\n *,\n signatures: t.Optional[t.Union[t.Callable[..., t.Any], t.Dict[str, t.Any]]] = None,\n options: t.Optional[\"tf.saved_model.SaveOptions\"] = None,\n metadata: t.Optional[t.Dict[str, t.Any]] = None,\n model_store: \"ModelStore\" = Provide[BentoMLContainer.model_store],\n) -> Tag:\n \"\"\"\n Save a model instance to BentoML modelstore.\n\n Args:\n name (:code:`str`):\n Name for given model instance. This should pass Python identifier check.\n model (:code:`Union[keras.Model, tf.Module, path-like objects]`):\n Instance of model to be saved\n metadata (:code:`Dict[str, Any]`, `optional`, default to :code:`None`):\n Custom metadata for given model.\n model_store (:mod:`~bentoml._internal.models.store.ModelStore`, default to :mod:`BentoMLContainer.model_store`):\n BentoML modelstore, provided by DI Container.\n signatures (:code:`Union[Callable[..., Any], dict]`, `optional`, default to :code:`None`):\n Refers to `Signatures explanation <https://www.tensorflow.org/api_docs/python/tf/saved_model/save>`_\n from Tensorflow documentation for more information.\n options (`tf.saved_model.SaveOptions`, `optional`, default to :code:`None`):\n :obj:`tf.saved_model.SaveOptions` object that specifies options for saving.\n\n Raises:\n ValueError: If :obj:`obj` is not trackable.\n\n Returns:\n :obj:`~bentoml._internal.types.Tag`: A :obj:`tag` with a format `name:version` where `name` is the user-defined model's name, and a generated `version` by BentoML.\n\n Examples:\n\n .. tabs::\n\n .. code-tab:: tensorflow_v1\n\n import tensorflow as tf\n import tempfile\n import bentoml\n\n location = \"\"\n\n # Function below builds model graph\n def cnn_model_fn():\n X = tf.compat.v1.placeholder(shape=[None, 2], dtype=tf.float32, name=\"X\")\n\n # dense layer\n inter1 = tf.compat.v1.layers.dense(inputs=X, units=1, activation=tf.nn.relu)\n p = tf.argmax(input=inter1, axis=1)\n\n # loss\n y = tf.compat.v1.placeholder(tf.float32, shape=[None, 1], name=\"y\")\n loss = tf.losses.softmax_cross_entropy(y, inter1)\n\n # training operation\n train_op = tf.compat.v1.train.AdamOptimizer().minimize(loss)\n\n return {\"p\": p, \"loss\": loss, \"train_op\": train_op, \"X\": X, \"y\": y}\n\n cnn_model = cnn_model_fn()\n\n with tempfile.TemporaryDirectory() as temp_dir:\n with tf.compat.v1.Session() as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n sess.run(cnn_model[\"p\"], {cnn_model[\"X\"]: test_data})\n\n inputs = {\"X\": cnn_model[\"X\"]}\n outputs = {\"prediction\": cnn_model[\"p\"]}\n\n tf.compat.v1.saved_model.simple_save(\n sess, temp_dir, inputs=inputs, outputs=outputs\n )\n location = temp_dir\n\n # then save the given model to BentoML modelstore:\n tag = bentoml.tensorflow.save(\"cnn_model\", location)\n\n .. code-tab:: tensorflow_v2\n\n import tensorflow as tf\n import numpy as np\n import bentoml\n\n class NativeModel(tf.Module):\n def __init__(self):\n super().__init__()\n self.weights = np.asfarray([[1.0], [1.0], [1.0], [1.0], [1.0]])\n self.dense = lambda inputs: tf.matmul(inputs, self.weights)\n\n @tf.function(\n input_signature=[tf.TensorSpec(shape=[1, 5], dtype=tf.float64, name=\"inputs\")]\n )\n def __call__(self, inputs):\n return self.dense(inputs)\n\n # then save the given model to BentoML modelstore:\n model = NativeModel()\n tag = bentoml.tensorflow.save(\"native_toy\", model)\n\n .. note::\n\n\n :code:`bentoml.tensorflow.save` API also support saving `RaggedTensor <https://www.tensorflow.org/guide/ragged_tensor>`_ model and Keras model. If you choose to save a Keras model\n with :code:`bentoml.tensorflow.save`, then the model will be saved under a :obj:`SavedModel` format instead of :obj:`.h5`.\n\n \"\"\" # noqa\n context: t.Dict[str, t.Any] = {\n \"framework_name\": \"tensorflow\",\n \"pip_dependencies\": [f\"tensorflow=={_tf_version}\"],\n \"import_from_tfhub\": False,\n }\n _model = Model.create(\n name,\n module=MODULE_NAME,\n options=None,\n context=context,\n metadata=metadata,\n )\n\n if isinstance(model, (str, bytes, os.PathLike, pathlib.Path)): # type: ignore[reportUnknownMemberType] # noqa\n assert os.path.isdir(model)\n copy_tree(str(model), _model.path)\n else:\n if TF2:\n tf.saved_model.save(\n model, _model.path, signatures=signatures, options=options\n )\n else:\n if options:\n logger.warning(\n f\"Parameter 'options: {str(options)}' is ignored when \"\n f\"using tensorflow {tf.__version__}\"\n )\n tf.saved_model.save(model, _model.path, signatures=signatures)\n\n _model.save(model_store)\n return _model.tag\n\n\nclass _TensorflowRunner(Runner):\n @inject\n def __init__(\n self,\n tag: Tag,\n predict_fn_name: str,\n device_id: str,\n partial_kwargs: t.Optional[t.Dict[str, t.Any]],\n name: str,\n resource_quota: t.Optional[t.Dict[str, t.Any]],\n batch_options: t.Optional[t.Dict[str, t.Any]],\n model_store: \"ModelStore\" = Provide[BentoMLContainer.model_store],\n ):\n in_store_tag = model_store.get(tag).tag\n self._tag = in_store_tag\n super().__init__(name, resource_quota, batch_options)\n\n self._device_id = device_id\n self._configure(device_id)\n self._predict_fn_name = predict_fn_name\n assert any(device_id in d.name for d in device_lib.list_local_devices())\n self._partial_kwargs: t.Dict[str, t.Any] = (\n partial_kwargs if partial_kwargs is not None else dict()\n )\n self._model_store = model_store\n\n def _configure(self, device_id: str) -> None:\n if TF2 and \"GPU\" in device_id:\n tf.config.set_visible_devices(device_id, \"GPU\")\n self._config_proto = dict(\n allow_soft_placement=True,\n log_device_placement=False,\n intra_op_parallelism_threads=self.num_concurrency_per_replica,\n inter_op_parallelism_threads=self.num_concurrency_per_replica,\n )\n\n @property\n def required_models(self) -> t.List[Tag]:\n return [self._tag]\n\n @property\n def num_concurrency_per_replica(self) -> int:\n if _is_gpu_available() and self.resource_quota.on_gpu:\n return 1\n return int(round(self.resource_quota.cpu))\n\n @property\n def num_replica(self) -> int:\n if _is_gpu_available() and self.resource_quota.on_gpu:\n return len(tf.config.list_physical_devices(\"GPU\"))\n return 1\n\n # pylint: disable=attribute-defined-outside-init\n def _setup(self) -> None:\n # setup a global session for model runner\n self._session = tf.compat.v1.Session(\n config=tf.compat.v1.ConfigProto(**self._config_proto)\n )\n self._model = load(self._tag, model_store=self._model_store)\n if not TF2:\n raw_predict_fn = self._model.signatures[\"serving_default\"]\n else:\n raw_predict_fn = getattr(self._model, self._predict_fn_name)\n self._predict_fn = functools.partial(raw_predict_fn, **self._partial_kwargs)\n\n def _run_batch(\n self,\n *args: t.Union[\n t.List[t.Union[int, float]], \"np.ndarray[t.Any, np.dtype[t.Any]]\", tf.Tensor\n ],\n **kwargs: t.Union[\n t.List[t.Union[int, float]], \"np.ndarray[t.Any, np.dtype[t.Any]]\", tf.Tensor\n ],\n ) -> \"np.ndarray[t.Any, np.dtype[t.Any]]\":\n params = Params[\n t.Union[\n t.List[t.Union[int, float]],\n \"np.ndarray[t.Any, np.dtype[t.Any]]\",\n tf.Tensor,\n ]\n ](*args, **kwargs)\n\n with tf.device(self._device_id):\n\n def _mapping(\n item: t.Union[\n t.List[t.Union[int, float]],\n \"np.ndarray[t.Any, np.dtype[t.Any]]\",\n tf.Tensor,\n ]\n ) -> tf.Tensor:\n if not isinstance(item, tf.Tensor):\n return tf.convert_to_tensor(item, dtype=tf.float32)\n else:\n return item\n\n params = params.map(_mapping)\n\n if TF2:\n tf.compat.v1.global_variables_initializer()\n res = self._predict_fn(*params.args, **params.kwargs)\n else:\n self._session.run(tf.compat.v1.global_variables_initializer())\n res = self._session.run(self._predict_fn(*params.args, **params.kwargs))\n return t.cast(\n \"np.ndarray[t.Any, np.dtype[t.Any]]\",\n res.numpy() if TF2 else res[\"prediction\"],\n )\n\n\n@inject\ndef load_runner(\n tag: t.Union[str, Tag],\n *,\n predict_fn_name: str = \"__call__\",\n device_id: str = \"CPU:0\",\n partial_kwargs: t.Optional[t.Dict[str, t.Any]] = None,\n name: t.Optional[str] = None,\n resource_quota: t.Union[None, t.Dict[str, t.Any]] = None,\n batch_options: t.Union[None, t.Dict[str, t.Any]] = None,\n model_store: \"ModelStore\" = Provide[BentoMLContainer.model_store],\n) -> \"_TensorflowRunner\":\n \"\"\"\n Runner represents a unit of serving logic that can be scaled horizontally to\n maximize throughput. `bentoml.tensorflow.load_runner` implements a Runner class that\n wrap around a Tensorflow model, which optimize it for the BentoML runtime.\n\n Args:\n tag (:code:`Union[str, Tag]`):\n Tag of a saved model in BentoML local modelstore.\n predict_fn_name (:code:`str`, default to :code:`__call__`):\n Inference function to be used.\n partial_kwargs (:code:`Dict[str, Any]`, `optional`, default to :code:`None`):\n Dictionary of partial kwargs that can be shared across different model.\n device_id (:code:`str`, `optional`, default to the first CPU):\n Optional devices to put the given model on. Refers to `Logical Devices <https://www.tensorflow.org/api_docs/python/tf/config/list_logical_devices>`_ from TF documentation.\n resource_quota (:code:`Dict[str, Any]`, default to :code:`None`):\n Dictionary to configure resources allocation for runner.\n batch_options (:code:`Dict[str, Any]`, default to :code:`None`):\n Dictionary to configure batch options for runner in a service context.\n model_store (:mod:`~bentoml._internal.models.store.ModelStore`, default to :mod:`BentoMLContainer.model_store`):\n BentoML modelstore, provided by DI Container.\n\n Returns:\n :obj:`~bentoml._internal.runner.Runner`: Runner instances for :mod:`bentoml.tensorflow` model\n\n Examples:\n\n .. tabs::\n\n .. code-tab:: tensorflow_v1\n\n import bentoml\n\n # load a runner from a given flag\n runner = bentoml.tensorflow.load_runner(tag)\n\n # load a runner on GPU:0\n runner = bentoml.tensorflow.load_runner(tag, resource_quota=dict(gpus=0), device_id=\"GPU:0\")\n\n .. code-tab:: tensorflow_v2\n\n import bentoml\n\n # load a runner from a given flag\n runner = bentoml.tensorflow.load_runner(tag)\n\n # load a runner on GPU:0\n runner = bentoml.tensorflow.load_runner(tag, resource_quota=dict(gpus=0), device_id=\"GPU:0\")\n\n \"\"\" # noqa\n tag = Tag.from_taglike(tag)\n if name is None:\n name = tag.name\n return _TensorflowRunner(\n tag=tag,\n predict_fn_name=predict_fn_name,\n device_id=device_id,\n partial_kwargs=partial_kwargs,\n name=name,\n resource_quota=resource_quota,\n batch_options=batch_options,\n model_store=model_store,\n )\n" ]
[ [ "tensorflow.compat.v1.saved_model.load_v2", "tensorflow.convert_to_tensor", "tensorflow.device", "tensorflow.compat.v1.ConfigProto", "tensorflow.compat.v1.get_default_graph", "tensorflow.saved_model.load", "tensorflow.python.client.device_lib.list_local_devices", "tensorflow.compat.v1.global_variables_initializer", "tensorflow.saved_model.save", "tensorflow.compat.v2.saved_model.load", "tensorflow.config.list_physical_devices", "tensorflow.test.is_gpu_available", "tensorflow.config.set_visible_devices" ] ]
seawavve/OAC
[ "66bfed8a1585c252e6b00c9fee36db7f3a4ba30a" ]
[ "result/covid_confimation_trend_data.py" ]
[ "#코로나 확진자 추이 크롤링\n# Run Time: 0 min\n\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport requests\n\n'''\n기준일:stateDt (index)\n누적확진자수:decideCnt\n누적격리해제수:clearCnt\n누적사망자수:deathCnt\n검사진행수:examCnt\n치료중환자수:careCnt\n누적결과음성수:resultNegCnt\n누적확진률:accDefRate\n\n당일확진자수:decCnt\n당일격리해제수:clCnt\n당일사망자수:dthCnt\n당일결과음성수:rnCnt\nstateDt,decideCnt,clearCnt,deathCnt,examCnt,careCnt,resnegCnt,accdefRate\n'''\n\n#text만 추출하는 함수\ndef gettext(html):\n text_list=[]\n for line in html:\n text=line.get_text()\n text_list.append(text)\n return text_list\n\nstateDt_list=[]\ndecideCnt_list=[]\nclearCnt_list=[]\ndeathCnt_list=[]\nexamCnt_list=[]\ncareCnt_list=[]\nresnegCnt_list=[]\naccdefRate_list=[]\n\nfor i in range(1):\n url='http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19InfStateJson?serviceKey=nJyjaOJ8GENB%2F2nQSLsVCRkTZDsj6wUbx6iqEHNVH6I2IghnyySx3JDrp2JWMyqHG%2BWa0Y21QBVkjg%2Fr4OzD9w%3D%3D&pageNo='+str(i)+'&numOfRows=10&startCreateDt=20200806&endCreateDt=20201106'\n\n req=requests.get(url) #공공API접근\n html=req.text\n soup=BeautifulSoup(html,'html.parser')\n #기준일\n html_stateDt=soup.findAll('statedt')\n stateDt_list.append(gettext(html_stateDt))\n\n #확진자수\n html_decideCnt=soup.findAll('decidecnt')\n decideCnt_list.append(gettext(html_decideCnt))\n\n #격리해제수\n html_clearCnt=soup.findAll('clearcnt')\n clearCnt_list.append(gettext(html_clearCnt))\n\n #사망자수\n html_deathCnt=soup.findAll('deathcnt')\n deathCnt_list.append(gettext(html_deathCnt))\n\n #검사진행수\n html_examCnt=soup.findAll('examcnt')\n examCnt_list.append(gettext(html_examCnt))\n\n #치료중인환자수\n html_careCnt=soup.findAll('carecnt')\n careCnt_list.append(gettext(html_careCnt))\n\n #결과음성수\n html_resnegCnt=soup.findAll('resutlnegcnt')\n resnegCnt_list.append(gettext(html_resnegCnt))\n\n #누적확진률\n html_accdefRate=soup.findAll('accdefrate')\n accdefRate_list.append(gettext(html_accdefRate))\n\nstateDt_list = sum(stateDt_list, [])\ndecideCnt_list = sum(decideCnt_list, [])\nclearCnt_list = sum(clearCnt_list, [])\ndeathCnt_list = sum(deathCnt_list, [])\nexamCnt_list = sum(examCnt_list, [])\ncareCnt_list = sum(careCnt_list, [])\nresnegCnt_list = sum(resnegCnt_list, [])\naccdefRate_list = sum(accdefRate_list, [])\n\ndthCnt_list=list(map(int,deathCnt_list))\ndecCnt_list=list(map(int,decideCnt_list))\nclCnt_list=list(map(int,clearCnt_list))\nrnCnt_list=list(map(int,resnegCnt_list))\n'''\n당일확진자수:decCnt\n당일격리해제수:clCnt\n당일사망자수:dthCnt\n당일결과음성수:rnCnt\n'''\n#누적 제거\nfor i in range(94):\n dthCnt_list[i]-=dthCnt_list[i+1]\ndthCnt_list[94]=0\n\nfor i in range(94):\n decCnt_list[i]-=decCnt_list[i+1]\ndecCnt_list[94]=0\nfor i in range(94):\n rnCnt_list[i]-=rnCnt_list[i+1]\nrnCnt_list[94]=0\nfor i in range(94):\n clCnt_list[i]-=clCnt_list[i+1]\nclCnt_list[94]=0\n\nresult=[]\nfor stateDt,decideCnt,clearCnt,deathCnt,examCnt,careCnt,resnegCnt,accdefRate,dthCnt,decCnt,rnCnt,clCnt in zip(stateDt_list,decideCnt_list,clearCnt_list,deathCnt_list,examCnt_list,careCnt_list,resnegCnt_list,accdefRate_list,dthCnt_list,decCnt_list,rnCnt_list,clCnt_list): \n row_data=[stateDt,decideCnt,clearCnt,deathCnt,examCnt,careCnt,resnegCnt,accdefRate,dthCnt,decCnt,rnCnt,clCnt]\n result.append(row_data)\n\ncovid_df=pd.DataFrame(result,columns=['stateDt','decideCnt','clearCnt','deathCnt','examCnt','careCnt','resnegCnt','accdefRate','dthCnt','decCnt','enCnt','clCnt'])\n\n\n\ncovid_df.to_csv('covid19_trend.csv')\n#display(covid_df)\n" ]
[ [ "pandas.DataFrame" ] ]
sha256burim/Implementation-of-TensorFlow-Fast-GAN-Neural-Style-Transfer
[ "ef6c1705b37d0e6c18aa001173f9be90ca83a8bc" ]
[ "fast_stylize.py" ]
[ "import functools\r\nimport os\r\n\r\nfrom matplotlib import gridspec\r\nimport matplotlib.pylab as plt\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport tensorflow_hub as hub\r\n\r\nprint(\"TF Version: \", tf.__version__)\r\nprint(\"TF-Hub version: \", hub.__version__)\r\nprint(\"Eager mode enabled: \", tf.executing_eagerly())\r\nprint(\"GPU available: \", tf.test.is_gpu_available())\r\n\r\n#Define image loading and visualization functions { display-mode: \"form\" }\r\n\r\ndef crop_center(image):\r\n \"\"\"Returns a cropped square image.\"\"\"\r\n shape = image.shape\r\n new_shape = min(shape[1], shape[2])\r\n offset_y = max(shape[1] - shape[2], 0) // 2\r\n offset_x = max(shape[2] - shape[1], 0) // 2\r\n image = tf.image.crop_to_bounding_box(\r\n image, offset_y, offset_x, new_shape, new_shape)\r\n return image\r\n\r\[email protected]_cache(maxsize=None)\r\ndef load_image(image_url, image_size=(256, 256), preserve_aspect_ratio=True):\r\n \"\"\"Loads and preprocesses images.\"\"\"\r\n # Cache image file locally.\r\n image_path = tf.keras.utils.get_file(os.path.basename(image_url)[-128:], image_url)\r\n # Load and convert to float32 numpy array, add batch dimension, and normalize to range [0, 1].\r\n img = plt.imread(image_path).astype(np.float32)[np.newaxis, ...]\r\n if img.max() > 1.0:\r\n img = img / 255.\r\n if len(img.shape) == 3:\r\n img = tf.stack([img, img, img], axis=-1)\r\n img = crop_center(img)\r\n img = tf.image.resize(img, image_size, preserve_aspect_ratio=True)\r\n return img\r\n\r\ndef show_n(images, titles=('',)):\r\n n = len(images)\r\n image_sizes = [image.shape[1] for image in images]\r\n w = (image_sizes[0] * 6) // 320\r\n plt.figure(figsize=(w * n, w))\r\n gs = gridspec.GridSpec(1, n, width_ratios=image_sizes)\r\n for i in range(n):\r\n plt.subplot(gs[i])\r\n plt.imshow(images[i][0], aspect='equal')\r\n plt.axis('off')\r\n plt.title(titles[i] if len(titles) > i else '')\r\n plt.show()\r\n\r\n#Load example images { display-mode: \"form\" }\r\n\r\ncontent_image_url = 'https://github.com/sha256burim/Implementation-of-TensorFlow-Fast-GAN-Neural-Style-Transfer/blob/main/face1.jpg' \r\nstyle_image_url = 'https://github.com/sha256burim/Implementation-of-TensorFlow-Fast-GAN-Neural-Style-Transfer/blob/main/van.jpg' \r\noutput_image_size = 500 \r\n\r\n# The content image size can be arbitrary.\r\ncontent_img_size = (output_image_size, output_image_size)\r\n# The style prediction model was trained with image size 256 and it's the \r\n# recommended image size for the style image (though, other sizes work as \r\n# well but will lead to different results).\r\n#style_img_size = (256, 256) #keep it at 256.\r\nstyle_img_size = (500, 500)\r\n\r\ncontent_image = load_image(content_image_url, content_img_size)\r\nstyle_image = load_image(style_image_url, style_img_size)\r\nstyle_image = tf.nn.avg_pool(style_image, ksize=[3,3], strides=[1,1], padding='SAME')\r\nshow_n([content_image, style_image], ['Content image', 'Style image'])\r\n\r\n# Load TF-Hub module.\r\n\r\nhub_handle = 'https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2'\r\nhub_module = hub.load(hub_handle)\r\n\r\n# Stylize content image with given style image.\r\n# This is pretty fast within a few milliseconds on a GPU.\r\n\r\noutputs = hub_module(tf.constant(content_image), tf.constant(style_image))\r\nstylized_image = outputs[0]\r\n\r\n# Visualize input images and the generated stylized image.\r\n\r\nshow_n([content_image, style_image, stylized_image], titles=['Original content image', 'Style image', 'Stylized image'])\r\n\r\n#Done, enjoy your stylized image\r\n" ]
[ [ "matplotlib.pylab.show", "tensorflow.executing_eagerly", "tensorflow.constant", "tensorflow.image.crop_to_bounding_box", "matplotlib.pylab.axis", "tensorflow.stack", "matplotlib.pylab.imread", "matplotlib.pylab.subplot", "tensorflow.image.resize", "matplotlib.pylab.figure", "tensorflow.nn.avg_pool", "matplotlib.gridspec.GridSpec", "matplotlib.pylab.imshow", "tensorflow.test.is_gpu_available" ] ]
SIME-LAB/albumentations
[ "7f3f5a3535780a66460b6e19cbdabbf0a294f267" ]
[ "tests/test_serialization.py" ]
[ "import json\nimport os\nimport random\nfrom unittest.mock import patch\n\nimport cv2\nimport numpy as np\nimport pytest\n\nimport albumentations as A\nimport albumentations.augmentations.functional as F\nfrom albumentations.core.serialization import SERIALIZABLE_REGISTRY, shorten_class_name\nfrom albumentations.core.transforms_interface import ImageOnlyTransform\n\nfrom .conftest import skipif_no_torch\nfrom .utils import (\n OpenMock,\n check_all_augs_exists,\n get_dual_transforms,\n get_image_only_transforms,\n get_transforms,\n set_seed,\n)\n\nTEST_SEEDS = (0, 1, 42, 111, 9999)\n\n\[email protected](\n [\"augmentation_cls\", \"params\"],\n get_transforms(\n custom_arguments={\n A.Crop: {\"y_min\": 0, \"y_max\": 10, \"x_min\": 0, \"x_max\": 10},\n A.CenterCrop: {\"height\": 10, \"width\": 10},\n A.CropNonEmptyMaskIfExists: {\"height\": 10, \"width\": 10},\n A.RandomCrop: {\"height\": 10, \"width\": 10},\n A.RandomResizedCrop: {\"height\": 10, \"width\": 10},\n A.RandomSizedCrop: {\"min_max_height\": (4, 8), \"height\": 10, \"width\": 10},\n A.CropAndPad: {\"px\": 10},\n A.Resize: {\"height\": 10, \"width\": 10},\n },\n except_augmentations={\n A.RandomCropNearBBox,\n A.RandomSizedBBoxSafeCrop,\n A.FDA,\n A.HistogramMatching,\n A.PixelDistributionAdaptation,\n A.Lambda,\n A.TemplateTransform,\n },\n ),\n)\[email protected](\"p\", [0.5, 1])\[email protected](\"seed\", TEST_SEEDS)\[email protected](\"always_apply\", (False, True))\ndef test_augmentations_serialization(augmentation_cls, params, p, seed, image, mask, always_apply):\n aug = augmentation_cls(p=p, always_apply=always_apply, **params)\n serialized_aug = A.to_dict(aug)\n deserialized_aug = A.from_dict(serialized_aug)\n set_seed(seed)\n aug_data = aug(image=image, mask=mask)\n set_seed(seed)\n deserialized_aug_data = deserialized_aug(image=image, mask=mask)\n assert np.array_equal(aug_data[\"image\"], deserialized_aug_data[\"image\"])\n assert np.array_equal(aug_data[\"mask\"], deserialized_aug_data[\"mask\"])\n\n\nAUGMENTATION_CLS_PARAMS = [\n [\n A.ImageCompression,\n {\n \"quality_lower\": 10,\n \"quality_upper\": 80,\n \"compression_type\": A.ImageCompression.ImageCompressionType.WEBP,\n },\n ],\n [A.JpegCompression, {\"quality_lower\": 10, \"quality_upper\": 80}],\n [A.HueSaturationValue, {\"hue_shift_limit\": 70, \"sat_shift_limit\": 95, \"val_shift_limit\": 55}],\n [A.RGBShift, {\"r_shift_limit\": 70, \"g_shift_limit\": 80, \"b_shift_limit\": 40}],\n [A.RandomBrightnessContrast, {\"brightness_limit\": 0.5, \"contrast_limit\": 0.8}],\n [A.Blur, {\"blur_limit\": 3}],\n [A.MotionBlur, {\"blur_limit\": 3}],\n [A.MedianBlur, {\"blur_limit\": 3}],\n [A.GaussianBlur, {\"blur_limit\": 3}],\n [A.GaussNoise, {\"var_limit\": (20, 90), \"mean\": 10, \"per_channel\": False}],\n [A.CLAHE, {\"clip_limit\": 2, \"tile_grid_size\": (12, 12)}],\n [A.RandomGamma, {\"gamma_limit\": (10, 90)}],\n [A.Cutout, {\"num_holes\": 4, \"max_h_size\": 4, \"max_w_size\": 4}],\n [A.CoarseDropout, {\"max_holes\": 4, \"max_height\": 4, \"max_width\": 4}],\n [A.RandomSnow, {\"snow_point_lower\": 0.2, \"snow_point_upper\": 0.4, \"brightness_coeff\": 4}],\n [\n A.RandomRain,\n {\n \"slant_lower\": -5,\n \"slant_upper\": 5,\n \"drop_length\": 15,\n \"drop_width\": 2,\n \"drop_color\": (100, 100, 100),\n \"blur_value\": 3,\n \"brightness_coefficient\": 0.5,\n \"rain_type\": \"heavy\",\n },\n ],\n [A.RandomFog, {\"fog_coef_lower\": 0.2, \"fog_coef_upper\": 0.8, \"alpha_coef\": 0.11}],\n [\n A.RandomSunFlare,\n {\n \"flare_roi\": (0.1, 0.1, 0.9, 0.6),\n \"angle_lower\": 0.1,\n \"angle_upper\": 0.95,\n \"num_flare_circles_lower\": 7,\n \"num_flare_circles_upper\": 11,\n \"src_radius\": 300,\n \"src_color\": (200, 200, 200),\n },\n ],\n [\n A.RandomShadow,\n {\n \"shadow_roi\": (0.1, 0.4, 0.9, 0.9),\n \"num_shadows_lower\": 2,\n \"num_shadows_upper\": 4,\n \"shadow_dimension\": 8,\n },\n ],\n [\n A.PadIfNeeded,\n {\"min_height\": 512, \"min_width\": 512, \"border_mode\": cv2.BORDER_CONSTANT, \"value\": (10, 10, 10)},\n ],\n [\n A.Rotate,\n {\n \"limit\": 120,\n \"interpolation\": cv2.INTER_CUBIC,\n \"border_mode\": cv2.BORDER_CONSTANT,\n \"value\": (10, 10, 10),\n },\n ],\n [\n A.SafeRotate,\n {\n \"limit\": 120,\n \"interpolation\": cv2.INTER_CUBIC,\n \"border_mode\": cv2.BORDER_CONSTANT,\n \"value\": (10, 10, 10),\n },\n ],\n [\n A.ShiftScaleRotate,\n {\n \"shift_limit\": 0.2,\n \"scale_limit\": 0.2,\n \"rotate_limit\": 70,\n \"interpolation\": cv2.INTER_CUBIC,\n \"border_mode\": cv2.BORDER_CONSTANT,\n \"value\": (10, 10, 10),\n },\n ],\n [\n A.ShiftScaleRotate,\n {\n \"shift_limit_x\": 0.3,\n \"shift_limit_y\": 0.4,\n \"scale_limit\": 0.2,\n \"rotate_limit\": 70,\n \"interpolation\": cv2.INTER_CUBIC,\n \"border_mode\": cv2.BORDER_CONSTANT,\n \"value\": (10, 10, 10),\n },\n ],\n [\n A.OpticalDistortion,\n {\n \"distort_limit\": 0.2,\n \"shift_limit\": 0.2,\n \"interpolation\": cv2.INTER_CUBIC,\n \"border_mode\": cv2.BORDER_CONSTANT,\n \"value\": (10, 10, 10),\n },\n ],\n [\n A.GridDistortion,\n {\n \"num_steps\": 10,\n \"distort_limit\": 0.5,\n \"interpolation\": cv2.INTER_CUBIC,\n \"border_mode\": cv2.BORDER_CONSTANT,\n \"value\": (10, 10, 10),\n },\n ],\n [\n A.ElasticTransform,\n {\n \"alpha\": 2,\n \"sigma\": 25,\n \"alpha_affine\": 40,\n \"interpolation\": cv2.INTER_CUBIC,\n \"border_mode\": cv2.BORDER_CONSTANT,\n \"value\": (10, 10, 10),\n },\n ],\n [A.CenterCrop, {\"height\": 10, \"width\": 10}],\n [A.RandomCrop, {\"height\": 10, \"width\": 10}],\n [A.CropNonEmptyMaskIfExists, {\"height\": 10, \"width\": 10}],\n [A.RandomSizedCrop, {\"min_max_height\": (4, 8), \"height\": 10, \"width\": 10}],\n [A.Crop, {\"x_max\": 64, \"y_max\": 64}],\n [A.ToFloat, {\"max_value\": 16536}],\n [A.Normalize, {\"mean\": (0.385, 0.356, 0.306), \"std\": (0.129, 0.124, 0.125), \"max_pixel_value\": 100.0}],\n [A.RandomBrightness, {\"limit\": 0.4}],\n [A.RandomContrast, {\"limit\": 0.4}],\n [A.RandomScale, {\"scale_limit\": 0.2, \"interpolation\": cv2.INTER_CUBIC}],\n [A.Resize, {\"height\": 64, \"width\": 64}],\n [A.SmallestMaxSize, {\"max_size\": 64, \"interpolation\": cv2.INTER_CUBIC}],\n [A.LongestMaxSize, {\"max_size\": 128, \"interpolation\": cv2.INTER_CUBIC}],\n [A.RandomGridShuffle, {\"grid\": (5, 5)}],\n [A.Solarize, {\"threshold\": 32}],\n [A.Posterize, {\"num_bits\": 1}],\n [A.Equalize, {\"mode\": \"pil\", \"by_channels\": False}],\n [A.MultiplicativeNoise, {\"multiplier\": (0.7, 2.3), \"per_channel\": True, \"elementwise\": True}],\n [\n A.ColorJitter,\n {\"brightness\": [0.2, 0.3], \"contrast\": [0.7, 0.9], \"saturation\": [1.2, 1.7], \"hue\": [-0.2, 0.1]},\n ],\n [\n A.Perspective,\n {\n \"scale\": 0.5,\n \"keep_size\": False,\n \"pad_mode\": cv2.BORDER_REFLECT_101,\n \"pad_val\": 10,\n \"mask_pad_val\": 100,\n \"fit_output\": True,\n \"interpolation\": cv2.INTER_CUBIC,\n },\n ],\n [A.Sharpen, {\"alpha\": [0.2, 0.5], \"lightness\": [0.5, 1.0]}],\n [A.Emboss, {\"alpha\": [0.2, 0.5], \"strength\": [0.5, 1.0]}],\n [A.RandomToneCurve, {\"scale\": 0.2}],\n [\n A.CropAndPad,\n {\n \"px\": 10,\n \"keep_size\": False,\n \"sample_independently\": False,\n \"interpolation\": cv2.INTER_CUBIC,\n \"pad_cval_mask\": [10, 20, 30],\n \"pad_cval\": [11, 12, 13],\n \"pad_mode\": cv2.BORDER_REFLECT101,\n },\n ],\n [\n A.Superpixels,\n {\"p_replace\": (0.5, 0.7), \"n_segments\": (20, 30), \"max_size\": 25, \"interpolation\": cv2.INTER_CUBIC},\n ],\n [\n A.Affine,\n {\n \"scale\": 0.5,\n \"translate_percent\": 0.7,\n \"translate_px\": None,\n \"rotate\": 33,\n \"shear\": 21,\n \"interpolation\": cv2.INTER_CUBIC,\n \"cval\": 25,\n \"cval_mask\": 1,\n \"mode\": cv2.BORDER_REFLECT,\n \"fit_output\": True,\n },\n ],\n [\n A.Affine,\n {\n \"scale\": {\"x\": [0.3, 0.5], \"y\": [0.1, 0.2]},\n \"translate_percent\": None,\n \"translate_px\": {\"x\": [10, 200], \"y\": [5, 101]},\n \"rotate\": [333, 360],\n \"shear\": {\"x\": [31, 38], \"y\": [41, 48]},\n \"interpolation\": 3,\n \"cval\": [10, 20, 30],\n \"cval_mask\": 1,\n \"mode\": cv2.BORDER_REFLECT,\n \"fit_output\": True,\n },\n ],\n [\n A.PiecewiseAffine,\n {\n \"scale\": 0.33,\n \"nb_rows\": (10, 20),\n \"nb_cols\": 33,\n \"interpolation\": 2,\n \"mask_interpolation\": 1,\n \"cval\": 10,\n \"cval_mask\": 20,\n \"mode\": \"edge\",\n \"absolute_scale\": True,\n \"keypoints_threshold\": 0.1,\n },\n ],\n [A.ChannelDropout, dict(channel_drop_range=(1, 2), fill_value=1)],\n [A.ChannelShuffle, {}],\n [A.Downscale, dict(scale_min=0.5, scale_max=0.75, interpolation=cv2.INTER_LINEAR)],\n [A.Flip, {}],\n [A.FromFloat, dict(dtype=\"uint8\", max_value=1)],\n [A.HorizontalFlip, {}],\n [A.ISONoise, dict(color_shift=(0.2, 0.3), intensity=(0.7, 0.9))],\n [A.InvertImg, {}],\n [A.MaskDropout, dict(max_objects=2, image_fill_value=10, mask_fill_value=20)],\n [A.NoOp, {}],\n [A.RandomResizedCrop, dict(height=20, width=30, scale=(0.5, 0.6), ratio=(0.8, 0.9))],\n [A.FancyPCA, dict(alpha=0.3)],\n [A.RandomRotate90, {}],\n [A.ToGray, {}],\n [A.ToSepia, {}],\n [A.Transpose, {}],\n [A.VerticalFlip, {}],\n [A.RingingOvershoot, dict(blur_limit=(7, 15), cutoff=(np.pi / 5, np.pi / 2))],\n [A.UnsharpMask, {\"blur_limit\": 3, \"sigma_limit\": 0.5, \"alpha\": 0.2, \"threshold\": 15}],\n [A.AdvancedBlur, dict(blur_limit=(3, 5), rotate_limit=(60, 90))],\n [A.PixelDropout, {\"dropout_prob\": 0.1, \"per_channel\": True, \"drop_value\": None}],\n [A.PixelDropout, {\"dropout_prob\": 0.1, \"per_channel\": False, \"drop_value\": None, \"mask_drop_value\": 15}],\n]\n\nAUGMENTATION_CLS_EXCEPT = {\n A.FDA,\n A.HistogramMatching,\n A.PixelDistributionAdaptation,\n A.Lambda,\n A.RandomCropNearBBox,\n A.RandomSizedBBoxSafeCrop,\n A.GridDropout,\n A.GlassBlur,\n A.TemplateTransform,\n}\n\n\[email protected](\n [\"augmentation_cls\", \"params\"], check_all_augs_exists(AUGMENTATION_CLS_PARAMS, AUGMENTATION_CLS_EXCEPT)\n)\[email protected](\"p\", [0.5, 1])\[email protected](\"seed\", TEST_SEEDS)\[email protected](\"always_apply\", (False, True))\ndef test_augmentations_serialization_with_custom_parameters(\n augmentation_cls, params, p, seed, image, mask, always_apply\n):\n aug = augmentation_cls(p=p, always_apply=always_apply, **params)\n serialized_aug = A.to_dict(aug)\n deserialized_aug = A.from_dict(serialized_aug)\n set_seed(seed)\n aug_data = aug(image=image, mask=mask)\n set_seed(seed)\n deserialized_aug_data = deserialized_aug(image=image, mask=mask)\n assert np.array_equal(aug_data[\"image\"], deserialized_aug_data[\"image\"])\n assert np.array_equal(aug_data[\"mask\"], deserialized_aug_data[\"mask\"])\n\n\[email protected](\n [\"augmentation_cls\", \"params\"], check_all_augs_exists(AUGMENTATION_CLS_PARAMS, AUGMENTATION_CLS_EXCEPT)\n)\[email protected](\"p\", [0.5, 1])\[email protected](\"seed\", TEST_SEEDS)\[email protected](\"always_apply\", (False, True))\[email protected](\"data_format\", (\"yaml\",))\ndef test_augmentations_serialization_to_file_with_custom_parameters(\n augmentation_cls, params, p, seed, image, mask, always_apply, data_format\n):\n with patch(\"builtins.open\", OpenMock()):\n aug = augmentation_cls(p=p, always_apply=always_apply, **params)\n filepath = \"serialized.{}\".format(data_format)\n A.save(aug, filepath, data_format=data_format)\n deserialized_aug = A.load(filepath, data_format=data_format)\n set_seed(seed)\n aug_data = aug(image=image, mask=mask)\n set_seed(seed)\n deserialized_aug_data = deserialized_aug(image=image, mask=mask)\n assert np.array_equal(aug_data[\"image\"], deserialized_aug_data[\"image\"])\n assert np.array_equal(aug_data[\"mask\"], deserialized_aug_data[\"mask\"])\n\n\[email protected](\n [\"augmentation_cls\", \"params\"],\n get_transforms(\n custom_arguments={\n A.Crop: {\"y_min\": 0, \"y_max\": 10, \"x_min\": 0, \"x_max\": 10},\n A.CenterCrop: {\"height\": 10, \"width\": 10},\n A.CropNonEmptyMaskIfExists: {\"height\": 10, \"width\": 10},\n A.RandomCrop: {\"height\": 10, \"width\": 10},\n A.RandomResizedCrop: {\"height\": 10, \"width\": 10},\n A.RandomSizedCrop: {\"min_max_height\": (4, 8), \"height\": 10, \"width\": 10},\n A.CropAndPad: {\"px\": 10},\n A.Resize: {\"height\": 10, \"width\": 10},\n A.RandomSizedBBoxSafeCrop: {\"height\": 10, \"width\": 10},\n },\n except_augmentations={\n A.RandomCropNearBBox,\n A.FDA,\n A.HistogramMatching,\n A.PixelDistributionAdaptation,\n A.Lambda,\n A.CoarseDropout,\n A.CropNonEmptyMaskIfExists,\n A.ElasticTransform,\n A.GridDistortion,\n A.RandomGridShuffle,\n A.GridDropout,\n A.MaskDropout,\n A.OpticalDistortion,\n A.TemplateTransform,\n },\n ),\n)\[email protected](\"p\", [0.5, 1])\[email protected](\"seed\", TEST_SEEDS)\[email protected](\"always_apply\", (False, True))\ndef test_augmentations_for_bboxes_serialization(\n augmentation_cls, params, p, seed, image, albumentations_bboxes, always_apply\n):\n aug = augmentation_cls(p=p, always_apply=always_apply, **params)\n serialized_aug = A.to_dict(aug)\n deserialized_aug = A.from_dict(serialized_aug)\n set_seed(seed)\n aug_data = aug(image=image, bboxes=albumentations_bboxes)\n set_seed(seed)\n deserialized_aug_data = deserialized_aug(image=image, bboxes=albumentations_bboxes)\n assert np.array_equal(aug_data[\"image\"], deserialized_aug_data[\"image\"])\n assert np.array_equal(aug_data[\"bboxes\"], deserialized_aug_data[\"bboxes\"])\n\n\[email protected](\n [\"augmentation_cls\", \"params\"],\n get_transforms(\n custom_arguments={\n A.Crop: {\"y_min\": 0, \"y_max\": 10, \"x_min\": 0, \"x_max\": 10},\n A.CenterCrop: {\"height\": 10, \"width\": 10},\n A.CropNonEmptyMaskIfExists: {\"height\": 10, \"width\": 10},\n A.RandomCrop: {\"height\": 10, \"width\": 10},\n A.RandomResizedCrop: {\"height\": 10, \"width\": 10},\n A.RandomSizedCrop: {\"min_max_height\": (4, 8), \"height\": 10, \"width\": 10},\n A.CropAndPad: {\"px\": 10},\n A.Resize: {\"height\": 10, \"width\": 10},\n },\n except_augmentations={\n A.RandomCropNearBBox,\n A.FDA,\n A.HistogramMatching,\n A.PixelDistributionAdaptation,\n A.Lambda,\n A.CoarseDropout,\n A.CropNonEmptyMaskIfExists,\n A.ElasticTransform,\n A.GridDistortion,\n A.RandomGridShuffle,\n A.GridDropout,\n A.MaskDropout,\n A.OpticalDistortion,\n A.RandomSizedBBoxSafeCrop,\n A.TemplateTransform,\n },\n ),\n)\[email protected](\"p\", [0.5, 1])\[email protected](\"seed\", TEST_SEEDS)\[email protected](\"always_apply\", (False, True))\ndef test_augmentations_for_keypoints_serialization(augmentation_cls, params, p, seed, image, keypoints, always_apply):\n aug = augmentation_cls(p=p, always_apply=always_apply, **params)\n serialized_aug = A.to_dict(aug)\n deserialized_aug = A.from_dict(serialized_aug)\n set_seed(seed)\n aug_data = aug(image=image, keypoints=keypoints)\n set_seed(seed)\n deserialized_aug_data = deserialized_aug(image=image, keypoints=keypoints)\n assert np.array_equal(aug_data[\"image\"], deserialized_aug_data[\"image\"])\n assert np.array_equal(aug_data[\"keypoints\"], deserialized_aug_data[\"keypoints\"])\n\n\[email protected](\n [\"augmentation_cls\", \"params\", \"call_params\"],\n [[A.RandomCropNearBBox, {\"max_part_shift\": 0.15}, {\"cropping_bbox\": [-59, 77, 177, 231]}]],\n)\[email protected](\"p\", [0.5, 1])\[email protected](\"seed\", TEST_SEEDS)\[email protected](\"always_apply\", (False, True))\ndef test_augmentations_serialization_with_call_params(\n augmentation_cls, params, call_params, p, seed, image, always_apply\n):\n aug = augmentation_cls(p=p, always_apply=always_apply, **params)\n annotations = {\"image\": image, **call_params}\n serialized_aug = A.to_dict(aug)\n deserialized_aug = A.from_dict(serialized_aug)\n set_seed(seed)\n aug_data = aug(**annotations)\n set_seed(seed)\n deserialized_aug_data = deserialized_aug(**annotations)\n assert np.array_equal(aug_data[\"image\"], deserialized_aug_data[\"image\"])\n\n\ndef test_from_float_serialization(float_image):\n aug = A.FromFloat(p=1, dtype=\"uint8\")\n serialized_aug = A.to_dict(aug)\n deserialized_aug = A.from_dict(serialized_aug)\n aug_data = aug(image=float_image)\n deserialized_aug_data = deserialized_aug(image=float_image)\n assert np.array_equal(aug_data[\"image\"], deserialized_aug_data[\"image\"])\n\n\[email protected](\"seed\", TEST_SEEDS)\ndef test_transform_pipeline_serialization(seed, image, mask):\n aug = A.Compose(\n [\n A.OneOrOther(\n A.Compose(\n [\n A.Resize(1024, 1024),\n A.RandomSizedCrop(min_max_height=(256, 1024), height=512, width=512, p=1),\n A.OneOf(\n [\n A.RandomSizedCrop(min_max_height=(256, 512), height=384, width=384, p=0.5),\n A.RandomSizedCrop(min_max_height=(256, 512), height=512, width=512, p=0.5),\n ]\n ),\n ]\n ),\n A.Compose(\n [\n A.Resize(1024, 1024),\n A.RandomSizedCrop(min_max_height=(256, 1025), height=256, width=256, p=1),\n A.OneOf([A.HueSaturationValue(p=0.5), A.RGBShift(p=0.7)], p=1),\n ]\n ),\n ),\n A.SomeOf(\n [\n A.HorizontalFlip(p=1),\n A.Transpose(p=1),\n A.HueSaturationValue(p=0.5),\n A.RandomBrightnessContrast(p=0.5),\n ],\n 2,\n replace=False,\n ),\n ]\n )\n serialized_aug = A.to_dict(aug)\n deserialized_aug = A.from_dict(serialized_aug)\n set_seed(seed)\n aug_data = aug(image=image, mask=mask)\n set_seed(seed)\n deserialized_aug_data = deserialized_aug(image=image, mask=mask)\n assert np.array_equal(aug_data[\"image\"], deserialized_aug_data[\"image\"])\n assert np.array_equal(aug_data[\"mask\"], deserialized_aug_data[\"mask\"])\n\n\[email protected](\n [\"bboxes\", \"bbox_format\", \"labels\"],\n [\n ([(20, 30, 40, 50)], \"coco\", [1]),\n ([(20, 30, 40, 50, 99), (10, 40, 30, 20, 9)], \"coco\", [1, 2]),\n ([(20, 30, 60, 80)], \"pascal_voc\", [2]),\n ([(20, 30, 60, 80, 99)], \"pascal_voc\", [1]),\n ([(0.2, 0.3, 0.4, 0.5)], \"yolo\", [2]),\n ([(0.2, 0.3, 0.4, 0.5, 99)], \"yolo\", [1]),\n ],\n)\[email protected](\"seed\", TEST_SEEDS)\ndef test_transform_pipeline_serialization_with_bboxes(seed, image, bboxes, bbox_format, labels):\n aug = A.Compose(\n [\n A.OneOrOther(\n A.Compose([A.RandomRotate90(), A.OneOf([A.HorizontalFlip(p=0.5), A.VerticalFlip(p=0.5)])]),\n A.Compose([A.Rotate(p=0.5), A.OneOf([A.HueSaturationValue(p=0.5), A.RGBShift(p=0.7)], p=1)]),\n ),\n A.SomeOf(\n [\n A.HorizontalFlip(p=1),\n A.Transpose(p=1),\n A.HueSaturationValue(p=0.5),\n A.RandomBrightnessContrast(p=0.5),\n ],\n n=5,\n ),\n ],\n bbox_params={\"format\": bbox_format, \"label_fields\": [\"labels\"]},\n )\n serialized_aug = A.to_dict(aug)\n deserialized_aug = A.from_dict(serialized_aug)\n set_seed(seed)\n aug_data = aug(image=image, bboxes=bboxes, labels=labels)\n set_seed(seed)\n deserialized_aug_data = deserialized_aug(image=image, bboxes=bboxes, labels=labels)\n assert np.array_equal(aug_data[\"image\"], deserialized_aug_data[\"image\"])\n assert np.array_equal(aug_data[\"bboxes\"], deserialized_aug_data[\"bboxes\"])\n\n\[email protected](\n [\"keypoints\", \"keypoint_format\", \"labels\"],\n [\n ([(20, 30, 40, 50)], \"xyas\", [1]),\n ([(20, 30, 40, 50, 99), (10, 40, 30, 20, 9)], \"xy\", [1, 2]),\n ([(20, 30, 60, 80)], \"yx\", [2]),\n ([(20, 30, 60, 80, 99)], \"xys\", [1]),\n ],\n)\[email protected](\"seed\", TEST_SEEDS)\ndef test_transform_pipeline_serialization_with_keypoints(seed, image, keypoints, keypoint_format, labels):\n aug = A.Compose(\n [\n A.OneOrOther(\n A.Compose([A.RandomRotate90(), A.OneOf([A.HorizontalFlip(p=0.5), A.VerticalFlip(p=0.5)])]),\n A.Compose([A.Rotate(p=0.5), A.OneOf([A.HueSaturationValue(p=0.5), A.RGBShift(p=0.7)], p=1)]),\n ),\n A.SomeOf(\n n=2,\n transforms=[\n A.HorizontalFlip(p=1),\n A.Transpose(p=1),\n A.HueSaturationValue(p=0.5),\n A.RandomBrightnessContrast(p=0.5),\n ],\n replace=False,\n ),\n ],\n keypoint_params={\"format\": keypoint_format, \"label_fields\": [\"labels\"]},\n )\n serialized_aug = A.to_dict(aug)\n deserialized_aug = A.from_dict(serialized_aug)\n set_seed(seed)\n aug_data = aug(image=image, keypoints=keypoints, labels=labels)\n set_seed(seed)\n deserialized_aug_data = deserialized_aug(image=image, keypoints=keypoints, labels=labels)\n assert np.array_equal(aug_data[\"image\"], deserialized_aug_data[\"image\"])\n assert np.array_equal(aug_data[\"keypoints\"], deserialized_aug_data[\"keypoints\"])\n\n\[email protected](\n [\"augmentation_cls\", \"params\"],\n get_image_only_transforms(\n except_augmentations={A.HistogramMatching, A.FDA, A.PixelDistributionAdaptation, A.TemplateTransform},\n ),\n)\[email protected](\"seed\", TEST_SEEDS)\ndef test_additional_targets_for_image_only_serialization(augmentation_cls, params, image, seed):\n aug = A.Compose([augmentation_cls(always_apply=True, **params)], additional_targets={\"image2\": \"image\"})\n image2 = image.copy()\n\n serialized_aug = A.to_dict(aug)\n deserialized_aug = A.from_dict(serialized_aug)\n set_seed(seed)\n aug_data = aug(image=image, image2=image2)\n set_seed(seed)\n deserialized_aug_data = deserialized_aug(image=image, image2=image2)\n assert np.array_equal(aug_data[\"image\"], deserialized_aug_data[\"image\"])\n assert np.array_equal(aug_data[\"image2\"], deserialized_aug_data[\"image2\"])\n\n\[email protected](\"seed\", TEST_SEEDS)\[email protected](\"p\", [1])\ndef test_lambda_serialization(image, mask, albumentations_bboxes, keypoints, seed, p):\n def vflip_image(image, **kwargs):\n return F.vflip(image)\n\n def vflip_mask(mask, **kwargs):\n return F.vflip(mask)\n\n def vflip_bbox(bbox, **kwargs):\n return F.bbox_vflip(bbox, **kwargs)\n\n def vflip_keypoint(keypoint, **kwargs):\n return F.keypoint_vflip(keypoint, **kwargs)\n\n aug = A.Lambda(name=\"vflip\", image=vflip_image, mask=vflip_mask, bbox=vflip_bbox, keypoint=vflip_keypoint, p=p)\n\n serialized_aug = A.to_dict(aug)\n deserialized_aug = A.from_dict(serialized_aug, lambda_transforms={\"vflip\": aug})\n set_seed(seed)\n aug_data = aug(image=image, mask=mask, bboxes=albumentations_bboxes, keypoints=keypoints)\n set_seed(seed)\n deserialized_aug_data = deserialized_aug(image=image, mask=mask, bboxes=albumentations_bboxes, keypoints=keypoints)\n assert np.array_equal(aug_data[\"image\"], deserialized_aug_data[\"image\"])\n assert np.array_equal(aug_data[\"mask\"], deserialized_aug_data[\"mask\"])\n assert np.array_equal(aug_data[\"bboxes\"], deserialized_aug_data[\"bboxes\"])\n assert np.array_equal(aug_data[\"keypoints\"], deserialized_aug_data[\"keypoints\"])\n\n\ndef test_serialization_v2_conversion_without_totensor():\n current_directory = os.path.dirname(os.path.abspath(__file__))\n files_directory = os.path.join(current_directory, \"files\")\n transform_0_4_6 = A.load(os.path.join(files_directory, \"transform_v0.4.6_without_totensor.json\"))\n with open(os.path.join(files_directory, \"output_v0.4.6_without_totensor.json\")) as f:\n output_0_4_6 = json.load(f)\n np.random.seed(42)\n image = np.random.randint(low=0, high=255, size=(256, 256, 3), dtype=np.uint8)\n random.seed(42)\n transformed_image = transform_0_4_6(image=image)[\"image\"]\n assert transformed_image.tolist() == output_0_4_6\n\n\n@skipif_no_torch\ndef test_serialization_v2_conversion_with_totensor():\n current_directory = os.path.dirname(os.path.abspath(__file__))\n files_directory = os.path.join(current_directory, \"files\")\n transform_0_4_6 = A.load(os.path.join(files_directory, \"transform_v0.4.6_with_totensor.json\"))\n with open(os.path.join(files_directory, \"output_v0.4.6_with_totensor.json\")) as f:\n output_0_4_6 = json.load(f)\n np.random.seed(42)\n image = np.random.randint(low=0, high=255, size=(256, 256, 3), dtype=np.uint8)\n random.seed(42)\n transformed_image = transform_0_4_6(image=image)[\"image\"]\n assert transformed_image.numpy().tolist() == output_0_4_6\n\n\ndef test_serialization_v2_without_totensor():\n current_directory = os.path.dirname(os.path.abspath(__file__))\n files_directory = os.path.join(current_directory, \"files\")\n transform = A.load(os.path.join(files_directory, \"transform_serialization_v2_without_totensor.json\"))\n with open(os.path.join(files_directory, \"output_v0.4.6_without_totensor.json\")) as f:\n output_0_4_6 = json.load(f)\n np.random.seed(42)\n image = np.random.randint(low=0, high=255, size=(256, 256, 3), dtype=np.uint8)\n random.seed(42)\n transformed_image = transform(image=image)[\"image\"]\n assert transformed_image.tolist() == output_0_4_6\n\n\n@skipif_no_torch\ndef test_serialization_v2_with_totensor():\n current_directory = os.path.dirname(os.path.abspath(__file__))\n files_directory = os.path.join(current_directory, \"files\")\n transform = A.load(os.path.join(files_directory, \"transform_serialization_v2_with_totensor.json\"))\n with open(os.path.join(files_directory, \"output_v0.4.6_with_totensor.json\")) as f:\n output_0_4_6 = json.load(f)\n np.random.seed(42)\n image = np.random.randint(low=0, high=255, size=(256, 256, 3), dtype=np.uint8)\n random.seed(42)\n transformed_image = transform(image=image)[\"image\"]\n assert transformed_image.numpy().tolist() == output_0_4_6\n\n\ndef test_custom_transform_with_overlapping_name():\n class HorizontalFlip(ImageOnlyTransform):\n pass\n\n assert SERIALIZABLE_REGISTRY[\"HorizontalFlip\"] == A.HorizontalFlip\n assert SERIALIZABLE_REGISTRY[\"tests.test_serialization.HorizontalFlip\"] == HorizontalFlip\n\n\ndef test_serialization_v2_to_dict():\n transform = A.Compose([A.HorizontalFlip()])\n transform_dict = A.to_dict(transform)[\"transform\"]\n assert transform_dict == {\n \"__class_fullname__\": \"Compose\",\n \"p\": 1.0,\n \"transforms\": [{\"__class_fullname__\": \"HorizontalFlip\", \"always_apply\": False, \"p\": 0.5}],\n \"bbox_params\": None,\n \"keypoint_params\": None,\n \"additional_targets\": {},\n }\n\n\[email protected](\n [\"class_fullname\", \"expected_short_class_name\"],\n [\n [\"albumentations.augmentations.transforms.HorizontalFlip\", \"HorizontalFlip\"],\n [\"HorizontalFlip\", \"HorizontalFlip\"],\n [\"some_module.HorizontalFlip\", \"some_module.HorizontalFlip\"],\n ],\n)\ndef test_shorten_class_name(class_fullname, expected_short_class_name):\n assert shorten_class_name(class_fullname) == expected_short_class_name\n\n\[email protected](\"seed\", TEST_SEEDS)\[email protected](\"p\", [1])\ndef test_template_transform_serialization(image, template, seed, p):\n template_transform = A.TemplateTransform(name=\"template\", templates=template, p=p)\n\n aug = A.Compose([A.Flip(), template_transform, A.Blur()])\n\n serialized_aug = A.to_dict(aug)\n deserialized_aug = A.from_dict(serialized_aug, lambda_transforms={\"template\": template_transform})\n\n set_seed(seed)\n aug_data = aug(image=image)\n set_seed(seed)\n deserialized_aug_data = deserialized_aug(image=image)\n\n assert np.array_equal(aug_data[\"image\"], deserialized_aug_data[\"image\"])\n" ]
[ [ "numpy.random.seed", "numpy.array_equal", "numpy.random.randint" ] ]
martius-lab/beta-nll
[ "669c9f251eb41464c1ec8b43751c7c742dd75cf9" ]
[ "src/models/variational_variance.py" ]
[ "\"\"\"Implements algorithms from\n\nStirn & Knowles, 2020: \"Variational Variance: Simple, Reliable, Calibrated\nHeteroscedastic Noise Variance Parameterization\".\n\"\"\"\nimport itertools\nimport math\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.distributions import gamma\nfrom torch.nn import functional as F\n\nfrom src.models import utils\nfrom src.models.networks import NormalGammaHead\n\n_LOG_2PI = math.log(2 * math.pi)\n\n\ndef exp_gaussian_nll_under_gamma_prec(mean, alpha, beta, target):\n \"\"\"Compute expected likelihood of log normal distribution\n under a Gamma distributed precision\n\n See below Eq. 1 in paper\n \"\"\"\n return -0.5 * (\n torch.digamma(alpha)\n - beta.log()\n - _LOG_2PI\n - alpha * ((target - mean) ** 2) / beta\n ).sum(axis=-1)\n\n\nclass NormalGammaPiHead(nn.Module):\n def __init__(self, inp_dim, outp_dim, n_components, **kwargs):\n super().__init__()\n self.normal_gamma_head = NormalGammaHead(inp_dim, outp_dim, **kwargs)\n self.pi = nn.Linear(inp_dim, outp_dim * n_components)\n\n def forward(self, inp):\n mean, alpha, beta = self.normal_gamma_head(inp)\n pi_logits = self.pi(inp).view(mean.shape[0], mean.shape[-1], -1)\n\n return mean, alpha, beta, pi_logits\n\n\ndef kl_gamma_mixture_of_gammas(dist, mixture_logits, mixture_dists, n_mc_samples):\n # dist: B x D\n # mixture_dists: D x C\n n_components = mixture_dists.rate.shape[-1]\n\n prec_samples = dist.rsample((n_mc_samples,)) # S x B x D\n prec_samples = prec_samples.unsqueeze(-1)\n prec_samples = prec_samples.expand((-1, -1, -1, n_components))\n\n ll_prior_c = mixture_dists.log_prob(prec_samples) # S x B x D x C\n log_pi = F.log_softmax(mixture_logits, dim=-1) # B x D x C\n ll_prior = torch.logsumexp(log_pi + ll_prior_c, axis=-1)\n ll_prior = torch.mean(ll_prior, axis=0) # Mean over MC samples\n\n kld = -dist.entropy() - ll_prior # B x D\n\n return kld.sum(axis=-1)\n\n\ndef get_vbem_standard_init(n_dims):\n params = [0.05, 0.1, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]\n alpha_beta = np.array(tuple(itertools.product(params, params)), dtype=np.float32).T\n alphas = utils.softmax_inverse(alpha_beta[0])\n alphas = torch.from_numpy(alphas).unsqueeze(0).repeat(n_dims, 1)\n betas = utils.softmax_inverse(alpha_beta[1])\n betas = torch.from_numpy(betas).unsqueeze(0).repeat(n_dims, 1)\n return alphas, betas\n\n\ndef get_vbem_star_standard_init(n_dims, n_components=100):\n # Initialize prior params on Unif[-3, 3]\n alphas = nn.Parameter(torch.rand(n_dims, n_components) * 6 - 3)\n betas = nn.Parameter(torch.rand(n_dims, n_components) * 6 - 3)\n return alphas, betas\n\n\nclass VBEMRegularizer(nn.Module):\n def __init__(\n self, prior_alphas, prior_betas, n_mc_samples=20, prior_trainable=True\n ):\n super().__init__()\n self.n_mc_samples = n_mc_samples\n\n if prior_trainable:\n self.prior_alphas = nn.Parameter(prior_alphas)\n self.prior_betas = nn.Parameter(prior_betas)\n else:\n self.register_buffer(\"prior_alphas\", prior_alphas)\n self.register_buffer(\"prior_betas\", prior_betas)\n\n def forward(self, pred):\n assert len(pred) == 4\n _, alpha, beta, pi_logits = pred\n\n dist = gamma.Gamma(alpha, beta)\n prior_dist = gamma.Gamma(\n F.softplus(self.prior_alphas), F.softplus(self.prior_betas)\n )\n\n return kl_gamma_mixture_of_gammas(\n dist, pi_logits, prior_dist, self.n_mc_samples\n )\n\n\nclass xVAMPRegularizer(nn.Module):\n def __init__(self, model, prior_inputs, n_mc_samples=20, prior_trainable=True):\n super().__init__()\n # Store in lambda to avoid having duplicate parameters in optimizer\n self.model = lambda *args, **kwargs: model(*args, **kwargs)\n self.n_mc_samples = n_mc_samples\n\n if prior_trainable:\n self.prior_inputs = nn.Parameter(prior_inputs.clone())\n else:\n self.register_buffer(\"prior_inputs\", prior_inputs.clone())\n\n def forward(self, pred):\n assert len(pred) == 4\n _, alpha, beta, pi_logits = pred\n dist = gamma.Gamma(alpha, beta)\n\n _, prior_alphas, prior_betas, _ = self.model(self.prior_inputs)\n prior_dist = gamma.Gamma(prior_alphas.T, prior_betas.T) # D x C\n\n return kl_gamma_mixture_of_gammas(\n dist, pi_logits, prior_dist, self.n_mc_samples\n )\n" ]
[ [ "torch.mean", "torch.nn.Parameter", "torch.nn.functional.log_softmax", "torch.digamma", "torch.distributions.gamma.Gamma", "torch.from_numpy", "torch.nn.Linear", "torch.rand", "torch.logsumexp", "torch.nn.functional.softplus" ] ]
jcantlord/PET-SinoGAN
[ "c83662ca2742955e4dbdfa5524ea814aad18a2dd" ]
[ "src/models/dcgan/train.py" ]
[ "\"\"\"\nTraining of DCGAN network\n\nBased on https://github.com/aladdinpersson\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\n\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nfrom model import Discriminator, Generator, initialize_weights\n\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nLEARNING_RATE_G = 2e-4\nLEARNING_RATE_D = 5e-5\nBATCH_SIZE = 128\nIMAGE_SIZE = 128\nCHANNELS_IMG = 1\nZ_DIM = 100\nNUM_EPOCHS = 120\nFEATURES_DISC = 64\nFEATURES_GEN = 64\n\ntransforms = transforms.Compose(\n [\n transforms.Grayscale(),\n transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)),\n transforms.ToTensor(),\n transforms.Normalize(\n [0.5 for _ in range(CHANNELS_IMG)], [0.5 for _ in range(CHANNELS_IMG)]),\n ]\n)\n\ndata_dir = '../input/real-bs-augmented/'\ndataset = datasets.ImageFolder(root=data_dir, transform=transforms)\n\ndataloader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True)\ngen = Generator(Z_DIM, CHANNELS_IMG, FEATURES_GEN).to(device)\ndisc = Discriminator(CHANNELS_IMG, FEATURES_DISC).to(device)\ninitialize_weights(gen)\ninitialize_weights(disc)\n\nopt_gen = optim.Adam(gen.parameters(), lr=LEARNING_RATE_G, betas=(0.5, 0.999))\nopt_disc = optim.Adam(disc.parameters(), lr=LEARNING_RATE_D, betas=(0.5, 0.999))\ncriterion = nn.BCELoss()\n\nfixed_noise = torch.randn(32, Z_DIM, 1, 1).to(device)\nwriter_real = SummaryWriter(f\"logs/real\")\nwriter_fake = SummaryWriter(f\"logs/fake\")\nstep = 0\n\ngen.train()\ndisc.train()\n\nfor epoch in range(NUM_EPOCHS):\n for batch_idx, (real, _) in enumerate(dataloader):\n real = real.to(device)\n noise = torch.randn((BATCH_SIZE, Z_DIM, 1, 1)).to(device)\n fake = gen(noise)\n\n ### Train Discriminator\n disc_real = disc(real).reshape(-1)\n loss_disc_real = criterion(disc_real, torch.ones_like(disc_real))\n\n disc_fake = disc(fake.detach()).reshape(-1)\n loss_disc_fake = criterion(disc_fake, torch.zeros_like(disc_fake))\n\n loss_disc = (loss_disc_real + loss_disc_fake) / 2\n disc.zero_grad()\n loss_disc.backward(retain_graph=True)\n opt_disc.step()\n\n ### Train Generator\n output = disc(fake).reshape(-1)\n loss_gen = criterion(output, torch.ones_like(output))\n gen.zero_grad()\n loss_gen.backward()\n opt_gen.step()\n\n if batch_idx % 100 == 0:\n print(\n f\"Epoch [{epoch}/{NUM_EPOCHS}] Batch {batch_idx}/{len(dataloader)} \\ Loss D: {loss_disc:.4f}, Loss G: {loss_gen:4f} \"\n )\n\n with torch.no_grad():\n fake = gen(fixed_noise)\n\n img_grid_real = torchvision.utils.make_grid(\n real[:32], normalize=True\n )\n\n img_grid_fake = torchvision.utils.make_grid(\n real[:32], normalize=True\n )\n\n writer_real.add_image(\"Real\", img_grid_real, global_step=step)\n writer_fake.add_image(\"Fake\", img_grid_fake, global_step=step)\n\n step += 1\n" ]
[ [ "torch.randn", "torch.utils.data.DataLoader", "torch.zeros_like", "torch.nn.BCELoss", "torch.no_grad", "torch.utils.tensorboard.SummaryWriter", "torch.cuda.is_available", "torch.ones_like" ] ]
sandialabs/BioCompoundDB
[ "8220e90544f43159843fa26758dc5a1333562fa7", "8220e90544f43159843fa26758dc5a1333562fa7" ]
[ "bcml/Parser/build_training.py", "bcml/KNNImpute/knnimpute/common.py" ]
[ "\"\"\"\nThis process takes in the training dataset and outputs\na data structure that includes the name of the molecule,\nthe predictor, and the CAS number\nAttributes:\n input_file (str): This is the training file that\n is read by the output\n Instance (class): This is a private class which\n structures each instance\n Model (class): This is a public class with the\n total structure of the set\n\"\"\"\n\nfrom __future__ import print_function\nimport numpy as np\nimport warnings\nimport sys\nfrom sklearn.preprocessing import Imputer\nfrom Boruta import boruta_py\nfrom sklearn.ensemble import RandomForestClassifier\nfrom KNNImpute.knnimpute import (\n knn_impute_optimistic,\n)\ntry:\n from collections import OrderedDict\nexcept ImportError:\n from ordereddict import OrderedDict\n\n\ndef dictitems(dict):\n if sys.version_info[0] >= 3:\n return dict.items()\n else:\n return dict.iteritems()\n\n\ndef verbose_print(verbose, line):\n if verbose:\n print(line)\n\n_possible_features = ('experimentalhash', 'binhash', 'padelhash', 'userhash')\n\n\ndef _convert_predictor(predictors, split_value):\n \"\"\"\"This function discretizes the predictors. This is currently\n set to handle a binary class, future versions will handle multi-class\n predictors\"\"\"\n preds = np.zeros(len(predictors), dtype=int)\n for i, value in np.ndenumerate(predictors):\n if value >= split_value:\n preds[i] = 1\n return preds\n\n\ndef _get_feature_names(compounds):\n \"\"\"This function handles collecting the feature names\"\"\"\n feature_names = {}\n for compound in compounds:\n for feature in sorted(_possible_features):\n if feature in compound.keys():\n keys = sorted(compound[feature].keys())\n for feat in keys:\n feature_names[feat] = 1\n compound[feat] = compound[feature][feat]\n return (compounds, sorted(feature_names.keys()))\n\n\nclass Process(object):\n \"\"\"This file reads a training file\"\"\"\n def _load_training_set(self):\n \"\"\"This function takes the features and\n compounds and loads them into a numpy array\n \"\"\"\n for index, value in np.ndenumerate(self.train):\n compound = self.compounds[index[0]]\n feature = list(self.feature_names)[index[1]]\n if (feature in compound.keys()) and (compound[feature] is not \"\")\\\n and (compound[feature] != \"NULL\")\\\n and (compound[feature] != \"False\"):\n self.train[index] = float(compound[feature])\n else:\n self.train[index] = np.nan\n\n def feature_selection(self, verbose, seed=False):\n \"\"\"This function runs Boruta feature selection to remove\n unimportant features from the data\"\"\"\n if verbose:\n verbose = 2\n '''Boruta cannot handle missing values. Either run impute_values\n before feature_selection, or the following function runs mean\n imputation prior to running Boruta'''\n if np.any(np.isnan(self.train)):\n warnings.warn('RandomForestClassifier requires no missing data,\\\n features being imputed by mean')\n X = self.train\n imp = Imputer(missing_values='NaN', strategy='mean', axis=0)\n imp.fit(X)\n self.train = imp.transform(X)\n rf = RandomForestClassifier(n_jobs=-1, oob_score=True, max_depth=5)\n feat_selector = boruta_py.BorutaPy(rf, n_estimators='auto',\n verbose=verbose, seed=seed)\n feat_selector.fit(self.train, self.predictors)\n self.feature_support = feat_selector.support_\n filtered_names = [i for indx, i in enumerate(self.feature_names) if self.feature_support[indx]]\n self.feature_names = filtered_names\n self.train = feat_selector.transform(self.train)\n\n def impute_values(self, distance, verbose, k=5):\n \"\"\"This function handles the missing values from\n the training set and estimates their value, based on\n the mean and reloads them into the training set\"\"\"\n verbose_print(verbose, 'Imputing using KNN strategy')\n X = self.train\n missing_mask = np.isnan(X)\n '''First impute uing knn optimistic'''\n impute = knn_impute_optimistic(X, missing_mask=missing_mask,\n distance=distance, k=k)\n X = impute.astype(float)\n '''For features with a small number of features, use mean\n imputation to remove NaN values'''\n imp = Imputer(missing_values='NaN', strategy='mean', axis=0)\n imp.fit(X)\n self.train = imp.transform(X)\n\n def __init__(self, model_input, split_value=False, verbose=False):\n \"\"\"This initialization function handles the heavy\n work of loading the features and processing the\n compounds\"\"\"\n self.input = model_input\n compounds = []\n predictors = []\n weights = []\n self.input.compound = OrderedDict(sorted(self.input.compound.items(), key=lambda t: t[0]))\n for id, compound in dictitems(self.input.compound):\n compounds.append(self.input.compound[id])\n predictors.append(self.input.compound[id]['predictor'])\n weights.append(self.input.compound[id]['weight'])\n predictor_values = np.array(predictors, '|S4').astype(np.float)\n weight_values = np.array(weights, '|S4').astype(np.float)\n self.weights = weight_values\n if split_value:\n self.predictors = _convert_predictor(predictor_values, split_value)\n else:\n print_line = \"Splitting at \" + str(np.median(predictor_values))\n verbose_print(verbose, print_line)\n self.predictors = _convert_predictor(predictor_values,\n np.median(predictor_values))\n self.rows = len(self.predictors)\n self.compounds, self.feature_names = _get_feature_names(compounds)\n self.columns = len(self.feature_names)\n '''Initialize the training array'''\n self.train = np.zeros((self.rows, self.columns,), dtype=np.float64)\n '''Load the training array'''\n self._load_training_set()\n", "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import, print_function, division\nimport time\n\nfrom six.moves import range\nimport numpy as np\n\nfrom .normalized_distance import all_pairs_normalized_distances\n\n\ndef knn_initialize(X, missing_mask, verbose=False, distance=False):\n \"\"\"\n Fill X with NaN values if necessary, construct the n_samples x n_samples\n distance matrix and set the self-distance of each row to infinity.\n \"\"\"\n X_row_major = X.copy(\"C\")\n if missing_mask.sum() != np.isnan(X_row_major).sum():\n # if the missing values have already been zero-filled need\n # to put NaN's back in the data matrix for the distances function\n X_row_major[missing_mask] = np.nan\n if distance is False:\n D = all_pairs_normalized_distances(X_row_major, verbose=verbose)\n else:\n D = distance\n # set diagonal of distance matrix to infinity since we don't want\n # points considering themselves as neighbors\n np.fill_diagonal(D, np.inf)\n #for i in range(X.shape[0]):\n # D[i, i] = np.inf\n return X_row_major, D\n" ]
[ [ "sklearn.ensemble.RandomForestClassifier", "numpy.isnan", "numpy.median", "sklearn.preprocessing.Imputer", "numpy.ndenumerate", "numpy.array", "numpy.zeros" ], [ "numpy.isnan", "numpy.fill_diagonal" ] ]
rzhangpku/MFAE
[ "5ced6bcde44645fe52a38b80266fd66f5c41ee2c" ]
[ "elmo_snli.py" ]
[ "\"\"\"\nTrain the ESIM model on the preprocessed SNLI dataset.\n\"\"\"\n# Aurelien Coet, 2018.\n\nfrom utils_elmo import train, validate\nfrom mfae.model_elmo2 import ESIM\nfrom mfae.data import ElmoDataset\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\nimport os\nimport sys\nimport argparse\nimport json\nimport numpy as np\nfrom allennlp.modules.elmo import batch_to_ids\nfrom torch.utils.data import DataLoader\nimport pickle\nimport torch\nimport matplotlib\nmatplotlib.use('Agg')\n\n\ndef transform_elmo_data(data, batch_size=128, shuffle=True):\n data_batch = dict()\n data_batch['premises'] = dict()\n data_batch['hypotheses'] = dict()\n data_batch['labels'] = dict()\n index = np.arange(len(data['labels']))\n if shuffle:\n np.random.shuffle(index)\n\n idx = -1\n for i in range(len(index)):\n if i % batch_size == 0:\n idx += 1\n data_batch['premises'][idx] = []\n data_batch['hypotheses'][idx] = []\n data_batch['labels'][idx] = []\n data_batch['premises'][idx].append(data['premises'][index[i]])\n data_batch['hypotheses'][idx].append(data['hypotheses'][index[i]])\n data_batch['labels'][idx].append(int(data['labels'][index[i]]))\n for i in range(len(data_batch['labels'])):\n data_batch['premises'][i] = batch_to_ids(data_batch['premises'][i])\n data_batch['hypotheses'][i] = batch_to_ids(data_batch['hypotheses'][i])\n return data_batch\n\ndef main(train_file,\n valid_file,\n options_file,\n weight_file,\n target_dir,\n embedding_size=512,\n hidden_size=300,\n dropout=0.5,\n num_classes=3,\n epochs=64,\n batch_size=32,\n lr=0.0004,\n patience=5,\n max_grad_norm=10.0,\n checkpoint=None):\n \"\"\"\n Train the ESIM model on the Quora dataset.\n\n Args:\n train_file: A path to some preprocessed data that must be used\n to train the model.\n valid_file: A path to some preprocessed data that must be used\n to validate the model.\n embeddings_file: A path to some preprocessed word embeddings that\n must be used to initialise the model.\n target_dir: The path to a directory where the trained model must\n be saved.\n hidden_size: The size of the hidden layers in the model. Defaults\n to 300.\n dropout: The dropout rate to use in the model. Defaults to 0.5.\n num_classes: The number of classes in the output of the model.\n Defaults to 3.\n epochs: The maximum number of epochs for training. Defaults to 64.\n batch_size: The size of the batches for training. Defaults to 32.\n lr: The learning rate for the optimizer. Defaults to 0.0004.\n patience: The patience to use for early stopping. Defaults to 5.\n checkpoint: A checkpoint from which to continue training. If None,\n training starts from scratch. Defaults to None.\n \"\"\"\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n print(20 * \"=\", \" Preparing for training \", 20 * \"=\")\n\n if not os.path.exists(target_dir):\n os.makedirs(target_dir)\n\n # -------------------- Data loading ------------------- #\n print(\"\\t* Loading training data...\")\n with open(train_file, \"rb\") as pkl: # train_file\n train_data = pickle.load(pkl)\n train_data = transform_elmo_data(train_data, batch_size=batch_size, shuffle=True)\n train_dataloader = DataLoader(ElmoDataset(train_data), batch_size=1, shuffle=True)\n\n print(\"\\t* Loading validation data...\")\n with open(valid_file, \"rb\") as pkl:\n valid_data = pickle.load(pkl)\n valid_data = transform_elmo_data(valid_data, batch_size=batch_size, shuffle=False)\n valid_dataloader = DataLoader(ElmoDataset(valid_data), batch_size=1, shuffle=False)\n\n # -------------------- Model definition ------------------- #\n print(\"\\t* Building model...\")\n # with open(embeddings_file, \"rb\") as pkl:\n # embeddings = torch.tensor(pickle.load(pkl), dtype=torch.float)\n\n model = ESIM(embedding_size,\n hidden_size,\n options_file, weight_file,\n dropout=dropout,\n num_classes=num_classes,\n device=device).to(device)\n\n # -------------------- Preparation for training ------------------- #\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer,\n mode=\"max\",\n factor=0.5,\n patience=0)\n\n best_score = 0.0\n start_epoch = 1\n\n # Data for loss curves plot.\n epochs_count = []\n train_losses = []\n valid_losses = []\n\n # Continuing training from a checkpoint if one was given as argument.\n if checkpoint:\n checkpoint = torch.load(checkpoint)\n start_epoch = checkpoint[\"epoch\"] + 1\n best_score = checkpoint[\"best_score\"]\n\n print(\"\\t* Training will continue on existing model from epoch {}...\"\n .format(start_epoch))\n\n model.load_state_dict(checkpoint[\"model\"])\n optimizer.load_state_dict(checkpoint[\"optimizer\"])\n epochs_count = checkpoint[\"epochs_count\"]\n train_losses = checkpoint[\"train_losses\"]\n valid_losses = checkpoint[\"valid_losses\"]\n\n # Compute loss and accuracy before starting (or resuming) training.\n _, valid_loss, valid_accuracy = validate(model,\n valid_dataloader,\n criterion)\n print(\"\\t* Validation loss before training: {:.4f}, accuracy: {:.4f}%\"\n .format(valid_loss, (valid_accuracy*100)))\n\n # -------------------- Training epochs ------------------- #\n print(\"\\n\",\n 20 * \"=\",\n \"Training ESIM model on device: {}\".format(device),\n 20 * \"=\")\n\n patience_counter = 0\n for epoch in range(start_epoch, epochs+1):\n epochs_count.append(epoch)\n\n print(\"* Training epoch {}:\".format(epoch))\n epoch_time, epoch_loss, epoch_accuracy = train(model,\n train_dataloader,\n optimizer,\n criterion,\n epoch,\n max_grad_norm)\n\n train_losses.append(epoch_loss)\n print(\"-> Training time: {:.4f}s, loss = {:.4f}, accuracy: {:.4f}%\"\n .format(epoch_time, epoch_loss, (epoch_accuracy*100)))\n\n print(\"* Validation for epoch {}:\".format(epoch))\n epoch_time, epoch_loss, epoch_accuracy = validate(model,\n valid_dataloader,\n criterion)\n\n valid_losses.append(epoch_loss)\n print(\"-> Valid. time: {:.4f}s, loss: {:.4f}, accuracy: {:.4f}%\\n\"\n .format(epoch_time, epoch_loss, (epoch_accuracy*100)))\n\n sys.stdout.flush() #刷新输出\n # Update the optimizer's learning rate with the scheduler.\n scheduler.step(epoch_accuracy)\n\n # Early stopping on validation accuracy.\n if epoch_accuracy < best_score:\n patience_counter += 1\n else:\n best_score = epoch_accuracy\n patience_counter = 0\n # Save the best model. The optimizer is not saved to avoid having\n # a checkpoint file that is too heavy to be shared. To resume\n # training from the best model, use the 'esim_*.pth.tar'\n # checkpoints instead.\n torch.save({\"epoch\": epoch,\n \"model\": model.state_dict(),\n \"best_score\": best_score,\n \"epochs_count\": epochs_count,\n \"train_losses\": train_losses,\n \"valid_losses\": valid_losses},\n os.path.join(target_dir, \"best.pth.tar\"))\n\n # Save the model at each epoch.\n torch.save({\"epoch\": epoch,\n \"model\": model.state_dict(),\n \"best_score\": best_score,\n \"optimizer\": optimizer.state_dict(),\n \"epochs_count\": epochs_count,\n \"train_losses\": train_losses,\n \"valid_losses\": valid_losses},\n os.path.join(target_dir, \"esim_{}.pth.tar\".format(epoch)))\n\n if patience_counter >= patience:\n print(\"-> Early stopping: patience limit reached, stopping...\")\n break\n\n # Plotting of the loss curves for the train and validation sets.\n fig = plt.figure()\n plt.plot(epochs_count, train_losses, \"-r\")\n plt.plot(epochs_count, valid_losses, \"-b\")\n plt.xlabel(\"epoch\")\n plt.ylabel(\"loss\")\n plt.legend([\"Training loss\", \"Validation loss\"])\n plt.title(\"Cross entropy loss\")\n fig.savefig('quora_loss.png')\n # plt.show()\n\n\nif __name__ == \"__main__\":\n default_config = \"../../config/training/snli_training_elmo.json\"\n\n parser = argparse.ArgumentParser(\n description=\"Train the ESIM model on quora\")\n parser.add_argument(\"--config\",\n default=default_config,\n help=\"Path to a json configuration file\")\n\n script_dir = os.path.dirname(os.path.realpath(__file__))\n script_dir = script_dir + '/scripts/training'\n\n parser.add_argument(\"--checkpoint\",\n default=None,#os.path.dirname(os.path.realpath(__file__)) + '/data/checkpoints/SNLI/elmo/' +\"esim_{}.pth.tar\".format(15),\n help=\"Path to a checkpoint file to resume training\")\n args = parser.parse_args()\n\n if args.config == default_config:\n config_path = os.path.join(script_dir, args.config)\n else:\n config_path = args.config\n\n with open(os.path.normpath(config_path), 'r') as config_file:\n config = json.load(config_file)\n\n main(os.path.normpath(os.path.join(script_dir, config[\"train_data\"])),\n os.path.normpath(os.path.join(script_dir, config[\"valid_data\"])),\n os.path.normpath(os.path.join(script_dir, config[\"options_file\"])),\n os.path.normpath(os.path.join(script_dir, config[\"weight_file\"])),\n os.path.normpath(os.path.join(script_dir, config[\"target_dir\"])),\n config[\"embedding_size\"],\n config[\"hidden_size\"],\n config[\"dropout\"],\n config[\"num_classes\"],\n config[\"epochs\"],\n config[\"batch_size\"],\n config[\"lr\"],\n config[\"patience\"],\n config[\"max_gradient_norm\"],\n args.checkpoint)\n" ]
[ [ "matplotlib.pyplot.legend", "torch.nn.CrossEntropyLoss", "torch.optim.lr_scheduler.ReduceLROnPlateau", "matplotlib.pyplot.title", "torch.load", "matplotlib.use", "numpy.random.shuffle", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "torch.cuda.is_available", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.figure" ] ]
indie/ngraph-bridge
[ "a702ee8294d0f24593ad0e9f63fe270a82d9c8b2" ]
[ "test/python/test_ngraph_serialize_flag.py" ]
[ "# ==============================================================================\n# Copyright 2019 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Pytest for a simple run on model testing framework\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pytest\nimport platform\nimport os\n\nimport tensorflow as tf\nimport numpy as np\nimport re\n\nfrom common import NgraphTest\nimport ngraph_bridge\n\n\nclass TestNgraphSerialize(NgraphTest):\n\n def test_ng_serialize_to_json(self):\n initial_contents = set(os.listdir())\n xshape = (3, 4, 5)\n x = tf.placeholder(tf.float32, shape=xshape)\n out = tf.nn.l2_loss(tf.abs(x))\n values = np.random.rand(*xshape)\n\n config = ngraph_bridge.update_config(tf.ConfigProto())\n ngraph_enable_serialize = os.environ.pop('NGRAPH_ENABLE_SERIALIZE',\n None)\n os.environ['NGRAPH_ENABLE_SERIALIZE'] = '1'\n ngraph_bridge.enable()\n with tf.Session(config=config) as sess:\n out = sess.run((out), feed_dict={x: values})\n os.environ.pop('NGRAPH_ENABLE_SERIALIZE', None)\n if ngraph_enable_serialize is not None:\n os.environ['NGRAPH_ENABLE_SERIALIZE'] = \\\n ngraph_enable_serialize\n\n final_contents = set(os.listdir())\n assert (len(final_contents) - len(initial_contents) == 1)\n new_files = final_contents.difference(initial_contents)\n flname = new_files.pop()\n assert (flname.startswith('tf_function_') and flname.endswith('json'))\n os.remove(flname)\n" ]
[ [ "tensorflow.placeholder", "tensorflow.ConfigProto", "numpy.random.rand", "tensorflow.Session", "tensorflow.abs" ] ]
huzecong/forte
[ "beae4e923c9a6873b582588972e6ec9919079271" ]
[ "forte/models/srl/data.py" ]
[ "import json\nfrom typing import List, NamedTuple, Tuple\n\nimport numpy as np\nimport torch\nfrom mypy_extensions import TypedDict\nimport texar.torch as tx\n\n\nclass SRLSpan(NamedTuple):\n predicate: int\n start: int\n end: int\n label: str\n\n\nclass Span(NamedTuple):\n start: int\n end: int\n label: str\n\n\nclass RawExample(TypedDict):\n speakers: List[List[str]]\n doc_key: str\n sentences: List[List[str]]\n srl: List[List[Tuple[int, int, int, str]]]\n constituents: List[List[Span]]\n cluster: List\n ner: List[List[Span]]\n\n\nclass Example(TypedDict):\n text: List[str]\n text_ids: np.ndarray\n srl: List[SRLSpan]\n\n\nclass SRLSpanData(tx.data.DatasetBase[str, Example]):\n def __init__(self, path: str, vocab: tx.data.Vocab, hparams):\n source = tx.data.TextLineDataSource(path)\n self._vocab = vocab\n super().__init__(source, hparams)\n\n def process(self, raw_example: str) -> Example:\n raw: RawExample = json.loads(raw_example)\n assert len(raw['sentences']) == 1\n sentence = raw['sentences'][0]\n example: Example = {\n 'text': sentence,\n 'text_ids': self._vocab.map_tokens_to_ids_py(sentence),\n 'srl': [SRLSpan(*items) for items in raw['srl'][0]]\n }\n return example\n\n def collate(self, examples: List[Example]) -> tx.data.Batch:\n sentences = [ex['text'] for ex in examples]\n tokens, length = tx.data.padded_batch(\n [ex['text_ids'] for ex in examples])\n srl = [ex['srl'] for ex in examples]\n return tx.data.Batch(\n len(examples), srl=srl, text=sentences,\n text_ids=torch.from_numpy(tokens).to(self.device),\n length=torch.tensor(length).to(self.device))\n" ]
[ [ "torch.from_numpy", "torch.tensor" ] ]
XuchanBao/pytorch-trpo
[ "5e87877ff22c8a1272381f84e37344604a522a1e" ]
[ "logger.py" ]
[ "import os\nimport sys\nimport shutil\nimport os.path as osp\nimport json\nimport time\nimport datetime\nimport tempfile\n\nLOG_OUTPUT_FORMATS = ['stdout', 'log', 'csv']\n# Also valid: json, tensorboard\n\nDEBUG = 10\nINFO = 20\nWARN = 30\nERROR = 40\n\nDISABLED = 50\n\nclass KVWriter(object):\n def writekvs(self, kvs):\n raise NotImplementedError\n\nclass SeqWriter(object):\n def writeseq(self, seq):\n raise NotImplementedError\n\nclass HumanOutputFormat(KVWriter, SeqWriter):\n def __init__(self, filename_or_file):\n if isinstance(filename_or_file, str):\n self.file = open(filename_or_file, 'wt')\n self.own_file = True\n else:\n assert hasattr(filename_or_file, 'read'), 'expected file or str, got %s'%filename_or_file\n self.file = filename_or_file\n self.own_file = False\n\n def writekvs(self, kvs):\n # Create strings for printing\n key2str = {}\n for (key, val) in sorted(kvs.items()):\n if isinstance(val, float):\n valstr = '%-8.3g' % (val,)\n else:\n valstr = str(val)\n key2str[self._truncate(key)] = self._truncate(valstr)\n\n # Find max widths\n if len(key2str) == 0:\n print('WARNING: tried to write empty key-value dict')\n return\n else:\n keywidth = max(map(len, key2str.keys()))\n valwidth = max(map(len, key2str.values()))\n\n # Write out the data\n dashes = '-' * (keywidth + valwidth + 7)\n lines = [dashes]\n for (key, val) in sorted(key2str.items()):\n lines.append('| %s%s | %s%s |' % (\n key,\n ' ' * (keywidth - len(key)),\n val,\n ' ' * (valwidth - len(val)),\n ))\n lines.append(dashes)\n self.file.write('\\n'.join(lines) + '\\n')\n\n # Flush the output to the file\n self.file.flush()\n\n def _truncate(self, s):\n return s[:20] + '...' if len(s) > 23 else s\n\n def writeseq(self, seq):\n for arg in seq:\n self.file.write(arg)\n self.file.write('\\n')\n self.file.flush()\n\n def close(self):\n if self.own_file:\n self.file.close()\n\nclass JSONOutputFormat(KVWriter):\n def __init__(self, filename):\n self.file = open(filename, 'wt')\n\n def writekvs(self, kvs):\n for k, v in sorted(kvs.items()):\n if hasattr(v, 'dtype'):\n v = v.tolist()\n kvs[k] = float(v)\n self.file.write(json.dumps(kvs) + '\\n')\n self.file.flush()\n\n def close(self):\n self.file.close()\n\nclass CSVOutputFormat(KVWriter):\n def __init__(self, filename):\n self.file = open(filename, 'w+t')\n self.keys = []\n self.sep = ','\n\n def writekvs(self, kvs):\n # Add our current row to the history\n extra_keys = kvs.keys() - self.keys\n if extra_keys:\n self.keys.extend(extra_keys)\n self.file.seek(0)\n lines = self.file.readlines()\n self.file.seek(0)\n for (i, k) in enumerate(self.keys):\n if i > 0:\n self.file.write(',')\n self.file.write(k)\n self.file.write('\\n')\n for line in lines[1:]:\n self.file.write(line[:-1])\n self.file.write(self.sep * len(extra_keys))\n self.file.write('\\n')\n for (i, k) in enumerate(self.keys):\n if i > 0:\n self.file.write(',')\n v = kvs.get(k)\n if v:\n self.file.write(str(v))\n self.file.write('\\n')\n self.file.flush()\n\n def close(self):\n self.file.close()\n\n\nclass TensorBoardOutputFormat(KVWriter):\n \"\"\"\n Dumps key/value pairs into TensorBoard's numeric format.\n \"\"\"\n def __init__(self, dir):\n os.makedirs(dir, exist_ok=True)\n self.dir = dir\n self.step = 1\n prefix = 'events'\n path = osp.join(osp.abspath(dir), prefix)\n import tensorflow as tf\n from tensorflow.python import pywrap_tensorflow\n from tensorflow.core.util import event_pb2\n from tensorflow.python.util import compat\n self.tf = tf\n self.event_pb2 = event_pb2\n self.pywrap_tensorflow = pywrap_tensorflow\n self.writer = pywrap_tensorflow.EventsWriter(compat.as_bytes(path))\n\n def writekvs(self, kvs):\n def summary_val(k, v):\n kwargs = {'tag': k, 'simple_value': float(v)}\n return self.tf.Summary.Value(**kwargs)\n summary = self.tf.Summary(value=[summary_val(k, v) for k, v in kvs.items()])\n event = self.event_pb2.Event(wall_time=time.time(), summary=summary)\n event.step = self.step # is there any reason why you'd want to specify the step?\n self.writer.WriteEvent(event)\n self.writer.Flush()\n self.step += 1\n\n def close(self):\n if self.writer:\n self.writer.Close()\n self.writer = None\n\ndef make_output_format(format, ev_dir):\n os.makedirs(ev_dir, exist_ok=True)\n rank = 0\n if format == 'stdout':\n return HumanOutputFormat(sys.stdout)\n elif format == 'log':\n suffix = \"\" if rank==0 else (\"-mpi%03i\"%rank)\n return HumanOutputFormat(osp.join(ev_dir, 'log%s.txt' % suffix))\n elif format == 'json':\n assert rank==0\n return JSONOutputFormat(osp.join(ev_dir, 'progress.json'))\n elif format == 'csv':\n assert rank==0\n return CSVOutputFormat(osp.join(ev_dir, 'progress.csv'))\n elif format == 'tensorboard':\n assert rank==0\n return TensorBoardOutputFormat(osp.join(ev_dir, 'tb'))\n else:\n raise ValueError('Unknown format specified: %s' % (format,))\n\n# ================================================================\n# API\n# ================================================================\n\ndef logkv(key, val):\n \"\"\"\n Log a value of some diagnostic\n Call this once for each diagnostic quantity, each iteration\n \"\"\"\n Logger.CURRENT.logkv(key, val)\n\ndef logkvs(d):\n \"\"\"\n Log a dictionary of key-value pairs\n \"\"\"\n for (k, v) in d.items():\n logkv(k, v)\n\ndef dumpkvs():\n \"\"\"\n Write all of the diagnostics from the current iteration\n level: int. (see logger.py docs) If the global logger level is higher than\n the level argument here, don't print to stdout.\n \"\"\"\n Logger.CURRENT.dumpkvs()\n\ndef getkvs():\n return Logger.CURRENT.name2val\n\n\ndef log(*args, level=INFO):\n \"\"\"\n Write the sequence of args, with no separators, to the console and output files (if you've configured an output file).\n \"\"\"\n Logger.CURRENT.log(*args, level=level)\n\ndef clear():\n Logger.CURRENT.clear()\n\ndef debug(*args):\n log(*args, level=DEBUG)\n\ndef info(*args):\n log(*args, level=INFO)\n\ndef warn(*args):\n log(*args, level=WARN)\n\ndef error(*args):\n log(*args, level=ERROR)\n\n\ndef set_level(level):\n \"\"\"\n Set logging threshold on current logger.\n \"\"\"\n Logger.CURRENT.set_level(level)\n\ndef get_dir():\n \"\"\"\n Get directory that log files are being written to.\n will be None if there is no output directory (i.e., if you didn't call start)\n \"\"\"\n return Logger.CURRENT.get_dir()\n\nrecord_tabular = logkv\ndump_tabular = dumpkvs\nclear_tabular = clear\n\n# ================================================================\n# Backend\n# ================================================================\n\nclass Logger(object):\n DEFAULT = None # A logger with no output files. (See right below class definition)\n # So that you can still log to the terminal without setting up any output files\n CURRENT = None # Current logger being used by the free functions above\n\n def __init__(self, dir, output_formats):\n self.name2val = {} # values this iteration\n self.level = INFO\n self.dir = dir\n self.output_formats = output_formats\n\n # Logging API, forwarded\n # ----------------------------------------\n def logkv(self, key, val):\n self.name2val[key] = val\n\n def clear(self):\n self.name2val = {}\n\n def dumpkvs(self):\n if self.level == DISABLED: return\n for fmt in self.output_formats:\n if isinstance(fmt, KVWriter):\n fmt.writekvs(self.name2val)\n self.name2val.clear()\n\n def log(self, *args, level=INFO):\n if self.level <= level:\n self._do_log(args)\n\n # Configuration\n # ----------------------------------------\n def set_level(self, level):\n self.level = level\n\n def get_dir(self):\n return self.dir\n\n def close(self):\n for fmt in self.output_formats:\n fmt.close()\n\n # Misc\n # ----------------------------------------\n def _do_log(self, args):\n for fmt in self.output_formats:\n if isinstance(fmt, SeqWriter):\n fmt.writeseq(map(str, args))\n\nLogger.DEFAULT = Logger.CURRENT = Logger(dir=None, output_formats=[HumanOutputFormat(sys.stdout)])\n\ndef configure(dir=None, format_strs=None):\n if dir is None:\n dir = os.getenv('OPENAI_LOGDIR')\n if dir is None:\n dir = osp.join(tempfile.gettempdir(),\n datetime.datetime.now().strftime(\"openai-%Y-%m-%d-%H-%M-%S-%f\"))\n assert isinstance(dir, str)\n os.makedirs(dir, exist_ok=True)\n\n if format_strs is None:\n strs = os.getenv('OPENAI_LOG_FORMAT')\n format_strs = strs.split(',') if strs else LOG_OUTPUT_FORMATS\n output_formats = [make_output_format(f, dir) for f in format_strs]\n\n Logger.CURRENT = Logger(dir=dir, output_formats=output_formats)\n log('Logging to %s'%dir)\n\ndef reset():\n if Logger.CURRENT is not Logger.DEFAULT:\n Logger.CURRENT.close()\n Logger.CURRENT = Logger.DEFAULT\n log('Reset logger')\n\nclass scoped_configure(object):\n def __init__(self, dir=None, format_strs=None):\n self.dir = dir\n self.format_strs = format_strs\n self.prevlogger = None\n def __enter__(self):\n self.prevlogger = Logger.CURRENT\n configure(dir=self.dir, format_strs=self.format_strs)\n def __exit__(self, *args):\n Logger.CURRENT.close()\n Logger.CURRENT = self.prevlogger\n\n# ================================================================\n\ndef _demo():\n info(\"hi\")\n debug(\"shouldn't appear\")\n set_level(DEBUG)\n debug(\"should appear\")\n dir = \"/tmp/testlogging\"\n if os.path.exists(dir):\n shutil.rmtree(dir)\n configure(dir=dir)\n logkv(\"a\", 3)\n logkv(\"b\", 2.5)\n dumpkvs()\n logkv(\"b\", -2.5)\n logkv(\"a\", 5.5)\n dumpkvs()\n info(\"^^^ should see a = 5.5\")\n\n logkv(\"b\", -2.5)\n dumpkvs()\n\n logkv(\"a\", \"longasslongasslongasslongasslongasslongassvalue\")\n dumpkvs()\n\n\n# ================================================================\n# Readers\n# ================================================================\n\ndef read_json(fname):\n import pandas\n ds = []\n with open(fname, 'rt') as fh:\n for line in fh:\n ds.append(json.loads(line))\n return pandas.DataFrame(ds)\n\ndef read_csv(fname):\n import pandas\n return pandas.read_csv(fname, index_col=None, comment='#')\n\ndef read_tb(path):\n \"\"\"\n path : a tensorboard file OR a directory, where we will find all TB files\n of the form events.*\n \"\"\"\n import pandas\n import numpy as np\n from glob import glob\n from collections import defaultdict\n import tensorflow as tf\n if osp.isdir(path):\n fnames = glob(osp.join(path, \"events.*\"))\n elif osp.basename(path).startswith(\"events.\"):\n fnames = [path]\n else:\n raise NotImplementedError(\"Expected tensorboard file or directory containing them. Got %s\"%path)\n tag2pairs = defaultdict(list)\n maxstep = 0\n for fname in fnames:\n for summary in tf.train.summary_iterator(fname):\n if summary.step > 0:\n for v in summary.summary.value:\n pair = (summary.step, v.simple_value)\n tag2pairs[v.tag].append(pair)\n maxstep = max(summary.step, maxstep)\n data = np.empty((maxstep, len(tag2pairs)))\n data[:] = np.nan\n tags = sorted(tag2pairs.keys())\n for (colidx,tag) in enumerate(tags):\n pairs = tag2pairs[tag]\n for (step, value) in pairs:\n data[step-1, colidx] = value\n return pandas.DataFrame(data, columns=tags)\n\nif __name__ == \"__main__\":\n _demo()\n" ]
[ [ "tensorflow.python.util.compat.as_bytes", "pandas.read_csv", "tensorflow.train.summary_iterator", "pandas.DataFrame" ] ]