repo_name
stringlengths
6
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
possible_versions
list
markveillette/high-fidelity-generative-compression
[ "d88b4d7f1212efa8611e91737ff6bf00bbf36670", "d88b4d7f1212efa8611e91737ff6bf00bbf36670", "d88b4d7f1212efa8611e91737ff6bf00bbf36670" ]
[ "src/loss/perceptual_similarity/dist_model.py", "src/compression/entropy_models.py", "src/loss/losses.py" ]
[ "\nfrom __future__ import absolute_import\n\nimport sys\nimport numpy as np\nimport torch\nfrom torch import nn\nimport os\nfrom collections import OrderedDict\nfrom torch.autograd import Variable\nimport itertools\nfrom .base_model import BaseModel\nfrom scipy.ndimage import zoom\nimport fractions\nimport functools\nimport skimage.transform\nfrom tqdm import tqdm\n\n\nfrom . import networks_basic as networks\nfrom . import perceptual_loss\n\nclass DistModel(BaseModel):\n def name(self):\n return self.model_name\n\n def initialize(self, model='net-lin', net='alex', colorspace='Lab', pnet_rand=False, pnet_tune=False, model_path=None,\n use_gpu=True, printNet=False, spatial=False, \n is_train=False, lr=.0001, beta1=0.5, version='0.1', gpu_ids=[0]):\n '''\n INPUTS\n model - ['net-lin'] for linearly calibrated network\n ['net'] for off-the-shelf network\n ['L2'] for L2 distance in Lab colorspace\n ['SSIM'] for ssim in RGB colorspace\n net - ['squeeze','alex','vgg']\n model_path - if None, will look in weights/[NET_NAME].pth\n colorspace - ['Lab','RGB'] colorspace to use for L2 and SSIM\n use_gpu - bool - whether or not to use a GPU\n printNet - bool - whether or not to print network architecture out\n spatial - bool - whether to output an array containing varying distances across spatial dimensions\n is_train - bool - [True] for training mode\n lr - float - initial learning rate\n beta1 - float - initial momentum term for adam\n version - 0.1 for latest, 0.0 was original (with a bug)\n gpu_ids - int array - [0] by default, gpus to use\n '''\n BaseModel.initialize(self, use_gpu=use_gpu, gpu_ids=gpu_ids)\n\n self.model = model\n self.net = net\n self.is_train = is_train\n self.spatial = spatial\n self.gpu_ids = gpu_ids\n self.model_name = '%s [%s]'%(model,net)\n\n if(self.model == 'net-lin'): # pretrained net + linear layer\n self.net = networks.PNetLin(pnet_rand=pnet_rand, pnet_tune=pnet_tune, pnet_type=net,\n use_dropout=True, spatial=spatial, version=version, lpips=True)\n kw = {}\n if not use_gpu:\n kw['map_location'] = 'cpu'\n if(model_path is None):\n import inspect\n model_path = os.path.abspath(os.path.join(inspect.getfile(self.initialize), '..', 'weights/v%s/%s.pth'%(version,net)))\n\n if(not is_train):\n print('Loading model from: %s'%model_path)\n self.net.load_state_dict(torch.load(model_path, **kw), strict=False)\n\n elif(self.model=='net'): # pretrained network\n self.net = networks.PNetLin(pnet_rand=pnet_rand, pnet_type=net, lpips=False)\n elif(self.model in ['L2','l2']):\n self.net = networks.L2(use_gpu=use_gpu,colorspace=colorspace) # not really a network, only for testing\n self.model_name = 'L2'\n elif(self.model in ['DSSIM','dssim','SSIM','ssim']):\n self.net = networks.DSSIM(use_gpu=use_gpu,colorspace=colorspace)\n self.model_name = 'SSIM'\n else:\n raise ValueError(\"Model [%s] not recognized.\" % self.model)\n\n self.parameters = list(self.net.parameters())\n\n if self.is_train: # training mode\n # extra network on top to go from distances (d0,d1) => predicted human judgment (h*)\n self.rankLoss = networks.BCERankingLoss()\n self.parameters += list(self.rankLoss.net.parameters())\n self.lr = lr\n self.old_lr = lr\n self.optimizer_net = torch.optim.Adam(self.parameters, lr=lr, betas=(beta1, 0.999))\n else: # test mode\n self.net.eval()\n\n if(use_gpu):\n self.net.to(gpu_ids[0])\n self.net = torch.nn.DataParallel(self.net, device_ids=gpu_ids)\n if(self.is_train):\n self.rankLoss = self.rankLoss.to(device=gpu_ids[0]) # just put this on GPU0\n\n if(printNet):\n print('---------- Networks initialized -------------')\n networks.print_network(self.net)\n print('-----------------------------------------------')\n\n def forward(self, in0, in1, retPerLayer=False):\n ''' Function computes the distance between image patches in0 and in1\n INPUTS\n in0, in1 - torch.Tensor object of shape Nx3xXxY - image patch scaled to [-1,1]\n OUTPUT\n computed distances between in0 and in1\n '''\n\n return self.net.forward(in0, in1, retPerLayer=retPerLayer)\n\n # ***** TRAINING FUNCTIONS *****\n def optimize_parameters(self):\n self.forward_train()\n self.optimizer_net.zero_grad()\n self.backward_train()\n self.optimizer_net.step()\n self.clamp_weights()\n\n def clamp_weights(self):\n for module in self.net.modules():\n if(hasattr(module, 'weight') and module.kernel_size==(1,1)):\n module.weight.data = torch.clamp(module.weight.data,min=0)\n\n def set_input(self, data):\n self.input_ref = data['ref']\n self.input_p0 = data['p0']\n self.input_p1 = data['p1']\n self.input_judge = data['judge']\n\n if(self.use_gpu):\n self.input_ref = self.input_ref.to(device=self.gpu_ids[0])\n self.input_p0 = self.input_p0.to(device=self.gpu_ids[0])\n self.input_p1 = self.input_p1.to(device=self.gpu_ids[0])\n self.input_judge = self.input_judge.to(device=self.gpu_ids[0])\n\n self.var_ref = Variable(self.input_ref,requires_grad=True)\n self.var_p0 = Variable(self.input_p0,requires_grad=True)\n self.var_p1 = Variable(self.input_p1,requires_grad=True)\n\n def forward_train(self): # run forward pass\n # print(self.net.module.scaling_layer.shift)\n # print(torch.norm(self.net.module.net.slice1[0].weight).item(), torch.norm(self.net.module.lin0.model[1].weight).item())\n\n self.d0 = self.forward(self.var_ref, self.var_p0)\n self.d1 = self.forward(self.var_ref, self.var_p1)\n self.acc_r = self.compute_accuracy(self.d0,self.d1,self.input_judge)\n\n self.var_judge = Variable(1.*self.input_judge).view(self.d0.size())\n\n self.loss_total = self.rankLoss.forward(self.d0, self.d1, self.var_judge*2.-1.)\n\n return self.loss_total\n\n def backward_train(self):\n torch.mean(self.loss_total).backward()\n\n def compute_accuracy(self,d0,d1,judge):\n ''' d0, d1 are Variables, judge is a Tensor '''\n d1_lt_d0 = (d1<d0).cpu().data.numpy().flatten()\n judge_per = judge.cpu().numpy().flatten()\n return d1_lt_d0*judge_per + (1-d1_lt_d0)*(1-judge_per)\n\n def get_current_errors(self):\n retDict = OrderedDict([('loss_total', self.loss_total.data.cpu().numpy()),\n ('acc_r', self.acc_r)])\n\n for key in retDict.keys():\n retDict[key] = np.mean(retDict[key])\n\n return retDict\n\n def get_current_visuals(self):\n zoom_factor = 256/self.var_ref.data.size()[2]\n\n ref_img = util.tensor2im(self.var_ref.data)\n p0_img = util.tensor2im(self.var_p0.data)\n p1_img = util.tensor2im(self.var_p1.data)\n\n ref_img_vis = zoom(ref_img,[zoom_factor, zoom_factor, 1],order=0)\n p0_img_vis = zoom(p0_img,[zoom_factor, zoom_factor, 1],order=0)\n p1_img_vis = zoom(p1_img,[zoom_factor, zoom_factor, 1],order=0)\n\n return OrderedDict([('ref', ref_img_vis),\n ('p0', p0_img_vis),\n ('p1', p1_img_vis)])\n\n def save(self, path, label):\n if(self.use_gpu):\n self.save_network(self.net.module, path, '', label)\n else:\n self.save_network(self.net, path, '', label)\n self.save_network(self.rankLoss.net, path, 'rank', label)\n\n def update_learning_rate(self,nepoch_decay):\n lrd = self.lr / nepoch_decay\n lr = self.old_lr - lrd\n\n for param_group in self.optimizer_net.param_groups:\n param_group['lr'] = lr\n\n print('update lr [%s] decay: %f -> %f' % (type,self.old_lr, lr))\n self.old_lr = lr\n\ndef score_2afc_dataset(data_loader, func, name=''):\n ''' Function computes Two Alternative Forced Choice (2AFC) score using\n distance function 'func' in dataset 'data_loader'\n INPUTS\n data_loader - CustomDatasetDataLoader object - contains a TwoAFCDataset inside\n func - callable distance function - calling d=func(in0,in1) should take 2\n pytorch tensors with shape Nx3xXxY, and return numpy array of length N\n OUTPUTS\n [0] - 2AFC score in [0,1], fraction of time func agrees with human evaluators\n [1] - dictionary with following elements\n d0s,d1s - N arrays containing distances between reference patch to perturbed patches \n gts - N array in [0,1], preferred patch selected by human evaluators\n (closer to \"0\" for left patch p0, \"1\" for right patch p1,\n \"0.6\" means 60pct people preferred right patch, 40pct preferred left)\n scores - N array in [0,1], corresponding to what percentage function agreed with humans\n CONSTS\n N - number of test triplets in data_loader\n '''\n\n d0s = []\n d1s = []\n gts = []\n\n for data in tqdm(data_loader.load_data(), desc=name):\n d0s+=func(data['ref'],data['p0']).data.cpu().numpy().flatten().tolist()\n d1s+=func(data['ref'],data['p1']).data.cpu().numpy().flatten().tolist()\n gts+=data['judge'].cpu().numpy().flatten().tolist()\n\n d0s = np.array(d0s)\n d1s = np.array(d1s)\n gts = np.array(gts)\n scores = (d0s<d1s)*(1.-gts) + (d1s<d0s)*gts + (d1s==d0s)*.5\n\n return(np.mean(scores), dict(d0s=d0s,d1s=d1s,gts=gts,scores=scores))\n\ndef score_jnd_dataset(data_loader, func, name=''):\n ''' Function computes JND score using distance function 'func' in dataset 'data_loader'\n INPUTS\n data_loader - CustomDatasetDataLoader object - contains a JNDDataset inside\n func - callable distance function - calling d=func(in0,in1) should take 2\n pytorch tensors with shape Nx3xXxY, and return pytorch array of length N\n OUTPUTS\n [0] - JND score in [0,1], mAP score (area under precision-recall curve)\n [1] - dictionary with following elements\n ds - N array containing distances between two patches shown to human evaluator\n sames - N array containing fraction of people who thought the two patches were identical\n CONSTS\n N - number of test triplets in data_loader\n '''\n\n ds = []\n gts = []\n\n for data in tqdm(data_loader.load_data(), desc=name):\n ds+=func(data['p0'],data['p1']).data.cpu().numpy().tolist()\n gts+=data['same'].cpu().numpy().flatten().tolist()\n\n sames = np.array(gts)\n ds = np.array(ds)\n\n sorted_inds = np.argsort(ds)\n ds_sorted = ds[sorted_inds]\n sames_sorted = sames[sorted_inds]\n\n TPs = np.cumsum(sames_sorted)\n FPs = np.cumsum(1-sames_sorted)\n FNs = np.sum(sames_sorted)-TPs\n\n precs = TPs/(TPs+FPs)\n recs = TPs/(TPs+FNs)\n score = util.voc_ap(recs,precs)\n\n return(score, dict(ds=ds,sames=sames))\n", "import abc\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\n# Custom\nfrom src.helpers import maths\n\nMIN_SCALE = 0.11\nMIN_LIKELIHOOD = 1e-9\nMAX_LIKELIHOOD = 1e4\nTAIL_MASS = 2**(-9)\n\nPRECISION_P = 16 # Precision of rANS coder\n\n# TODO: Unit tests\n\nlower_bound_toward = maths.LowerBoundToward.apply\n \nclass ContinuousEntropyModel(nn.Module, metaclass=abc.ABCMeta):\n \"\"\"\n Base class for pre-computation of integer probability tables for use in entropy coding.\n \"\"\"\n def __init__(self, distribution, likelihood_bound=MIN_LIKELIHOOD, tail_mass=TAIL_MASS,\n precision=PRECISION_P):\n \"\"\"\n The layer assumes that the input tensor is at least 2D, with a batch dimension\n at the beginning and a channel dimension, specified by subclassing this layer. \n The layer trains an independent probability density model for each 'channel',\n but assumes that across all other dimensions, the inputs are i.i.d. (independent\n and identically distributed).\n\n Parameters:\n distribution: Distribution with CDF / quantile / likelihood methods\n\n Note:\n The batch dimensions are indexes into independent, non-identical parameterizations \n of this distribution - [B, n_channels], where B usually = 1.\n (Dimensions which are not assumed i.i.d.)\n \"\"\"\n\n super(ContinuousEntropyModel, self).__init__()\n\n self.distribution = distribution\n self.likelihood_bound = float(likelihood_bound)\n self.tail_mass = float(tail_mass)\n self.precision = int(precision)\n\n def quantize_st(self, inputs, offsets=None):\n # Ignore rounding in backward pass\n values = inputs\n\n if offsets is not None:\n offsets = offsets.to(values)\n values = values - offsets\n\n delta = (torch.floor(values + 0.5) - values).detach()\n values = values + delta\n\n if offsets is not None:\n values = values + offsets\n\n return values\n\n def dequantize(self, x, offsets=None):\n\n if offsets is not None:\n values = x.type_as(offsets)\n values = values + offsets\n else:\n values = x.to(torch.float32)\n\n return values\n\n @abc.abstractmethod\n def build_tables(self, **kwargs):\n pass\n\n\n\nif __name__ == '__main__':\n\n print('Hi!')\n", "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\nfrom src.helpers.utils import get_scheduled_params\n\ndef weighted_rate_loss(config, total_nbpp, total_qbpp, step_counter, ignore_schedule=False):\n \"\"\"\n Heavily penalize the rate with weight lambda_A >> lambda_B if it exceeds \n some target r_t, otherwise penalize with lambda_B\n \"\"\"\n lambda_A = get_scheduled_params(config.lambda_A, config.lambda_schedule, step_counter, ignore_schedule)\n lambda_B = get_scheduled_params(config.lambda_B, config.lambda_schedule, step_counter, ignore_schedule)\n\n assert lambda_A > lambda_B, \"Expected lambda_A > lambda_B, got (A) {} <= (B) {}\".format(\n lambda_A, lambda_B)\n\n target_bpp = get_scheduled_params(config.target_rate, config.target_schedule, step_counter, ignore_schedule)\n\n total_qbpp = total_qbpp.item()\n if total_qbpp > target_bpp:\n rate_penalty = lambda_A\n else:\n rate_penalty = lambda_B\n weighted_rate = rate_penalty * total_nbpp\n\n return weighted_rate, float(rate_penalty)\n\ndef _non_saturating_loss(D_real_logits, D_gen_logits, D_real=None, D_gen=None):\n\n D_loss_real = F.binary_cross_entropy_with_logits(input=D_real_logits,\n target=torch.ones_like(D_real_logits))\n D_loss_gen = F.binary_cross_entropy_with_logits(input=D_gen_logits,\n target=torch.zeros_like(D_gen_logits))\n D_loss = D_loss_real + D_loss_gen\n\n G_loss = F.binary_cross_entropy_with_logits(input=D_gen_logits,\n target=torch.ones_like(D_gen_logits))\n\n return D_loss, G_loss\n\ndef _least_squares_loss(D_real, D_gen, D_real_logits=None, D_gen_logits=None):\n D_loss_real = torch.mean(torch.square(D_real - 1.0))\n D_loss_gen = torch.mean(torch.square(D_gen))\n D_loss = 0.5 * (D_loss_real + D_loss_gen)\n\n G_loss = 0.5 * torch.mean(torch.square(D_gen - 1.0))\n \n return D_loss, G_loss\n\ndef gan_loss(gan_loss_type, disc_out, mode='generator_loss'):\n\n if gan_loss_type == 'non_saturating':\n loss_fn = _non_saturating_loss\n elif gan_loss_type == 'least_squares':\n loss_fn = _least_squares_loss\n else:\n raise ValueError('Invalid GAN loss')\n\n D_loss, G_loss = loss_fn(D_real=disc_out.D_real, D_gen=disc_out.D_gen,\n D_real_logits=disc_out.D_real_logits, D_gen_logits=disc_out.D_gen_logits)\n \n loss = G_loss if mode == 'generator_loss' else D_loss\n \n return loss\n" ]
[ [ "torch.optim.Adam", "torch.mean", "torch.clamp", "torch.load", "scipy.ndimage.zoom", "numpy.cumsum", "numpy.mean", "numpy.argsort", "torch.nn.DataParallel", "numpy.array", "numpy.sum", "torch.autograd.Variable" ], [ "torch.floor" ], [ "torch.zeros_like", "torch.square", "torch.ones_like" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
SOPR-T/SOPR-T
[ "3242461fa8b3e917cde70be497beb1158a7b27e6", "3242461fa8b3e917cde70be497beb1158a7b27e6" ]
[ "d3rlpy-master/tests/models/torch/test_dynamics.py", "src/train_policy.py" ]
[ "import pytest\nimport torch\n\nfrom d3rlpy.models.encoders import DefaultEncoderFactory\nfrom d3rlpy.models.torch.dynamics import (\n ProbabilisticDynamicsModel,\n ProbabilisticEnsembleDynamicsModel,\n _compute_ensemble_variance,\n)\n\nfrom .model_test import DummyEncoder, check_parameter_updates\n\n\[email protected](\"batch_size\", [32])\[email protected](\"observation_shape\", [(100,)])\[email protected](\"n_ensembles\", [5])\[email protected](\"variance_type\", [\"max\", \"data\"])\ndef test_compute_ensemble_variance(\n batch_size, observation_shape, n_ensembles, variance_type\n):\n observations = torch.rand((batch_size, n_ensembles) + observation_shape)\n rewards = torch.rand(batch_size, n_ensembles, 1)\n variances = torch.rand(batch_size, n_ensembles, 1)\n\n if variance_type == \"max\":\n ref = variances.max(dim=1).values\n elif variance_type == \"data\":\n data = torch.cat([observations, rewards], dim=2)\n ref = (data.std(dim=1) ** 2).sum(dim=1, keepdims=True)\n\n variances = _compute_ensemble_variance(\n observations, rewards, variances, variance_type\n )\n\n assert variances.shape == (batch_size, 1)\n assert torch.allclose(variances, ref)\n\n\[email protected](\"feature_size\", [100])\[email protected](\"action_size\", [2])\[email protected](\"batch_size\", [32])\ndef test_probabilistic_dynamics_model(feature_size, action_size, batch_size):\n encoder = DummyEncoder(feature_size, action_size, True)\n dynamics = ProbabilisticDynamicsModel(encoder)\n\n # check output shape\n x = torch.rand(batch_size, feature_size)\n action = torch.rand(batch_size, action_size)\n pred_x, pred_reward = dynamics(x, action)\n assert pred_x.shape == (batch_size, feature_size)\n assert pred_reward.shape == (batch_size, 1)\n\n # check variance\n _, _, variance = dynamics.predict_with_variance(x, action)\n assert variance.shape == (batch_size, 1)\n\n # TODO: check error\n reward = torch.rand(batch_size, 1)\n loss = dynamics.compute_error(x, action, reward, x)\n assert loss.shape == (batch_size, 1)\n\n # check layer connection\n check_parameter_updates(dynamics, (x, action, reward, x))\n\n\[email protected](\"feature_size\", [100])\[email protected](\"action_size\", [2])\[email protected](\"batch_size\", [32])\[email protected](\"n_ensembles\", [5])\[email protected](\"variance_type\", [\"max\", \"data\"])\ndef test_probabilistic_ensemble_dynamics_dynamics_model(\n feature_size, action_size, batch_size, n_ensembles, variance_type\n):\n encoder = DummyEncoder(feature_size, action_size, True)\n models = []\n for _ in range(n_ensembles):\n models.append(ProbabilisticDynamicsModel(encoder))\n\n dynamics = ProbabilisticEnsembleDynamicsModel(models)\n\n # check output shape\n x = torch.rand(batch_size, feature_size)\n action = torch.rand(batch_size, action_size)\n pred_x, pred_reward = dynamics(x, action)\n assert pred_x.shape == (batch_size, n_ensembles, feature_size)\n assert pred_reward.shape == (batch_size, n_ensembles, 1)\n\n # check variance without indices\n pred_x, pred_reward, variances = dynamics.predict_with_variance(\n x, action, variance_type=variance_type\n )\n assert pred_x.shape == (batch_size, n_ensembles, feature_size)\n assert pred_reward.shape == (batch_size, n_ensembles, 1)\n assert variances.shape == (batch_size, 1)\n\n # check variance with indices\n indices = torch.randint(n_ensembles, size=(batch_size,))\n pred_x, pred_reward, variances = dynamics.predict_with_variance(\n x, action, variance_type=variance_type, indices=indices\n )\n assert pred_x.shape == (batch_size, feature_size)\n assert pred_reward.shape == (batch_size, 1)\n assert variances.shape == (batch_size, 1)\n\n # TODO: check error\n reward = torch.rand(batch_size, 1)\n loss = dynamics.compute_error(x, action, reward, x)\n\n # check layer connection\n check_parameter_updates(dynamics, (x, action, reward, x))\n", "import argparse\nimport numpy as np\nimport os\nimport torch\n\nimport offline_agent\nimport online_agent\nfrom utils.constants import env_list\n\n\nif __name__ == \"__main__\":\n\t\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"--env\", default=\"HalfCheetah-v2\") # OpenAI gym environment name\n\tparser.add_argument(\"--seed\", default=0, type=int) # Sets Gym, PyTorch and Numpy seeds\n\tparser.add_argument(\"--T\", type=int, default=100)\t\t\t # epochs for offline algorithms and steps for online algorithms\n\tparser.add_argument(\"--save_interval\", default=1, type=float) # For online algos, this means the intervals of saving steps\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t # and for offline algos, this means the intervals of saving epochs\n\tparser.add_argument(\"--batch_size\", default=128, type=int) # Mini batch size for networks\n\tparser.add_argument(\"--algo\", type=str, default=None, \t \t # select algos\n\t\t\t\t\t\tchoices=['BCloning', 'BCQ', 'offDDPG', 'BEAR', 'CQL', 'onlineDDPG', 'onlineSAC', 'MOPO', 'CRR']) \n\tparser.add_argument('--model_path', type=str, default='../models_try/')\t# where to save model\n\tparser.add_argument('--buffer_path', type=str, default='D4RLdata')\t\t# where is the data for offline training\n\targs = parser.parse_args()\n\n\tprint(\"---------------------------------------\")\n\tprint(f'setting: training {args.algo}, Env: {args.env}, seed: {args.seed}')\n\tprint(\"---------------------------------------\")\n\n\tif not os.path.exists(args.model_path):\n\t\tos.makedirs(args.model_path, exist_ok=True)\n\n\ttorch.manual_seed(args.seed)\n\tnp.random.seed(args.seed)\n\t\n\tstate_dim = env_list[args.env]['state_dim'] #env.observation_space.shape[0]\n\taction_dim = env_list[args.env]['action_dim'] #env.action_space.shape[0] \n\tmax_action = env_list[args.env]['max_action'] #float(env.action_space.high[0])\n\n\tdevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\t\n\tonline = args.algo in ['onlineDDPG', 'onlineSAC']\n\n\tif online:\n\t\ttrainer = online_agent.OnlineAgent(state_dim, action_dim, batch_size=args.batch_size, algo=args.algo, device=device)\n\telse:\n\t\ttrainer = offline_agent.OfflineAgent(state_dim, action_dim, batch_size=args.batch_size, algo=args.algo, device=device)\n\ttrainer.train(args, device=device)\n\n\t\n\t# os.makedirs(f'/mnt/exps/models/{args.model_path}/', exist_ok=True)\n\tos.system(f'mv {args.model_path}/{args.algo} /mnt/exps/models_our/{args.model_path}/')\n\tif args.algo == 'MOPO':\n\t\tos.system(f'mv {args.model_path}/MOPO_SAC/ /mnt/exps/models_retry/{args.model_path}/')\n" ]
[ [ "torch.allclose", "torch.randint", "torch.rand", "torch.cat" ], [ "torch.manual_seed", "torch.cuda.is_available", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
LockdownInnovators/CodeNames
[ "b82fc9c85d4887ae81f331de6f2058e5e2cdccd9" ]
[ "engine.py" ]
[ "from __future__ import print_function, division\n\nimport itertools\nimport re\nimport sys\nimport os\nimport platform\n\nimport numpy as np\n\nimport model\nfrom config import config\n\nCLUE_PATTERN = r'^([a-zA-Z]+) ({0})$'\nUNLIMITED = \"unlimited\"\n\n\n# noinspection PyAttributeOutsideInit\nclass GameEngine(object):\n\n def __init__(self, seed=None, expert=False, word2vec_models=None):\n\n # Load our word list if necessary.\n # TODO: Max length of 11 is hardcoded here and in print_board()\n if word2vec_models is None:\n word2vec_models = {}\n with open(config.word_list) as f:\n _words = [line.rstrip().lower().replace(' ', '_') for line in f.readlines()]\n self.words = np.array(_words)\n\n # Initialize our word embedding models.\n self.models = {k: model.WordEmbedding(w2v) for k, w2v in word2vec_models.items()}\n\n # Initialize random numbers.\n self.generator = np.random.RandomState(seed=seed)\n\n # Register expert mode\n self.expert = expert\n self.unfound_words = (set(), set())\n\n # Useful regular expressions.\n if self.expert:\n self.valid_clue = re.compile(CLUE_PATTERN.format(\"[0-9]|\" + UNLIMITED))\n else:\n self.valid_clue = re.compile(CLUE_PATTERN.format(\"[0-9]\"))\n\n def initialize_random_game(self, size=5):\n\n self.size = size\n\n # Shuffle the wordlist.\n shuffle = self.generator.choice(\n len(self.words), size * size, replace=False)\n self.board = self.words[shuffle]\n\n # Specify the layout for this game.\n assignments = self.generator.permutation(size * size)\n self.owner = np.empty(size * size, int)\n self.owner[assignments[0]] = 0 # assassin\n self.owner[assignments[1:10]] = 1 # first player: 9 words\n self.owner[assignments[10:18]] = 2 # second player: 8 words\n self.owner[assignments[18:]] = 3 # bystander: 7 words\n\n self.assassin_word = self.board[self.owner == 0]\n\n # All cards are initially visible.\n self.visible = np.ones_like(self.owner, dtype=bool)\n\n self.num_turns = -1\n\n def initialize_from_words(self, initial_words, size=5):\n \"\"\"\n The initial_words parameter should be in the format:\n\n ASSASSIN;TEAM1;TEAM2;NEUTRAL\n\n where each group consists of comma-separated words from the word list.\n\n The total number of words must be <= size * size. Any missing words\n are considered to be already covered and neutral.\n \"\"\"\n self.size = size\n\n word_groups = initial_words.split(';')\n if len(word_groups) != 4:\n raise ValueError('Expected 4 groups separated by semicolon.')\n\n board, owner, visible = [], [], []\n for group_index, word_group in enumerate(word_groups):\n words = word_group.split(',')\n for word in words:\n word = word.lower().replace(' ', '_')\n if word not in self.words:\n raise ValueError('Invalid word \"{0}\".'.format(word))\n if word in board:\n raise ValueError('Duplicate word \"{0}\".'.format(word))\n board.append(word)\n owner.append(group_index)\n visible.append(True)\n if len(board) > size * size:\n raise ValueError('Too many words. Expected <= {0}.'.format(size * size))\n # Add dummy hidden words if necessary.\n while len(board) < size * size:\n board.append('---')\n owner.append(3)\n visible.append(False)\n\n self.board = np.array(board)\n self.owner = np.array(owner)\n self.visible = np.array(visible)\n\n # Perform a random shuffle of the board.\n shuffle = self.generator.permutation(size * size)\n self.board = self.board[shuffle]\n self.owner = self.owner[shuffle]\n self.visible = self.visible[shuffle]\n\n self.assassin_word = self.board[self.owner == 0]\n self.num_turns = -1\n\n def print_board(self, spymaster=False, clear_screen=True):\n\n if clear_screen:\n if platform.system() == 'Windows':\n os.system('cls')\n else:\n print(chr(27) + '[2J')\n\n board = self.board.reshape(self.size, self.size)\n owner = self.owner.reshape(self.size, self.size)\n visible = self.visible.reshape(self.size, self.size)\n\n for row in range(self.size):\n for col in range(self.size):\n word = board[row, col]\n tag = '#<>-'[owner[row, col]]\n if not visible[row, col]:\n word = tag * 11\n elif not spymaster:\n tag = ' '\n if not spymaster or owner[row, col] in (0, 1, 2):\n word = word.upper()\n print('{0}{1:11s} '.format(tag, word), end='')\n print('')\n\n def play_computer_spymaster(self, gamma=1.0, verbose=True):\n\n say('Thinking...')\n sys.stdout.flush()\n\n # Loop over all permutations of words.\n num_words = len(self.player_words)\n best_score, saved_clues = [], []\n for count in range(max(num_words, 2), 0, -1):\n # Multiply similarity scores by this factor for any clue\n # corresponding to this many words.\n bonus_factor = count ** gamma\n for group in itertools.combinations(range(num_words), count):\n words = self.player_words[list(group)]\n clue, score = self.models[f'{self.player + 1} Master'].get_clue(clue_words=words,\n pos_words=self.player_words,\n neg_words=np.concatenate((\n self.opponent_words,\n self.neutral_words)),\n veto_words=self.assassin_word)\n if clue:\n best_score.append(score * bonus_factor)\n saved_clues.append((clue, words))\n num_clues = len(saved_clues)\n order = sorted(range(num_clues), key=lambda k: best_score[k], reverse=True)\n\n if verbose:\n self.print_board(spymaster=True)\n for i in order[:10]:\n clue, words = saved_clues[i]\n say(u'{0:.3f} {1} = {2}'.format(best_score[i], ' + '.join([w.upper() for w in words]), clue))\n\n clue, words = saved_clues[order[0]]\n self.unfound_words[self.player].update(words)\n if self.expert and self._should_say_unlimited(nb_clue_words=len(words)):\n return clue, UNLIMITED\n else:\n return clue, len(words)\n\n def _should_say_unlimited(self, nb_clue_words, threshold_opponent=2):\n \"\"\"\n Announce \"unlimited\" if :\n (1) the opposing team risks winning with their next clue,\n (2) and our +1 guess isn't enough to catch up during this clue,\n (3) but all the words hinted by the current and previous clues\n are enough to catch up and win\n \"\"\"\n return (len(self.opponent_words) <= threshold_opponent # (1)\n and nb_clue_words + 1 < len(self.player_words) # (2)\n and self.unfound_words[self.player]\n == set(self.player_words)) # (3)\n\n def play_human_spymaster(self):\n\n self.print_board(spymaster=True)\n\n while True:\n clue = ask('{0} Enter your clue: '.format(self.player_label))\n matched = self.valid_clue.match(clue)\n if matched:\n word, count = matched.groups()\n if count != UNLIMITED:\n count = int(count)\n return word, count\n say('Invalid clue, should be WORD COUNT.')\n\n def play_human_team(self, word, count):\n\n num_guesses = 0\n while (self.expert and count == UNLIMITED) or num_guesses < count + 1:\n self.print_board(clear_screen=(num_guesses == 0))\n say(u'{0} your clue is: {1} {2}'.format(self.player_label, word, count))\n\n num_guesses += 1\n while True:\n guess = ask('{0} enter your guess #{1}: '.format(self.player_label, num_guesses))\n guess = guess.strip().lower().replace(' ', '_')\n if guess == '':\n # Team does not want to make any more guesses.\n return True\n if guess in self.board[self.visible]:\n break\n say('Invalid guess, should be a visible word.')\n\n loc = np.where(self.board == guess)[0]\n self.visible[loc] = False\n\n if guess == self.assassin_word:\n say('{0} You guessed the assasin - game over!'.format(self.player_label))\n return False\n\n if guess in self.player_words:\n self.unfound_words[self.player].discard(guess)\n if num_guesses == len(self.player_words):\n say('{0} You won!!!'.format(self.player_label))\n return False\n else:\n ask('{0} Congratulations, keep going! (hit ENTER)\\n'.format(self.player_label))\n else:\n if guess in self.opponent_words:\n ask('{0} Sorry, word from opposing team! (hit ENTER)\\n'.format(self.player_label))\n else:\n ask('{0} Sorry, bystander! (hit ENTER)\\n'.format(self.player_label))\n break\n\n return True\n\n def play_computer_team(self, word, count):\n num_guesses = 0\n say(u'{0} (computer) your clue is: {1} {2}'.format(self.player_label, word, count))\n guesses = self.models[f'{self.player + 1} Guesser'].get_closest_board_words_to(word, count, self.player_words)\n for guess in guesses:\n num_guesses += 1\n say(f'Computer guess #{num_guesses}: {guess}')\n loc = np.where(self.board == guess)[0]\n self.visible[loc] = False\n\n if guess == self.assassin_word:\n say('{0} (computer) guessed the assasin - game over!'.format(self.player_label))\n return False\n\n if guess in self.player_words:\n self.unfound_words[self.player].discard(guess)\n if num_guesses == len(self.player_words):\n say('{0} (computer) You won!!!'.format(self.player_label))\n return False\n else:\n ask('{0} Congratulations computer, keep going! (hit ENTER)\\n'.format(self.player_label))\n else:\n if guess in self.opponent_words:\n ask('{0} Sorry computer, word from opposing team! (hit ENTER)\\n'.format(self.player_label))\n else:\n ask('{0} Sorry computer, bystander! (hit ENTER)\\n'.format(self.player_label))\n break\n\n return True\n\n def next_turn(self):\n self.num_turns += 1\n\n self.player = self.num_turns % 2\n self.opponent = (self.player + 1) % 2\n\n self.player_label = '<>'[self.player] * 3\n self.player_words = self.board[(self.owner == self.player + 1) & self.visible]\n self.opponent_words = self.board[(self.owner == self.opponent + 1) & self.visible]\n self.neutral_words = self.board[(self.owner == 3) & self.visible]\n\n def play_turn(self, spymaster='human', team='human'):\n\n self.next_turn()\n\n if spymaster == 'human':\n word, count = self.play_human_spymaster()\n else:\n word, count = self.play_computer_spymaster()\n\n if team == 'human':\n ongoing = self.play_human_team(word, count)\n else:\n ongoing = self.play_computer_team(word, count)\n\n return ongoing\n\n def play_game(self, spymaster1='human', team1='human',\n spymaster2='human', team2='human', init=None):\n\n if init is None:\n self.initialize_random_game()\n else:\n self.initialize_from_words(init)\n\n while True:\n if not self.play_turn(spymaster1, team1): break\n if not self.play_turn(spymaster2, team2): break\n\n\ndef say(message):\n print((message + '\\n').encode('utf8'))\n\n\ndef ask(message):\n try:\n return input(message)\n except KeyboardInterrupt:\n say('\\nBye.')\n sys.exit(0)\n" ]
[ [ "numpy.ones_like", "numpy.random.RandomState", "numpy.concatenate", "numpy.array", "numpy.where", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
aaxwaz/youtube-8m
[ "3c3ceae83173d6b9eaef6072308a2804ba56bcf5", "3c3ceae83173d6b9eaef6072308a2804ba56bcf5" ]
[ "other_train/train_loadCorrMat.py", "other_frame_level_model/FV_fv1Only_SVDMidTanh_hiddenLayer/frame_level_models.py" ]
[ "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Binary for training Tensorflow models on the YouTube-8M dataset.\"\"\"\n\nimport json\nimport os\nimport time\n\nimport eval_util\nimport export_model\nimport losses\nimport frame_level_models\nimport video_level_models\nimport readers\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nfrom tensorflow import app\nfrom tensorflow import flags\nfrom tensorflow import gfile\nfrom tensorflow import logging\nfrom tensorflow.python.client import device_lib\nimport utils\nimport numpy as np \n\nFLAGS = flags.FLAGS\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \n\nif __name__ == \"__main__\":\n # Dataset flags.\n flags.DEFINE_string(\"train_dir\", \"/tmp/yt8m_model/\",\n \"The directory to save the model files in.\")\n flags.DEFINE_string(\n \"train_data_pattern\", \"\",\n \"File glob for the training dataset. If the files refer to Frame Level \"\n \"features (i.e. tensorflow.SequenceExample), then set --reader_type \"\n \"format. The (Sequence)Examples are expected to have 'rgb' byte array \"\n \"sequence feature as well as a 'labels' int64 context feature.\")\n flags.DEFINE_string(\"feature_names\", \"mean_rgb\", \"Name of the feature \"\n \"to use for training.\")\n flags.DEFINE_string(\"feature_sizes\", \"1024\", \"Length of the feature vectors.\")\n\n # Model flags.\n flags.DEFINE_bool(\n \"frame_features\", False,\n \"If set, then --train_data_pattern must be frame-level features. \"\n \"Otherwise, --train_data_pattern must be aggregated video-level \"\n \"features. The model must also be set appropriately (i.e. to read 3D \"\n \"batches VS 4D batches.\")\n flags.DEFINE_string(\n \"model\", \"LogisticModel\",\n \"Which architecture to use for the model. Models are defined \"\n \"in models.py.\")\n flags.DEFINE_bool(\n \"start_new_model\", False,\n \"If set, this will not resume from a checkpoint and will instead create a\"\n \" new model instance.\")\n\n # Training flags.\n flags.DEFINE_integer(\"num_gpu\", 1,\n \"The maximum number of GPU devices to use for training. \"\n \"Flag only applies if GPUs are installed\")\n flags.DEFINE_integer(\"batch_size\", 1024,\n \"How many examples to process per batch for training.\")\n flags.DEFINE_string(\"label_loss\", \"CrossEntropyLoss\",\n \"Which loss function to use for training the model.\")\n flags.DEFINE_float(\n \"regularization_penalty\", 1.0,\n \"How much weight to give to the regularization loss (the label loss has \"\n \"a weight of 1).\")\n flags.DEFINE_float(\"base_learning_rate\", 0.01,\n \"Which learning rate to start with.\")\n flags.DEFINE_float(\"learning_rate_decay\", 0.95,\n \"Learning rate decay factor to be applied every \"\n \"learning_rate_decay_examples.\")\n flags.DEFINE_float(\"learning_rate_decay_examples\", 4000000,\n \"Multiply current learning rate by learning_rate_decay \"\n \"every learning_rate_decay_examples.\")\n flags.DEFINE_integer(\"num_epochs\", 5,\n \"How many passes to make over the dataset before \"\n \"halting training.\")\n flags.DEFINE_integer(\"max_steps\", None,\n \"The maximum number of iterations of the training loop.\")\n flags.DEFINE_integer(\"export_model_steps\", 10000000000,\n \"The period, in number of steps, with which the model \"\n \"is exported for batch prediction.\")\n flags.DEFINE_float(\"save_checkpoint_every_n_hour\", 0.4,\n \"Save the checkpoint every n hours.\")\n flags.DEFINE_integer(\"validate_every_n_training_steps\", 100, \n \"eval on training for every n steps\")\n\n\n # Other flags.\n flags.DEFINE_integer(\"num_readers\", 12,\n \"How many threads to use for reading input files.\")\n flags.DEFINE_string(\"optimizer\", \"AdamOptimizer\",\n \"What optimizer class to use.\")\n flags.DEFINE_float(\"clip_gradient_norm\", 1.0, \"Norm to clip gradients to.\")\n flags.DEFINE_bool(\n \"log_device_placement\", False,\n \"Whether to write the device on which every op will run into the \"\n \"logs on startup.\")\n\ndef validate_class_name(flag_value, category, modules, expected_superclass):\n \"\"\"Checks that the given string matches a class of the expected type.\n\n Args:\n flag_value: A string naming the class to instantiate.\n category: A string used further describe the class in error messages\n (e.g. 'model', 'reader', 'loss').\n modules: A list of modules to search for the given class.\n expected_superclass: A class that the given class should inherit from.\n\n Raises:\n FlagsError: If the given class could not be found or if the first class\n found with that name doesn't inherit from the expected superclass.\n\n Returns:\n True if a class was found that matches the given constraints.\n \"\"\"\n candidates = [getattr(module, flag_value, None) for module in modules]\n for candidate in candidates:\n if not candidate:\n continue\n if not issubclass(candidate, expected_superclass):\n raise flags.FlagsError(\"%s '%s' doesn't inherit from %s.\" %\n (category, flag_value,\n expected_superclass.__name__))\n return True\n raise flags.FlagsError(\"Unable to find %s '%s'.\" % (category, flag_value))\n\ndef get_input_data_tensors(reader,\n data_pattern,\n batch_size=1000,\n num_epochs=None,\n num_readers=1):\n \"\"\"Creates the section of the graph which reads the training data.\n\n Args:\n reader: A class which parses the training data.\n data_pattern: A 'glob' style path to the data files.\n batch_size: How many examples to process at a time.\n num_epochs: How many passes to make over the training data. Set to 'None'\n to run indefinitely.\n num_readers: How many I/O threads to use.\n\n Returns:\n A tuple containing the features tensor, labels tensor, and optionally a\n tensor containing the number of frames per video. The exact dimensions\n depend on the reader being used.\n\n Raises:\n IOError: If no files matching the given pattern were found.\n \"\"\"\n logging.info(\"Using batch size of \" + str(batch_size) + \" for training.\")\n with tf.name_scope(\"train_input\"):\n files = gfile.Glob(data_pattern)\n if not files:\n raise IOError(\"Unable to find training files. data_pattern='\" +\n data_pattern + \"'.\")\n logging.info(\"Number of training files: %s.\", str(len(files)))\n filename_queue = tf.train.string_input_producer(\n files, num_epochs=num_epochs, shuffle=True)\n training_data = [\n reader.prepare_reader(filename_queue) for _ in range(num_readers)\n ]\n\n return tf.train.shuffle_batch_join(\n training_data,\n batch_size=batch_size,\n capacity=batch_size * 5,\n min_after_dequeue=batch_size,\n allow_smaller_final_batch=True,\n enqueue_many=True)\n\n\ndef find_class_by_name(name, modules):\n \"\"\"Searches the provided modules for the named class and returns it.\"\"\"\n modules = [getattr(module, name, None) for module in modules]\n return next(a for a in modules if a)\n\ndef build_graph(reader,\n model,\n train_data_pattern,\n label_loss_fn=losses.CrossEntropyLoss(),\n batch_size=1000,\n base_learning_rate=0.01,\n learning_rate_decay_examples=1000000,\n learning_rate_decay=0.95,\n optimizer_class=tf.train.AdamOptimizer,\n clip_gradient_norm=1.0,\n regularization_penalty=1,\n num_readers=1,\n num_epochs=None, \n corr_mat=None):\n \"\"\"Creates the Tensorflow graph.\n\n This will only be called once in the life of\n a training model, because after the graph is created the model will be\n restored from a meta graph file rather than being recreated.\n\n Args:\n reader: The data file reader. It should inherit from BaseReader.\n model: The core model (e.g. logistic or neural net). It should inherit\n from BaseModel.\n train_data_pattern: glob path to the training data files.\n label_loss_fn: What kind of loss to apply to the model. It should inherit\n from BaseLoss.\n batch_size: How many examples to process at a time.\n base_learning_rate: What learning rate to initialize the optimizer with.\n optimizer_class: Which optimization algorithm to use.\n clip_gradient_norm: Magnitude of the gradient to clip to.\n regularization_penalty: How much weight to give the regularization loss\n compared to the label loss.\n num_readers: How many threads to use for I/O operations.\n num_epochs: How many passes to make over the data. 'None' means an\n unlimited number of passes.\n \"\"\"\n\n global_step = tf.Variable(0, trainable=False, name=\"global_step\")\n\n local_device_protos = device_lib.list_local_devices()\n gpus = [x.name for x in local_device_protos if x.device_type == 'GPU']\n gpus = gpus[:FLAGS.num_gpu]\n num_gpus = len(gpus)\n\n if num_gpus > 0:\n logging.info(\"Using the following GPUs to train: \" + str(gpus))\n num_towers = num_gpus\n device_string = '/gpu:%d'\n else:\n logging.info(\"No GPUs found. Training on CPU.\")\n num_towers = 1\n device_string = '/cpu:%d'\n\n learning_rate = tf.train.exponential_decay(\n base_learning_rate,\n global_step * batch_size * num_towers,\n learning_rate_decay_examples,\n learning_rate_decay,\n staircase=True)\n tf.summary.scalar('learning_rate', learning_rate)\n\n optimizer = optimizer_class(learning_rate)\n unused_video_id, model_input_raw, labels_batch, num_frames = (\n get_input_data_tensors(\n reader,\n train_data_pattern,\n batch_size=batch_size * num_towers,\n num_readers=num_readers,\n num_epochs=num_epochs))\n tf.summary.histogram(\"model/input_raw\", model_input_raw)\n\n feature_dim = len(model_input_raw.get_shape()) - 1\n\n model_input = tf.nn.l2_normalize(model_input_raw, feature_dim)\n\n tower_inputs = tf.split(model_input, num_towers)\n tower_labels = tf.split(labels_batch, num_towers)\n tower_num_frames = tf.split(num_frames, num_towers)\n tower_gradients = []\n tower_predictions = []\n tower_label_losses = []\n tower_reg_losses = []\n\n for i in range(num_towers):\n # For some reason these 'with' statements can't be combined onto the same\n # line. They have to be nested.\n with tf.device(device_string % i):\n with (tf.variable_scope((\"tower\"), reuse=True if i > 0 else None)):\n with (slim.arg_scope([slim.model_variable, slim.variable], device=\"/cpu:0\" if num_gpus!=1 else \"/gpu:0\")):\n result = model.create_model(\n tower_inputs[i],\n num_frames=tower_num_frames[i],\n vocab_size=reader.num_classes,\n corr_mat_init=corr_mat,\n labels=tower_labels[i])\n for variable in slim.get_model_variables():\n tf.summary.histogram(variable.op.name, variable)\n\n predictions0 = result[\"predictions0\"]\n predictions = result[\"predictions\"]\n \n tower_predictions.append(predictions)\n\n label_loss = label_loss_fn.calculate_loss(predictions0, tower_labels[i])\n\n if \"regularization_loss\" in result.keys():\n reg_loss = result[\"regularization_loss\"]\n else:\n reg_loss = tf.constant(0.0)\n\n reg_losses = tf.losses.get_regularization_losses()\n if reg_losses:\n reg_loss += tf.add_n(reg_losses)\n\n tower_reg_losses.append(reg_loss)\n\n # Adds update_ops (e.g., moving average updates in batch normalization) as\n # a dependency to the train_op.\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n if \"update_ops\" in result.keys():\n update_ops += result[\"update_ops\"]\n if update_ops:\n with tf.control_dependencies(update_ops):\n barrier = tf.no_op(name=\"gradient_barrier\")\n with tf.control_dependencies([barrier]):\n label_loss = tf.identity(label_loss)\n\n tower_label_losses.append(label_loss)\n\n # Incorporate the L2 weight penalties etc.\n final_loss = regularization_penalty * reg_loss + label_loss\n gradients = optimizer.compute_gradients(final_loss,\n colocate_gradients_with_ops=False)\n tower_gradients.append(gradients)\n\n\n label_loss = tf.reduce_mean(tf.stack(tower_label_losses))\n tf.summary.scalar(\"label_loss\", label_loss)\n if regularization_penalty != 0:\n reg_loss = tf.reduce_mean(tf.stack(tower_reg_losses))\n tf.summary.scalar(\"reg_loss\", reg_loss)\n merged_gradients = utils.combine_gradients(tower_gradients)\n\n if clip_gradient_norm > 0:\n with tf.name_scope('clip_grads'):\n merged_gradients = utils.clip_gradient_norms(merged_gradients, clip_gradient_norm)\n\n train_op = optimizer.apply_gradients(merged_gradients, global_step=global_step)\n\n tf.add_to_collection(\"global_step\", global_step)\n tf.add_to_collection(\"loss\", label_loss)\n tf.add_to_collection(\"predictions\", tf.concat(tower_predictions, 0))\n tf.add_to_collection(\"input_batch_raw\", model_input_raw)\n tf.add_to_collection(\"input_batch\", model_input)\n tf.add_to_collection(\"num_frames\", num_frames)\n tf.add_to_collection(\"labels\", tf.cast(labels_batch, tf.float32))\n tf.add_to_collection(\"train_op\", train_op)\n\nclass Trainer(object):\n \"\"\"A Trainer to train a Tensorflow graph.\"\"\"\n\n def __init__(self, cluster, task, train_dir, model, reader, model_exporter,\n log_device_placement=True, max_steps=None,\n export_model_steps=1000, corr_mat = None):\n \"\"\"\"Creates a Trainer.\n\n Args:\n cluster: A tf.train.ClusterSpec if the execution is distributed.\n None otherwise.\n task: A TaskSpec describing the job type and the task index.\n \"\"\"\n\n self.cluster = cluster\n self.task = task\n self.is_master = (task.type == \"master\" and task.index == 0)\n self.train_dir = train_dir\n self.config = tf.ConfigProto(\n allow_soft_placement=True,log_device_placement=log_device_placement)\n self.model = model\n self.reader = reader\n self.model_exporter = model_exporter\n self.max_steps = max_steps\n self.max_steps_reached = False\n self.export_model_steps = export_model_steps\n self.last_model_export_step = 0\n self.corr_mat = corr_mat\n\n# if self.is_master and self.task.index > 0:\n# raise StandardError(\"%s: Only one replica of master expected\",\n# task_as_string(self.task))\n\n def run(self, start_new_model=False):\n \"\"\"Performs training on the currently defined Tensorflow graph.\n\n Returns:\n A tuple of the training Hit@1 and the training PERR.\n \"\"\"\n if self.is_master and start_new_model:\n self.remove_training_directory(self.train_dir)\n\n if not os.path.exists(self.train_dir):\n os.makedirs(self.train_dir)\n\n model_flags_dict = {\n \"model\": FLAGS.model,\n \"feature_sizes\": FLAGS.feature_sizes,\n \"feature_names\": FLAGS.feature_names,\n \"frame_features\": FLAGS.frame_features,\n \"label_loss\": FLAGS.label_loss,\n }\n flags_json_path = os.path.join(FLAGS.train_dir, \"model_flags.json\")\n if os.path.exists(flags_json_path):\n existing_flags = json.load(open(flags_json_path))\n if existing_flags != model_flags_dict:\n logging.error(\"Model flags do not match existing file %s. Please \"\n \"delete the file, change --train_dir, or pass flag \"\n \"--start_new_model\",\n flags_json_path)\n logging.error(\"Ran model with flags: %s\", str(model_flags_dict))\n logging.error(\"Previously ran with flags: %s\", str(existing_flags))\n exit(1)\n else:\n # Write the file.\n with open(flags_json_path, \"w\") as fout:\n\n fout.write(json.dumps(model_flags_dict))\n\n target, device_fn = self.start_server_if_distributed()\n\n meta_filename = self.get_meta_filename(start_new_model, self.train_dir)\n\n with tf.Graph().as_default() as graph:\n if meta_filename:\n saver = self.recover_model(meta_filename)\n\n with tf.device(device_fn):\n if not meta_filename:\n saver = self.build_model(self.model, self.reader, self.corr_mat)\n\n global_step = tf.get_collection(\"global_step\")[0]\n loss = tf.get_collection(\"loss\")[0]\n predictions = tf.get_collection(\"predictions\")[0]\n labels = tf.get_collection(\"labels\")[0]\n train_op = tf.get_collection(\"train_op\")[0]\n init_op = tf.global_variables_initializer()\n\n sv = tf.train.Supervisor(\n graph,\n logdir=self.train_dir,\n init_op=init_op,\n is_chief=self.is_master,\n global_step=global_step,\n #save_model_secs=15 * 60,\n save_model_secs=int(FLAGS.save_checkpoint_every_n_hour * 3600),\n #save_summaries_secs=120,\n save_summaries_secs=int(FLAGS.save_checkpoint_every_n_hour * 3600),\n saver=saver)\n logging.info(\"%s: Starting managed session.\", task_as_string(self.task))\n with sv.managed_session(target, config=self.config) as sess:\n try:\n logging.info(\"%s: Entering training loop.\", task_as_string(self.task))\n while (not sv.should_stop()) and (not self.max_steps_reached):\n batch_start_time = time.time()\n _, global_step_val, loss_val, predictions_val, labels_val = sess.run(\n [train_op, global_step, loss, predictions, labels])\n seconds_per_batch = time.time() - batch_start_time\n examples_per_second = labels_val.shape[0] / seconds_per_batch\n\n if self.max_steps and self.max_steps <= global_step_val:\n self.max_steps_reached = True\n\n #if self.is_master and global_step_val % 10 == 0 and self.train_dir:\n if self.is_master and global_step_val % FLAGS.validate_every_n_training_steps == 0 and self.train_dir:\n eval_start_time = time.time()\n hit_at_one = eval_util.calculate_hit_at_one(predictions_val, labels_val)\n perr = eval_util.calculate_precision_at_equal_recall_rate(predictions_val,\n labels_val)\n gap = eval_util.calculate_gap(predictions_val, labels_val)\n eval_end_time = time.time()\n eval_time = eval_end_time - eval_start_time\n\n logging.info(\"training step \" + str(global_step_val) + \" | Loss: \" + (\"%.2f\" % loss_val) +\n \" Examples/sec: \" + (\"%.2f\" % examples_per_second) + \" | Hit@1: \" +\n (\"%.2f\" % hit_at_one) + \" PERR: \" + (\"%.2f\" % perr) +\n \" GAP: \" + (\"%.2f\" % gap))\n\n sv.summary_writer.add_summary(\n utils.MakeSummary(\"model/Training_Hit@1\", hit_at_one),\n global_step_val)\n sv.summary_writer.add_summary(\n utils.MakeSummary(\"model/Training_Perr\", perr), global_step_val)\n sv.summary_writer.add_summary(\n utils.MakeSummary(\"model/Training_GAP\", gap), global_step_val)\n sv.summary_writer.add_summary(\n utils.MakeSummary(\"global_step/Examples/Second\",\n examples_per_second), global_step_val)\n sv.summary_writer.flush()\n\n with open(FLAGS.train_dir + '/global_step_{%d}_training_GAP_{%.6f}.txt' % (global_step_val, gap), 'w') as f:\n f.write('\\n')\n\n # Exporting the model every x steps\n time_to_export = ((self.last_model_export_step == 0) or\n (global_step_val - self.last_model_export_step\n >= self.export_model_steps))\n\n if self.is_master and time_to_export:\n self.export_model(global_step_val, sv.saver, sv.save_path, sess)\n self.last_model_export_step = global_step_val\n else:\n #logging.info(\"training step \" + str(global_step_val) + \" | Loss: \" +\n #(\"%.2f\" % loss_val) + \" Examples/sec: \" + (\"%.2f\" % examples_per_second))\n continue\n except tf.errors.OutOfRangeError:\n logging.info(\"%s: Done training -- epoch limit reached.\",\n task_as_string(self.task))\n\n logging.info(\"%s: Exited training loop.\", task_as_string(self.task))\n sv.Stop()\n\n def export_model(self, global_step_val, saver, save_path, session):\n\n # If the model has already been exported at this step, return.\n if global_step_val == self.last_model_export_step:\n return\n\n last_checkpoint = saver.save(session, save_path, global_step_val)\n\n model_dir = \"{0}/export/step_{1}\".format(self.train_dir, global_step_val)\n logging.info(\"%s: Exporting the model at step %s to %s.\",\n task_as_string(self.task), global_step_val, model_dir)\n\n self.model_exporter.export_model(\n model_dir=model_dir,\n global_step_val=global_step_val,\n last_checkpoint=last_checkpoint)\n\n def start_server_if_distributed(self):\n \"\"\"Starts a server if the execution is distributed.\"\"\"\n\n if self.cluster:\n logging.info(\"%s: Starting trainer within cluster %s.\",\n task_as_string(self.task), self.cluster.as_dict())\n server = start_server(self.cluster, self.task)\n target = server.target\n device_fn = tf.train.replica_device_setter(\n ps_device=\"/job:ps\",\n worker_device=\"/job:%s/task:%d\" % (self.task.type, self.task.index),\n cluster=self.cluster)\n else:\n target = \"\"\n device_fn = \"\"\n return (target, device_fn)\n\n def remove_training_directory(self, train_dir):\n \"\"\"Removes the training directory.\"\"\"\n try:\n logging.info(\n \"%s: Removing existing train directory.\",\n task_as_string(self.task))\n gfile.DeleteRecursively(train_dir)\n except:\n logging.error(\n \"%s: Failed to delete directory \" + train_dir +\n \" when starting a new model. Please delete it manually and\" +\n \" try again.\", task_as_string(self.task))\n\n def get_meta_filename(self, start_new_model, train_dir):\n if start_new_model:\n logging.info(\"%s: Flag 'start_new_model' is set. Building a new model.\",\n task_as_string(self.task))\n return None\n\n latest_checkpoint = tf.train.latest_checkpoint(train_dir)\n if not latest_checkpoint:\n logging.info(\"%s: No checkpoint file found. Building a new model.\",\n task_as_string(self.task))\n return None\n\n meta_filename = latest_checkpoint + \".meta\"\n if not gfile.Exists(meta_filename):\n logging.info(\"%s: No meta graph file found. Building a new model.\",\n task_as_string(self.task))\n return None\n else:\n return meta_filename\n\n def recover_model(self, meta_filename):\n logging.info(\"%s: Restoring from meta graph file %s\",\n task_as_string(self.task), meta_filename)\n return tf.train.import_meta_graph(meta_filename)\n\n def build_model(self, model, reader, corr_mat = None):\n \"\"\"Find the model and build the graph.\"\"\"\n\n label_loss_fn = find_class_by_name(FLAGS.label_loss, [losses])()\n optimizer_class = find_class_by_name(FLAGS.optimizer, [tf.train])\n\n build_graph(reader=reader,\n model=model,\n optimizer_class=optimizer_class,\n clip_gradient_norm=FLAGS.clip_gradient_norm,\n train_data_pattern=FLAGS.train_data_pattern,\n label_loss_fn=label_loss_fn,\n base_learning_rate=FLAGS.base_learning_rate,\n learning_rate_decay=FLAGS.learning_rate_decay,\n learning_rate_decay_examples=FLAGS.learning_rate_decay_examples,\n regularization_penalty=FLAGS.regularization_penalty,\n num_readers=FLAGS.num_readers,\n batch_size=FLAGS.batch_size,\n num_epochs=FLAGS.num_epochs, \n corr_mat = corr_mat)\n\n return tf.train.Saver(max_to_keep=0, keep_checkpoint_every_n_hours=FLAGS.save_checkpoint_every_n_hour)\n\n\ndef get_reader():\n # Convert feature_names and feature_sizes to lists of values.\n feature_names, feature_sizes = utils.GetListOfFeatureNamesAndSizes(\n FLAGS.feature_names, FLAGS.feature_sizes)\n\n if FLAGS.frame_features:\n reader = readers.YT8MFrameFeatureReader(\n feature_names=feature_names, feature_sizes=feature_sizes)\n else:\n reader = readers.YT8MAggregatedFeatureReader(\n feature_names=feature_names, feature_sizes=feature_sizes)\n\n return reader\n\n\nclass ParameterServer(object):\n \"\"\"A parameter server to serve variables in a distributed execution.\"\"\"\n\n def __init__(self, cluster, task):\n \"\"\"Creates a ParameterServer.\n\n Args:\n cluster: A tf.train.ClusterSpec if the execution is distributed.\n None otherwise.\n task: A TaskSpec describing the job type and the task index.\n \"\"\"\n\n self.cluster = cluster\n self.task = task\n\n def run(self):\n \"\"\"Starts the parameter server.\"\"\"\n\n logging.info(\"%s: Starting parameter server within cluster %s.\",\n task_as_string(self.task), self.cluster.as_dict())\n server = start_server(self.cluster, self.task)\n server.join()\n\n\ndef start_server(cluster, task):\n \"\"\"Creates a Server.\n\n Args:\n cluster: A tf.train.ClusterSpec if the execution is distributed.\n None otherwise.\n task: A TaskSpec describing the job type and the task index.\n \"\"\"\n\n if not task.type:\n raise ValueError(\"%s: The task type must be specified.\" %\n task_as_string(task))\n if task.index is None:\n raise ValueError(\"%s: The task index must be specified.\" %\n task_as_string(task))\n\n # Create and start a server.\n return tf.train.Server(\n tf.train.ClusterSpec(cluster),\n protocol=\"grpc\",\n job_name=task.type,\n task_index=task.index)\n\ndef task_as_string(task):\n return \"/job:%s/task:%s\" % (task.type, task.index)\n\ndef main(unused_argv):\n # Load the environment.\n env = json.loads(os.environ.get(\"TF_CONFIG\", \"{}\"))\n\n # Load the cluster data from the environment.\n cluster_data = env.get(\"cluster\", None)\n cluster = tf.train.ClusterSpec(cluster_data) if cluster_data else None\n\n # Load the task data from the environment.\n task_data = env.get(\"task\", None) or {\"type\": \"master\", \"index\": 0}\n task = type(\"TaskSpec\", (object,), task_data)\n\n # Logging the version.\n logging.set_verbosity(tf.logging.INFO)\n logging.info(\"%s: Tensorflow version: %s.\",\n task_as_string(task), tf.__version__)\n\n # Dispatch to a master, a worker, or a parameter server.\n if not cluster or task.type == \"master\" or task.type == \"worker\":\n model = find_class_by_name(FLAGS.model,\n [frame_level_models, video_level_models])()\n\n reader = get_reader()\n\n model_exporter = export_model.ModelExporter(\n frame_features=FLAGS.frame_features,\n model=model,\n reader=reader)\n\n mat_dir = '/home/weimin/yt8m/code/youtube-8m/'\n with open(mat_dir + 'corr_mat.npz', 'rb') as f:\n corr_mat = np.load(f)\n\n Trainer(cluster, task, FLAGS.train_dir, model, reader, model_exporter,\n FLAGS.log_device_placement, FLAGS.max_steps,\n FLAGS.export_model_steps, corr_mat).run(start_new_model=FLAGS.start_new_model)\n\n elif task.type == \"ps\":\n ParameterServer(cluster, task).run()\n else:\n raise ValueError(\"%s: Invalid task_type: %s.\" %\n (task_as_string(task), task.type))\n\nif __name__ == \"__main__\":\n app.run()\n", "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Contains a collection of models which operate on variable-length sequences.\n\"\"\"\nimport math\nimport numpy as np \n\nimport models\nimport video_level_models\nimport tensorflow as tf\nimport model_utils as utils\n\nimport tensorflow.contrib.slim as slim\nfrom tensorflow import flags\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_bool(\"gating_remove_diag\", False,\n \"Remove diag for self gating\")\n\nflags.DEFINE_bool(\"lightvlad\", False,\n \"Light or full NetVLAD\")\nflags.DEFINE_bool(\"vlagd\", False,\n \"vlagd of vlad\")\n\nflags.DEFINE_integer(\"iterations\", 30,\n \"Number of frames per batch for DBoF.\")\nflags.DEFINE_bool(\"dbof_add_batch_norm\", True,\n \"Adds batch normalization to the DBoF model.\")\nflags.DEFINE_bool(\n \"sample_random_frames\", True,\n \"If true samples random frames (for frame level models). If false, a random\"\n \"sequence of frames is sampled instead.\")\nflags.DEFINE_integer(\"dbof_cluster_size\", 16384,\n \"Number of units in the DBoF cluster layer.\")\nflags.DEFINE_integer(\"dbof_hidden_size\", 2048,\n \"Number of units in the DBoF hidden layer.\")\nflags.DEFINE_bool(\"dbof_relu\", True, 'add ReLU to hidden layer')\nflags.DEFINE_integer(\"dbof_var_features\", 0,\n \"Variance features on top of Dbof cluster layer.\")\n\nflags.DEFINE_string(\"dbof_activation\", \"relu\", 'dbof activation')\n\nflags.DEFINE_bool(\"softdbof_maxpool\", False, 'add max pool to soft dbof')\n\nflags.DEFINE_integer(\"netvlad_cluster_size\", 64,\n \"Number of units in the NetVLAD cluster layer.\")\nflags.DEFINE_bool(\"netvlad_relu\", True, 'add ReLU to hidden layer')\nflags.DEFINE_integer(\"netvlad_dimred\", -1,\n \"NetVLAD output dimension reduction\")\nflags.DEFINE_integer(\"gatednetvlad_dimred\", 1024,\n \"GatedNetVLAD output dimension reduction\")\n\nflags.DEFINE_bool(\"gating\", False,\n \"Gating for NetVLAD\")\nflags.DEFINE_integer(\"hidden_size\", 1024,\n \"size of hidden layer for BasicStatModel.\")\n\n\nflags.DEFINE_integer(\"netvlad_hidden_size\", 1024,\n \"Number of units in the NetVLAD hidden layer.\")\n\nflags.DEFINE_integer(\"SVD_dim\", 256, \n \"Dimension of SVD vector\")\n\nflags.DEFINE_integer(\"CNN_filter_factor\", 2, \n \"Num of conv filters = cluster_size / CNN_filter_factor. \")\nflags.DEFINE_integer(\"CNN_conv_strides\", 1, \n \"Num of strides for conv layer. \")\n\nflags.DEFINE_integer(\"reduced_reshape_input_feature_size\", 256, \n \"Feature size after reduction\")\n\nflags.DEFINE_integer(\"netvlad_hidden_size_video\", 1024,\n \"Number of units in the NetVLAD video hidden layer.\")\n\nflags.DEFINE_integer(\"netvlad_hidden_size_audio\", 64,\n \"Number of units in the NetVLAD audio hidden layer.\")\n\n\nflags.DEFINE_bool(\"netvlad_add_batch_norm\", True,\n \"Adds batch normalization to the DBoF model.\")\n\nflags.DEFINE_integer(\"fv_cluster_size\", 64,\n \"Number of units in the NetVLAD cluster layer.\")\n\nflags.DEFINE_integer(\"fv_hidden_size\", 2048,\n \"Number of units in the NetVLAD hidden layer.\")\nflags.DEFINE_bool(\"fv_relu\", True,\n \"ReLU after the NetFV hidden layer.\")\n\n\nflags.DEFINE_bool(\"fv_couple_weights\", True,\n \"Coupling cluster weights or not\")\n \nflags.DEFINE_float(\"fv_coupling_factor\", 0.01,\n \"Coupling factor\")\n\n\nflags.DEFINE_string(\"dbof_pooling_method\", \"max\",\n \"The pooling method used in the DBoF cluster layer. \"\n \"Choices are 'average' and 'max'.\")\nflags.DEFINE_string(\"video_level_classifier_model\", \"MoeModel_CG\",\n \"Some Frame-Level models can be decomposed into a \"\n \"generalized pooling operation followed by a \"\n \"classifier layer\")\nflags.DEFINE_integer(\"lstm_cells\", 1024, \"Number of LSTM cells.\")\nflags.DEFINE_integer(\"lstm_layers\", 2, \"Number of LSTM layers.\")\nflags.DEFINE_integer(\"lstm_cells_video\", 1024, \"Number of LSTM cells (video).\")\nflags.DEFINE_integer(\"lstm_cells_audio\", 128, \"Number of LSTM cells (audio).\")\n\n\n\nflags.DEFINE_integer(\"gru_cells\", 1024, \"Number of GRU cells.\")\nflags.DEFINE_integer(\"gru_cells_video\", 1024, \"Number of GRU cells (video).\")\nflags.DEFINE_integer(\"gru_cells_audio\", 128, \"Number of GRU cells (audio).\")\nflags.DEFINE_integer(\"gru_layers\", 2, \"Number of GRU layers.\")\nflags.DEFINE_bool(\"lstm_random_sequence\", False,\n \"Random sequence input for lstm.\")\nflags.DEFINE_bool(\"gru_random_sequence\", False,\n \"Random sequence input for gru.\")\nflags.DEFINE_bool(\"gru_backward\", False, \"BW reading for GRU\")\nflags.DEFINE_bool(\"lstm_backward\", False, \"BW reading for LSTM\")\n\nflags.DEFINE_bool(\"fc_dimred\", True, \"Adding FC dimred after pooling\")\n\nflags.DEFINE_bool(\"attention_relu\", True, \"Attention relu\")\n\nflags.DEFINE_bool(\"use_attention_for_VLAD\", False, \"Attention for VLAD\")\n\n#python train.py --train_data_pattern=${HOME}/yt8m/v2/video/train*.tfrecord --model=NetVLADModelLF \n#--train_dir=~/yt8m/v2/models/frame/sample_model --frame_features=True \n#--feature_names=\"rgb,audio\" --feature_sizes=\"1024,128\" --batch_size=80 --base_learning_rate=0.0002 \n#--netvlad_cluster_size=256 --netvlad_hidden_size=1024 --moe_l2=1e-6 --iterations=300 --learning_rate_decay=0.8 \n#--netvlad_relu=False --gating=True --moe_prob_gating=True --max_step=700000\n\nclass NetVLADModelLF(models.BaseModel):\n \"\"\"Creates a NetVLAD based model.\n Args:\n model_input: A 'batch_size' x 'max_frames' x 'num_features' matrix of\n input features.\n vocab_size: The number of classes in the dataset.\n num_frames: A vector of length 'batch' which indicates the number of\n frames for each video (before padding).\n Returns:\n A dictionary with a tensor containing the probability predictions of the\n model in the 'predictions' key. The dimensions of the tensor are\n 'batch_size' x 'num_classes'.\n \"\"\"\n\n def create_model(self,\n model_input,\n vocab_size,\n num_frames,\n iterations=None,\n add_batch_norm=None,\n sample_random_frames=None,\n cluster_size=None,\n hidden_size=None,\n is_training=True,\n **unused_params):\n iterations = iterations or FLAGS.iterations\n add_batch_norm = add_batch_norm or FLAGS.netvlad_add_batch_norm\n random_frames = sample_random_frames or FLAGS.sample_random_frames\n cluster_size = cluster_size or FLAGS.netvlad_cluster_size\n hidden1_size = hidden_size or FLAGS.netvlad_hidden_size\n relu = FLAGS.netvlad_relu\n dimred = FLAGS.netvlad_dimred\n gating = FLAGS.gating\n remove_diag = FLAGS.gating_remove_diag\n lightvlad = FLAGS.lightvlad\n vlagd = FLAGS.vlagd\n SVD_dim = FLAGS.SVD_dim\n\n num_frames = tf.cast(tf.expand_dims(num_frames, 1), tf.float32)\n if random_frames:\n model_input = utils.SampleRandomFrames(model_input, num_frames,\n iterations)\n else:\n model_input = utils.SampleRandomSequence(model_input, num_frames,\n iterations)\n\n max_frames = model_input.get_shape().as_list()[1]\n feature_size = model_input.get_shape().as_list()[2]\n reshaped_input = tf.reshape(model_input, [-1, feature_size])\n\n video_NetVLAD = NetFV(1024,max_frames,int(cluster_size), add_batch_norm, is_training)\n audio_NetVLAD = NetFV(128,max_frames,int(cluster_size/2), add_batch_norm, is_training)\n\n if add_batch_norm:# and not lightvlad:\n reshaped_input = slim.batch_norm(\n reshaped_input,\n center=True,\n scale=True,\n is_training=is_training,\n scope=\"input_bn\")\n\n with tf.variable_scope(\"video_VLAD\"):\n vlad_video = video_NetVLAD.forward(reshaped_input[:,0:1024]) \n\n with tf.variable_scope(\"audio_VLAD\"):\n vlad_audio = audio_NetVLAD.forward(reshaped_input[:,1024:])\n\n vlad = tf.concat([vlad_video, vlad_audio],1) # None x vlad_dim\n\n vlad_dim = vlad.get_shape().as_list()[1]\n\n ##### simplier SVD #####\n SVD_mat1 = tf.get_variable(\"hidden1_weights\",\n [vlad_dim, SVD_dim],\n initializer=tf.glorot_uniform_initializer())\n\n SVD_mat2 = tf.get_variable(\"hidden2_weights\",\n [SVD_dim, int(hidden1_size*2)],\n initializer=tf.glorot_uniform_initializer())\n\n SVD_mat1_biases = tf.get_variable(\"SVD_mat1_biases\",\n [SVD_dim],\n initializer = tf.random_normal_initializer(stddev=0.01))\n\n SVD_mat2_biases = tf.get_variable(\"SVD_mat2_biases\",\n [int(hidden1_size*2)],\n initializer = tf.random_normal_initializer(stddev=0.01))\n ##### simplier SVD #####\n\n activation = tf.matmul(vlad, SVD_mat1) # None x 256\n activation += SVD_mat1_biases\n tf.summary.histogram(\"activation_in_mid_of_SVD_before_tanh\", activation)\n\n activation = tf.nn.tanh(activation)\n tf.summary.histogram(\"activation_in_mid_of_SVD_after_tanh\", activation)\n\n activation = tf.matmul(activation, SVD_mat2) # None x 2*hidden1_size\n activation += SVD_mat2_biases\n tf.summary.histogram(\"activation_after_SVD_project\", activation)\n\n ## gating part \n gating_weights = tf.get_variable(\"gating_weights_2\",\n [int(2*hidden1_size), hidden1_size],\n initializer = tf.random_normal_initializer(stddev=1 / math.sqrt(hidden1_size)))\n \n gates = tf.matmul(activation, gating_weights)\n\n gates = slim.batch_norm(\n gates,\n center=True,\n scale=True,\n is_training=is_training,\n scope=\"gating_bn\")\n\n gates = tf.sigmoid(gates)\n tf.summary.histogram(\"gates_layer\", gates)\n ## gating part \n\n activation = tf.nn.tanh(activation) # first tanh \n tf.summary.histogram(\"activation_after_1_tanh\", activation)\n\n activation = tf.layers.dropout(activation, rate = 0.3, training = is_training)\n tf.summary.histogram(\"activation_after_1_tanh_after_dropout\", activation)\n\n activation_hidden_weights = tf.get_variable(\"activation_hidden_weights\",\n [int(hidden1_size*2), hidden1_size],\n initializer=tf.glorot_uniform_initializer())\n activation = tf.matmul(activation, activation_hidden_weights) \n tf.summary.histogram(\"activation_fter_1_tanh_after_hidden_weights\", activation)\n\n activation = slim.batch_norm(\n activation,\n center=True,\n scale=True,\n is_training=is_training,\n scope=\"hidden_layer_bn\")\n tf.summary.histogram(\"activation_fter_1_tanh_after_hidden_weights_after_bn\", activation)\n\n activation = tf.nn.tanh(activation) # second tanh\n tf.summary.histogram(\"activation_fter_1_tanh_after_hidden_weights_after_bn_after_2_tanh\", activation)\n\n activation = tf.multiply(activation, gates)\n tf.summary.histogram(\"activation_right_before_video\", activation)\n\n\n aggregated_model = getattr(video_level_models,\n FLAGS.video_level_classifier_model)\n\n return aggregated_model().create_model(\n model_input=activation,\n vocab_size=vocab_size,\n is_training=is_training,\n **unused_params)\n\nclass NetFV():\n def __init__(self, feature_size,max_frames,cluster_size, add_batch_norm, is_training):\n self.feature_size = feature_size\n self.max_frames = max_frames\n self.is_training = is_training\n self.add_batch_norm = add_batch_norm\n self.cluster_size = cluster_size\n\n def forward(self,reshaped_input):\n cluster_weights = tf.get_variable(\"cluster_weights\",\n [self.feature_size, self.cluster_size],\n initializer = tf.random_normal_initializer(stddev=1 / math.sqrt(self.feature_size)))\n \n covar_weights = tf.get_variable(\"covar_weights\",\n [self.feature_size, self.cluster_size],\n initializer = tf.random_normal_initializer(mean=1.0, stddev=1 /math.sqrt(self.feature_size)))\n \n covar_weights = tf.square(covar_weights)\n eps = tf.constant([1e-6])\n covar_weights = tf.add(covar_weights,eps)\n\n tf.summary.histogram(\"cluster_weights\", cluster_weights)\n activation = tf.matmul(reshaped_input, cluster_weights)\n if self.add_batch_norm:\n activation = slim.batch_norm(\n activation,\n center=True,\n scale=True,\n is_training=self.is_training,\n scope=\"cluster_bn\")\n else:\n cluster_biases = tf.get_variable(\"cluster_biases\",\n [self.cluster_size],\n initializer = tf.random_normal(stddev=1 / math.sqrt(self.feature_size)))\n activation += cluster_biases\n\n tf.summary.histogram(\"activation_before_softmax\", activation)\n activation = tf.nn.softmax(activation)\n tf.summary.histogram(\"activation_after_softmax\", activation)\n\n activation = tf.reshape(activation, [-1, self.max_frames, self.cluster_size]) # None x max_frames x cluster_size\n\n a_sum = tf.reduce_sum(activation,-2,keep_dims=True) # None x 1 x cluster_size\n\n if not FLAGS.fv_couple_weights:\n cluster_weights2 = tf.get_variable(\"cluster_weights2\",\n [1,self.feature_size, self.cluster_size],\n initializer = tf.random_normal_initializer(stddev=1 / math.sqrt(self.feature_size)))\n else:\n cluster_weights2 = tf.scalar_mul(FLAGS.fv_coupling_factor,cluster_weights) # None x feature_sizes x cluster_size\n\n a = tf.multiply(a_sum,cluster_weights2) # None x feature_size x cluster_size\n \n activation = tf.transpose(activation,perm=[0,2,1]) # None x cluster_size x max_frames\n \n reshaped_input = tf.reshape(reshaped_input,[-1,self.max_frames,self.feature_size])\n fv1 = tf.matmul(activation,reshaped_input) # None x cluster_size x feature_sizes\n \n fv1 = tf.transpose(fv1,perm=[0,2,1]) # None x feature_sizes x cluster_size\n\n fv1 = tf.subtract(fv1,a) # None x feature_sizes x cluster_size\n fv1 = tf.divide(fv1,covar_weights) \n\n fv1 = tf.nn.l2_normalize(fv1,1)\n fv1 = tf.reshape(fv1,[-1,self.cluster_size*self.feature_size])\n fv1 = tf.nn.l2_normalize(fv1,1)\n tf.summary.histogram(\"fv1_output\", fv1)\n\n return fv1\n\n\n\n\n\n\n" ]
[ [ "tensorflow.device", "tensorflow.concat", "tensorflow.gfile.DeleteRecursively", "tensorflow.python.client.device_lib.list_local_devices", "tensorflow.control_dependencies", "tensorflow.flags.FlagsError", "tensorflow.stack", "tensorflow.gfile.Exists", "tensorflow.cast", "tensorflow.flags.DEFINE_float", "tensorflow.summary.scalar", "tensorflow.add_n", "tensorflow.Graph", "tensorflow.Variable", "tensorflow.train.shuffle_batch_join", "tensorflow.get_collection", "tensorflow.train.import_meta_graph", "tensorflow.train.exponential_decay", "tensorflow.ConfigProto", "tensorflow.logging.set_verbosity", "tensorflow.name_scope", "tensorflow.train.Saver", "numpy.load", "tensorflow.app.run", "tensorflow.nn.l2_normalize", "tensorflow.contrib.slim.arg_scope", "tensorflow.identity", "tensorflow.global_variables_initializer", "tensorflow.gfile.Glob", "tensorflow.train.string_input_producer", "tensorflow.logging.info", "tensorflow.no_op", "tensorflow.split", "tensorflow.add_to_collection", "tensorflow.flags.DEFINE_bool", "tensorflow.flags.DEFINE_integer", "tensorflow.summary.histogram", "tensorflow.losses.get_regularization_losses", "tensorflow.train.latest_checkpoint", "tensorflow.contrib.slim.get_model_variables", "tensorflow.constant", "tensorflow.flags.DEFINE_string", "tensorflow.train.ClusterSpec", "tensorflow.train.replica_device_setter", "tensorflow.logging.error", "tensorflow.variable_scope" ], [ "tensorflow.concat", "tensorflow.layers.dropout", "tensorflow.reduce_sum", "tensorflow.flags.DEFINE_float", "tensorflow.subtract", "tensorflow.divide", "tensorflow.add", "tensorflow.square", "tensorflow.random_normal_initializer", "tensorflow.nn.l2_normalize", "tensorflow.matmul", "tensorflow.scalar_mul", "tensorflow.nn.tanh", "tensorflow.flags.DEFINE_bool", "tensorflow.contrib.slim.batch_norm", "tensorflow.flags.DEFINE_integer", "tensorflow.summary.histogram", "tensorflow.multiply", "tensorflow.constant", "tensorflow.nn.softmax", "tensorflow.transpose", "tensorflow.flags.DEFINE_string", "tensorflow.reshape", "tensorflow.sigmoid", "tensorflow.expand_dims", "tensorflow.glorot_uniform_initializer", "tensorflow.variable_scope" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.4", "1.5", "1.7", "1.0", "1.2" ] } ]
sergimasot/PycQED_py3
[ "54ad1b14929ffe5cc87cf59423a970e4b9baa3e1", "54ad1b14929ffe5cc87cf59423a970e4b9baa3e1", "54ad1b14929ffe5cc87cf59423a970e4b9baa3e1" ]
[ "pycqed/measurement/waveform_control/pulsar.py", "pycqed/measurement/pulse_sequences/multi_qubit_tek_seq_elts.py", "pycqed/analysis/tools/cryoscope_tools.py" ]
[ "# Originally by Wolfgang Pfaff\n# Modified by Adriaan Rol 9/2015\n# Modified by Ants Remm 5/2017\n# Modified by Michael Kerschbaum 5/2019\nimport os\nimport shutil\nimport ctypes\nimport numpy as np\nimport logging\nfrom qcodes.instrument.base import Instrument\nfrom qcodes.instrument.parameter import (\n ManualParameter, InstrumentRefParameter)\nimport qcodes.utils.validators as vals\nimport time\n\nfrom pycqed.instrument_drivers.virtual_instruments.virtual_awg5014 import \\\n VirtualAWG5014\nfrom pycqed.instrument_drivers.virtual_instruments.virtual_AWG8 import \\\n VirtualAWG8\n# exception catching removed because it does not work in python versions before\n# 3.6\ntry:\n from qcodes.instrument_drivers.tektronix.AWG5014 import Tektronix_AWG5014\nexcept Exception:\n Tektronix_AWG5014 = type(None)\ntry:\n from pycqed.instrument_drivers.physical_instruments.ZurichInstruments.\\\n UHFQuantumController import UHFQC\nexcept Exception:\n UHFQC = type(None)\ntry:\n from pycqed.instrument_drivers.physical_instruments.ZurichInstruments. \\\n ZI_HDAWG8 import ZI_HDAWG8\nexcept Exception:\n ZI_HDAWG8 = type(None)\nlog = logging.getLogger(__name__)\n\nfrom pycqed.instrument_drivers.physical_instruments.ZurichInstruments. \\\n dummy_UHFQC import dummy_UHFQC\n\nclass UHFQCPulsar:\n \"\"\"\n Defines the Zurich Instruments UHFQC specific functionality for the Pulsar\n class\n \"\"\"\n _supportedAWGtypes = (UHFQC, dummy_UHFQC)\n \n _uhf_sequence_string_template = (\n \"const WINT_EN = 0x03ff0000;\\n\"\n \"const WINT_TRIG = 0x00000010;\\n\"\n \"const IAVG_TRIG = 0x00000020;\\n\"\n \"var RO_TRIG;\\n\"\n \"if (getUserReg(1)) {{\\n\"\n \" RO_TRIG = WINT_EN + IAVG_TRIG;\\n\"\n \"}} else {{\\n\"\n \" RO_TRIG = WINT_EN + WINT_TRIG;\\n\"\n \"}}\\n\"\n \"setTrigger(WINT_EN);\\n\"\n \"\\n\"\n \"{wave_definitions}\\n\"\n \"\\n\"\n \"var loop_cnt = getUserReg(0);\\n\"\n \"\\n\"\n \"repeat (loop_cnt) {{\\n\"\n \" {playback_string}\\n\"\n \"}}\\n\"\n )\n\n def _create_awg_parameters(self, awg, channel_name_map):\n if not isinstance(awg, UHFQCPulsar._supportedAWGtypes):\n return super()._create_awg_parameters(awg, channel_name_map)\n \n name = awg.name\n\n self.add_parameter('{}_reuse_waveforms'.format(awg.name),\n initial_value=True, vals=vals.Bool(),\n parameter_class=ManualParameter)\n self.add_parameter('{}_minimize_sequencer_memory'.format(awg.name),\n initial_value=True, vals=vals.Bool(),\n parameter_class=ManualParameter,\n docstring=\"Minimizes the sequencer \"\n \"memory by repeating specific sequence \"\n \"patterns (eg. readout) passed in \"\n \"'repeat dictionary'\")\n self.add_parameter('{}_enforce_single_element'.format(awg.name),\n initial_value=False, vals=vals.Bool(),\n parameter_class=ManualParameter,\n docstring=\"Group all the pulses on this AWG into \"\n \"a single element. Useful for making sure \"\n \"that the master AWG has only one waveform\"\n \" per segment.\")\n self.add_parameter('{}_granularity'.format(awg.name),\n get_cmd=lambda: 16)\n self.add_parameter('{}_element_start_granularity'.format(awg.name),\n initial_value=8/(1.8e9),\n parameter_class=ManualParameter)\n self.add_parameter('{}_min_length'.format(awg.name),\n get_cmd=lambda: 16 /(1.8e9))\n self.add_parameter('{}_inter_element_deadtime'.format(awg.name),\n # get_cmd=lambda: 80 / 2.4e9)\n get_cmd=lambda: 8 / (1.8e9))\n # get_cmd=lambda: 0 / 2.4e9)\n self.add_parameter('{}_precompile'.format(awg.name), \n initial_value=False, vals=vals.Bool(),\n label='{} precompile segments'.format(awg.name),\n parameter_class=ManualParameter)\n self.add_parameter('{}_delay'.format(awg.name), \n initial_value=0, label='{} delay'.format(name), \n unit='s', parameter_class=ManualParameter,\n docstring='Global delay applied to this '\n 'channel. Positive values move pulses'\n ' on this channel forward in time')\n self.add_parameter('{}_trigger_channels'.format(awg.name), \n initial_value=[],\n label='{} trigger channel'.format(awg.name), \n parameter_class=ManualParameter)\n self.add_parameter('{}_active'.format(awg.name), initial_value=True,\n label='{} active'.format(awg.name),\n vals=vals.Bool(),\n parameter_class=ManualParameter)\n self.add_parameter('{}_compensation_pulse_min_length'.format(name), \n initial_value=0, unit='s',\n parameter_class=ManualParameter)\n self.add_parameter('{}_trigger_source'.format(awg.name), \n initial_value='Dig1',\n vals=vals.Enum('Dig1', 'Dig2', 'DIO'),\n parameter_class=ManualParameter, \n docstring='Defines for which trigger source \\\n the AWG should wait, before playing \\\n the next waveform. Allowed values \\\n are: \"Dig1\", \"Dig2\", \"DIO\"')\n\n for ch_nr in range(2):\n id = 'ch{}'.format(ch_nr + 1)\n name = channel_name_map.get(id, awg.name + '_' + id)\n self._uhfqc_create_channel_parameters(id, name, awg)\n self.channels.add(name)\n\n def _uhfqc_create_channel_parameters(self, id, name, awg):\n self.add_parameter('{}_id'.format(name), get_cmd=lambda _=id: _)\n self.add_parameter('{}_awg'.format(name), get_cmd=lambda _=awg.name: _)\n self.add_parameter('{}_type'.format(name), get_cmd=lambda: 'analog')\n self.add_parameter('{}_amp'.format(name),\n label='{} amplitude'.format(name), unit='V',\n set_cmd=self._uhfqc_setter(awg, id, 'amp'),\n get_cmd=self._uhfqc_getter(awg, id, 'amp'),\n vals=vals.Numbers(0.075, 1.5),\n initial_value=0.75)\n self.add_parameter('{}_offset'.format(name),\n label='{} offset'.format(name), unit='V',\n set_cmd=self._uhfqc_setter(awg, id, 'offset'),\n get_cmd=self._uhfqc_getter(awg, id, 'offset'),\n vals=vals.Numbers(-1.5, 1.5),\n initial_value=0)\n self.add_parameter('{}_distortion'.format(name),\n label='{} distortion mode'.format(name),\n initial_value='off',\n vals=vals.Enum('off', 'precalculate'),\n parameter_class=ManualParameter)\n self.add_parameter('{}_distortion_dict'.format(name),\n label='{} distortion dictionary'.format(name),\n vals=vals.Dict(),\n parameter_class=ManualParameter)\n self.add_parameter('{}_charge_buildup_compensation'.format(name),\n parameter_class=ManualParameter,\n vals=vals.Bool(), initial_value=False)\n self.add_parameter('{}_compensation_pulse_scale'.format(name),\n parameter_class=ManualParameter,\n vals=vals.Numbers(0., 1.), initial_value=0.5)\n self.add_parameter('{}_compensation_pulse_delay'.format(name), \n initial_value=0, unit='s',\n parameter_class=ManualParameter)\n self.add_parameter('{}_compensation_pulse_gaussian_filter_sigma'.format(name),\n initial_value=0, unit='s',\n parameter_class=ManualParameter)\n\n @staticmethod\n def _uhfqc_setter(obj, id, par):\n if par == 'offset':\n def s(val):\n obj.set('sigouts_{}_offset'.format(int(id[2])-1), val)\n elif par == 'amp':\n def s(val):\n obj.set('sigouts_{}_range'.format(int(id[2])-1), val)\n else:\n raise NotImplementedError('Unknown parameter {}'.format(par))\n return s\n\n def _uhfqc_getter(self, obj, id, par):\n if par == 'offset':\n def g():\n return obj.get('sigouts_{}_offset'.format(int(id[2])-1))\n elif par == 'amp':\n def g():\n if self._awgs_prequeried_state:\n return obj.parameters['sigouts_{}_range' \\\n .format(int(id[2])-1)].get_latest()/2\n else:\n return obj.get('sigouts_{}_range' \\\n .format(int(id[2])-1))/2\n else:\n raise NotImplementedError('Unknown parameter {}'.format(par))\n return g \n\n def _program_awg(self, obj, awg_sequence, waveforms, repeat_pattern=None):\n if not isinstance(obj, UHFQCPulsar._supportedAWGtypes):\n return super()._program_awg(obj, awg_sequence, waveforms, repeat_pattern)\n\n if not self._zi_waves_cleared:\n _zi_clear_waves()\n self._zi_waves_cleared = True\n waves_to_upload = {h: waveforms[h]\n for codewords in awg_sequence.values() \n if codewords is not None\n for cw, chids in codewords.items()\n if cw != 'metadata'\n for h in chids.values()}\n self._zi_write_waves(waves_to_upload)\n\n defined_waves = set()\n wave_definitions = []\n playback_strings = []\n\n ch_has_waveforms = {'ch1': False, 'ch2': False}\n\n current_segment = 'no_segment'\n\n def play_element(element, playback_strings, wave_definitions):\n if awg_sequence[element] is None:\n current_segment = element\n playback_strings.append(f'// Segment {current_segment}')\n return playback_strings, wave_definitions\n playback_strings.append(f'// Element {element}')\n\n metadata = awg_sequence[element].pop('metadata', {})\n if list(awg_sequence[element].keys()) != ['no_codeword']:\n raise NotImplementedError('UHFQC sequencer does currently\\\n not support codewords!')\n chid_to_hash = awg_sequence[element]['no_codeword']\n\n wave = (chid_to_hash.get('ch1', None), None,\n chid_to_hash.get('ch2', None), None)\n wave_definitions += self._zi_wave_definition(wave,\n defined_waves)\n\n acq = metadata.get('acq', False)\n playback_strings += self._zi_playback_string(name=obj.name,\n device='uhf', \n wave=wave, \n acq=acq)\n\n ch_has_waveforms['ch1'] |= wave[0] is not None\n ch_has_waveforms['ch2'] |= wave[2] is not None\n return playback_strings, wave_definitions\n\n if repeat_pattern is None:\n for element in awg_sequence:\n playback_strings, wave_definitions = play_element(element,\n playback_strings,\n wave_definitions)\n else:\n real_indicies = []\n for index, element in enumerate(awg_sequence):\n if awg_sequence[element] is not None:\n real_indicies.append(index)\n el_total = len(real_indicies)\n\n def repeat_func(n, el_played, index, playback_strings, wave_definitions):\n if isinstance(n, tuple):\n el_played_list = []\n if n[0] > 1:\n playback_strings.append('repeat ('+str(n[0])+') {')\n for t in n[1:]:\n el_cnt, playback_strings, wave_definitions = repeat_func(t,\n el_played,\n index + np.sum(\n el_played_list),\n playback_strings,\n wave_definitions)\n el_played_list.append(el_cnt)\n if n[0] > 1:\n playback_strings.append('}')\n return int(n[0] * np.sum(el_played_list)), playback_strings, wave_definitions\n else:\n for k in range(n):\n el_index = real_indicies[int(index)+k]\n element = list(awg_sequence.keys())[el_index]\n playback_strings, wave_definitions = play_element(element,\n playback_strings,\n wave_definitions)\n el_played = el_played + 1\n return el_played, playback_strings, wave_definitions\n\n\n\n el_played, playback_strings, wave_definitions = repeat_func(repeat_pattern, 0, 0,\n playback_strings, wave_definitions)\n\n\n if int(el_played) != int(el_total):\n log.error(el_played, ' is not ', el_total)\n raise ValueError('Check number of sequences in repeat pattern')\n\n\n if not (ch_has_waveforms['ch1'] or ch_has_waveforms['ch2']):\n return\n self.awgs_with_waveforms(obj.name)\n \n awg_str = self._uhf_sequence_string_template.format(\n wave_definitions='\\n'.join(wave_definitions),\n playback_string='\\n '.join(playback_strings),\n )\n\n # Necessary hack to pass the UHFQC drivers sanity check \n # in acquisition_initialize()\n obj._awg_program_features['loop_cnt'] = True\n obj._awg_program_features['avg_cnt'] = False\n # Hack needed to have \n obj._awg_needs_configuration[0] = False\n obj._awg_program[0] = True\n\n obj.configure_awg_from_string(awg_nr=0, program_string=awg_str, timeout=600)\n\n def _is_awg_running(self, obj):\n if not isinstance(obj, UHFQCPulsar._supportedAWGtypes):\n return super()._is_awg_running(obj)\n return obj.awgs_0_enable() != 0\n\n def _clock(self, obj, cid=None):\n if not isinstance(obj, UHFQCPulsar._supportedAWGtypes):\n return super()._clock(obj)\n return obj.clock_freq()\n\nclass HDAWG8Pulsar:\n \"\"\"\n Defines the Zurich Instruments HDAWG8 specific functionality for the Pulsar\n class\n \"\"\"\n _supportedAWGtypes = (ZI_HDAWG8, VirtualAWG8, )\n\n _hdawg_sequence_string_template = (\n \"{wave_definitions}\\n\"\n \"\\n\"\n \"{codeword_table_defs}\\n\"\n \"\\n\"\n \"while (1) {{\\n\"\n \" {playback_string}\\n\"\n \"}}\\n\"\n )\n\n def _create_awg_parameters(self, awg, channel_name_map):\n if not isinstance(awg, HDAWG8Pulsar._supportedAWGtypes):\n return super()._create_awg_parameters(awg, channel_name_map)\n \n name = awg.name\n\n self.add_parameter('{}_reuse_waveforms'.format(awg.name),\n initial_value=True, vals=vals.Bool(),\n parameter_class=ManualParameter)\n self.add_parameter('{}_minimize_sequencer_memory'.format(awg.name),\n initial_value=False, vals=vals.Bool(),\n parameter_class=ManualParameter,\n docstring=\"Minimizes the sequencer \"\n \"memory by repeating specific sequence \"\n \"patterns (eg. readout) passed in \"\n \"'repeat dictionary'\")\n self.add_parameter('{}_enforce_single_element'.format(awg.name),\n initial_value=False, vals=vals.Bool(),\n parameter_class=ManualParameter,\n docstring=\"Group all the pulses on this AWG into \"\n \"a single element. Useful for making sure \"\n \"that the master AWG has only one waveform\"\n \" per segment.\")\n self.add_parameter('{}_granularity'.format(awg.name),\n get_cmd=lambda: 16)\n self.add_parameter('{}_element_start_granularity'.format(awg.name),\n initial_value=8/(2.4e9),\n parameter_class=ManualParameter)\n self.add_parameter('{}_min_length'.format(awg.name),\n initial_value=16 /(2.4e9),\n parameter_class=ManualParameter)\n self.add_parameter('{}_inter_element_deadtime'.format(awg.name),\n # get_cmd=lambda: 80 / 2.4e9)\n get_cmd=lambda: 8 / (2.4e9))\n # get_cmd=lambda: 0 / 2.4e9)\n self.add_parameter('{}_precompile'.format(awg.name), \n initial_value=False, vals=vals.Bool(),\n label='{} precompile segments'.format(awg.name),\n parameter_class=ManualParameter)\n self.add_parameter('{}_delay'.format(awg.name), \n initial_value=0, label='{} delay'.format(name), \n unit='s', parameter_class=ManualParameter,\n docstring='Global delay applied to this '\n 'channel. Positive values move pulses'\n ' on this channel forward in time')\n self.add_parameter('{}_trigger_channels'.format(awg.name), \n initial_value=[],\n label='{} trigger channel'.format(awg.name), \n parameter_class=ManualParameter)\n self.add_parameter('{}_active'.format(awg.name), initial_value=True,\n label='{} active'.format(awg.name),\n vals=vals.Bool(),\n parameter_class=ManualParameter)\n self.add_parameter('{}_compensation_pulse_min_length'.format(name), \n initial_value=0, unit='s',\n parameter_class=ManualParameter)\n self.add_parameter('{}_trigger_source'.format(awg.name), \n initial_value='Dig1',\n vals=vals.Enum('Dig1', 'DIO', 'ZSync'),\n parameter_class=ManualParameter, \n docstring='Defines for which trigger source \\\n the AWG should wait, before playing \\\n the next waveform. Allowed values \\\n are: \"Dig1\", \"DIO\", \"ZSync\"')\n\n for ch_nr in range(8):\n id = 'ch{}'.format(ch_nr + 1)\n name = channel_name_map.get(id, awg.name + '_' + id)\n self._hdawg_create_analog_channel_parameters(id, name, awg)\n self.channels.add(name)\n id = 'ch{}m'.format(ch_nr + 1)\n name = channel_name_map.get(id, awg.name + '_' + id)\n self._hdawg_create_marker_channel_parameters(id, name, awg)\n self.channels.add(name)\n\n def _hdawg_create_analog_channel_parameters(self, id, name, awg):\n self.add_parameter('{}_id'.format(name), get_cmd=lambda _=id: _)\n self.add_parameter('{}_awg'.format(name), get_cmd=lambda _=awg.name: _)\n self.add_parameter('{}_type'.format(name), get_cmd=lambda: 'analog')\n self.add_parameter('{}_offset'.format(name),\n label='{} offset'.format(name), unit='V',\n set_cmd=self._hdawg_setter(awg, id, 'offset'),\n get_cmd=self._hdawg_getter(awg, id, 'offset'),\n vals=vals.Numbers())\n self.add_parameter('{}_amp'.format(name),\n label='{} amplitude'.format(name), unit='V',\n set_cmd=self._hdawg_setter(awg, id, 'amp'),\n get_cmd=self._hdawg_getter(awg, id, 'amp'),\n vals=vals.Numbers(0.01, 5.0))\n self.add_parameter('{}_distortion'.format(name),\n label='{} distortion mode'.format(name),\n initial_value='off',\n vals=vals.Enum('off', 'precalculate'),\n parameter_class=ManualParameter)\n self.add_parameter('{}_distortion_dict'.format(name),\n label='{} distortion dictionary'.format(name),\n vals=vals.Dict(),\n parameter_class=ManualParameter)\n self.add_parameter('{}_charge_buildup_compensation'.format(name),\n parameter_class=ManualParameter,\n vals=vals.Bool(), initial_value=False)\n self.add_parameter('{}_compensation_pulse_scale'.format(name),\n parameter_class=ManualParameter,\n vals=vals.Numbers(0., 1.), initial_value=0.5)\n self.add_parameter('{}_compensation_pulse_delay'.format(name), \n initial_value=0, unit='s',\n parameter_class=ManualParameter)\n self.add_parameter('{}_compensation_pulse_gaussian_filter_sigma'.format(name),\n initial_value=0, unit='s',\n parameter_class=ManualParameter)\n self.add_parameter('{}_internal_modulation'.format(name), \n initial_value=False, vals=vals.Bool(),\n parameter_class=ManualParameter)\n \n def _hdawg_create_marker_channel_parameters(self, id, name, awg):\n self.add_parameter('{}_id'.format(name), get_cmd=lambda _=id: _)\n self.add_parameter('{}_awg'.format(name), get_cmd=lambda _=awg.name: _)\n self.add_parameter('{}_type'.format(name), get_cmd=lambda: 'marker')\n self.add_parameter('{}_offset'.format(name),\n label='{} offset'.format(name), unit='V',\n set_cmd=self._hdawg_setter(awg, id, 'offset'),\n get_cmd=self._hdawg_getter(awg, id, 'offset'),\n vals=vals.Numbers())\n self.add_parameter('{}_amp'.format(name),\n label='{} amplitude'.format(name), unit='V',\n set_cmd=self._hdawg_setter(awg, id, 'amp'),\n get_cmd=self._hdawg_getter(awg, id, 'amp'),\n vals=vals.Numbers(0.01, 5.0))\n \n @staticmethod\n def _hdawg_setter(obj, id, par):\n if par == 'offset':\n if id[-1] != 'm':\n def s(val):\n obj.set('sigouts_{}_offset'.format(int(id[2])-1), val)\n else:\n s = None\n elif par == 'amp':\n if id[-1] != 'm':\n def s(val):\n obj.set('sigouts_{}_range'.format(int(id[2])-1), 2*val)\n else:\n s = None\n else:\n raise NotImplementedError('Unknown parameter {}'.format(par))\n return s\n\n def _hdawg_getter(self, obj, id, par):\n if par == 'offset':\n if id[-1] != 'm':\n def g():\n return obj.get('sigouts_{}_offset'.format(int(id[2])-1))\n else:\n return lambda: 0\n elif par == 'amp':\n if id[-1] != 'm':\n def g():\n if self._awgs_prequeried_state:\n return obj.parameters['sigouts_{}_range' \\\n .format(int(id[2])-1)].get_latest()/2\n else:\n return obj.get('sigouts_{}_range' \\\n .format(int(id[2])-1))/2\n else:\n return lambda: 1\n else:\n raise NotImplementedError('Unknown parameter {}'.format(par))\n return g \n\n def get_divisor(self, chid, awg):\n '''\n Divisor is 1 for non modulated channels and 2 for modulated non \n marker channels.\n '''\n\n if chid[-1]=='m':\n return 1\n\n name = self._id_channel(chid, awg)\n if self.get(f\"{name}_internal_modulation\"):\n return 2\n else: \n return 1\n\n \n def _program_awg(self, obj, awg_sequence, waveforms, repeat_pattern=None):\n if not isinstance(obj, HDAWG8Pulsar._supportedAWGtypes):\n return super()._program_awg(obj, awg_sequence, waveforms, repeat_pattern)\n \n if not self._zi_waves_cleared:\n _zi_clear_waves()\n self._zi_waves_cleared = True\n \n chids = [f'ch{i+1}{m}' for i in range(8) for m in ['','m']]\n divisor = {chid: self.get_divisor(chid, obj.name) for chid in chids}\n \n waves_to_upload = {h: divisor[chid]*waveforms[h][::divisor[chid]]\n for codewords in awg_sequence.values() \n if codewords is not None \n for cw, chids in codewords.items() \n if cw != 'metadata'\n for chid, h in chids.items()}\n self._zi_write_waves(waves_to_upload)\n \n ch_has_waveforms = {'ch{}{}'.format(i + 1, m): False \n for i in range(8) for m in ['','m']}\n\n for awg_nr in self._hdawg_active_awgs(obj):\n defined_waves = set()\n codeword_table = {}\n wave_definitions = []\n codeword_table_defs = []\n playback_strings = []\n interleaves = []\n\n prev_dio_valid_polarity = obj.get(\n 'awgs_{}_dio_valid_polarity'.format(awg_nr))\n \n added_cw = set()\n ch1id = 'ch{}'.format(awg_nr * 2 + 1)\n ch1mid = 'ch{}m'.format(awg_nr * 2 + 1)\n ch2id = 'ch{}'.format(awg_nr * 2 + 2)\n ch2mid = 'ch{}m'.format(awg_nr * 2 + 2)\n chids = [ch1id, ch2id]\n\n channels = [self._id_channel(chid, obj.name) for chid in chids]\n\n codeword_el = set()\n if all([self.get(\n f'{chan}_internal_modulation') for chan in channels]):\n internal_mod = True\n elif not any([self.get(\n f'{chan}_internal_modulation') for chan in channels]):\n internal_mod = False\n else:\n raise NotImplementedError('Internal modulation can only be' \n 'specified per sub AWG!')\n\n counter = 1\n current_segment = 'no_segment'\n for element in awg_sequence:\n if awg_sequence[element] is None:\n current_segment = element\n playback_strings.append(f'// Segment {current_segment}')\n continue\n playback_strings.append(f'// Element {element}')\n \n metadata = awg_sequence[element].pop('metadata', {})\n \n nr_cw = len(set(awg_sequence[element].keys()) - \\\n {'no_codeword'})\n\n if nr_cw == 1:\n log.warning(\n f'Only one codeword has been set for {element}')\n else:\n for cw in awg_sequence[element]:\n if cw == 'no_codeword':\n if nr_cw != 0:\n continue\n chid_to_hash = awg_sequence[element][cw]\n wave = tuple(chid_to_hash.get(ch, None)\n for ch in [ch1id, ch1mid, ch2id, ch2mid])\n wave_definitions += self._zi_wave_definition(wave,\n defined_waves)\n \n if nr_cw != 0:\n w1, w2 = self._zi_waves_to_wavenames(wave)\n if cw not in codeword_table:\n codeword_table_defs += \\\n self._zi_codeword_table_entry(cw, wave)\n codeword_table[cw] = (w1, w2)\n elif codeword_table[cw] != (w1, w2) \\\n and self.reuse_waveforms():\n log.warning('Same codeword used for different '\n 'waveforms. Using first waveform. '\n f'Ignoring element {element}.')\n\n ch_has_waveforms[ch1id] |= wave[0] is not None\n ch_has_waveforms[ch1mid] |= wave[1] is not None\n ch_has_waveforms[ch2id] |= wave[2] is not None\n ch_has_waveforms[ch2mid] |= wave[3] is not None\n\n if not internal_mod:\n playback_strings += self._zi_playback_string(name=obj.name,\n device='hdawg', wave=wave, codeword=(nr_cw != 0),\n append_zeros=self.append_zeros())\n else:\n pb_string, interleave_string = \\\n self._zi_interleaved_playback_string(name=obj.name, \n device='hdawg', counter=counter, wave=wave, \n codeword=(nr_cw != 0)) \n counter += 1\n playback_strings += pb_string\n interleaves += interleave_string\n \n if not any([ch_has_waveforms[ch] \n for ch in [ch1id, ch1mid, ch2id, ch2mid]]):\n continue\n \n awg_str = self._hdawg_sequence_string_template.format(\n wave_definitions='\\n'.join(wave_definitions+interleaves),\n codeword_table_defs='\\n'.join(codeword_table_defs),\n playback_string='\\n '.join(playback_strings))\n\n # Hack needed to pass the sanity check of the ZI_base_instrument\n # class in \n obj._awg_needs_configuration[awg_nr] = False\n obj._awg_program[awg_nr] = True\n\n obj.configure_awg_from_string(awg_nr, awg_str, timeout=600)\n\n obj.set('awgs_{}_dio_valid_polarity'.format(awg_nr),\n prev_dio_valid_polarity)\n\n for ch in range(8):\n obj.set('sigouts_{}_on'.format(ch), ch_has_waveforms[f'ch{ch+1}'])\n\n if any(ch_has_waveforms.values()):\n self.awgs_with_waveforms(obj.name)\n\n def _is_awg_running(self, obj):\n if not isinstance(obj, HDAWG8Pulsar._supportedAWGtypes):\n return super()._is_awg_running(obj)\n\n return any([obj.get('awgs_{}_enable'.format(awg_nr)) for awg_nr in\n self._hdawg_active_awgs(obj)])\n\n def _clock(self, obj, cid):\n if not isinstance(obj, HDAWG8Pulsar._supportedAWGtypes):\n return super()._clock(obj, cid)\n return obj.clock_freq()\n\n def _hdawg_active_awgs(self, obj):\n return [0,1,2,3]\n\nclass AWG5014Pulsar:\n \"\"\"\n Defines the Tektronix AWG5014 specific functionality for the Pulsar class\n \"\"\"\n _supportedAWGtypes = (Tektronix_AWG5014, VirtualAWG5014, )\n\n def _create_awg_parameters(self, awg, channel_name_map):\n if not isinstance(awg, AWG5014Pulsar._supportedAWGtypes):\n return super()._create_awg_parameters(awg, channel_name_map)\n \n self.add_parameter('{}_reuse_waveforms'.format(awg.name),\n initial_value=True, vals=vals.Bool(),\n parameter_class=ManualParameter)\n self.add_parameter('{}_minimize_sequencer_memory'.format(awg.name),\n initial_value=False, vals=vals.Bool(),\n parameter_class=ManualParameter,\n docstring=\"Minimizes the sequencer \"\n \"memory by repeating specific sequence \"\n \"patterns (eg. readout) passed in \"\n \"'repeat dictionary'\")\n self.add_parameter('{}_enforce_single_element'.format(awg.name),\n initial_value=False, vals=vals.Bool(),\n parameter_class=ManualParameter,\n docstring=\"Group all the pulses on this AWG into \"\n \"a single element. Useful for making sure \"\n \"that the master AWG has only one waveform\"\n \" per segment.\")\n self.add_parameter('{}_granularity'.format(awg.name),\n get_cmd=lambda: 4)\n self.add_parameter('{}_element_start_granularity'.format(awg.name),\n initial_value=4/(1.2e9),\n parameter_class=ManualParameter)\n self.add_parameter('{}_min_length'.format(awg.name),\n get_cmd=lambda: 256/(1.2e9)) # Can not be triggered \n # faster than 210 ns.\n self.add_parameter('{}_inter_element_deadtime'.format(awg.name),\n get_cmd=lambda: 0)\n self.add_parameter('{}_precompile'.format(awg.name), \n initial_value=False, \n label='{} precompile segments'.format(awg.name),\n parameter_class=ManualParameter, vals=vals.Bool())\n self.add_parameter('{}_delay'.format(awg.name), initial_value=0,\n label='{} delay'.format(awg.name), unit='s',\n parameter_class=ManualParameter,\n docstring=\"Global delay applied to this channel. \"\n \"Positive values move pulses on this \"\n \"channel forward in time\")\n self.add_parameter('{}_trigger_channels'.format(awg.name), \n initial_value=[],\n label='{} trigger channels'.format(awg.name), \n parameter_class=ManualParameter)\n self.add_parameter('{}_active'.format(awg.name), initial_value=True,\n label='{} active'.format(awg.name), \n vals=vals.Bool(),\n parameter_class=ManualParameter)\n self.add_parameter('{}_compensation_pulse_min_length'.format(awg.name), \n initial_value=0, unit='s',\n parameter_class=ManualParameter)\n\n for ch_nr in range(4):\n id = 'ch{}'.format(ch_nr + 1)\n name = channel_name_map.get(id, awg.name + '_' + id)\n self._awg5014_create_analog_channel_parameters(id, name, awg)\n self.channels.add(name)\n id = 'ch{}m1'.format(ch_nr + 1)\n name = channel_name_map.get(id, awg.name + '_' + id)\n self._awg5014_create_marker_channel_parameters(id, name, awg)\n self.channels.add(name)\n id = 'ch{}m2'.format(ch_nr + 1)\n name = channel_name_map.get(id, awg.name + '_' + id)\n self._awg5014_create_marker_channel_parameters(id, name, awg)\n self.channels.add(name)\n\n def _awg5014_create_analog_channel_parameters(self, id, name, awg):\n self.add_parameter('{}_id'.format(name), get_cmd=lambda _=id: _)\n self.add_parameter('{}_awg'.format(name), get_cmd=lambda _=awg.name: _)\n self.add_parameter('{}_type'.format(name), get_cmd=lambda: 'analog')\n self.add_parameter('{}_offset_mode'.format(name), \n parameter_class=ManualParameter, \n vals=vals.Enum('software', 'hardware'))\n offset_mode_func = self.parameters['{}_offset_mode'.format(name)]\n self.add_parameter('{}_offset'.format(name),\n label='{} offset'.format(name), unit='V',\n set_cmd=self._awg5014_setter(awg, id, 'offset', \n offset_mode_func),\n get_cmd=self._awg5014_getter(awg, id, 'offset', \n offset_mode_func),\n vals=vals.Numbers())\n self.add_parameter('{}_amp'.format(name),\n label='{} amplitude'.format(name), unit='V',\n set_cmd=self._awg5014_setter(awg, id, 'amp'),\n get_cmd=self._awg5014_getter(awg, id, 'amp'),\n vals=vals.Numbers(0.01, 2.25))\n self.add_parameter('{}_distortion'.format(name),\n label='{} distortion mode'.format(name),\n initial_value='off',\n vals=vals.Enum('off', 'precalculate'),\n parameter_class=ManualParameter)\n self.add_parameter('{}_distortion_dict'.format(name),\n label='{} distortion dictionary'.format(name),\n vals=vals.Dict(),\n parameter_class=ManualParameter)\n self.add_parameter('{}_charge_buildup_compensation'.format(name),\n parameter_class=ManualParameter,\n vals=vals.Bool(), initial_value=False)\n self.add_parameter('{}_compensation_pulse_scale'.format(name),\n parameter_class=ManualParameter,\n vals=vals.Numbers(0., 1.), initial_value=0.5)\n self.add_parameter('{}_compensation_pulse_delay'.format(name), \n initial_value=0, unit='s',\n parameter_class=ManualParameter)\n self.add_parameter('{}_compensation_pulse_gaussian_filter_sigma'.format(name),\n initial_value=0, unit='s',\n parameter_class=ManualParameter)\n \n def _awg5014_create_marker_channel_parameters(self, id, name, awg):\n self.add_parameter('{}_id'.format(name), get_cmd=lambda _=id: _)\n self.add_parameter('{}_awg'.format(name), get_cmd=lambda _=awg.name: _)\n self.add_parameter('{}_type'.format(name), get_cmd=lambda: 'marker')\n self.add_parameter('{}_offset'.format(name),\n label='{} offset'.format(name), unit='V',\n set_cmd=self._awg5014_setter(awg, id, 'offset'),\n get_cmd=self._awg5014_getter(awg, id, 'offset'),\n vals=vals.Numbers(-2.7, 2.7))\n self.add_parameter('{}_amp'.format(name),\n label='{} amplitude'.format(name), unit='V',\n set_cmd=self._awg5014_setter(awg, id, 'amp'),\n get_cmd=self._awg5014_getter(awg, id, 'amp'),\n vals=vals.Numbers(-5.4, 5.4))\n\n @staticmethod\n def _awg5014_setter(obj, id, par, offset_mode_func=None):\n if id in ['ch1', 'ch2', 'ch3', 'ch4']:\n if par == 'offset':\n def s(val):\n if offset_mode_func() == 'software':\n obj.set('{}_offset'.format(id), val)\n elif offset_mode_func() == 'hardware':\n obj.set('{}_DC_out'.format(id), val)\n else:\n raise ValueError('Invalid offset mode for AWG5014: '\n '{}'.format(offset_mode_func()))\n elif par == 'amp':\n def s(val):\n obj.set('{}_amp'.format(id), 2*val)\n else:\n raise NotImplementedError('Unknown parameter {}'.format(par))\n else:\n id_raw = id[:3] + '_' + id[3:] # convert ch1m1 to ch1_m1\n if par == 'offset':\n def s(val):\n h = obj.get('{}_high'.format(id_raw))\n l = obj.get('{}_low'.format(id_raw))\n obj.set('{}_high'.format(id_raw), val + h - l)\n obj.set('{}_low'.format(id_raw), val)\n elif par == 'amp':\n def s(val):\n l = obj.get('{}_low'.format(id_raw))\n obj.set('{}_high'.format(id_raw), l + val)\n else:\n raise NotImplementedError('Unknown parameter {}'.format(par))\n return s\n\n def _awg5014_getter(self, obj, id, par, offset_mode_func=None):\n if id in ['ch1', 'ch2', 'ch3', 'ch4']:\n if par == 'offset':\n def g():\n if offset_mode_func() == 'software':\n return obj.get('{}_offset'.format(id))\n elif offset_mode_func() == 'hardware':\n return obj.get('{}_DC_out'.format(id))\n else:\n raise ValueError('Invalid offset mode for AWG5014: '\n '{}'.format(offset_mode_func()))\n \n elif par == 'amp':\n def g():\n if self._awgs_prequeried_state:\n return obj.parameters['{}_amp'.format(id)] \\\n .get_latest()/2\n else:\n return obj.get('{}_amp'.format(id))/2\n else:\n raise NotImplementedError('Unknown parameter {}'.format(par))\n else:\n id_raw = id[:3] + '_' + id[3:] # convert ch1m1 to ch1_m1\n if par == 'offset':\n def g():\n return obj.get('{}_low'.format(id_raw))\n elif par == 'amp':\n def g():\n if self._awgs_prequeried_state:\n h = obj.get('{}_high'.format(id_raw))\n l = obj.get('{}_low'.format(id_raw))\n else:\n h = obj.parameters['{}_high'.format(id_raw)]\\\n .get_latest()\n l = obj.parameters['{}_low'.format(id_raw)]\\\n .get_latest()\n return h - l\n else:\n raise NotImplementedError('Unknown parameter {}'.format(par))\n return g\n\n def _program_awg(self, obj, awg_sequence, waveforms, repeat_pattern=None):\n if not isinstance(obj, AWG5014Pulsar._supportedAWGtypes):\n return super()._program_awg(obj, awg_sequence, waveforms, repeat_pattern)\n\n pars = {\n 'ch{}_m{}_low'.format(ch + 1, m + 1)\n for ch in range(4) for m in range(2)\n }\n pars |= {\n 'ch{}_m{}_high'.format(ch + 1, m + 1)\n for ch in range(4) for m in range(2)\n }\n pars |= {\n 'ch{}_offset'.format(ch + 1) for ch in range(4)\n }\n old_vals = {}\n for par in pars:\n old_vals[par] = obj.get(par)\n\n packed_waveforms = {}\n wfname_l = []\n\n grp_has_waveforms = {f'ch{i+1}': False for i in range(4)}\n\n for element in awg_sequence:\n if awg_sequence[element] is None:\n continue\n metadata = awg_sequence[element].pop('metadata', {})\n if list(awg_sequence[element].keys()) != ['no_codeword']:\n raise NotImplementedError('AWG5014 sequencer does '\n 'not support codewords!')\n chid_to_hash = awg_sequence[element]['no_codeword']\n\n if not any(chid_to_hash):\n continue # no waveforms\n \n maxlen = max([len(waveforms[h]) for h in chid_to_hash.values()])\n maxlen = max(maxlen, 256)\n\n wfname_l.append([])\n for grp in [f'ch{i + 1}' for i in range(4)]:\n wave = (chid_to_hash.get(grp, None),\n chid_to_hash.get(grp + 'm1', None), \n chid_to_hash.get(grp + 'm2', None))\n grp_has_waveforms[grp] |= (wave != (None, None, None))\n wfname = self._hash_to_wavename((maxlen, wave))\n grp_wfs = [np.pad(waveforms.get(h, [0]), \n (0, maxlen - len(waveforms.get(h, [0]))), \n 'constant', constant_values=0) for h in wave]\n packed_waveforms[wfname] = obj.pack_waveform(*grp_wfs)\n wfname_l[-1].append(wfname)\n if any([wf[0] != 0 for wf in grp_wfs]):\n log.warning(f'Element {element} starts with non-zero ' \n f'entry on {obj.name}.')\n\n if not any(grp_has_waveforms.values()):\n for grp in ['ch1', 'ch2', 'ch3', 'ch4']:\n obj.set('{}_state'.format(grp), grp_has_waveforms[grp])\n return None\n\n self.awgs_with_waveforms(obj.name)\n\n nrep_l = [1] * len(wfname_l)\n goto_l = [0] * len(wfname_l)\n goto_l[-1] = 1\n wait_l = [1] * len(wfname_l)\n logic_jump_l = [0] * len(wfname_l)\n\n filename = 'pycqed_pulsar.awg'\n\n awg_file = obj.generate_awg_file(packed_waveforms, np.array(wfname_l).transpose().copy(),\n nrep_l, wait_l, goto_l, logic_jump_l,\n self._awg5014_chan_cfg(obj.name))\n obj.send_awg_file(filename, awg_file)\n obj.load_awg_file(filename)\n\n for par in pars:\n obj.set(par, old_vals[par])\n\n time.sleep(.1)\n # Waits for AWG to be ready\n obj.is_awg_ready()\n\n for grp in ['ch1', 'ch2', 'ch3', 'ch4']:\n obj.set('{}_state'.format(grp), 1*grp_has_waveforms[grp])\n\n hardware_offsets = 0\n for grp in ['ch1', 'ch2', 'ch3', 'ch4']:\n cname = self._id_channel(grp, obj.name)\n offset_mode = self.get('{}_offset_mode'.format(cname))\n if offset_mode == 'hardware':\n hardware_offsets = 1\n obj.DC_output(hardware_offsets)\n\n return awg_file\n\n def _is_awg_running(self, obj):\n if not isinstance(obj, AWG5014Pulsar._supportedAWGtypes):\n return super()._is_awg_running(obj)\n\n return obj.get_state() != 'Idle'\n\n def _clock(self, obj, cid=None):\n if not isinstance(obj, AWG5014Pulsar._supportedAWGtypes):\n return super()._clock(obj, cid)\n return obj.clock_freq()\n\n @staticmethod\n def _awg5014_group_ids(cid):\n \"\"\"\n Returns all id-s corresponding to a single channel group.\n For example `Pulsar._awg5014_group_ids('ch2')` returns `['ch2',\n 'ch2m1', 'ch2m2']`.\n\n Args:\n cid: An id of one of the AWG5014 channels.\n\n Returns: A list of id-s corresponding to the same group as `cid`.\n \"\"\"\n return [cid[:3], cid[:3] + 'm1', cid[:3] + 'm2'] \n\n def _awg5014_chan_cfg(self, awg):\n channel_cfg = {}\n for channel in self.channels:\n if self.get('{}_awg'.format(channel)) != awg:\n continue\n cid = self.get('{}_id'.format(channel))\n amp = self.get('{}_amp'.format(channel))\n off = self.get('{}_offset'.format(channel))\n if self.get('{}_type'.format(channel)) == 'analog':\n offset_mode = self.get('{}_offset_mode'.format(channel))\n channel_cfg['ANALOG_METHOD_' + cid[2]] = 1\n channel_cfg['ANALOG_AMPLITUDE_' + cid[2]] = amp * 2\n if offset_mode == 'software':\n channel_cfg['ANALOG_OFFSET_' + cid[2]] = off\n channel_cfg['DC_OUTPUT_LEVEL_' + cid[2]] = 0\n channel_cfg['EXTERNAL_ADD_' + cid[2]] = 0\n else:\n channel_cfg['ANALOG_OFFSET_' + cid[2]] = 0\n channel_cfg['DC_OUTPUT_LEVEL_' + cid[2]] = off\n channel_cfg['EXTERNAL_ADD_' + cid[2]] = 1\n else:\n channel_cfg['MARKER1_METHOD_' + cid[2]] = 2\n channel_cfg['MARKER2_METHOD_' + cid[2]] = 2\n channel_cfg['MARKER{}_LOW_{}'.format(cid[-1], cid[2])] = \\\n off\n channel_cfg['MARKER{}_HIGH_{}'.format(cid[-1], cid[2])] = \\\n off + amp\n channel_cfg['CHANNEL_STATE_' + cid[2]] = 0\n\n for channel in self.channels:\n if self.get('{}_awg'.format(channel)) != awg:\n continue\n if self.get('{}_active'.format(awg)):\n cid = self.get('{}_id'.format(channel))\n channel_cfg['CHANNEL_STATE_' + cid[2]] = 1\n return channel_cfg\n\n\nclass Pulsar(AWG5014Pulsar, HDAWG8Pulsar, UHFQCPulsar, Instrument):\n \"\"\"\n A meta-instrument responsible for all communication with the AWGs.\n Contains information about all the available awg-channels in the setup.\n Starting, stopping and programming and changing the parameters of the AWGs\n should be done through Pulsar. Supports Tektronix AWG5014 and partially\n ZI UHFLI.\n\n Args:\n master_awg: Name of the AWG that triggers all the other AWG-s and\n should be started last (after other AWG-s are already\n waiting for a trigger.\n \"\"\"\n def __init__(self, name='Pulsar', master_awg=None):\n super().__init__(name)\n\n self.add_parameter('master_awg', \n parameter_class=InstrumentRefParameter,\n initial_value=master_awg)\n self.add_parameter('inter_element_spacing',\n vals=vals.MultiType(vals.Numbers(0),\n vals.Enum('auto')),\n set_cmd=self._set_inter_element_spacing,\n get_cmd=self._get_inter_element_spacing)\n self.add_parameter('reuse_waveforms', initial_value=False,\n parameter_class=ManualParameter, vals=vals.Bool())\n self.add_parameter('append_zeros', initial_value=0, vals=vals.Ints(),\n parameter_class=ManualParameter)\n self.add_parameter('flux_crosstalk_cancellation', initial_value=False,\n parameter_class=ManualParameter, vals=vals.Bool())\n self.add_parameter('flux_channels', initial_value=[],\n parameter_class=ManualParameter, vals=vals.Lists())\n self.add_parameter('flux_crosstalk_cancellation_mtx',\n initial_value=None, parameter_class=ManualParameter)\n self.add_parameter('flux_crosstalk_cancellation_shift_mtx',\n initial_value=None, parameter_class=ManualParameter)\n\n self._inter_element_spacing = 'auto'\n self.channels = set() # channel names\n self.awgs = set() # AWG names\n self.last_sequence = None\n self.last_elements = None\n self._awgs_with_waveforms = set()\n\n self._awgs_prequeried_state = False\n\n self._zi_waves_cleared = False\n self._hash_to_wavename_table = {}\n\n self.num_seg = 0\n\n Pulsar._instance = self\n\n @staticmethod\n def get_instance():\n return Pulsar._instance\n\n # channel handling\n def define_awg_channels(self, awg, channel_name_map=None):\n \"\"\"\n The AWG object must be created before creating channels for that AWG\n\n Args:\n awg: AWG object to add to the pulsar.\n channel_name_map: A dictionary that maps channel ids to channel\n names. (default {})\n \"\"\"\n if channel_name_map is None:\n channel_name_map = {}\n\n for channel_name in channel_name_map.values():\n if channel_name in self.channels:\n raise KeyError(\"Channel named '{}' already defined\".format(\n channel_name))\n if awg.name in self.awgs:\n raise KeyError(\"AWG '{}' already added to pulsar\".format(awg.name))\n\n fail = None\n super()._create_awg_parameters(awg, channel_name_map)\n # try:\n # super()._create_awg_parameters(awg, channel_name_map)\n # except AttributeError as e:\n # fail = e\n # if fail is not None:\n # raise TypeError('Unsupported AWG instrument: {}. '\n # .format(awg.name) + str(fail))\n \n self.awgs.add(awg.name)\n\n def find_awg_channels(self, awg):\n channel_list = []\n for channel in self.channels:\n if self.get('{}_awg'.format(channel)) == awg:\n channel_list.append(channel)\n\n return channel_list\n\n def AWG_obj(self, **kw):\n \"\"\"\n Return the AWG object corresponding to a channel or an AWG name.\n\n Args:\n awg: Name of the AWG Instrument.\n channel: Name of the channel\n\n Returns: An instance of Instrument class corresponding to the AWG\n requested.\n \"\"\"\n awg = kw.get('awg', None)\n chan = kw.get('channel', None)\n if awg is not None and chan is not None:\n raise ValueError('Both `awg` and `channel` arguments passed to '\n 'Pulsar.AWG_obj()')\n elif awg is None and chan is not None:\n name = self.get('{}_awg'.format(chan))\n elif awg is not None and chan is None:\n name = awg\n else:\n raise ValueError('Either `awg` or `channel` argument needs to be '\n 'passed to Pulsar.AWG_obj()')\n return Instrument.find_instrument(name)\n\n def clock(self, channel=None, awg=None):\n \"\"\"\n Returns the clock rate of channel or AWG 'instrument_ref' \n Args:\n isntrument_ref: name of the channel or AWG\n Returns: clock rate in samples per second\n \"\"\"\n if channel is not None and awg is not None:\n raise ValueError('Both channel and awg arguments passed to '\n 'Pulsar.clock()')\n if channel is None and awg is None:\n raise ValueError('Neither channel nor awg arguments passed to '\n 'Pulsar.clock()')\n\n if channel is not None:\n awg = self.get('{}_awg'.format(channel))\n \n if self._awgs_prequeried_state:\n return self._clocks[awg]\n else:\n fail = None\n obj = self.AWG_obj(awg=awg)\n try:\n return super()._clock(obj)\n except AttributeError as e:\n fail = e\n if fail is not None:\n raise TypeError('Unsupported AWG instrument: {} of type {}. '\n .format(obj.name, type(obj)) + str(fail))\n\n def active_awgs(self):\n \"\"\"\n Returns:\n A set of the names of the active AWGs registered\n\n Inactive AWGs don't get started or stopped. Also the waveforms on\n inactive AWGs don't get updated.\n \"\"\"\n return {awg for awg in self.awgs if self.get('{}_active'.format(awg))}\n\n def awgs_with_waveforms(self, awg=None):\n \"\"\"\n Adds an awg to the set of AWGs with waveforms programmed, or returns \n set of said AWGs.\n \"\"\"\n if awg == None:\n return self._awgs_with_waveforms\n else:\n self._awgs_with_waveforms.add(awg)\n\n def start(self, exclude=None):\n \"\"\"\n Start the active AWGs. If multiple AWGs are used in a setup where the\n slave AWGs are triggered by the master AWG, then the slave AWGs must be\n running and waiting for trigger when the master AWG is started to\n ensure synchronous playback.\n \"\"\"\n if exclude is None:\n exclude = []\n\n # Start only the AWGs which have at least one channel programmed, i.e.\n # where at least one channel has state = 1. \n awgs_with_waveforms = self.awgs_with_waveforms()\n used_awgs = set(self.active_awgs()) & awgs_with_waveforms\n \n for awg in used_awgs:\n self._stop_awg(awg)\n\n if self.master_awg() is None:\n for awg in used_awgs:\n if awg not in exclude:\n self._start_awg(awg)\n else:\n if self.master_awg() not in exclude:\n self.master_awg.get_instr().stop()\n for awg in used_awgs:\n if awg != self.master_awg() and awg not in exclude:\n self._start_awg(awg)\n tstart = time.time()\n for awg in used_awgs:\n if awg == self.master_awg() or awg in exclude:\n continue\n good = False\n while not (good or time.time() > tstart + 10):\n if self._is_awg_running(awg):\n good = True\n else:\n time.sleep(0.1)\n if not good:\n raise Exception('AWG {} did not start in 10s'\n .format(awg))\n if self.master_awg() not in exclude:\n self.master_awg.get_instr().start()\n\n def stop(self):\n \"\"\"\n Stop all active AWGs.\n \"\"\"\n\n awgs_with_waveforms = set(self.awgs_with_waveforms())\n used_awgs = set(self.active_awgs()) & awgs_with_waveforms\n\n for awg in used_awgs:\n self._stop_awg(awg)\n \n def program_awgs(self, sequence, awgs='all'):\n\n # Stores the last uploaded sequence for easy access and plotting\n self.last_sequence = sequence\n\n if awgs == 'all':\n awgs = self.active_awgs()\n\n # initializes the set of AWGs with waveforms\n self._awgs_with_waveforms -= awgs\n\n\n # prequery all AWG clock values and AWG amplitudes\n self.AWGs_prequeried(True)\n\n log.info(f'Starting compilation of sequence {sequence.name}')\n t0 = time.time()\n waveforms, awg_sequences = sequence.generate_waveforms_sequences()\n log.info(f'Finished compilation of sequence {sequence.name} in '\n f'{time.time() - t0}')\n\n\n channels_used = self._channels_in_awg_sequences(awg_sequences)\n repeat_dict = self._generate_awg_repeat_dict(sequence.repeat_patterns,\n channels_used)\n self._zi_waves_cleared = False\n self._hash_to_wavename_table = {}\n\n for awg in awgs:\n log.info(f'Started programming {awg}')\n t0 = time.time()\n if awg in repeat_dict.keys():\n self._program_awg(self.AWG_obj(awg=awg),\n awg_sequences.get(awg, {}), waveforms,\n repeat_pattern=repeat_dict[awg])\n else:\n self._program_awg(self.AWG_obj(awg=awg),\n awg_sequences.get(awg, {}), waveforms)\n log.info(f'Finished programming {awg} in {time.time() - t0}')\n \n self.num_seg = len(sequence.segments)\n self.AWGs_prequeried(False)\n\n def _program_awg(self, obj, awg_sequence, waveforms, repeat_pattern=None):\n \"\"\"\n Program the AWG with a sequence of segments.\n\n Args:\n obj: the instance of the AWG to program\n sequence: the `Sequence` object that determines the segment order,\n repetition and trigger wait\n el_wfs: A dictionary from element name to a dictionary from channel\n id to the waveform.\n loop: Boolean flag, whether the segments should be looped over.\n Default is `True`.\n \"\"\"\n # fail = None\n # try:\n # super()._program_awg(obj, awg_sequence, waveforms)\n # except AttributeError as e:\n # fail = e\n # if fail is not None:\n # raise TypeError('Unsupported AWG instrument: {} of type {}. '\n # .format(obj.name, type(obj)) + str(fail))\n if repeat_pattern is not None:\n super()._program_awg(obj, awg_sequence, waveforms,\n repeat_pattern=repeat_pattern)\n else:\n super()._program_awg(obj, awg_sequence, waveforms)\n\n def _hash_to_wavename(self, h):\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n if h not in self._hash_to_wavename_table:\n hash_int = abs(hash(h))\n wname = ''.join(to_base(hash_int, len(alphabet), alphabet))[::-1]\n while wname in self._hash_to_wavename_table.values():\n hash_int += 1\n wname = ''.join(to_base(hash_int, len(alphabet), alphabet)) \\\n [::-1]\n self._hash_to_wavename_table[h] = wname\n return self._hash_to_wavename_table[h]\n\n def _zi_wave_definition(self, wave, defined_waves=None):\n if defined_waves is None:\n defined_waves = set()\n wave_definition = []\n w1, w2 = self._zi_waves_to_wavenames(wave)\n for analog, marker, wc in [(wave[0], wave[1], w1), \n (wave[2], wave[3], w2)]:\n if analog is not None:\n wa = self._hash_to_wavename(analog)\n if wa not in defined_waves:\n wave_definition.append(f'wave {wa} = \"{wa}\";')\n defined_waves.add(wa)\n if marker is not None: \n wm = self._hash_to_wavename(marker)\n if wm not in defined_waves:\n wave_definition.append(f'wave {wm} = \"{wm}\";')\n defined_waves.add(wm)\n if analog is not None and marker is not None:\n if wc not in defined_waves:\n wave_definition.append(f'wave {wc} = {wa} + {wm};')\n defined_waves.add(wc)\n return wave_definition\n\n def _zi_playback_string(self, name, device, wave, acq=False, codeword=False,\n append_zeros=0):\n playback_string = []\n w1, w2 = self._zi_waves_to_wavenames(wave)\n\n trig_source = self.get('{}_trigger_source'.format(name))\n if trig_source == 'Dig1':\n playback_string.append(\n 'waitDigTrigger(1{});'.format(', 1' if device == 'uhf' else ''))\n elif trig_source == 'Dig2':\n playback_string.append('waitDigTrigger(2,1);')\n else:\n playback_string.append(f'wait{trig_source}Trigger();')\n\n if codeword and not (w1 is None and w2 is None):\n playback_string.append('playWaveDIO();')\n else:\n if w1 is None and w2 is not None:\n # This hack is needed due to a bug on the HDAWG.\n # Remove this if case once the bug is fixed.\n playback_string.append(f'playWave(marker(1,0)*0*{w2}, {w2});')\n elif w1 is not None and w2 is None:\n # This hack is needed due to a bug on the HDAWG.\n # Remove this if case once the bug is fixed.\n playback_string.append(f'playWave({w1}, marker(1,0)*0*{w1});')\n elif w1 is not None or w2 is not None:\n playback_string.append('playWave({});'.format(\n _zi_wavename_pair_to_argument(w1, w2)))\n if acq:\n playback_string.append('setTrigger(RO_TRIG);')\n playback_string.append('setTrigger(WINT_EN);')\n if append_zeros:\n playback_string.append(f'playZero({append_zeros});')\n return playback_string\n\n def _zi_interleaved_playback_string(self, name, device, counter, \n wave, acq=False, codeword=False):\n playback_string = []\n w1, w2 = self._zi_waves_to_wavenames(wave)\n if w1 is None or w2 is None:\n raise ValueError('When using HDAWG modulation both I and Q need ' \n 'to be defined')\n \n wname = f'wave{counter}'\n interleaves = [f'wave {wname} = interleave({w1}, {w2});']\n\n if not codeword:\n if not acq:\n playback_string.append(f'prefetch({wname},{wname});')\n \n trig_source = self.get('{}_trigger_source'.format(name))\n if trig_source == 'Dig1':\n playback_string.append(\n 'waitDigTrigger(1{});'.format(', 1' if device == 'uhf' else ''))\n elif trig_source == 'Dig2':\n playback_string.append('waitDigTrigger(2,1);')\n else:\n playback_string.append(f'wait{trig_source}Trigger();')\n\n if codeword:\n # playback_string.append('playWaveDIO();')\n raise NotImplementedError('Modulation in combination with codeword'\n 'pulses has not yet been implemented!')\n else:\n playback_string.append(f'playWave({wname},{wname});')\n if acq:\n playback_string.append('setTrigger(RO_TRIG);')\n playback_string.append('setTrigger(WINT_EN);')\n return playback_string, interleaves\n\n def _zi_codeword_table_entry(self, codeword, wave):\n w1, w2 = self._zi_waves_to_wavenames(wave)\n if w1 is None and w2 is not None:\n # This hack is needed due to a bug on the HDAWG. \n # Remove this if case once the bug is fixed.\n return [f'setWaveDIO({codeword}, zeros(1) + marker(1, 0), {w2});']\n elif not (w1 is None and w2 is None):\n return ['setWaveDIO({}, {});'.format(codeword, \n _zi_wavename_pair_to_argument(w1, w2))]\n else:\n return []\n\n def _zi_waves_to_wavenames(self, wave):\n wavenames = []\n for analog, marker in [(wave[0], wave[1]), (wave[2], wave[3])]:\n if analog is None and marker is None:\n wavenames.append(None)\n elif analog is None and marker is not None:\n wavenames.append(self._hash_to_wavename(marker))\n elif analog is not None and marker is None:\n wavenames.append(self._hash_to_wavename(analog))\n else:\n wavenames.append(self._hash_to_wavename((analog, marker)))\n return wavenames\n\n def _zi_write_waves(self, waveforms):\n wave_dir = _zi_wave_dir()\n for h, wf in waveforms.items():\n filename = os.path.join(wave_dir, self._hash_to_wavename(h)+'.csv')\n fmt = '%.18e' if wf.dtype == np.float else '%d'\n np.savetxt(filename, wf, delimiter=\",\", fmt=fmt)\n\n def _start_awg(self, awg):\n obj = self.AWG_obj(awg=awg)\n obj.start()\n\n def _stop_awg(self, awg):\n obj = self.AWG_obj(awg=awg)\n obj.stop()\n\n def _is_awg_running(self, awg):\n fail = None\n obj = self.AWG_obj(awg=awg)\n try:\n return super()._is_awg_running(obj)\n except AttributeError as e:\n fail = e\n if fail is not None:\n raise TypeError('Unsupported AWG instrument: {} of type {}. '\n .format(obj.name, type(obj)) + str(fail))\n\n def _set_inter_element_spacing(self, val):\n self._inter_element_spacing = val\n\n def _get_inter_element_spacing(self):\n if self._inter_element_spacing != 'auto':\n return self._inter_element_spacing\n else:\n max_spacing = 0\n for awg in self.awgs:\n max_spacing = max(max_spacing, self.get(\n '{}_inter_element_deadtime'.format(awg)))\n return max_spacing\n\n def AWGs_prequeried(self, status=None):\n if status is None:\n return self._awgs_prequeried_state\n elif status:\n self._awgs_prequeried_state = False\n self._clocks = {}\n for awg in self.awgs:\n self._clocks[awg] = self.clock(awg=awg)\n for c in self.channels:\n # prequery also the output amplitude values\n self.get(c + '_amp')\n self._awgs_prequeried_state = True\n else:\n self._awgs_prequeried_state = False\n\n def _id_channel(self, cid, awg):\n \"\"\"\n Returns the channel name corresponding to the channel with id `cid` on\n the AWG `awg`.\n\n Args:\n cid: An id of one of the channels.\n awg: The name of the AWG.\n\n Returns: The corresponding channel name. If the channel is not found,\n returns `None`.\n \"\"\"\n for cname in self.channels:\n if self.get('{}_awg'.format(cname)) == awg and \\\n self.get('{}_id'.format(cname)) == cid:\n return cname\n return None\n\n @staticmethod\n def _channels_in_awg_sequences(awg_sequences):\n \"\"\"\n identifies all channels used in the given awg keyed sequence\n :param awg_sequences (dict): awg sequences keyed by awg name, i.e. as\n returned by sequence.generate_sequence_waveforms()\n :return: dictionary keyed by awg of with all channel used during the sequence\n \"\"\"\n channels_used = dict()\n for awg in awg_sequences:\n channels_used[awg] = set()\n for segname in awg_sequences[awg]:\n if awg_sequences[awg][segname] is None:\n continue\n elements = awg_sequences[awg][segname]\n for cw in elements:\n if cw != \"metadata\":\n channels_used[awg] |= elements[cw].keys()\n return channels_used\n\n def _generate_awg_repeat_dict(self, repeat_dict_per_ch, channels_used):\n \"\"\"\n Translates a repeat dictionary keyed by channels to a repeat dictionary\n keyed by awg. Checks whether all channels in channels_used have an entry.\n :param repeat_dict_per_ch: keys: channels_id, values: repeat pattern\n :param channels_used (dict): list of channel used on each awg\n :return:\n \"\"\"\n awg_ch_repeat_dict = dict()\n repeat_dict_per_awg = dict()\n for cname in repeat_dict_per_ch:\n awg = self.get(f\"{cname}_awg\")\n chid = self.get(f\"{cname}_id\")\n\n if not awg in awg_ch_repeat_dict.keys():\n awg_ch_repeat_dict[awg] = []\n awg_ch_repeat_dict[awg].append(chid)\n if repeat_dict_per_awg.get(awg, repeat_dict_per_ch[cname]) \\\n != repeat_dict_per_ch[cname]:\n raise NotImplementedError(f\"Repeat pattern on {cname} is \"\n f\"different from at least one other channel on {awg}:\"\n f\"{repeat_dict_per_ch[cname]} vs {repeat_dict_per_awg[awg]}\")\n repeat_dict_per_awg[awg] = repeat_dict_per_ch[cname]\n \n for awg_repeat, chs_repeat in awg_ch_repeat_dict.items():\n for ch in channels_used[awg_repeat]:\n assert ch in chs_repeat, f\"Repeat pattern \" \\\n f\"provided for {awg_repeat} but no pattern was given on \" \\\n f\"{ch}. All used channels on the same awg must have a \" \\\n f\"repeat pattern.\"\n\n return repeat_dict_per_awg\n\n\ndef to_base(n, b, alphabet=None, prev=None):\n if prev is None: prev = []\n if n == 0: \n if alphabet is None: return prev\n else: return [alphabet[i] for i in prev]\n return to_base(n//b, b, alphabet, prev+[n%b])\n\ndef _zi_wave_dir():\n if os.name == 'nt':\n dll = ctypes.windll.shell32\n buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH + 1)\n if dll.SHGetSpecialFolderPathW(None, buf, 0x0005, False):\n _basedir = buf.value\n else:\n log.warning('Could not extract my documents folder')\n else:\n _basedir = os.path.expanduser('~')\n wave_dir = os.path.join(_basedir, 'Zurich Instruments', 'LabOne',\n 'WebServer', 'awg', 'waves')\n if not os.path.exists(wave_dir):\n os.makedirs(wave_dir)\n return wave_dir\n\n\ndef _zi_clear_waves():\n wave_dir = _zi_wave_dir()\n for f in os.listdir(wave_dir):\n if f.endswith(\".csv\"):\n os.remove(os.path.join(wave_dir, f))\n elif f.endswith('.cache'):\n shutil.rmtree(os.path.join(wave_dir, f))\n\n\ndef _zi_wavename_pair_to_argument(w1, w2):\n if w1 is not None and w2 is not None:\n return f'{w1}, {w2}'\n elif w1 is not None and w2 is None:\n return f'1, {w1}'\n elif w1 is None and w2 is not None:\n return f'2, {w2}'\n else:\n return ''", "import logging\nlog = logging.getLogger(__name__)\nimport itertools\nimport numpy as np\nfrom copy import deepcopy\nimport pycqed.measurement.waveform_control.sequence as sequence\nfrom pycqed.utilities.general import add_suffix_to_dict_keys\nimport pycqed.measurement.randomized_benchmarking.randomized_benchmarking as rb\nimport pycqed.measurement.randomized_benchmarking.two_qubit_clifford_group as tqc\nfrom pycqed.measurement.pulse_sequences.single_qubit_tek_seq_elts import \\\n get_pulse_dict_from_pars, add_preparation_pulses, pulse_list_list_seq, \\\n prepend_pulses, add_suffix, sweep_pulse_params\nfrom pycqed.measurement.gate_set_tomography.gate_set_tomography import \\\n create_experiment_list_pyGSTi_qudev as get_exp_list\nfrom pycqed.measurement.waveform_control import pulsar as ps\nimport pycqed.measurement.waveform_control.segment as segment\nfrom pycqed.analysis_v2 import tomography_qudev as tomo\n\nstation = None\nkernel_dir = 'kernels/'\n# You need to explicitly set this before running any functions from this module\n# I guess there are cleaner solutions :)\ncached_kernels = {}\n\n\ndef n_qubit_off_on(pulse_pars_list, RO_pars_list, return_seq=False,\n parallel_pulses=False, preselection=False, upload=True,\n RO_spacing=2000e-9):\n n = len(pulse_pars_list)\n seq_name = '{}_qubit_OffOn_sequence'.format(n)\n seq = sequence.Sequence(seq_name)\n seg_list = []\n\n RO_pars_list_presel = deepcopy(RO_pars_list)\n \n for i, RO_pars in enumerate(RO_pars_list):\n RO_pars['name'] = 'RO_{}'.format(i)\n RO_pars['element_name'] = 'RO'\n if i != 0:\n RO_pars['ref_point'] = 'start'\n for i, RO_pars_presel in enumerate(RO_pars_list_presel):\n RO_pars_presel['ref_pulse'] = RO_pars_list[-1]['name']\n RO_pars_presel['ref_point'] = 'start'\n RO_pars_presel['element_name'] = 'RO_presel'\n RO_pars_presel['pulse_delay'] = -RO_spacing\n\n # Create a dict with the parameters for all the pulses\n pulse_dict = dict()\n for i, pulse_pars in enumerate(pulse_pars_list):\n pars = pulse_pars.copy()\n if i == 0 and parallel_pulses:\n pars['ref_pulse'] = 'segment_start'\n if i != 0 and parallel_pulses:\n pars['ref_point'] = 'start'\n pulses = add_suffix_to_dict_keys(\n get_pulse_dict_from_pars(pars), ' {}'.format(i))\n pulse_dict.update(pulses)\n\n # Create a list of required pulses\n pulse_combinations = []\n\n for pulse_list in itertools.product(*(n*[['I', 'X180']])):\n pulse_comb = (n)*['']\n for i, pulse in enumerate(pulse_list):\n pulse_comb[i] = pulse + ' {}'.format(i)\n pulse_combinations.append(pulse_comb)\n for i, pulse_comb in enumerate(pulse_combinations):\n pulses = []\n for j, p in enumerate(pulse_comb):\n pulses += [pulse_dict[p]]\n pulses += RO_pars_list\n if preselection:\n pulses = pulses + RO_pars_list_presel\n\n seg = segment.Segment('segment_{}'.format(i), pulses)\n seg_list.append(seg)\n seq.add(seg)\n\n repeat_dict = {}\n repeat_pattern = ((1.0 + int(preselection))*len(pulse_combinations),1)\n for i, RO_pars in enumerate(RO_pars_list):\n repeat_dict = seq.repeat(RO_pars, None, repeat_pattern)\n\n if upload:\n ps.Pulsar.get_instance().program_awgs(seq)\n if return_seq:\n return seq, seg_list\n else:\n return seq_name\n\n\ndef two_qubit_randomized_benchmarking_seqs(\n qb1n, qb2n, operation_dict, cliffords, nr_seeds=None,\n max_clifford_idx=11520, cz_pulse_name=None, cal_points=None,\n net_clifford=0, clifford_decomposition_name='HZ',\n cl_sequence=None, sampling_seeds=None,\n interleaved_gate=None, upload=True, prep_params=dict()):\n\n \"\"\"\n Args\n qb1n (str): name of qb1\n qb2n (str): name of qb2\n operation_dict (dict): dict with all operations from both qubits and\n with the multiplexed RO pulse pars\n cliffords (array): array of ints specifying the number of random\n Cliffords to generate in each sequence\n nr_seeds (array): array of the form np.arange(nr_seeds_value)\n max_clifford_idx (int): specifies up to which index of the elements in\n the two-qubit Clifford group to include in the random generation.\n See measurement/randomized_benchmarking/two_qubit_clifford_group.py.\n CZ_pulse_name (str): pycqed name of the CZ pulse\n cal_points (CalibrationPoints): instance of CalibrationPoints\n net_clifford (int): 0 or 1; whether the recovery Clifford returns\n qubits to ground statea (0) or puts them in the excited states (1)\n clifford_decomp_name (str): the decomposition of Clifford gates\n into primitives; can be \"XY\", \"HZ\", or \"5Primitives\"\n cl_sequence (list): the Clifford sequence to use for all seeds. Can\n also be lists of lists in which case the user must ensure that\n len(nr seeds) % len(cl_sequence) == 0.\n sampling_seeds (array of ints): ints that will be used as seeds for\n the random generation of Cliffords. Should have the same length\n as nr_seeds.\n interleaved_gate (str): pycqed name for a gate\n upload (bool): whether to upload sequence to AWGs\n prep_params (dict): qubit preparation_params dict\n \"\"\"\n\n # This is used for checking that the recovery is correct\n import qutip as qtp\n standard_pulses = {\n 'I': qtp.qeye(2),\n 'Z0': qtp.qeye(2),\n 'X180': qtp.sigmax(),\n 'mX180': qtp.sigmax(),\n 'Y180': qtp.sigmay(),\n 'mY180': qtp.sigmay(),\n 'X90': qtp.rotation(qtp.sigmax(), np.pi / 2),\n 'mX90': qtp.rotation(qtp.sigmax(), -np.pi / 2),\n 'Y90': qtp.rotation(qtp.sigmay(), np.pi / 2),\n 'mY90': qtp.rotation(qtp.sigmay(), -np.pi / 2),\n 'Z90': qtp.rotation(qtp.sigmaz(), np.pi / 2),\n 'mZ90': qtp.rotation(qtp.sigmaz(), -np.pi / 2),\n 'Z180': qtp.sigmaz(),\n 'mZ180': qtp.sigmaz(),\n 'CZ': qtp.cphase(np.pi)\n }\n\n seq_name = '2Qb_RB_sequence'\n\n if sampling_seeds is None:\n if nr_seeds is None:\n raise ValueError('Please provide either \"sampling_seeds\" or '\n '\"nr_seeds.\"')\n sampling_seeds = [None] * len(nr_seeds)\n else:\n nr_seeds = np.arange(len(sampling_seeds))\n\n # Set Clifford decomposition\n tqc.gate_decomposition = rb.get_clifford_decomposition(\n clifford_decomposition_name)\n if cl_sequence is not None:\n if isinstance(cl_sequence[0], list):\n # if cl_sequence is a list of lists such that\n # len(nr_seeds) != len(cl_sequence) but\n # len(nr_seeds) % len(cl_sequence) == 0,\n # then create as many copies of the lists in cl_sequence until\n # len(cl_sequence) == len(nr_seeds).\n assert len(nr_seeds) % len(cl_sequence) == 0\n k = len(nr_seeds) // len(cl_sequence)\n cl_seq_temp = k * cl_sequence\n\n sequences = []\n for nCl in cliffords:\n pulse_list_list_all = []\n for s in nr_seeds:\n if cl_sequence is None:\n cl_seq = rb.randomized_benchmarking_sequence_new(\n nCl,\n number_of_qubits=2,\n max_clifford_idx=max_clifford_idx,\n interleaving_cl=interleaved_gate,\n desired_net_cl=net_clifford,\n seed=sampling_seeds[s])\n elif isinstance(cl_sequence[0], list):\n cl_seq = cl_seq_temp[s]\n else:\n cl_seq = cl_sequence\n\n pulse_list = []\n pulsed_qubits = {qb1n, qb2n}\n pulse_tuples_list_all = []\n for idx in cl_seq:\n pulse_tuples_list = tqc.TwoQubitClifford(idx).gate_decomposition\n pulse_tuples_list_all += pulse_tuples_list\n\n for j, pulse_tuple in enumerate(pulse_tuples_list):\n if isinstance(pulse_tuple[1], list):\n pulse_list += [operation_dict[cz_pulse_name]]\n pulsed_qubits = {qb1n, qb2n}\n else:\n qb_name = qb1n if '0' in pulse_tuple[1] else qb2n\n pulse_name = pulse_tuple[0]\n if 'Z' not in pulse_name:\n if qb_name not in pulsed_qubits:\n pulse_name += 's'\n else:\n pulsed_qubits = set()\n pulsed_qubits |= {qb_name}\n pulse_list += [\n operation_dict[pulse_name + ' ' + qb_name]]\n\n # check recovery\n gproduct = qtp.tensor(qtp.identity(2), qtp.identity(2))\n for i, cl_tup in enumerate(pulse_tuples_list_all):\n if cl_tup[0] == 'CZ':\n gproduct = standard_pulses[cl_tup[0]] * gproduct\n else:\n eye_2qb = [qtp.identity(2), qtp.identity(2)]\n eye_2qb[int(cl_tup[1][-1])] = standard_pulses[cl_tup[0]]\n gproduct = qtp.tensor(eye_2qb) * gproduct\n x = gproduct.full() / gproduct.full()[0][0]\n assert (np.all((np.allclose(np.real(x), np.eye(4)),\n np.allclose(np.imag(x), np.zeros(4)))))\n\n pulse_list += generate_mux_ro_pulse_list(\n [qb1n, qb2n], operation_dict)\n pulse_list_w_prep = add_preparation_pulses(\n pulse_list, operation_dict, [qb1n, qb2n], **prep_params)\n pulse_list_list_all.append(pulse_list_w_prep)\n seq = pulse_list_list_seq(pulse_list_list_all, seq_name+f'_{nCl}',\n upload=False)\n if cal_points is not None:\n seq.extend(cal_points.create_segments(operation_dict,\n **prep_params))\n sequences.append(seq)\n\n # reuse sequencer memory by repeating readout pattern\n for s in sequences:\n s.repeat_ro(f\"RO {qb1n}\", operation_dict)\n s.repeat_ro(f\"RO {qb2n}\", operation_dict)\n\n if upload:\n ps.Pulsar.get_instance().program_awgs(sequences[0])\n\n return sequences, np.arange(sequences[0].n_acq_elements()), \\\n np.arange(len(cliffords))\n\n\ndef n_qubit_simultaneous_randomized_benchmarking_seq(qubit_names_list,\n operation_dict,\n nr_cliffords_value, #scalar\n nr_seeds, #array\n net_clifford=0,\n gate_decomposition='HZ',\n interleaved_gate=None,\n cal_points=False,\n upload=True,\n upload_all=True,\n seq_name=None,\n verbose=False,\n return_seq=False):\n\n \"\"\"\n Args:\n qubit_list (list): list of qubit names to perform RB on\n operation_dict (dict): operation dictionary for all qubits\n nr_cliffords_value (int): number of Cliffords in the sequence\n nr_seeds (numpy.ndarray): numpy.arange(nr_seeds_int) where nr_seeds_int\n is the number of times to repeat each Clifford sequence of\n length nr_cliffords_value\n net_clifford (int): 0 or 1; refers to the final state after the recovery\n Clifford has been applied. 0->gnd state, 1->exc state.\n gate_decomposition (str): 'HZ' or 'XY'\n interleaved_gate (str): used for regular single qubit Clifford IRB\n string referring to one of the gates in the single qubit\n Clifford group\n cal_points (bool): whether to use cal points\n upload (bool): upload sequence to AWG or not\n upload_all (bool): whether to upload to all AWGs\n seq_name (str): name of this sequences\n verbose (bool): print runtime info\n return_seq (bool): if True, returns seq, element list;\n if False, returns only seq_name\n \"\"\"\n\n raise NotImplementedError(\n 'n_qubit_simultaneous_randomized_benchmarking_seq has not been '\n 'converted to the latest waveform generation code and can not be used.')\n\n # get number of qubits\n n = len(qubit_names_list)\n\n for qb_nr, qb_name in enumerate(qubit_names_list):\n operation_dict['Z0 ' + qb_name] = \\\n deepcopy(operation_dict['Z180 ' + qb_name])\n operation_dict['Z0 ' + qb_name]['basis_rotation'][qb_name] = 0\n\n if seq_name is None:\n seq_name = 'SRB_sequence'\n seq = sequence.Sequence(seq_name)\n el_list = []\n\n if upload_all:\n upload_AWGs = 'all'\n else:\n upload_AWGs = ['AWG1']\n for qbn in qubit_names_list:\n X90_pulse = deepcopy(operation_dict['X90 ' + qbn])\n upload_AWGs += [station.pulsar.get(X90_pulse['I_channel'] + '_AWG'),\n station.pulsar.get(X90_pulse['Q_channel'] + '_AWG')]\n upload_AWGs = list(set(upload_AWGs))\n\n for elt_idx, i in enumerate(nr_seeds):\n\n if cal_points and (elt_idx == (len(nr_seeds)-2)):\n pulse_keys = n*['I']\n\n pulse_keys_w_suffix = []\n for k, pk in enumerate(pulse_keys):\n pk_name = pk if k == 0 else pk+'s'\n pulse_keys_w_suffix.append(pk_name+' '+qubit_names_list[k % n])\n\n pulse_list = []\n for pkws in pulse_keys_w_suffix:\n pulse_list.append(operation_dict[pkws])\n\n elif cal_points and (elt_idx == (len(nr_seeds)-1)):\n pulse_keys = n*['X180']\n\n pulse_keys_w_suffix = []\n for k, pk in enumerate(pulse_keys):\n pk_name = pk if k == 0 else pk+'s'\n pulse_keys_w_suffix.append(pk_name+' '+qubit_names_list[k % n])\n\n pulse_list = []\n for pkws in pulse_keys_w_suffix:\n pulse_list.append(operation_dict[pkws])\n\n else:\n # if clifford_sequence_list is None:\n clifford_sequence_list = []\n for index in range(n):\n clifford_sequence_list.append(\n rb.randomized_benchmarking_sequence(\n nr_cliffords_value, desired_net_cl=net_clifford,\n interleaved_gate=interleaved_gate))\n\n pulse_keys = rb.decompose_clifford_seq_n_qubits(\n clifford_sequence_list,\n gate_decomp=gate_decomposition)\n\n # interleave pulses for each qubit to obtain [pulse0_qb0,\n # pulse0_qb1,..pulse0_qbN,..,pulseN_qb0, pulseN_qb1,..,pulseN_qbN]\n pulse_keys_w_suffix = []\n for k, lst in enumerate(pulse_keys):\n pulse_keys_w_suffix.append([x+' '+qubit_names_list[k % n]\n for x in lst])\n\n pulse_keys_by_qubit = []\n for k in range(n):\n pulse_keys_by_qubit.append([x for l in pulse_keys_w_suffix[k::n]\n for x in l])\n # # make all qb sequences the same length\n # max_len = 0\n # for pl in pulse_keys_by_qubit:\n # if len(pl) > max_len:\n # max_len = len(pl)\n # for ii, pl in enumerate(pulse_keys_by_qubit):\n # if len(pl) < max_len:\n # pl += (max_len-len(pl))*['I ' + qubit_names_list[ii]]\n\n pulse_list = []\n max_len = max([len(pl) for pl in pulse_keys_by_qubit])\n for j in range(max_len):\n for k in range(n):\n if j < len(pulse_keys_by_qubit[k]):\n pulse_list.append(deepcopy(operation_dict[\n pulse_keys_by_qubit[k][j]]))\n\n # Make the correct pulses simultaneous\n for p in pulse_list:\n p['refpoint'] = 'end'\n a = [iii for iii in pulse_list if\n iii['pulse_type'] == 'SSB_DRAG_pulse']\n a[0]['refpoint'] = 'end'\n refpoint = [a[0]['target_qubit']]\n\n for p in a[1:]:\n if p['target_qubit'] not in refpoint:\n p['refpoint'] = 'start'\n refpoint.append(p['target_qubit'])\n else:\n p['refpoint'] = 'end'\n refpoint = [p['target_qubit']]\n\n # add RO pulse pars at the end\n pulse_list += [operation_dict['RO mux']]\n el = multi_pulse_elt(elt_idx, station, pulse_list)\n el_list.append(el)\n seq.append_element(el, trigger_wait=True)\n\n if upload:\n station.pulsar.program_awgs(seq, *el_list,\n AWGs=upload_AWGs,\n channels='all',\n verbose=verbose)\n if return_seq:\n return seq, el_list\n else:\n return seq_name\n\n\ndef n_qubit_reset(qb_names, operation_dict, prep_params=dict(), upload=True,\n states=('g','e',)):\n \"\"\"\n :param qb_names: list of qb_names to perform simultaneous reset upon\n :param states (tuple): ('g','e',) for active reset e, ('g','f',) for active\n reset f and ('g', 'e', 'f') for both.\n :param prep_params (dict): preparation parameters. Note: should be\n multi_qb_preparation_params, ie. threshold mapping should be of the\n form: {qbi: thresh_map_qbi for qbi in qb_names}\n\n :return:\n \"\"\"\n\n seq_name = '{}_reset_x{}_sequence'.format(qb_names,\n prep_params.get('reset_reps',\n '_default_n_reps'))\n\n\n pulses = generate_mux_ro_pulse_list(qb_names, operation_dict)\n reset_and_last_ro_pulses = \\\n add_preparation_pulses(pulses, operation_dict, qb_names, **prep_params)\n swept_pulses = []\n\n state_ops = dict(g=['I '], e=['X180 '], f=['X180 ', 'X180_ef '])\n for s in states:\n pulses = deepcopy(reset_and_last_ro_pulses)\n state_pulses = []\n segment_pulses = []\n # generate one sub list for each qubit, with qb pulse naming\n for qbn in qb_names:\n qb_state_pulses = [deepcopy(operation_dict[op + qbn]) for op in\n state_ops[s]]\n for op, p in zip(state_ops[s], qb_state_pulses):\n p['name'] = op + qbn\n state_pulses += [qb_state_pulses]\n # reference end of state pulse to start of first reset pulse,\n # to effectively prepend the state pulse\n\n for qb_state_pulses in state_pulses:\n segment_pulses += prepend_pulses(pulses, qb_state_pulses)[\n :len(qb_state_pulses)]\n swept_pulses.append(segment_pulses + pulses)\n\n seq = pulse_list_list_seq(swept_pulses, seq_name, upload=False)\n\n # reuse sequencer memory by repeating readout pattern\n # 1. get all readout pulse names (if they are on different uhf,\n # they will be applied to different channels)\n ro_pulse_names = [f\"RO {qbn}\" for qbn in qb_names]\n # 2. repeat readout for each ro_pulse.\n [seq.repeat_ro(pn, operation_dict) for pn in ro_pulse_names]\n\n log.debug(seq)\n\n if upload:\n ps.Pulsar.get_instance().program_awgs(seq)\n\n return seq, np.arange(seq.n_acq_elements())\n\n\ndef parity_correction_seq(\n qb1n, qb2n, qb3n, operation_dict, CZ_pulses, feedback_delay=900e-9,\n prep_sequence=None, reset=True, nr_parity_measurements=1,\n tomography_basis=tomo.DEFAULT_BASIS_ROTS,\n parity_op='ZZ', upload=True, verbose=False, return_seq=False, \n preselection=False, ro_spacing=1e-6, dd_scheme=None, nr_dd_pulses=4,\n skip_n_initial_parity_checks=0, skip_elem='RO'):\n \"\"\"\n\n | elem 1 | elem 2 | (elem 3, 2) | elem 4\n\n |q0> |======|---------*--------------------------( )-|======|\n | prep | | ( repeat )| tomo |\n |q1> | q0, |--mY90s--*--*--Y90--meas=Y180------( parity )| q0, |\n | q2 | | || ( measurement )| q2 |\n |q2> |======|------------*------------Y180-------( )-|======|\n \n required elements:\n elem_1:\n contains everything up to the first readout including preparation\n and first parity measurement\n elem_2 (x2):\n contains conditional Y180 on q1 and q2\n elem_3:\n additional parity measurements\n elem_4 (x6**2):\n tomography rotations for q0 and q2\n\n Args:\n parity_op: 'ZZ', 'XX', 'XX,ZZ' or 'ZZ,XX' specifies the type of parity \n measurement\n \"\"\"\n raise NotImplementedError(\n 'parity_correction_seq has not been '\n 'converted to the latest waveform generation code and can not be used.')\n\n if parity_op not in ['ZZ', 'XX', 'XX,ZZ', 'ZZ,XX']:\n raise ValueError(\"Invalid parity operator '{}'\".format(parity_op))\n\n operation_dict['RO mux_presel'] = operation_dict['RO mux'].copy()\n operation_dict['RO mux_presel']['pulse_delay'] = \\\n -ro_spacing - feedback_delay - operation_dict['RO mux']['length']\n operation_dict['RO mux_presel']['refpoint'] = 'end'\n operation_dict['RO mux_presel'].pop('basis_rotation', {})\n\n operation_dict['RO presel_dummy'] = {\n 'pulse_type': 'SquarePulse',\n 'channel': operation_dict['RO mux']['acq_marker_channel'],\n 'amplitude': 0.0,\n 'length': ro_spacing + feedback_delay,\n 'pulse_delay': 0}\n operation_dict['I rr_decay'] = {\n 'pulse_type': 'SquarePulse',\n 'channel': operation_dict['RO mux']['acq_marker_channel'],\n 'amplitude': 0.0,\n 'length': 400e-9,\n 'pulse_delay': 0}\n operation_dict['RO skip'] = {\n 'pulse_type': 'SquarePulse',\n 'channel': operation_dict['RO mux']['acq_marker_channel'],\n 'amplitude': 0.0,\n 'length': operation_dict['RO mux']['length'],\n 'pulse_delay': 0\n }\n operation_dict['CZ1 skip'] = operation_dict[CZ_pulses[0]].copy()\n operation_dict['CZ1 skip']['amplitude'] = 0\n operation_dict['CZ2 skip'] = operation_dict[CZ_pulses[1]].copy()\n operation_dict['CZ2 skip']['amplitude'] = 0\n\n if dd_scheme is None:\n dd_pulses = [{\n 'pulse_type': 'SquarePulse',\n 'channel': operation_dict['RO mux']['acq_marker_channel'],\n 'amplitude': 0.0,\n 'length': feedback_delay,\n 'pulse_delay': 0}]\n else:\n dd_pulses = get_dd_pulse_list(\n operation_dict,\n # [qb2n],\n [qb1n, qb3n],\n feedback_delay,\n nr_pulses=nr_dd_pulses,\n dd_scheme=dd_scheme,\n init_buffer=0)\n\n if prep_sequence is None:\n if parity_op[0] == 'X':\n prep_sequence = []\n else:\n prep_sequence = ['Y90 ' + qb1n, 'Y90s ' + qb3n]\n elif prep_sequence == 'mixed':\n prep_sequence = ['Y90 ' + qb1n, 'Y90s ' + qb3n, 'RO mux', 'I rr_decay']\n \n xx_sequence_first = ['Y90 ' + qb1n, 'mY90s ' + qb2n, 'Y90s ' + qb3n,\n CZ_pulses[0],\n CZ_pulses[1],\n # 'mY90 ' + qb1n,\n 'Y90 ' + qb2n,\n 'RO ' + qb2n]\n xx_sequence_after_z = deepcopy(xx_sequence_first)\n xx_sequence_after_x = ['mY90 ' + qb2n,\n CZ_pulses[0],\n CZ_pulses[1],\n # 'mY90 ' + qb1n,\n 'Y90 ' + qb2n,\n 'RO ' + qb2n]\n zz_sequence_first = ['mY90 ' + qb2n,\n CZ_pulses[0],\n CZ_pulses[1],\n 'Y90 ' + qb2n,\n 'RO ' + qb2n]\n zz_sequence_after_z = deepcopy(zz_sequence_first)\n zz_sequence_after_x = ['mY90 ' + qb2n, 'mY90s ' + qb3n, 'mY90s ' + qb1n,\n CZ_pulses[0],\n CZ_pulses[1],\n 'Y90 ' + qb2n,\n 'RO ' + qb2n]\n pretomo_after_z = []\n pretomo_after_x = ['mY90 ' + qb3n, 'mY90s ' + qb1n,]\n\n\n # create the elements\n el_list = []\n\n # first element\n if parity_op in ['XX', 'XX,ZZ']: \n op_sequence = prep_sequence + xx_sequence_first\n else:\n op_sequence = prep_sequence + zz_sequence_first\n\n def skip_parity_check(op_sequence, skip_elem, CZ_pulses, qb2n):\n if skip_elem == 'RO':\n op_sequence = ['RO skip' if op == ('RO ' + qb2n) else op\n for op in op_sequence]\n if skip_elem == 'CZ D1' or skip_elem == 'CZ both':\n op_sequence = ['CZ1 skip' if op == CZ_pulses[0] else op\n for op in op_sequence]\n if skip_elem == 'CZ D2' or skip_elem == 'CZ both':\n op_sequence = ['CZ2 skip' if op == CZ_pulses[1] else op\n for op in op_sequence]\n return op_sequence\n if skip_n_initial_parity_checks > 0:\n op_sequence = skip_parity_check(op_sequence, skip_elem, CZ_pulses, qb2n)\n pulse_list = [operation_dict[pulse] for pulse in op_sequence]\n pulse_list += dd_pulses\n if preselection:\n pulse_list.append(operation_dict['RO mux_presel'])\n # RO presel dummy is referenced to end of RO mux presel => it happens\n # before the preparation pulses!\n pulse_list.append(operation_dict['RO presel_dummy'])\n el_main = multi_pulse_elt(0, station, pulse_list, trigger=True, \n name='m')\n el_list.append(el_main)\n\n # feedback elements\n fb_sequence_0 = ['I ' + qb3n, 'Is ' + qb2n]\n fb_sequence_1 = ['X180 ' + qb3n] if reset else ['I ' + qb3n]\n fb_sequence_1 += ['X180s ' + qb2n]# if reset else ['Is ' + qb2n]\n pulse_list = [operation_dict[pulse] for pulse in fb_sequence_0]\n el_list.append(multi_pulse_elt(0, station, pulse_list, name='f0',\n trigger=False, previous_element=el_main))\n pulse_list = [operation_dict[pulse] for pulse in fb_sequence_1]\n el_fb = multi_pulse_elt(1, station, pulse_list, name='f1',\n trigger=False, previous_element=el_main)\n el_list.append(el_fb)\n\n # repeated parity measurement element(s). Phase errors need to be corrected \n # for by careful selection of qubit drive IF-s.\n if parity_op == 'ZZ':\n pulse_list = [operation_dict[pulse] for pulse in zz_sequence_after_z]\n pulse_list += dd_pulses\n el_repeat = multi_pulse_elt(0, station, pulse_list, trigger=False, \n name='rz', previous_element=el_fb)\n el_list.append(el_repeat)\n elif parity_op == 'XX':\n pulse_list = [operation_dict[pulse] for pulse in xx_sequence_after_x]\n pulse_list += dd_pulses\n el_repeat = multi_pulse_elt(0, station, pulse_list, trigger=False, \n name='rx', previous_element=el_fb)\n el_list.append(el_repeat)\n elif parity_op == 'ZZ,XX':\n pulse_list = [operation_dict[pulse] for pulse in xx_sequence_after_z]\n pulse_list += dd_pulses\n el_repeat_x = multi_pulse_elt(0, station, pulse_list, trigger=False, \n name='rx', previous_element=el_fb)\n el_list.append(el_repeat_x)\n\n pulse_list = [operation_dict[pulse] for pulse in zz_sequence_after_x]\n pulse_list += dd_pulses\n el_repeat_z = multi_pulse_elt(1, station, pulse_list, trigger=False, \n name='rz', previous_element=el_fb)\n el_list.append(el_repeat_z)\n elif parity_op == 'XX,ZZ':\n pulse_list = [operation_dict[pulse] for pulse in zz_sequence_after_x]\n pulse_list += dd_pulses\n el_repeat_z = multi_pulse_elt(0, station, pulse_list, trigger=False, \n name='rz', previous_element=el_fb)\n el_list.append(el_repeat_z)\n\n pulse_list = [operation_dict[pulse] for pulse in xx_sequence_after_z]\n pulse_list += dd_pulses\n el_repeat_x = multi_pulse_elt(1, station, pulse_list, trigger=False, \n name='rx', previous_element=el_fb)\n el_list.append(el_repeat_x)\n \n # repeated parity measurement element(s) with skipped parity check.\n if skip_n_initial_parity_checks > 1:\n if parity_op == 'ZZ':\n op_sequence = skip_parity_check(zz_sequence_after_z,\n skip_elem, CZ_pulses, qb2n)\n pulse_list = [operation_dict[pulse] for pulse in op_sequence]\n pulse_list += dd_pulses\n el_repeat_skip = multi_pulse_elt(0, station, pulse_list,\n trigger=False, name='rzs',\n previous_element=el_fb)\n el_list.append(el_repeat_skip)\n elif parity_op == 'XX':\n op_sequence = skip_parity_check(xx_sequence_after_x,\n skip_elem, CZ_pulses, qb2n)\n pulse_list = [operation_dict[pulse] for pulse in op_sequence]\n pulse_list += dd_pulses\n el_repeat_skip = multi_pulse_elt(0, station, pulse_list,\n trigger=False, name='rxs',\n previous_element=el_fb)\n el_list.append(el_repeat_skip)\n elif parity_op == 'ZZ,XX':\n op_sequence = skip_parity_check(xx_sequence_after_z,\n skip_elem, CZ_pulses, qb2n)\n pulse_list = [operation_dict[pulse] for pulse in op_sequence]\n pulse_list += dd_pulses\n el_repeat_x_skip = multi_pulse_elt(0, station, pulse_list,\n trigger=False, name='rxs',\n previous_element=el_fb)\n el_list.append(el_repeat_x_skip)\n\n op_sequence = skip_parity_check(zz_sequence_after_x,\n skip_elem, CZ_pulses, qb2n)\n pulse_list = [operation_dict[pulse] for pulse in op_sequence]\n pulse_list += dd_pulses\n el_repeat_z_skip = multi_pulse_elt(0, station, pulse_list,\n trigger=False, name='rzs',\n previous_element=el_fb)\n el_list.append(el_repeat_z_skip)\n elif parity_op == 'XX,ZZ':\n op_sequence = skip_parity_check(zz_sequence_after_x,\n skip_elem, CZ_pulses, qb2n)\n pulse_list = [operation_dict[pulse] for pulse in op_sequence]\n pulse_list += dd_pulses\n el_repeat_z_skip = multi_pulse_elt(0, station, pulse_list,\n trigger=False, name='rzs',\n previous_element=el_fb)\n el_list.append(el_repeat_z_skip)\n\n op_sequence = skip_parity_check(xx_sequence_after_z,\n skip_elem, CZ_pulses, qb2n)\n pulse_list = [operation_dict[pulse] for pulse in op_sequence]\n pulse_list += dd_pulses\n el_repeat_x_skip = multi_pulse_elt(0, station, pulse_list,\n trigger=False, name='rxs',\n previous_element=el_fb)\n el_list.append(el_repeat_x_skip)\n\n # check that the qubits do not acquire any phase over one round of parity \n # correction\n for qbn in [qb1n, qb2n, qb3n]:\n ifreq = operation_dict['X180 ' + qbn]['mod_frequency']\n if parity_op in ['XX', 'ZZ']:\n elements_length = el_fb.ideal_length() + el_repeat.ideal_length()\n dynamic_phase = el_repeat.drive_phase_offsets.get(qbn, 0)\n else:\n elements_length = el_fb.ideal_length() + el_repeat_x.ideal_length()\n dynamic_phase = el_repeat_x.drive_phase_offsets.get(qbn, 0)\n log.info('Length difference of XX and ZZ cycles: {} s'.format(\n el_repeat_x.ideal_length() - el_repeat_z.ideal_length()\n ))\n dynamic_phase -= el_main.drive_phase_offsets.get(qbn, 0)\n phase_from_if = 360*ifreq*elements_length\n total_phase = phase_from_if + dynamic_phase\n total_mod_phase = (total_phase + 180) % 360 - 180\n log.info(qbn + ' aquires a phase of {} ≡ {} (mod 360)'.format(\n total_phase, total_mod_phase) + ' degrees each correction ' + \n 'cycle. You should reduce the intermediate frequency by {} Hz.'\\\n .format(total_mod_phase/elements_length/360))\n\n # tomography elements\n if parity_op in ['XX', ['XX,ZZ', 'ZZ,XX'][nr_parity_measurements % 2]]:\n pretomo = pretomo_after_x\n else:\n pretomo = pretomo_after_z\n tomography_sequences = get_tomography_pulses(qb1n, qb3n,\n basis_pulses=tomography_basis)\n for i, tomography_sequence in enumerate(tomography_sequences):\n pulse_list = [operation_dict[pulse] for pulse in \n pretomo + tomography_sequence + ['RO mux']]\n el_list.append(multi_pulse_elt(i, station, pulse_list, trigger=False,\n name='t{}'.format(i),\n previous_element=el_fb))\n\n # create the sequence\n seq_name = 'Two qubit entanglement by parity measurement'\n seq = sequence.Sequence(seq_name)\n seq.codewords[0] = 'f0'\n seq.codewords[1] = 'f1'\n for i in range(len(tomography_basis)**2):\n seq.append('m_{}'.format(i), 'm', trigger_wait=True)\n seq.append('f_{}_0'.format(i), 'codeword', trigger_wait=False)\n for j in range(1, nr_parity_measurements):\n if parity_op in ['XX', ['XX,ZZ', 'ZZ,XX'][j % 2]]:\n el_name = 'rx'\n else:\n el_name = 'rz'\n if j < skip_n_initial_parity_checks:\n el_name += 's'\n seq.append('r_{}_{}'.format(i, j), el_name,\n trigger_wait=False)\n seq.append('f_{}_{}'.format(i, j), 'codeword',\n trigger_wait=False)\n seq.append('t_{}'.format(i), 't{}'.format(i),\n trigger_wait=False)\n\n if upload:\n station.pulsar.program_awgs(seq, *el_list, verbose=verbose)\n\n if return_seq:\n return seq, el_list\n else:\n return seq_name\n\n\ndef parity_correction_no_reset_seq(\n q0n, q1n, q2n, operation_dict, CZ_pulses, feedback_delay=900e-9,\n prep_sequence=None, ro_spacing=1e-6, dd_scheme=None, nr_dd_pulses=0,\n tomography_basis=tomo.DEFAULT_BASIS_ROTS,\n upload=True, verbose=False, return_seq=False, preselection=False):\n \"\"\"\n\n | elem 1 | elem 2 | elem 3\n\n |q0> |======|---------*------------------------|======|\n | prep | | | tomo |\n |q1> | q0, |--mY90s--*--*--Y90--meas===-------| q0, |\n | q2 | | || | q2 |\n |q2> |======|------------*------------X180-----|======|\n\n required elements:\n prep_sequence:\n contains everything up to the first readout\n Echo decoupling elements\n contains nr_echo_pulses X180 equally-spaced pulses on q0n, q2n\n FOR THIS TO WORK, ALL QUBITS MUST HAVE THE SAME PI-PULSE LENGTH\n feedback x 2 (for the two readout results):\n contains conditional Y80 on q1 and q2\n tomography x 6**2:\n measure all observables of the two qubits X/Y/Z\n \"\"\"\n raise NotImplementedError(\n 'parity_correction_no_reset_seq has not been '\n 'converted to the latest waveform generation code and can not be used.')\n\n operation_dict['RO mux_presel'] = operation_dict['RO mux'].copy()\n operation_dict['RO mux_presel']['pulse_delay'] = \\\n -ro_spacing - feedback_delay - operation_dict['RO mux']['length']\n operation_dict['RO mux_presel']['refpoint'] = 'end'\n\n operation_dict['RO presel_dummy'] = {\n 'pulse_type': 'SquarePulse',\n 'channel': operation_dict['RO mux']['acq_marker_channel'],\n 'amplitude': 0.0,\n 'length': ro_spacing+feedback_delay,\n 'pulse_delay': 0}\n\n if dd_scheme is None:\n dd_pulses = [{\n 'pulse_type': 'SquarePulse',\n 'channel': operation_dict['RO mux']['acq_marker_channel'],\n 'amplitude': 0.0,\n 'length': feedback_delay,\n 'pulse_delay': 0}]\n else:\n dd_pulses = get_dd_pulse_list(\n operation_dict,\n # [qb2n],\n [q0n, q2n],\n feedback_delay,\n nr_pulses=nr_dd_pulses,\n dd_scheme=dd_scheme,\n init_buffer=0)\n\n if prep_sequence is None:\n prep_sequence = ['Y90 ' + q0n, 'Y90s ' + q2n,\n 'mY90 ' + q1n,\n CZ_pulses[0], CZ_pulses[1],\n 'Y90 ' + q1n,\n 'RO ' + q1n]\n\n pulse_list = [operation_dict[pulse] for pulse in prep_sequence] + dd_pulses\n\n if preselection:\n pulse_list.append(operation_dict['RO mux_presel'])\n # RO presel dummy is referenced to end of RO mux presel => it happens\n # before the preparation pulses!\n pulse_list.append(operation_dict['RO presel_dummy'])\n\n idle_length = operation_dict['X180 ' + q1n]['sigma']\n idle_length *= operation_dict['X180 ' + q1n]['nr_sigma']\n idle_length += 2*8/2.4e9\n idle_pulse = {\n 'pulse_type': 'SquarePulse',\n 'channel': operation_dict['RO mux']['acq_marker_channel'],\n 'amplitude': 0.0,\n 'length': idle_length,\n 'pulse_delay': 0}\n pulse_list.append(idle_pulse)\n\n # tomography elements\n tomography_sequences = get_tomography_pulses(q0n, q2n,\n basis_pulses=tomography_basis)\n # create the elements\n el_list = []\n for i, tomography_sequence in enumerate(tomography_sequences):\n tomography_sequence.append('RO mux')\n pulse_list_tomo = deepcopy(pulse_list) + \\\n [operation_dict[pulse] for pulse in\n tomography_sequence]\n el_list.append(multi_pulse_elt(i, station, pulse_list_tomo,\n trigger=True,\n name='tomography_{}'.format(i)))\n\n # create the sequence\n seq_name = 'Two qubit entanglement by parity measurement'\n seq = sequence.Sequence(seq_name)\n # for i in range(len(tomography_basis)**2):\n for i, tomography_sequence in enumerate(tomography_sequences):\n seq.append('tomography_{}'.format(i), 'tomography_{}'.format(i),\n trigger_wait=True)\n\n if upload:\n station.pulsar.program_awgs(seq, *el_list, verbose=verbose)\n\n if return_seq:\n return seq, el_list\n else:\n return seq_name\n\n\ndef parity_single_round_seq(ancilla_qubit_name, data_qubit_names, CZ_map,\n preps, cal_points, prep_params, operation_dict,\n upload=True):\n seq_name = 'Parity_1_round_sequence'\n qb_names = [ancilla_qubit_name] + data_qubit_names\n\n main_ops = ['Y90 ' + ancilla_qubit_name]\n for i, dqn in enumerate(data_qubit_names):\n op = 'CZ ' + ancilla_qubit_name + ' ' + dqn\n main_ops += CZ_map.get(op, [op])\n if i == len(data_qubit_names)/2 - 1:\n main_ops += ['Y180 ' + ancilla_qubit_name]\n # for dqnecho in enumerate(data_qubit_names):\n # # main_ops += ['Y180s ' + dqnecho]\n # if len(data_qubit_names)%2 == 0:\n main_ops += ['Y90 ' + ancilla_qubit_name]\n # else:\n # main_ops += ['mY90 ' + ancilla_qubit_name]\n\n all_opss = []\n for prep in preps:\n prep_ops = [{'g': 'I ', 'e': 'X180 ', '+': 'Y90 ', '-': 'mY90 '}[s] \\\n + dqn for s, dqn in zip(prep, data_qubit_names)]\n end_ops = [{'g': 'I ', 'e': 'I ', '+': 'Y90 ', '-': 'Y90 '}[s] \\\n + dqn for s, dqn in zip(prep, data_qubit_names)]\n all_opss.append(prep_ops + main_ops + end_ops)\n all_pulsess = []\n for all_ops, prep in zip(all_opss, preps):\n all_pulses = []\n for i, op in enumerate(all_ops):\n all_pulses.append(deepcopy(operation_dict[op]))\n # if i == 0:\n # all_pulses[-1]['ref_pulse'] = 'segment_start'\n # elif 0 < i <= len(data_qubit_names):\n # all_pulses[-1]['ref_point'] = 'start'\n if 'CZ' not in op:\n all_pulses[-1]['element_name'] = f'drive_{prep}'\n else:\n all_pulses[-1]['element_name'] = f'flux_{prep}'\n all_pulses += generate_mux_ro_pulse_list(qb_names, operation_dict)\n all_pulsess.append(all_pulses)\n\n # all_pulsess_with_prep = \\\n # [add_preparation_pulses(seg, operation_dict, qb_names, **prep_params)\n # for seg in all_pulsess]\n all_pulsess_with_prep = all_pulsess\n\n seq = pulse_list_list_seq(all_pulsess_with_prep, seq_name, upload=False)\n\n # add calibration segments\n if cal_points is not None:\n seq.extend(cal_points.create_segments(operation_dict, **prep_params))\n\n [seq.repeat_ro(f\"RO {qbn}\", operation_dict) for qbn in qb_names]\n\n if upload:\n ps.Pulsar.get_instance().program_awgs(seq)\n\n return seq, np.arange(seq.n_acq_elements())\n\n\ndef parity_single_round__phases_seq(ancilla_qubit_name, data_qubit_names, CZ_map,\n phases, prep_anc,\n cal_points, prep_params,\n operation_dict,\n upload=True):\n seq_name = 'Parity_1_round_sequence'\n qb_names = [ancilla_qubit_name] + data_qubit_names\n\n if prep_anc=='e':\n main_ops = ['Y180 ' + ancilla_qubit_name]\n else:\n main_ops = ['I ' + ancilla_qubit_name]\n for i, dqn in enumerate(data_qubit_names):\n op = 'CZ ' + ancilla_qubit_name + ' ' + dqn\n main_ops += CZ_map.get(op, [op])\n if i == len(data_qubit_names)/2 - 1:\n main_ops += ['Y180 ' + ancilla_qubit_name]\n\n prep_ops = ['Y90' + (' ' if i==0 else 's ') + dqn for i,dqn in\n enumerate(data_qubit_names)]\n end_ops = ['mY90' + (' ' if i==0 else 's ') + dqn for i,dqn in\n enumerate(data_qubit_names)]\n\n all_pulsess = []\n for n, phase in enumerate(phases):\n all_pulses = []\n for i, op in enumerate(prep_ops+main_ops):\n all_pulses.append(deepcopy(operation_dict[op]))\n if 'CZ' not in op:\n all_pulses[-1]['element_name'] = f'drive_{n}'\n else:\n all_pulses[-1]['element_name'] = f'flux_{n}'\n for i, op in enumerate(end_ops):\n all_pulses.append(deepcopy(operation_dict[op]))\n all_pulses[-1]['element_name'] = f'drive_{n}'\n all_pulses[-1]['phase'] = phase/np.pi*180\n\n all_pulses += generate_mux_ro_pulse_list(qb_names, operation_dict)\n all_pulsess.append(all_pulses)\n\n all_pulsess_with_prep = \\\n [add_preparation_pulses(seg, operation_dict, qb_names, **prep_params)\n for seg in all_pulsess]\n\n seq = pulse_list_list_seq(all_pulsess_with_prep, seq_name, upload=False)\n\n # add calibration segments\n if cal_points is not None:\n seq.extend(cal_points.create_segments(operation_dict, **prep_params))\n\n if upload:\n ps.Pulsar.get_instance().program_awgs(seq)\n\n return seq, np.arange(seq.n_acq_elements())\n\n\ndef n_qubit_tomo_seq(\n qubit_names, operation_dict, prep_sequence=None,\n prep_name=None,\n rots_basis=tomo.DEFAULT_BASIS_ROTS,\n upload=True, return_seq=False,\n preselection=False, ro_spacing=1e-6):\n \"\"\"\n\n \"\"\"\n\n # create the sequence\n if prep_name is None:\n seq_name = 'N-qubit tomography'\n else:\n seq_name = prep_name + ' tomography'\n seq = sequence.Sequence(seq_name)\n seg_list = []\n\n if prep_sequence is None:\n prep_sequence = ['Y90 ' + qubit_names[0]]\n\n # tomography elements\n tomography_sequences = get_tomography_pulses(*qubit_names,\n basis_pulses=rots_basis)\n for i, tomography_sequence in enumerate(tomography_sequences):\n pulse_list = [operation_dict[pulse] for pulse in prep_sequence]\n # tomography_sequence.append('RO mux')\n # if preselection:\n # tomography_sequence.append('RO mux_presel')\n # tomography_sequence.append('RO presel_dummy')\n pulse_list.extend([operation_dict[pulse] for pulse in\n tomography_sequence])\n ro_pulses = generate_mux_ro_pulse_list(qubit_names, operation_dict)\n pulse_list.extend(ro_pulses)\n\n if preselection:\n ro_pulses_presel = generate_mux_ro_pulse_list(\n qubit_names, operation_dict, 'RO_presel', 'start', -ro_spacing)\n pulse_list.extend(ro_pulses_presel)\n seg = segment.Segment('tomography_{}'.format(i), pulse_list)\n seg_list.append(seg)\n seq.add(seg)\n if upload:\n ps.Pulsar.get_instance().program_awgs(seq)\n if return_seq:\n return seq, seg_list\n else:\n return seq_name\n\n\ndef get_tomography_pulses(*qubit_names, basis_pulses=('I', 'X180', 'Y90',\n 'mY90', 'X90', 'mX90')):\n tomo_sequences = [[]]\n for i, qb in enumerate(qubit_names):\n if i == 0:\n qb = ' ' + qb\n else:\n qb = 's ' + qb\n tomo_sequences_new = []\n for sequence in tomo_sequences:\n for pulse in basis_pulses:\n tomo_sequences_new.append(sequence + [pulse+qb])\n tomo_sequences = tomo_sequences_new\n return tomo_sequences\n\n\ndef get_decoupling_pulses(*qubit_names, nr_pulses=4):\n if nr_pulses % 2 != 0:\n logging.warning('Odd number of dynamical decoupling pulses')\n echo_sequences = []\n for pulse in nr_pulses*['X180']:\n for i, qb in enumerate(qubit_names):\n if i == 0:\n qb = ' ' + qb\n else:\n qb = 's ' + qb\n echo_sequences.append(pulse+qb)\n return echo_sequences\n\n\ndef n_qubit_ref_seq(qubit_names, operation_dict, ref_desc, upload=True,\n return_seq=False, preselection=False, ro_spacing=1e-6):\n \"\"\"\n Calibration points for arbitrary combinations\n\n Arguments:\n qubits: List of calibrated qubits for obtaining the pulse\n dictionaries.\n ref_desc: Description of the calibration sequence. Dictionary\n name of the state as key, and list of pulses names as values.\n \"\"\"\n\n\n # create the elements\n seq_name = 'Calibration'\n seq = sequence.Sequence(seq_name)\n seg_list = []\n\n # calibration elements\n # calibration_sequences = []\n # for pulses in ref_desc:\n # calibration_sequences.append(\n # [pulse+' '+qb for qb, pulse in zip(qubit_names, pulses)])\n\n calibration_sequences = []\n for pulses in ref_desc:\n calibration_sequence_new = []\n for i, pulse in enumerate(pulses):\n if i == 0:\n qb = ' ' + qubit_names[i]\n else:\n qb = 's ' + qubit_names[i]\n calibration_sequence_new.append(pulse+qb)\n calibration_sequences.append(calibration_sequence_new)\n\n for i, calibration_sequence in enumerate(calibration_sequences):\n pulse_list = []\n pulse_list.extend(\n [operation_dict[pulse] for pulse in calibration_sequence])\n ro_pulses = generate_mux_ro_pulse_list(qubit_names, operation_dict)\n pulse_list.extend(ro_pulses)\n\n if preselection:\n ro_pulses_presel = generate_mux_ro_pulse_list(\n qubit_names, operation_dict, 'RO_presel', 'start', -ro_spacing)\n pulse_list.extend(ro_pulses_presel)\n seg = segment.Segment('calibration_{}'.format(i), pulse_list)\n seg_list.append(seg)\n seq.add(seg)\n if upload:\n ps.Pulsar.get_instance().program_awgs(seq)\n\n if return_seq:\n return seq, seg_list\n else:\n return seq_name\n\n\ndef n_qubit_ref_all_seq(qubit_names, operation_dict, upload=True,\n return_seq=False, preselection=False, ro_spacing=1e-6):\n \"\"\"\n Calibration points for all combinations\n \"\"\"\n\n return n_qubit_ref_seq(qubit_names, operation_dict,\n ref_desc=itertools.product([\"I\", \"X180\"],\n repeat=len(qubit_names)),\n upload=upload, return_seq=return_seq,\n preselection=preselection, ro_spacing=ro_spacing)\n\n\ndef Ramsey_add_pulse_seq(times, measured_qubit_name,\n pulsed_qubit_name, operation_dict,\n artificial_detuning=None,\n cal_points=True,\n verbose=False,\n upload=True, return_seq=False):\n raise NotImplementedError(\n 'Ramsey_add_pulse_seq has not been '\n 'converted to the latest waveform generation code and can not be used.')\n\n if np.any(times > 1e-3):\n logging.warning('The values in the times array might be too large.'\n 'The units should be seconds.')\n\n seq_name = 'Ramsey_with_additional_pulse_sequence'\n seq = sequence.Sequence(seq_name)\n el_list = []\n\n\n pulse_pars_x1 = deepcopy(operation_dict['X90 ' + measured_qubit_name])\n pulse_pars_x1['refpoint'] = 'end'\n pulse_pars_x2 = deepcopy(pulse_pars_x1)\n pulse_pars_x2['refpoint'] = 'start'\n RO_pars = operation_dict['RO ' + measured_qubit_name]\n add_pulse_pars = deepcopy(operation_dict['X180 ' + pulsed_qubit_name])\n\n for i, tau in enumerate(times):\n if cal_points and (i == (len(times)-4) or i == (len(times)-3)):\n el = multi_pulse_elt(i, station, [\n operation_dict['I ' + measured_qubit_name], RO_pars])\n elif cal_points and (i == (len(times)-2) or i == (len(times)-1)):\n el = multi_pulse_elt(i, station, [\n operation_dict['X180 ' + measured_qubit_name], RO_pars])\n else:\n pulse_pars_x2['pulse_delay'] = tau\n if artificial_detuning is not None:\n Dphase = ((tau-times[0]) * artificial_detuning * 360) % 360\n pulse_pars_x2['phase'] = Dphase\n\n if i % 2 == 0:\n el = multi_pulse_elt(\n i, station, [operation_dict['X90 ' + measured_qubit_name],\n pulse_pars_x2, RO_pars])\n else:\n el = multi_pulse_elt(i, station,\n [add_pulse_pars, pulse_pars_x1,\n # [pulse_pars_x1, add_pulse_pars,\n pulse_pars_x2, RO_pars])\n el_list.append(el)\n seq.append_element(el, trigger_wait=True)\n if upload:\n station.pulsar.program_awgs(seq, *el_list, verbose=verbose)\n\n if return_seq:\n return seq, el_list\n else:\n return seq_name\n\n\ndef ramsey_add_pulse_seq_active_reset(\n times, measured_qubit_name, pulsed_qubit_name,\n operation_dict, cal_points, n=1, artificial_detunings = 0,\n upload=True, for_ef=False, last_ge_pulse=False, prep_params=dict()):\n '''\n Azz sequence: Ramsey on measured_qubit\n pi-pulse on pulsed_qubit\n Input pars:\n times: array of delays (s)\n n: number of pulses (1 is conventional Ramsey)\n '''\n seq_name = 'Ramsey_with_additional_pulse_sequence'\n\n # Operations\n if for_ef:\n ramsey_ops_measured = [\"X180\"] + [\"X90_ef\"] * 2 * n\n ramsey_ops_pulsed = [\"X180\"]\n if last_ge_pulse:\n ramsey_ops_measured += [\"X180\"]\n else:\n ramsey_ops_measured = [\"X90\"] * 2 * n\n ramsey_ops_pulsed = [\"X180\"]\n\n ramsey_ops_measured += [\"RO\"]\n ramsey_ops_measured = add_suffix(ramsey_ops_measured, \" \" + measured_qubit_name)\n ramsey_ops_pulsed = add_suffix(ramsey_ops_pulsed, \" \" + pulsed_qubit_name)\n ramsey_ops_init = ramsey_ops_pulsed + ramsey_ops_measured\n ramsey_ops_det = ramsey_ops_measured\n\n # pulses\n ramsey_pulses_init = [deepcopy(operation_dict[op]) for op in ramsey_ops_init]\n ramsey_pulses_det = [deepcopy(operation_dict[op]) for op in ramsey_ops_det]\n\n # name and reference swept pulse\n for i in range(n):\n idx = -2 #(2 if for_ef else 1) + i * 2 + 1\n ramsey_pulses_init[idx][\"name\"] = f\"Ramsey_x2_{i}\"\n ramsey_pulses_init[idx]['ref_point'] = 'start'\n ramsey_pulses_det[idx][\"name\"] = f\"Ramsey_x2_{i}\"\n ramsey_pulses_det[idx]['ref_point'] = 'start'\n\n # compute dphase\n a_d = artificial_detunings if np.ndim(artificial_detunings) == 1 \\\n else [artificial_detunings]\n dphase = [((t - times[0]) * a_d[i % len(a_d)] * 360) % 360\n for i, t in enumerate(times)]\n\n # sweep pulses\n params = {f'Ramsey_x2_{i}.pulse_delay': times for i in range(n)}\n params.update({f'Ramsey_x2_{i}.phase': dphase for i in range(n)})\n swept_pulses_init = sweep_pulse_params(ramsey_pulses_init, params)\n swept_pulses_det = sweep_pulse_params(ramsey_pulses_det, params)\n swept_pulses = np.ravel((swept_pulses_init,swept_pulses_det), order='F')\n\n # add preparation pulses\n swept_pulses_with_prep = \\\n [add_preparation_pulses(p, operation_dict,\n [pulsed_qubit_name, measured_qubit_name],\n **prep_params)\n for p in swept_pulses]\n seq = pulse_list_list_seq(swept_pulses_with_prep, seq_name, upload=False)\n\n # add calibration segments\n seq.extend(cal_points.create_segments(operation_dict, **prep_params))\n\n # reuse sequencer memory by repeating readout pattern\n seq.repeat_ro(f\"RO {measured_qubit_name}\", operation_dict)\n\n log.debug(seq)\n if upload:\n ps.Pulsar.get_instance().program_awgs(seq)\n\n return seq, np.arange(seq.n_acq_elements())\n\ndef Ramsey_add_pulse_sweep_phase_seq(\n phases, measured_qubit_name,\n pulsed_qubit_name, operation_dict,\n verbose=False,\n upload=True, return_seq=False,\n cal_points=True):\n raise NotImplementedError(\n 'Ramsey_add_pulse_sweep_phase_seq has not been '\n 'converted to the latest waveform generation code and can not be used.')\n\n seq_name = 'Ramsey_with_additional_pulse_sweep_phase_sequence'\n seq = sequence.Sequence(seq_name)\n el_list = []\n\n X90_2 = deepcopy(operation_dict['X90 ' + measured_qubit_name])\n for i, theta in enumerate(phases):\n X90_2['phase'] = theta*180/np.pi\n if cal_points and (theta == phases[-4] or theta == phases[-3]):\n el = multi_pulse_elt(i, station,\n [operation_dict['I ' + measured_qubit_name],\n operation_dict['RO ' + measured_qubit_name]])\n elif cal_points and (theta == phases[-2] or theta == phases[-1]):\n el = multi_pulse_elt(i, station,\n [operation_dict['X180 ' + measured_qubit_name],\n operation_dict['RO ' + measured_qubit_name]])\n else:\n if i % 2 == 0:\n el = multi_pulse_elt(\n i, station, [operation_dict['X90 ' + measured_qubit_name],\n X90_2,\n operation_dict['RO ' + measured_qubit_name]])\n else:\n # X90_2['phase'] += 12\n # VZ = deepcopy(operation_dict['Z180 '+measured_qubit_name])\n # VZ['basis_rotation'][measured_qubit_name] = -12\n el = multi_pulse_elt(\n i, station, [operation_dict['X90 ' + measured_qubit_name],\n operation_dict['X180s ' + pulsed_qubit_name],\n # VZ,\n X90_2,\n operation_dict['RO ' + measured_qubit_name]])\n el_list.append(el)\n seq.append_element(el, trigger_wait=True)\n if upload:\n station.pulsar.program_awgs(seq, *el_list, verbose=verbose)\n\n if return_seq:\n return seq, el_list\n else:\n return seq_name\n\n#### Multi-qubit time-domain\ndef general_multi_qubit_seq(\n sweep_params,\n sweep_points,\n qb_names,\n operation_dict, # of all qubits\n qb_names_DD=None,\n cal_points=True,\n no_cal_points=4,\n nr_echo_pulses=0,\n idx_DD_start=-1,\n UDD_scheme=True,\n upload=True,\n return_seq=False,\n verbose=False):\n \"\"\"\n sweep_params = {\n\t Pulse_type: (pulse_pars)\n }\n Ex:\n # Rabi\n sweep_params = (\n\t ('X180', {'pulse_pars': {'amplitude': (lambda sp: sp),\n\t 'repeat': 3}}), # for n-rabi; leave out if normal rabi\n\t )\n\n\t # Ramsey\n sweep_params = (\n ('X90', {}),\n ('X90', {'pulse_pars': {'refpoint': 'start',\n 'pulse_delay': (lambda sp: sp),\n 'phase': (lambda sp:\n ( (sp-sweep_points[0]) *\n art_det * 360) % 360)}}),\n )\n\n # T1\n\t sweep_params = (\n\t ('X180', {}),\n\t ('RO_mux', {'pulse_pars': {'pulse_delay': (lambda sp: sp)}})\n )\n\n # Echo\n sweep_params = (\n ('X90', {}),\n ('X180', {'pulse_pars': {'refpoint': 'start',\n 'pulse_delay': (lambda sp: sp/2)}}),\n ('X90', {'pulse_pars': {\n 'refpoint': 'start',\n 'pulse_delay': (lambda sp: sp/2),\n 'phase': (lambda sp:\n ((sp-sweep_points[0]) * artificial_detuning *\n 360) % 360)}})\n\n )\n\n # QScale\n sweep_params = (\n ('X90', {'pulse_pars': {'motzoi': (lambda sp: sp)},\n 'condition': (lambda i: i%3==0)}),\n ('X180', {'pulse_pars': {'motzoi': (lambda sp: sp)},\n 'condition': (lambda i: i%3==0)}),\n ('X90', {'pulse_pars': {'motzoi': (lambda sp: sp)},\n 'condition': (lambda i: i%3==1)}),\n ('Y180', {'pulse_pars': {'motzoi': (lambda sp: sp)},\n 'condition': (lambda i: i%3==1)}),\n ('X90', {'pulse_pars': {'motzoi': (lambda sp: sp)},\n 'condition': (lambda i: i%3==2)}),\n ('mY180', {'pulse_pars': {'motzoi': (lambda sp: sp)},\n 'condition': (lambda i: i%3==2)}),\n ('RO', {})\n )\n \"\"\"\n raise NotImplementedError(\n 'general_multi_qubit_seq has not been '\n 'converted to the latest waveform generation code and can not be used.')\n\n\n seq_name = 'TD_sequence'\n seq = sequence.Sequence(seq_name)\n el_list = []\n\n len_sweep_pts = len(sweep_points)\n\n if (not isinstance(sweep_points, list) and\n not isinstance(sweep_points, np.ndarray)):\n if isinstance(sweep_points, dict):\n len_sweep_pts = len(sweep_points[list(sweep_points)[0]])\n assert (np.all([len_sweep_pts ==\n len(sp) for sp in sweep_points.values()]))\n else:\n raise ValueError('Unrecognized type for \"sweep_points\".')\n\n for i in np.arange(len_sweep_pts):\n pulse_list = []\n if cal_points and no_cal_points == 4 and \\\n (i == (len_sweep_pts-4) or i == (len_sweep_pts-3)):\n for qb_name in qb_names:\n qbn = ' ' + qb_name\n if qb_name != qb_names[0]:\n qbn = 's ' + qb_name\n pulse_list += [operation_dict['I' + qbn]]\n elif cal_points and no_cal_points == 4 and \\\n (i == (len_sweep_pts-2) or i == (len_sweep_pts-1)):\n for qb_name in qb_names:\n qbn = ' ' + qb_name\n if qb_name != qb_names[0]:\n qbn = 's ' + qb_name\n pulse_list += [operation_dict['X180' + qbn]]\n elif cal_points and no_cal_points == 2 and \\\n (i == (len_sweep_pts-2) or i == (len_sweep_pts-1)):\n for qb_name in qb_names:\n qbn = ' ' + qb_name\n if qb_name != qb_names[0]:\n qbn = 's ' + qb_name\n pulse_list += [operation_dict['I' + qbn]]\n else:\n for sweep_tuple in sweep_params:\n pulse_key = [x for x in sweep_tuple if isinstance(x, str)][0]\n params_dict = [x for x in sweep_tuple if isinstance(x, dict)][0]\n\n proceed = True\n\n if 'condition' in params_dict:\n if not params_dict['condition'](i):\n proceed = False\n\n if proceed:\n if 'mux' in pulse_key:\n pulse_pars_dict = deepcopy(operation_dict[pulse_key])\n if 'pulse_pars' in params_dict:\n for pulse_par_name, pulse_par in \\\n params_dict['pulse_pars'].items():\n if hasattr(pulse_par, '__call__'):\n if isinstance(sweep_points, dict):\n if 'RO mux' in sweep_points.keys():\n pulse_pars_dict[pulse_par_name] = \\\n pulse_par(sweep_points[\n 'RO mux'][i])\n else:\n pulse_pars_dict[pulse_par_name] = \\\n pulse_par(sweep_points[i])\n else:\n pulse_pars_dict[pulse_par_name] = \\\n pulse_par\n pulse_list += [pulse_pars_dict]\n else:\n for qb_name in qb_names:\n pulse_pars_dict = deepcopy(\n operation_dict[pulse_key + ' ' + qb_name])\n if 'pulse_pars' in params_dict:\n for pulse_par_name, pulse_par in \\\n params_dict['pulse_pars'].items():\n if hasattr(pulse_par, '__call__'):\n if isinstance(sweep_points, dict):\n pulse_pars_dict[pulse_par_name] = \\\n pulse_par(sweep_points[\n qb_name][i])\n else:\n if pulse_par_name == \\\n 'basis_rotation':\n pulse_pars_dict[\n pulse_par_name] = {}\n pulse_pars_dict[pulse_par_name][\n [qbn for qbn in qb_names if\n qbn != qb_name][0]] = \\\n - pulse_par(sweep_points[i])\n\n else:\n pulse_pars_dict[\n pulse_par_name] = \\\n pulse_par(sweep_points[i])\n else:\n pulse_pars_dict[pulse_par_name] = \\\n pulse_par\n if qb_name != qb_names[0]:\n pulse_pars_dict['refpoint'] = 'simultaneous'\n\n pulse_list += [pulse_pars_dict]\n\n if 'repeat' in params_dict:\n n = params_dict['repeat']\n pulse_list = n*pulse_list\n\n if nr_echo_pulses != 0:\n if qb_names_DD is None:\n qb_names_DD = qb_names\n pulse_list = get_DD_pulse_list(operation_dict, qb_names,\n DD_time=sweep_points[i],\n qb_names_DD=qb_names_DD,\n pulse_dict_list=pulse_list,\n nr_echo_pulses=nr_echo_pulses,\n idx_DD_start=idx_DD_start,\n UDD_scheme=UDD_scheme)\n\n if not np.any([p['operation_type'] == 'RO' for p in pulse_list]):\n pulse_list += [operation_dict['RO mux']]\n el = multi_pulse_elt(i, station, pulse_list)\n\n el_list.append(el)\n seq.append_element(el, trigger_wait=True)\n\n if upload:\n station.pulsar.program_awgs(seq, *el_list, verbose=verbose)\n\n if return_seq:\n return seq, el_list\n else:\n return seq\n\n\ndef get_dd_pulse_list(operation_dict, qb_names, dd_time, nr_pulses=4, \n dd_scheme='cpmg', init_buffer=0, refpoint='end'):\n drag_pulse_length = (operation_dict['X180 ' + qb_names[-1]]['nr_sigma'] * \\\n operation_dict['X180 ' + qb_names[-1]]['sigma'])\n pulse_list = []\n def cpmg_delay(i, nr_pulses=nr_pulses):\n if i == 0 or i == nr_pulses:\n return 1/nr_pulses/2\n else:\n return 1/nr_pulses\n\n def udd_delay(i, nr_pulses=nr_pulses):\n delay = np.sin(0.5*np.pi*(i + 1)/(nr_pulses + 1))**2\n delay -= np.sin(0.5*np.pi*i/(nr_pulses + 1))**2\n return delay\n\n if dd_scheme == 'cpmg':\n delay_func = cpmg_delay\n elif dd_scheme == 'udd':\n delay_func = udd_delay\n else:\n raise ValueError('Unknown decoupling scheme \"{}\"'.format(dd_scheme))\n\n for i in range(nr_pulses+1):\n delay_pulse = {\n 'pulse_type': 'SquarePulse',\n 'channel': operation_dict['X180 ' + qb_names[0]]['I_channel'],\n 'amplitude': 0.0,\n 'length': dd_time*delay_func(i),\n 'pulse_delay': 0}\n if i == 0:\n delay_pulse['pulse_delay'] = init_buffer\n delay_pulse['refpoint'] = refpoint\n if i == 0 or i == nr_pulses:\n delay_pulse['length'] -= drag_pulse_length/2\n else:\n delay_pulse['length'] -= drag_pulse_length\n if delay_pulse['length'] > 0:\n pulse_list.append(delay_pulse)\n else:\n raise Exception(\"Dynamical decoupling pulses don't fit in the \"\n \"specified dynamical decoupling duration \"\n \"{:.2f} ns\".format(dd_time*1e9))\n if i != nr_pulses:\n for j, qbn in enumerate(qb_names):\n pulse_name = 'X180 ' if j == 0 else 'X180s '\n pulse_pulse = deepcopy(operation_dict[pulse_name + qbn])\n pulse_list.append(pulse_pulse)\n return pulse_list\n\n\ndef get_DD_pulse_list(operation_dict, qb_names, DD_time,\n qb_names_DD=None,\n pulse_dict_list=None, idx_DD_start=-1,\n nr_echo_pulses=4, UDD_scheme=True):\n\n n = len(qb_names)\n if qb_names_DD is None:\n qb_names_DD = qb_names\n if pulse_dict_list is None:\n pulse_dict_list = []\n elif len(pulse_dict_list) < 2*n:\n raise ValueError('The pulse_dict_list must have at least two entries.')\n\n idx_DD_start *= n\n pulse_dict_list_end = pulse_dict_list[idx_DD_start::]\n pulse_dict_list = pulse_dict_list[0:idx_DD_start]\n\n X180_pulse_dict = operation_dict['X180 ' + qb_names_DD[0]]\n DRAG_length = X180_pulse_dict['nr_sigma']*X180_pulse_dict['sigma']\n X90_separation = DD_time - DRAG_length\n\n if UDD_scheme:\n pulse_positions_func = \\\n lambda idx, N: np.sin(np.pi*idx/(2*N+2))**2\n pulse_delays_func = (lambda idx, N: X90_separation*(\n pulse_positions_func(idx, N) -\n pulse_positions_func(idx-1, N)) -\n ((0.5 if idx == 1 else 1)*DRAG_length))\n\n if nr_echo_pulses*DRAG_length > X90_separation:\n pass\n else:\n for p_nr in range(nr_echo_pulses):\n for qb_name in qb_names_DD:\n if qb_name == qb_names_DD[0]:\n DD_pulse_dict = deepcopy(operation_dict[\n 'X180 ' + qb_name])\n DD_pulse_dict['refpoint'] = 'end'\n DD_pulse_dict['pulse_delay'] = pulse_delays_func(\n p_nr+1, nr_echo_pulses)\n else:\n DD_pulse_dict = deepcopy(operation_dict[\n 'X180s ' + qb_name])\n pulse_dict_list.append(DD_pulse_dict)\n\n for j in range(n):\n if j == 0:\n pulse_dict_list_end[j]['refpoint'] = 'end'\n pulse_dict_list_end[j]['pulse_delay'] = pulse_delays_func(\n 1, nr_echo_pulses)\n else:\n pulse_dict_list_end[j]['pulse_delay'] = 0\n else:\n echo_pulse_delay = (X90_separation -\n nr_echo_pulses*DRAG_length) / \\\n nr_echo_pulses\n if echo_pulse_delay < 0:\n pass\n else:\n start_end_delay = echo_pulse_delay/2\n for p_nr in range(nr_echo_pulses):\n for qb_name in qb_names_DD:\n if qb_name == qb_names_DD[0]:\n DD_pulse_dict = deepcopy(operation_dict[\n 'X180 ' + qb_name])\n DD_pulse_dict['refpoint'] = 'end'\n DD_pulse_dict['pulse_delay'] = \\\n (start_end_delay if p_nr == 0 else echo_pulse_delay)\n else:\n DD_pulse_dict = deepcopy(operation_dict[\n 'X180s ' + qb_name])\n pulse_dict_list.append(DD_pulse_dict)\n for j in range(n):\n if j == 0:\n pulse_dict_list_end[j]['refpoint'] = 'end'\n pulse_dict_list_end[j]['pulse_delay'] = start_end_delay\n else:\n pulse_dict_list_end[j]['pulse_delay'] = 0\n\n pulse_dict_list += pulse_dict_list_end\n\n return pulse_dict_list\n\n\ndef pygsti_seq(qb_names, pygsti_listOfExperiments, operation_dict,\n preselection=True, ro_spacing=1e-6,\n seq_name=None, upload=True, upload_all=True,\n return_seq=False, verbose=False):\n raise NotImplementedError(\n 'pygsti_seq has not been '\n 'converted to the latest waveform generation code and can not be used.')\n\n if seq_name is None:\n seq_name = 'GST_sequence'\n seq = sequence.Sequence(seq_name)\n el_list = []\n\n tup_lst = [g.tup for g in pygsti_listOfExperiments]\n str_lst = []\n for t1 in tup_lst:\n s = ''\n for t in t1:\n s += str(t)\n str_lst += [s]\n experiment_lists = get_exp_list(filename='',\n pygstiGateList=str_lst,\n qb_names=qb_names)\n if preselection:\n RO_str = 'RO' if len(qb_names) == 1 else 'RO mux'\n operation_dict[RO_str+'_presel'] = \\\n operation_dict[experiment_lists[0][-1]].copy()\n operation_dict[RO_str+'_presel']['pulse_delay'] = -ro_spacing\n operation_dict[RO_str+'_presel']['refpoint'] = 'start'\n operation_dict[RO_str+'presel_dummy'] = {\n 'pulse_type': 'SquarePulse',\n 'channel': operation_dict[\n experiment_lists[0][-1]]['acq_marker_channel'],\n 'amplitude': 0.0,\n 'length': ro_spacing,\n 'pulse_delay': 0}\n\n if upload_all:\n upload_AWGs = 'all'\n else:\n upload_AWGs = ['AWG1']\n for qbn in qb_names:\n X90_pulse = deepcopy(operation_dict['X90 ' + qbn])\n upload_AWGs += [station.pulsar.get(X90_pulse['I_channel'] + '_AWG'),\n station.pulsar.get(X90_pulse['Q_channel'] + '_AWG')]\n if len(qb_names) > 1:\n CZ_pulse_name = 'CZ {} {}'.format(qb_names[1], qb_names[0])\n if len([i for i in experiment_lists if CZ_pulse_name in i]) > 0:\n CZ_pulse = operation_dict[CZ_pulse_name]\n upload_AWGs += [station.pulsar.get(CZ_pulse['channel'] + '_AWG')]\n for ch in CZ_pulse['aux_channels_dict']:\n upload_AWGs += [station.pulsar.get(ch + '_AWG')]\n upload_AWGs = list(set(upload_AWGs))\n for i, exp_lst in enumerate(experiment_lists):\n pulse_lst = [operation_dict[p] for p in exp_lst]\n if preselection:\n pulse_lst.append(operation_dict[RO_str+'_presel'])\n pulse_lst.append(operation_dict[RO_str+'presel_dummy'])\n el = multi_pulse_elt(i, station, pulse_lst)\n el_list.append(el)\n seq.append_element(el, trigger_wait=True)\n\n if upload:\n station.pulsar.program_awgs(seq, *el_list,\n AWGs=upload_AWGs,\n channels='all',\n verbose=verbose)\n\n if return_seq:\n return seq, el_list\n else:\n return seq_name\n\n\ndef generate_mux_ro_pulse_list(qubit_names, operation_dict, element_name='RO',\n ref_point='end', pulse_delay=0.0):\n ro_pulses = []\n for j, qb_name in enumerate(qubit_names):\n ro_pulse = deepcopy(operation_dict['RO ' + qb_name])\n ro_pulse['pulse_name'] = '{}_{}'.format(element_name, j)\n ro_pulse['element_name'] = element_name\n if j == 0:\n ro_pulse['pulse_delay'] = pulse_delay\n ro_pulse['ref_point'] = ref_point\n else:\n ro_pulse['ref_point'] = 'start'\n ro_pulses.append(ro_pulse)\n return ro_pulses\n\n\ndef interleaved_pulse_list_equatorial_seg(\n qubit_names, operation_dict, interleaved_pulse_list, phase, \n pihalf_spacing=None, prep_params=None, segment_name='equatorial_segment'):\n prep_params = {} if prep_params is None else prep_params\n pulse_list = []\n for notfirst, qbn in enumerate(qubit_names):\n pulse_list.append(deepcopy(operation_dict['X90 ' + qbn])) \n pulse_list[-1]['ref_point'] = 'start'\n if not notfirst:\n pulse_list[-1]['name'] = 'refpulse'\n pulse_list += interleaved_pulse_list\n for notfirst, qbn in enumerate(qubit_names):\n pulse_list.append(deepcopy(operation_dict['X90 ' + qbn])) \n pulse_list[-1]['phase'] = phase\n if notfirst:\n pulse_list[-1]['ref_point'] = 'start'\n elif pihalf_spacing is not None:\n pulse_list[-1]['ref_pulse'] = 'refpulse'\n pulse_list[-1]['ref_point'] = 'start'\n pulse_list[-1]['pulse_delay'] = pihalf_spacing\n pulse_list += generate_mux_ro_pulse_list(qubit_names, operation_dict)\n pulse_list = add_preparation_pulses(pulse_list, operation_dict, qubit_names, **prep_params)\n return segment.Segment(segment_name, pulse_list)\n\n\ndef interleaved_pulse_list_list_equatorial_seq(\n qubit_names, operation_dict, interleaved_pulse_list_list, phases, \n pihalf_spacing=None, prep_params=None, cal_points=None,\n sequence_name='equatorial_sequence', upload=True):\n prep_params = {} if prep_params is None else prep_params\n seq = sequence.Sequence(sequence_name)\n for i, interleaved_pulse_list in enumerate(interleaved_pulse_list_list):\n for j, phase in enumerate(phases):\n seg = interleaved_pulse_list_equatorial_seg(\n qubit_names, operation_dict, interleaved_pulse_list, phase,\n pihalf_spacing=pihalf_spacing, prep_params=prep_params, segment_name=f'segment_{i}_{j}')\n seq.add(seg)\n if cal_points is not None:\n seq.extend(cal_points.create_segments(operation_dict, **prep_params))\n if upload:\n ps.Pulsar.get_instance().program_awgs(seq)\n return seq, np.arange(seq.n_acq_elements())\n\n\ndef measurement_induced_dephasing_seq(\n measured_qubit_names, dephased_qubit_names, operation_dict, \n ro_amp_scales, phases, pihalf_spacing=None, prep_params=None,\n cal_points=None, upload=True, sequence_name='measurement_induced_dephasing_seq'):\n interleaved_pulse_list_list = []\n for i, ro_amp_scale in enumerate(ro_amp_scales):\n interleaved_pulse_list = generate_mux_ro_pulse_list(\n measured_qubit_names, operation_dict, \n element_name=f'interleaved_readout_{i}')\n for pulse in interleaved_pulse_list:\n pulse['amplitude'] *= ro_amp_scale\n pulse['operation_type'] = None\n interleaved_pulse_list_list.append(interleaved_pulse_list)\n return interleaved_pulse_list_list_equatorial_seq(\n dephased_qubit_names, operation_dict, interleaved_pulse_list_list, \n phases, pihalf_spacing=pihalf_spacing, prep_params=prep_params,\n cal_points=cal_points, sequence_name=sequence_name, upload=upload)\n\n\ndef drive_cancellation_seq(\n drive_op_code, ramsey_qubit_names, operation_dict,\n sweep_points, n_pulses=1, pihalf_spacing=None, prep_params=None,\n cal_points=None, upload=True, sequence_name='drive_cancellation_seq'):\n \"\"\"\n Sweep pulse cancellation parameters and measure Ramsey on qubits the\n cancellation is for.\n\n Args:\n drive_op_code: Operation code for the pulse to be cancelled, including\n the qubit name.\n ramsey_qubit_names: A list of qubit names corresponding to the\n undesired targets of the pulse that is being cancelled.\n sweep_points: A SweepPoints object that describes the pulse\n parameters to sweep. The sweep point keys should be of the form\n `qb.param`, where `qb` is the name of the qubit the cancellation\n is for and `param` is a parameter in the pulses\n cancellation_params dict. For example to sweep the amplitude of\n the cancellation pulse on qb1, you could configure the sweep\n points as `SweepPoints('qb1.amplitude', np.linspace(0, 1, 21))`.\n The Ramsey phases must be given in the second sweep dimension with\n sweep name 'phases'.\n n_pulses: Number of pulse repetitions done between the Ramsey\n pulses. Useful for amplification of small errors. Defaults to 1.\n Rest of the arguments are passed down to\n interleaved_pulse_list_list_equatorial_seq\n \"\"\"\n\n len_sweep = len(list(sweep_points[0].values())[0][0])\n # create len_sweep instances of n pulses, where the n references correspond\n # to the same dictionary instance\n interleaved_pulse_list_list = \\\n [n_pulses*[deepcopy(operation_dict[drive_op_code])]\n for _ in range(len_sweep)]\n for key, (values, unit, label) in sweep_points[0].items():\n assert len(values) == len_sweep\n tqb, param = key.split('.')\n iq = operation_dict[f'X180 {tqb}']['I_channel'], \\\n operation_dict[f'X180 {tqb}']['Q_channel']\n for pulse_list, value in zip(interleaved_pulse_list_list, values):\n # since all n pulses in pulse_list are the same dict. we only need\n # to modify the first element.\n pulse_list[0]['cancellation_params'][iq][param] = value\n # make last segment a calibration segment\n interleaved_pulse_list_list[-1][0]['amplitude'] = 0\n\n return interleaved_pulse_list_list_equatorial_seq(\n ramsey_qubit_names, operation_dict, interleaved_pulse_list_list,\n sweep_points[1]['phase'][0], pihalf_spacing=pihalf_spacing,\n prep_params=prep_params, cal_points=cal_points,\n sequence_name=sequence_name, upload=upload)\n\n\ndef fluxline_crosstalk_seq(target_qubit_name, crosstalk_qubits_names,\n crosstalk_qubits_amplitudes, sweep_points,\n operation_dict, crosstalk_fluxpulse_length,\n target_fluxpulse_length, prep_params,\n cal_points, upload=True,\n sequence_name='fluxline_crosstalk_seq'):\n \"\"\"\n Applies a flux pulse on the target qubit with various amplitudes.\n Measure the phase shift due to these pulses on the crosstalk qubits which\n are measured in a Ramsey setting and fluxed to a more sensitive frequency.\n\n Args:\n target_qubit_name: the qubit to which a fluxpulse with varying amplitude\n is applied\n crosstalk_qubits_names: a list of qubits to do a Ramsey on.\n crosstalk_qubits_amplitudes: A dictionary from crosstalk qubit names\n to flux pulse amplitudes that are applied to them to increase their\n flux sensitivity. Missing amplitudes are set to 0.\n sweep_points: A SweepPoints object, where the first sweep dimension is\n over Ramsey phases and must be called 'phase' and the second sweep\n dimenstion is over the target qubit pulse amplitudes and must be\n called 'target_amp'.\n operation_dict: A dictionary of pulse dictionaries corresponding to the\n various operations that can be done.\n target_fluxpulse_length: length of the flux pulse on the target qubit.\n crosstalk_fluxpulse_length: length of the flux pulses on the crosstalk\n qubits\n prep_params: Perparation parameters dictionary specifying the type\n of state preparation.\n cal_points: CalibrationPoints object determining the used calibration\n points\n upload: Whether the experimental sequence should be uploaded.\n Defaults to True.\n sequence_name: Overwrite the sequence name. Defaults to\n 'fluxline_crosstalk_seq'.\n \"\"\"\n\n interleaved_pulse_list_list = []\n buffer_start = 0\n buffer_end = 0\n pi_len = 0\n for qbn in crosstalk_qubits_names:\n buffer_start = max(buffer_start,\n operation_dict[f'FP {qbn}']['buffer_length_start'])\n buffer_end = max(buffer_end,\n operation_dict[f'FP {qbn}']['buffer_length_end'])\n pi_len = max(pi_len, operation_dict[f'X180 {qbn}']['nr_sigma'] *\n operation_dict[f'X180 {qbn}']['sigma'])\n\n for amp in sweep_points[1]['target_amp'][0]:\n interleaved_pulse_list = []\n for i, qbn in enumerate(crosstalk_qubits_names):\n pulse = deepcopy(operation_dict[f'FP {qbn}'])\n if i > 0:\n pulse['ref_point'] = 'middle'\n pulse['ref_point_new'] = 'middle'\n pulse['amplitude'] = crosstalk_qubits_amplitudes.get(qbn, 0)\n pulse['pulse_length'] = crosstalk_fluxpulse_length\n pulse['buffer_length_start'] = buffer_start\n pulse['buffer_length_end'] = buffer_end\n interleaved_pulse_list += [pulse]\n pulse = deepcopy(operation_dict[f'FP {target_qubit_name}'])\n pulse['amplitude'] = amp\n pulse['pulse_length'] = target_fluxpulse_length\n pulse['ref_point'] = 'middle'\n pulse['ref_point_new'] = 'middle'\n interleaved_pulse_list += [pulse]\n interleaved_pulse_list_list += [interleaved_pulse_list]\n\n pihalf_spacing = buffer_start + crosstalk_fluxpulse_length + buffer_end + \\\n pi_len\n return interleaved_pulse_list_list_equatorial_seq(\n crosstalk_qubits_names, operation_dict, interleaved_pulse_list_list,\n sweep_points[0]['phase'][0], pihalf_spacing=pihalf_spacing,\n prep_params=prep_params, cal_points=cal_points,\n sequence_name=sequence_name, upload=upload)\n\ndef multi_parity_multi_round_seq(ancilla_qubit_names,\n data_qubit_names,\n parity_map,\n CZ_map,\n prep,\n operation_dict,\n mode='tomo',\n parity_seperation=800e-9,\n rots_basis=('I', 'Y90', 'X90'),\n parity_loops=1,\n cal_points=None,\n prep_params=None,\n upload=True,\n max_acq_length=1e-6,\n ):\n seq_name = 'Multi_Parity_{}_round_sequence'.format(parity_loops)\n qb_names = ancilla_qubit_names + data_qubit_names\n\n # Dummy pulses are used to make sure that all UHFs are triggered even if\n # only part of the qubits are read out.\n # First get all RO pulses, then throw away all except one per channel pair.\n dummy_pulses = [deepcopy(operation_dict['RO ' + qbn]) for qbn in qb_names]\n dummy_pulses = {(p['I_channel'], p['Q_channel']): p for p in dummy_pulses}\n for p in dummy_pulses.values():\n p.update({'amplitude': 0.00001,\n 'pulse_length': 50e-09,\n 'pulse_delay': 0,\n 'mod_frequency': 900.0e6,\n 'op_code': ''})\n \n echo_pulses = [('Y180' + 's ' + dqb)\n for n, dqb in enumerate(data_qubit_names)]\n\n\n parity_ops_list = []\n echoed_round = {}\n for i in range(len(parity_map)):\n echoed_round[parity_map[i]['round']] = False\n\n for i in range(len(parity_map)):\n parity_ops = []\n anc_name = parity_map[i]['ancilla']\n\n basis_op = 'I'\n\n if parity_map[i]['type'] == 'Z':\n basis_op = 'I'\n elif parity_map[i]['type'] == 'X':\n basis_op = 'Y90'\n elif parity_map[i]['type'] == 'Y':\n basis_op = 'X90'\n\n for n, dqb in enumerate(parity_map[i]['data']):\n if dqb in data_qubit_names:\n op = basis_op + ('' if n==0 else 's') + ' ' + dqb\n parity_ops.append(op)\n parity_ops.append('Y90 ' + anc_name)\n\n for n, dqb in enumerate(parity_map[i]['data']):\n op = 'CZ ' + anc_name + ' ' + dqb\n op = CZ_map.get(op, [op])\n ops = parity_ops+op\n if n==1 and parity_map[i]['type'] == 'X':\n ops.append('Y180 ' + anc_name)\n ops.append('Z180 ' + parity_map[i]['data'][-1])\n ops.append('Z180 ' + parity_map[i]['data'][-2])\n print('ECHO')\n elif n==0 and parity_map[i]['type'] == 'Z':\n ops.append('Y180 ' + anc_name)\n ops.append('Z180 ' + parity_map[i]['data'][-1])\n print('ECHO')\n parity_ops = ops\n\n parity_ops.append('I ' + anc_name)\n parity_ops.append('Y90s ' + anc_name)\n print('ECHO')\n\n for n, dqb in enumerate(parity_map[i]['data']):\n if dqb in data_qubit_names:\n op = ('m' if basis_op is not 'I' else '') + basis_op + ('' if n==0\n else\n 's') + ' ' + dqb\n # op = basis_op + ('' if n==0 else 's') + ' ' + dqb\n parity_ops.append(op)\n parity_ops.append('I ' + parity_map[i]['data'][-1])\n parity_ops.append('RO ' + anc_name)\n parity_ops_list.append(parity_ops)\n\n\n\n prep_ops = [{'g': 'I ', 'e': 'X180 ', '+': 'Y90 ', '-': 'mY90 '}[s] \\\n + dqn for s, dqn in zip(prep, data_qubit_names)]\n prep_mode = False\n\n end_sequence = []\n if mode=='tomo':\n end_sequences = get_tomography_pulses(*data_qubit_names,\n basis_pulses=rots_basis)\n elif mode=='onoff':\n end_sequences = [[rot + ('s ' if i==0 else ' ') + dqb\n for i, dqb in enumerate(data_qubit_names)]\n for rot in rots_basis]\n elif mode=='preps':\n prep_ops = [[{'g': 'I ', 'e': 'X180 ', '+': 'Y90 ', '-': 'mY90 '}[s] \\\n + dqn for s, dqn in zip(preps, data_qubit_names)]\n for preps in rots_basis]\n end_sequences = [['I ' + data_qubit_names[0]] for preps in rots_basis]\n prep_mode = True\n else:\n end_sequences = ['I ' + data_qubit_names[0]]\n\n first_readout = dict()\n rounds = 0\n for k in range(len(parity_map)):\n first_readout[parity_map[k]['round']] = True\n if parity_map[k]['round'] > rounds:\n rounds = parity_map[k]['round']\n\n all_pulsess = []\n for t, end_sequence in enumerate(end_sequences):\n all_pulses = []\n\n if prep_mode:\n prep_pulses = [deepcopy(operation_dict[op]) for op in\n prep_ops[t]]\n else:\n prep_pulses = [deepcopy(operation_dict[op]) for op in\n prep_ops]\n\n for pulse in prep_pulses:\n # pulse['element_name'] = f'prep_tomo_{t}'\n pulse['element_name'] = f'drive_tomo_{t}'\n pulse['ref_pulse'] = 'segment_start'\n pulse['pulse_delay'] = -pulse['sigma']*pulse['nr_sigma']\n all_pulses += prep_pulses\n\n for m in range(parity_loops):\n for round in first_readout.keys():\n first_readout[round] = True\n\n for k in range(len(parity_map)):\n round = parity_map[k]['round']\n anc_name = parity_map[k]['ancilla']\n\n for i, op in enumerate(parity_ops_list[k]):\n all_pulses.append(deepcopy(operation_dict[op]))\n if op == 'I '+anc_name:\n all_pulses[-1]['basis_rotation'] = parity_map[k][\n 'phases']\n if i == 0:\n all_pulses[-1]['ref_pulse'] = 'segment_start'\n all_pulses[-1]['pulse_delay'] = np.sum(\n parity_seperation[:round])+m*np.sum(parity_seperation)\n if 'CZ' not in op and 'RO' not in op:\n all_pulses[-1]['element_name'] = f'drive_tomo_{t}'\n # all_pulses[-1]['element_name'] = f'drive_{round}_loop' + \\\n # f'_{m}_tomo_{t}'\n elif 'CZ' in op:\n all_pulses[-1]['element_name'] = f'flux_tomo_{t}'\n if 'RO' in op:\n all_pulses[-1]['element_name'] = f'ro_{round}_loop' + \\\n f'_{m}_tomo_{t}'\n if first_readout[round] is True:\n all_pulses[-1]['name'] = f'first_ro_{round}_loop' + \\\n f'_{m}_tomo_{t}'\n else:\n all_pulses[-1]['ref_pulse'] = f'first_ro_{round}' + \\\n f'_loop_{m}_tomo_{t}'\n all_pulses[-1]['ref_point'] = 'start'\n\n first_readout[round] = False\n\n # Add dummy pulses for all UHFs\n for p in dummy_pulses.values():\n all_pulses.append(deepcopy(p))\n all_pulses[-1]['element_name'] = f'ro_{round}_loop' + \\\n f'_{m}_tomo_{t}'\n all_pulses[-1]['ref_pulse'] = f'first_ro_{round}' + \\\n f'_loop_{m}_tomo_{t}'\n all_pulses[-1]['ref_point'] = 'start'\n\n # if (m!=parity_loops-1) or ( (parity_loops%2==0)\n # and m==parity_loops-1):\n if m != parity_loops - 1:\n # print('Logical Echo')\n for i, op in enumerate(echo_pulses):\n all_pulses.append(deepcopy(operation_dict[op]))\n all_pulses[-1]['element_name'] = f'drive_tomo_{t}'\n # all_pulses[-1]['pulse_delay'] = -50e-9\n\n end_pulses = [deepcopy(operation_dict[op]) for op in end_sequence]\n\n for pulse in end_pulses:\n pulse['element_name'] = f'drive_tomo_{t}'\n pulse['ref_pulse'] = f'first_ro_{rounds}' + \\\n f'_loop_{parity_loops-1}_tomo_{t}'\n pulse['pulse_delay'] = max_acq_length + 5e-9 # account for UHF deadtime\n pulse['ref_point'] = 'start'\n all_pulses += end_pulses\n all_pulses += generate_mux_ro_pulse_list(qb_names, operation_dict)\n all_pulsess.append(all_pulses)\n\n\n if prep_params is not None:\n all_pulsess_with_prep = \\\n [add_preparation_pulses(seg, operation_dict, qb_names, **prep_params)\n for seg in all_pulsess]\n else:\n all_pulsess_with_prep = all_pulsess\n\n seq = pulse_list_list_seq(all_pulsess_with_prep, seq_name, upload=False)\n\n # add calibration segments\n if cal_points is not None:\n seq.extend(cal_points.create_segments(operation_dict, **prep_params))\n\n # This will currently only work with pre-selection\n ROs = (rounds+1)\n repeat_patern = (len(end_sequences), 1, (parity_loops, ROs), 1)\n for qbn in qb_names:\n pulse = 'RO ' + qbn\n repeat_dict = seq.repeat(pulse, operation_dict, repeat_patern)\n\n log.debug(repeat_dict)\n\n if upload:\n ps.Pulsar.get_instance().program_awgs(seq)\n\n log.debug('sweep_points: ', seq.n_acq_elements())\n return seq, np.arange(seq.n_acq_elements())\n\n\ndef ro_dynamic_phase_seq(hard_sweep_dict, qbp_name, qbr_names,\n operation_dict, pulse_separation, init_state,\n cal_points=None, prep_params=dict(), upload=True):\n\n \"\"\"\n RO cross-dephasing measurement sequence. Measures the dynamic phase induced\n on qbr by a measurement tone on the pulsed qubit (qbp).\n Args:\n qbp_name: pulsed qubit name; RO pulse is applied on this qubit\n qbr_names: ramsey (measured) qubits\n phases: array of phases for the second piHalf pulse on qbr\n operation_dict: contains operation dicts from both qubits;\n !!! Must contain 'RO mux' which is the mux RO pulse only for\n the measured_qubits (qbr_names) !!!\n pulse_separation: separation between the two pi-half pulses, shouls be\n equal to integration length\n cal_points: use cal points\n \"\"\"\n\n seq_name = 'ro_dynamic_phase_sequence'\n dummy_ro_1 = {'pulse_type': 'GaussFilteredCosIQPulse',\n 'I_channel': 'UHF1_ch1',\n 'Q_channel': 'UHF1_ch2',\n 'amplitude': 0.00001,\n 'pulse_length': 50e-09,\n 'pulse_delay': 0,\n 'mod_frequency': 900.0e6,\n 'phase': 0,\n 'phi_skew': 0,\n 'alpha': 1,\n 'gaussian_filter_sigma': 1e-09,\n 'nr_sigma': 2,\n 'phase_lock': True,\n 'basis_rotation': {},\n 'operation_type': 'RO'}\n dummy_ro_2 = {'pulse_type': 'GaussFilteredCosIQPulse',\n 'I_channel': 'UHF2_ch1',\n 'Q_channel': 'UHF2_ch2',\n 'amplitude': 0.00001,\n 'pulse_length': 50e-09,\n 'pulse_delay': 0,\n 'mod_frequency': 900.0e6,\n 'phase': 0,\n 'phi_skew': 0,\n 'alpha': 1,\n 'gaussian_filter_sigma': 1e-09,\n 'nr_sigma': 2,\n 'phase_lock': True,\n 'basis_rotation': {},\n 'operation_type': 'RO'}\n\n # put together n-qubit calibration point pulse lists\n # put together n-qubit ramsey pulse lists\n pulse_list = []\n for j, qbr_name in enumerate(qbr_names):\n pulse_list.append(deepcopy(operation_dict['X90 ' + qbr_name]))\n pulse_list[-1]['name'] = f'x1_{qbr_name}'\n pulse_list[-1]['ref_pulse'] = 'segment_start'\n pulse_list[-1]['refpoint'] = 'start'\n\n ro_probe = deepcopy(operation_dict['RO ' + qbp_name])\n pulse_list.append(ro_probe)\n pulse_list[-1]['name'] = f'ro_probe'\n pulse_list[-1]['element_name'] = f'ro_probe'\n pulse_list.append(dummy_ro_1)\n pulse_list[-1]['refpoint'] = 'start'\n pulse_list[-1]['element_name'] = f'ro_probe'\n pulse_list.append(dummy_ro_2)\n pulse_list[-1]['refpoint'] = 'start'\n pulse_list[-1]['element_name'] = f'ro_probe'\n\n for j, qbr_name in enumerate(qbr_names):\n pulse_list.append(deepcopy(operation_dict['X90 ' + qbr_name]))\n pulse_list[-1]['name'] = f'x2_{qbr_name}'\n pulse_list[-1]['ref_pulse'] = 'segment_start'\n pulse_list[-1]['refpoint'] = 'start'\n pulse_list[-1]['pulse_delay'] = pulse_separation\n\n ro_list = generate_mux_ro_pulse_list(qbr_names+[qbp_name], operation_dict)\n pulse_list += ro_list\n\n if init_state == 'e':\n pulse_list.append(deepcopy(operation_dict['X180 ' + qbp_name]))\n pulse_list[-1]['ref_pulse'] = 'segment_start'\n pulse_list[-1]['refpoint'] = 'start'\n pulse_list[-1]['pulse_delay'] = -100e-9\n\n params = {f'x2_{qbr_name}.{k}': v['values']\n for k, v in hard_sweep_dict.items() for qbr_name in qbr_names}\n hsl = len(list(hard_sweep_dict.values())[0]['values'])\n params.update({f'ro_probe.amplitude': np.concatenate(\n [ro_probe['amplitude'] * np.ones(hsl // 2), np.zeros(hsl // 2)])})\n\n swept_pulses = sweep_pulse_params(pulse_list, params)\n\n swept_pulses_with_prep = \\\n [add_preparation_pulses(p, operation_dict, [qbp_name], **prep_params)\n for p in swept_pulses]\n seq = pulse_list_list_seq(swept_pulses_with_prep, seq_name, upload=False)\n\n if cal_points is not None:\n # add calibration segments\n seq.extend(cal_points.create_segments(operation_dict, **prep_params))\n\n log.debug(seq)\n if upload:\n ps.Pulsar.get_instance().program_awgs(seq)\n\n return seq, np.arange(seq.n_acq_elements())\n\n\n## Multi-qubit time-domain sequences ##\n\ndef n_qubit_rabi_seq(qubit_names, operation_dict, sweep_points, cal_points,\n upload=True, n=1, for_ef=False,\n last_ge_pulse=False, prep_params=dict()):\n '''\n Rabi sequence for n qubits.\n Args:\n qubit_names: list of qubit names\n operation_dict: operation_dict for all qubit in qubit_names\n sweep_points: instance of SweepPoints class\n cal_points: instance of CalibrationPoints class\n upload: whether to upload sequence to instrument or not\n n: number of pulses (1 is conventional Rabi)\n for_ef: whether to do rabi between ef transition\n last_ge_pulse: whether to use a ge pulse at the end of each segment\n for a rabi between ef transition\n prep_params: qubit preparation params\n Returns:\n sequence (Sequence): sequence object\n segment_indices (list): array of range of n_segments including\n calibration_segments. To be used as sweep_points for the MC.\n '''\n\n seq_name = 'n_qubit_Rabi_sequence'\n\n pulse_list = []\n # add Rabi amplitudes segments\n for qbn in qubit_names:\n rabi_ops = [\"X180_ef \" + qbn if for_ef else \"X180 \" + qbn] * n\n if for_ef:\n rabi_ops = [\"X180 \" + qbn] + rabi_ops # prepend ge pulse\n if last_ge_pulse:\n rabi_ops += [\"X180 \" + qbn] # append ge pulse\n\n rabi_pulses = [deepcopy(operation_dict[op]) for op in rabi_ops]\n rabi_pulses[0]['ref_pulse'] = 'segment_start'\n for i in np.arange(1 if for_ef else 0, n + 1 if for_ef else n):\n rabi_pulses[i][\"name\"] = f\"Rabi_{i-1 if for_ef else i}_{qbn}\"\n\n pulse_list += rabi_pulses\n pulse_list += generate_mux_ro_pulse_list(qubit_names, operation_dict)\n\n params_to_sweep = {\n f'Rabi_{i}_{qbn}.amplitude': list(sweep_points[0].values())[j][0]\n for i in range(n) for j, qbn in enumerate(qubit_names)}\n swept_pulses = sweep_pulse_params(pulse_list, params_to_sweep)\n swept_pulses_with_prep = \\\n [add_preparation_pulses(p, operation_dict, qubit_names, **prep_params)\n for p in swept_pulses]\n seq = pulse_list_list_seq(swept_pulses_with_prep, seq_name, upload=False)\n\n # add calibration segments\n seq.extend(cal_points.create_segments(operation_dict, **prep_params))\n\n # reuse sequencer memory by repeating readout pattern\n [seq.repeat_ro(f\"RO {qbn}\", operation_dict) for qbn in qubit_names]\n\n log.debug(seq)\n if upload:\n ps.Pulsar.get_instance().program_awgs(seq)\n\n return seq, np.arange(seq.n_acq_elements())\n\n\ndef n_qubit_ramsey_seq(qubit_names, operation_dict, sweep_points, cal_points,\n artificial_detuning=0, upload=True, for_ef=False,\n last_ge_pulse=False, prep_params=dict()):\n '''\n Ramsey sequence for n qubits.\n Args:\n qubit_names: list of qubit names\n operation_dict: operation_dict for all qubit in qubit_names\n sweep_points: instance of SweepPoints class\n cal_points: instance of CalibrationPoints class\n artificial_detunings: Detuning of second pi-half pulse.\n upload: whether to upload sequence to instrument or not\n n: number of pulses (1 is conventional Rabi)\n for_ef: whether to do rabi between ef transition\n last_ge_pulse: whether to use a ge pulse at the end of each segment\n for a rabi between ef transition\n prep_params: qubit preparation params\n Returns:\n sequence (Sequence): sequence object\n segment_indices (list): array of range of n_segments including\n calibration_segments. To be used as sweep_points for the MC.\n '''\n\n seq_name = 'n_qubit_Ramsey_sequence'\n\n pulse_list = []\n # add Ramsey segments\n for qbn in qubit_names:\n ramsey_ops = [\"X90_ef \" + qbn if for_ef else \"X90 \" + qbn] * 2\n if for_ef:\n ramsey_ops = [\"X180 \" + qbn] + ramsey_ops # prepend ge pulse\n if last_ge_pulse:\n ramsey_ops += [\"X180 \" + qbn] # append ge pulse\n\n ramsey_pulses = [deepcopy(operation_dict[op]) for op in ramsey_ops]\n ramsey_pulses[0]['ref_pulse'] = 'segment_start'\n ramsey_pulses[2 if for_ef else 1][\"name\"] = f\"Ramsey_{qbn}\"\n ramsey_pulses[2 if for_ef else 1][\"ref_point\"] = 'start'\n\n pulse_list += ramsey_pulses\n pulse_list += generate_mux_ro_pulse_list(qubit_names, operation_dict)\n\n params_to_sweep = {}\n for j, qbn in enumerate(qubit_names):\n times = list(sweep_points[0].values())[j][0]\n params_to_sweep.update({f'Ramsey_{qbn}.pulse_delay': times})\n params_to_sweep.update({\n f'Ramsey_{qbn}.phase':\n ((times-times[0])*artificial_detuning*360) % 360})\n swept_pulses = sweep_pulse_params(pulse_list, params_to_sweep)\n swept_pulses_with_prep = \\\n [add_preparation_pulses(p, operation_dict, qubit_names, **prep_params)\n for p in swept_pulses]\n seq = pulse_list_list_seq(swept_pulses_with_prep, seq_name, upload=False)\n\n # add calibration segments\n seq.extend(cal_points.create_segments(operation_dict, **prep_params))\n\n # reuse sequencer memory by repeating readout pattern\n [seq.repeat_ro(f\"RO {qbn}\", operation_dict) for qbn in qubit_names]\n\n log.debug(seq)\n if upload:\n ps.Pulsar.get_instance().program_awgs(seq)\n\n return seq, np.arange(seq.n_acq_elements())\n\n\ndef n_qubit_qscale_seq(qubit_names, operation_dict, sweep_points, cal_points,\n upload=True, for_ef=False,\n last_ge_pulse=False, prep_params=dict()):\n '''\n DRAG pulse calibration sequence for n qubits.\n Args:\n qubit_names: list of qubit names\n operation_dict: operation_dict for all qubit in qubit_names\n sweep_points: instance of SweepPoints class\n cal_points: instance of CalibrationPoints class\n upload: whether to upload sequence to instrument or not\n n: number of pulses (1 is conventional Rabi)\n for_ef: whether to do rabi between ef transition\n last_ge_pulse: whether to use a ge pulse at the end of each segment\n for a rabi between ef transition\n prep_params: qubit preparation params\n Returns:\n sequence (Sequence): sequence object\n segment_indices (list): array of range of n_segments including\n calibration_segments. To be used as sweep_points for the MC.\n '''\n\n seq_name = 'n_qubit_qscale_sequence'\n\n # Operations\n qscale_base_ops = [['X90', 'X180'], ['X90', 'Y180'], ['X90', 'mY180']]\n\n # add DRAG calibration segments\n final_pulses = []\n for base_ops in qscale_base_ops:\n pulse_list = []\n for qbn in qubit_names:\n qscale_ops = add_suffix(base_ops, \"_ef\" if for_ef else \"\")\n if for_ef:\n qscale_ops = ['X180'] + qscale_ops\n if last_ge_pulse:\n qscale_ops += [\"X180\"]\n qscale_ops = add_suffix(qscale_ops, \" \" + qbn)\n\n qscale_pulses = [deepcopy(operation_dict[op]) for op in qscale_ops]\n qscale_pulses[0]['ref_pulse'] = 'segment_start'\n # name and reference swept pulse\n for i in range(len(base_ops)):\n idx = (1 if for_ef else 0) + i\n qscale_pulses[idx][\"name\"] = f\"Qscale_{i}_{qbn}\"\n pulse_list += qscale_pulses\n pulse_list += generate_mux_ro_pulse_list(qubit_names, operation_dict)\n\n params_to_sweep = {\n f'Qscale_*_{qbn}.motzoi': list(sweep_points[0].values())[j][0]\n for j, qbn in enumerate(qubit_names)}\n swept_pulses = sweep_pulse_params(pulse_list, params_to_sweep)\n swept_pulses_with_prep = \\\n [add_preparation_pulses(p, operation_dict, qubit_names,\n **prep_params)\n for p in swept_pulses]\n final_pulses.append(swept_pulses_with_prep)\n\n # intertwine pulses in same order as base_ops\n # 1. get one list of list from the 3 lists of list\n f_p = np.array(final_pulses)\n reordered_pulses = [[X90X180, X90Y180, X90mY180]\n for X90X180, X90Y180, X90mY180\n in zip(f_p[0], f_p[1], f_p[2])]\n # 2. reshape to list of list\n len_swp_pts = len(list(sweep_points[0].values())[0][0])\n final_pulses = np.squeeze(np.reshape(reordered_pulses,\n (3*len_swp_pts, -1))).tolist()\n\n seq = pulse_list_list_seq(final_pulses, seq_name, upload=False)\n\n # add calibration segments\n seq.extend(cal_points.create_segments(operation_dict, **prep_params))\n\n # reuse sequencer memory by repeating readout pattern\n [seq.repeat_ro(f\"RO {qbn}\", operation_dict) for qbn in qubit_names]\n\n log.debug(seq)\n if upload:\n ps.Pulsar.get_instance().program_awgs(seq)\n\n return seq, np.arange(seq.n_acq_elements())\n\n\ndef n_qubit_t1_seq(qubit_names, operation_dict, sweep_points, cal_points,\n upload=True, for_ef=False, last_ge_pulse=False,\n prep_params=dict()):\n '''\n T1 sequence for n qubits.\n Args:\n qubit_names: list of qubit names\n operation_dict: operation_dict for all qubit in qubit_names\n sweep_points: instance of SweepPoints class\n cal_points: instance of CalibrationPoints class\n upload: whether to upload sequence to instrument or not\n for_ef: whether to do rabi between ef transition\n last_ge_pulse: whether to use a ge pulse at the end of each segment\n for a rabi between ef transition\n prep_params: qubit preparation params\n Returns:\n sequence (Sequence): sequence object\n segment_indices (list): array of range of n_segments including\n calibration_segments. To be used as sweep_points for the MC.\n '''\n\n seq_name = 'n_qubit_T1_sequence'\n\n pulse_list = []\n # add delays segments\n for j, qbn in enumerate(qubit_names):\n t1_ops = [\"X180_ef \" + qbn if for_ef else \"X180 \" + qbn]\n if for_ef:\n t1_ops = [\"X180 \" + qbn] + t1_ops # prepend ge pulse\n if last_ge_pulse:\n t1_ops += [\"X180 \" + qbn] # append ge pulse\n\n t1_pulses = [deepcopy(operation_dict[op]) for op in t1_ops]\n t1_pulses[0]['ref_pulse'] = 'segment_start'\n if for_ef and last_ge_pulse:\n t1_pulses[-1]['name'] = f\"delayed_pulse_{qbn}\"\n\n pulse_list += t1_pulses\n pulse_list += generate_mux_ro_pulse_list(qubit_names, operation_dict)\n if not (for_ef and last_ge_pulse):\n pulse_list[-len(qubit_names)][\"name\"] = f\"delayed_pulse\"\n\n params_to_sweep = {}\n for j, qbn in enumerate(qubit_names):\n delay_times = list(sweep_points[0].values())[j][0]\n if for_ef and last_ge_pulse:\n delays = np.array(delay_times)\n params_to_sweep.update({f'delayed_pulse_{qbn}.pulse_delay': delays})\n else:\n delays = np.array(delay_times) + pulse_list[-1][\"pulse_delay\"]\n params_to_sweep.update({f'delayed_pulse.pulse_delay': delays})\n\n swept_pulses = sweep_pulse_params(pulse_list, params_to_sweep)\n swept_pulses_with_prep = \\\n [add_preparation_pulses(p, operation_dict, qubit_names, **prep_params)\n for p in swept_pulses]\n seq = pulse_list_list_seq(swept_pulses_with_prep, seq_name, upload=False)\n\n # add calibration segments\n seq.extend(cal_points.create_segments(operation_dict, **prep_params))\n\n # reuse sequencer memory by repeating readout pattern\n [seq.repeat_ro(f\"RO {qbn}\", operation_dict) for qbn in qubit_names]\n\n log.debug(seq)\n if upload:\n ps.Pulsar.get_instance().program_awgs(seq)\n\n return seq, np.arange(seq.n_acq_elements())\n\n\ndef n_qubit_echo_seq(qubit_names, operation_dict, sweep_points, cal_points,\n artificial_detuning=0, upload=True, for_ef=False,\n last_ge_pulse=False, prep_params=dict()):\n '''\n Echo sequence for n qubits.\n Args:\n qubit_names: list of qubit names\n operation_dict: operation_dict for all qubit in qubit_names\n sweep_points: instance of SweepPoints class\n cal_points: instance of CalibrationPoints class\n artificial_detunings: Detuning of second pi-half pulse.\n upload: whether to upload sequence to instrument or not\n n: number of pulses (1 is conventional Rabi)\n for_ef: whether to do rabi between ef transition\n last_ge_pulse: whether to use a ge pulse at the end of each segment\n for a rabi between ef transition\n prep_params: qubit preparation params\n Returns:\n sequence (Sequence): sequence object\n segment_indices (list): array of range of n_segments including\n calibration_segments. To be used as sweep_points for the MC.\n '''\n\n seq_name = 'n_qubit_Ramsey_sequence'\n\n pulse_list = []\n # add Echo segments\n for qbn in qubit_names:\n echo_ops = [\"X90_ef \" + qbn if for_ef else \"X90 \" + qbn]\n echo_ops = echo_ops + \\\n [\"X180_ef \" + qbn if for_ef else \"X180 \" + qbn] + \\\n echo_ops\n if for_ef:\n echo_ops = [\"X180 \" + qbn] + echo_ops # prepend ge pulse\n if last_ge_pulse:\n echo_ops += [\"X180 \" + qbn] # append ge pulse\n\n echo_ops = [deepcopy(operation_dict[op]) for op in echo_ops]\n echo_ops[0]['ref_pulse'] = 'segment_start'\n echo_ops[2 if for_ef else 1][\"name\"] = f\"Echo_pi_{qbn}\"\n echo_ops[2 if for_ef else 1][\"ref_point\"] = 'start'\n echo_ops[3 if for_ef else 2][\"name\"] = f\"Echo_pihalf_{qbn}\"\n echo_ops[3 if for_ef else 2][\"ref_point\"] = 'start'\n\n pulse_list += echo_ops\n pulse_list += generate_mux_ro_pulse_list(qubit_names, operation_dict)\n\n params_to_sweep = {}\n for j, qbn in enumerate(qubit_names):\n times = list(sweep_points[0].values())[j][0]\n params_to_sweep.update({f'Echo_pi_{qbn}.pulse_delay': times/2})\n params_to_sweep.update({f'Echo_pihalf_{qbn}.pulse_delay': times/2})\n params_to_sweep.update({\n f'Echo_pihalf_{qbn}.phase':\n ((times-times[0])*artificial_detuning*360) % 360})\n swept_pulses = sweep_pulse_params(pulse_list, params_to_sweep)\n swept_pulses_with_prep = \\\n [add_preparation_pulses(p, operation_dict, qubit_names, **prep_params)\n for p in swept_pulses]\n seq = pulse_list_list_seq(swept_pulses_with_prep, seq_name, upload=False)\n\n # add calibration segments\n seq.extend(cal_points.create_segments(operation_dict, **prep_params))\n\n # reuse sequencer memory by repeating readout pattern\n [seq.repeat_ro(f\"RO {qbn}\", operation_dict) for qbn in qubit_names]\n\n log.debug(seq)\n if upload:\n ps.Pulsar.get_instance().program_awgs(seq)\n\n return seq, np.arange(seq.n_acq_elements())\n", "\"\"\"\nTools to for cryoscope analysis\nBrian Tarasinski\nDec 2017\nEdited by Adriaan Rol\n\"\"\"\nfrom typing import Union\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker\nfrom pycqed.analysis.tools.plotting import (set_xlabel, set_ylabel,\n flex_colormesh_plot_vs_xy)\n\nimport scipy.signal as ss\nimport scipy.optimize as so\nimport scipy.interpolate as si\n\n\ndef normalize_sincos(\n data,\n window_size_frac=500,\n window_size=None,\n do_envelope=True):\n\n if window_size is None:\n window_size = len(data) // window_size_frac\n\n # window size for savgol filter must be odd\n window_size -= (window_size + 1) % 2\n\n mean_data_r = ss.savgol_filter(data.real, window_size, 0, 0)\n mean_data_i = ss.savgol_filter(data.imag, window_size, 0, 0)\n\n mean_data = mean_data_r + 1j * mean_data_i\n\n if do_envelope:\n envelope = np.sqrt(\n ss.savgol_filter(\n (np.abs(\n data -\n mean_data))**2,\n window_size,\n 0,\n 0))\n else:\n envelope = 1\n norm_data = ((data - mean_data) / envelope)\n return norm_data\n\n\ndef fft_based_freq_guess_complex(y):\n \"\"\"\n guess the shape of a sinusoidal complex signal y (in multiples of\n sampling rate), by selecting the peak in the fft.\n return guess (f, ph, off, amp) for the model\n y = amp*exp(2pi i f t + ph) + off.\n \"\"\"\n fft = np.fft.fft(y)[1:len(y)]\n freq_guess_idx = np.argmax(np.abs(fft))\n if freq_guess_idx >= len(y) // 2:\n freq_guess_idx -= len(y)\n freq_guess = 1 / len(y) * (freq_guess_idx + 1)\n\n phase_guess = np.angle(fft[freq_guess_idx]) + np.pi / 2\n amp_guess = np.absolute(fft[freq_guess_idx]) / len(y)\n offset_guess = np.mean(y)\n\n return freq_guess, phase_guess, offset_guess, amp_guess\n\n\nclass CryoscopeAnalyzer:\n def __init__(\n self,\n time,\n complex_data,\n norm_window_size=61,\n demod_freq=None,\n derivative_window_length=None,\n derivative_order=2,\n nyquist_order=0,\n demod_smooth=None):\n \"\"\"\n analyse a cryoscope measurement.\n\n time: array of times (lengths of Z pulse)\n complex_data: measured data, combine x- and y- results in a\n complex number\n\n norm_window_size: window size used for normalizing sine and cosine\n\n demod_freq: frequency for demodulation. Is guessed if None.\n\n derivative_window_length, derivative_order: parameters of the sovgol\n filter used for extracting frequency.\n Needs some playing around sometimes.\n\n demod_smooth: when the demodulated signal should be smoothed before\n taking derivative, set this to a tuple (window_length, order),\n again parametrizing a sovgol filter.\n\n \"\"\"\n self.time = time\n self.data = complex_data\n self.norm_data = normalize_sincos(self.data, window_size=61)\n self.demod_freq = demod_freq\n self.derivative_window_length = derivative_window_length\n self.demod_smooth = demod_smooth\n self.nyquist_order = nyquist_order\n\n self.sampling_rate = 1 / (self.time[1] - self.time[0])\n\n if self.derivative_window_length is None:\n self.derivative_window_length = 7 / self.sampling_rate\n\n self.derivative_window_size = max(\n 3, int(self.derivative_window_length * self.sampling_rate))\n self.derivative_window_size += (self.derivative_window_size + 1) % 2\n\n if self.demod_freq is None:\n self.demod_freq = - \\\n fft_based_freq_guess_complex(self.norm_data)[\n 0] * self.sampling_rate\n\n self.demod_data = np.exp(\n 2 * np.pi * 1j * self.time * self.demod_freq) * self.norm_data\n\n if self.demod_smooth:\n n, o = self.demod_smooth\n r, i = self.demod_data.real, self.demod_data.imag\n r = ss.savgol_filter(r, n, o, 0)\n i = ss.savgol_filter(i, n, o, 0)\n self.demod_data = r + 1j * i\n\n # extract the phase. unwrapping only works well if demodulation is\n # good!\n self.phase = np.unwrap(np.angle(self.demod_data))\n\n # extract frequency by a lowpass-derivative filter.\n\n # use a savitzky golay filter: it take sliding window of length\n # `window_length`, fits a polynomial, returns derivative at\n # middle point\n self.detuning = ss.savgol_filter(\n self.phase / (\n 2 * np.pi),\n window_length=self.derivative_window_size,\n polyorder=derivative_order,\n deriv=1) * self.sampling_rate\n self.real_detuning = self.get_real_detuning(self.nyquist_order)\n\n def get_real_detuning(self, nyquist_order=None):\n if nyquist_order is None:\n nyquist_order = self.nyquist_order\n\n real_detuning = self.detuning-self.demod_freq+self.sampling_rate*nyquist_order\n return real_detuning\n\n def get_amplitudes(self):\n \"\"\"\n Converts the real detuning to amplitude\n \"\"\"\n real_detuning = self.get_real_detuning()\n if hasattr(self, 'freq_to_amp'):\n\n amplitudes = self.freq_to_amp(real_detuning)\n return amplitudes\n else:\n raise NotImplementedError('Add a \"freq_to_amp\" method.')\n\n def plot_short_time_fft(self, ax=None,\n title='Short time Fourier Transform',\n window_size=100, **kw):\n\n if ax is None:\n ax = plt.gca()\n ax.set_title(title)\n\n f, t, Zxx = ss.stft(self.norm_data, fs=self.sampling_rate,\n nperseg=window_size,\n noverlap=0.95 * window_size, return_onesided=False)\n m = np.argsort(f)\n ax.pcolormesh(self.time[0] + t, f[m], np.abs(Zxx)[m, :])\n ax.set_ylabel('Frequency')\n ax.set_xlabel('Time')\n\n formatter = matplotlib.ticker.EngFormatter(unit='s')\n ax.xaxis.set_major_formatter(formatter)\n formatter = matplotlib.ticker.EngFormatter(unit='Hz')\n ax.yaxis.set_major_formatter(formatter)\n\n def plot_raw_data(self, ax=None, title=\"Raw cryoscope data\",\n style=\".-\", **kw):\n if ax is None:\n ax = plt.gca()\n ax.set_title(title)\n ax.plot(self.time, self.data.real, style, label=\"Re\", color=\"C0\")\n ax.plot(self.time, self.data.imag, style, label=\"Im\", color=\"C1\")\n ax.legend()\n set_xlabel(ax, 'Time', 's')\n set_ylabel(ax, \"Amplitude\", 'a.u.')\n\n def plot_normalized_data(self, ax=None, title='Normalized cryoscope data',\n style=\".-\", **kw):\n if ax is None:\n ax = plt.gca()\n ax.set_title(title)\n\n ax.plot(\n self.time,\n self.norm_data.real,\n style,\n label=\"Re\",\n color=\"C0\")\n ax.plot(self.time, self.norm_data.imag, style, label=\"Im\", color=\"C1\")\n ax.legend()\n ax.set_xlabel(\"Time\")\n ax.set_ylabel(\"Amplitude\")\n formatter = matplotlib.ticker.EngFormatter(unit='s')\n ax.xaxis.set_major_formatter(formatter)\n\n def plot_demodulated_data(self, ax=None,\n title='Demodulated cryoscope data',\n style=\".-\", **kw):\n if ax is None:\n ax = plt.gca()\n ax.set_title(title)\n ax.plot(\n self.time,\n self.demod_data.real,\n style,\n label=\"Re\",\n color=\"C0\")\n ax.plot(\n self.time,\n self.demod_data.imag,\n style,\n label=\"Im\",\n color=\"C1\")\n ax.legend()\n ax.set_xlabel(\"Time\")\n ax.set_ylabel(\"Amplitude\")\n formatter = matplotlib.ticker.EngFormatter(unit='s')\n ax.xaxis.set_major_formatter(formatter)\n\n def plot_normalized_data_circle(self, ax=None,\n title='Normalized cryoscope data', **kw):\n if ax is None:\n ax = plt.gca()\n ax.set_title(title)\n ax.set_xlabel(\"Re\")\n ax.set_ylabel(\"Im\")\n ax.plot(self.norm_data.real, self.norm_data.imag, \".\")\n\n def plot_phase(self, ax=None, title=\"Cryoscope demodulated phase\",\n wrap=False, **kw):\n if ax is None:\n ax = plt.gca()\n ax.set_title(title)\n if wrap:\n ax.plot(self.time, self.phase % (2 * np.pi), \".\", color=\"C0\")\n else:\n ax.plot(self.time, self.phase, \".\", label=\"Im\", color=\"C0\")\n set_xlabel(ax, 'Time', 's')\n set_ylabel(ax, 'Phase', 'deg')\n\n def plot_detuning(self, ax=None,\n title=\"Detuning from demodulation frequency\", **kw):\n if ax is None:\n ax = plt.gca()\n ax.set_title(title)\n ax.plot(self.time, self.detuning, \".-\", color=\"C0\")\n set_xlabel(ax, 'Time', 's')\n set_ylabel(ax, 'Frequency', 'Hz')\n\n def plot_frequency(self, ax=None, title='Detuning frequency',\n nyquists=None, style=\".-\", show_demod_freq=True, **kw):\n if ax is None:\n ax = plt.gca()\n ax.set_title(title)\n\n if nyquists is None:\n nyquists = [self.nyquist_order]\n for n in nyquists:\n if show_demod_freq:\n ax.axhline(-self.demod_freq + self.sampling_rate *\n n, linestyle='--', c='grey')\n real_detuning = self.get_real_detuning(n)\n ax.plot(self.time, real_detuning, style)\n set_xlabel(ax, 'Time', 's')\n set_ylabel(ax, 'Frequency', 'Hz')\n\n def plot_amplitude(self, ax=None, title='Cryoscope amplitude',\n nyquists=None, style=\".-\", **kw):\n if ax is None:\n ax = plt.gca()\n ax.set_title(title)\n amp = self.get_amplitudes()\n ax.plot(self.time, amp, style)\n set_xlabel(ax, 'Time', 's')\n set_ylabel(ax, 'Amplitude', 'V')\n\n\ndef sincos_model_real_imag(times, freq, phase):\n r, i = np.cos(2 *\n np.pi *\n times *\n freq +\n phase), np.sin(2 *\n np.pi *\n times *\n freq +\n phase)\n return np.hstack((r, i))\n\n\nclass DacArchAnalysis:\n \"\"\"\n Given cryscope time series from a square region in time and amplitude,\n fit complex oscillations to obtain a dac arch. Tries to be smart about\n supersampled signals, after constructing the arc, fits a polynomial\n in order to facilitate interpolation.\n \"\"\"\n\n def __init__(\n self,\n times,\n amps,\n data,\n exclusion_indices=[],\n poly_fit_order=2,\n nyquist_calc='auto',\n invert_frequency_sign=False,\n plot_fits=False):\n \"\"\"\n Extract a dac arch from a set of cryoscope-style measurements.\n\n times: array of pulse lengths\n amps: array of pulse amplitudes\n\n data: 2D array of measurement results (size of len(times x amps)).\n Complex numbers containing x- and y- values\n\n poly_fit_order: order of model used for fitting the dac-arch\n\n invert_frequency_sign: boolean. might be useful if x and y are\n interchanged in measurement\n\n plot_fits: plots how the fit is going, for display.\n \"\"\"\n self.data = data\n self.times = times\n self.amps = np.array(amps)\n\n self.poly_fit_order = poly_fit_order\n\n self.sampling_rate = 1 / (self.times[1] - self.times[0])\n\n self.freqs = []\n self.excl_amps = []\n self.excl_freqs = []\n self.exclusion_indices = exclusion_indices\n\n self.norm_data = []\n\n for d in self.data:\n self.norm_data.append(normalize_sincos(d, window_size=11))\n\n self.norm_data = np.array(self.norm_data)\n\n for nd in self.norm_data:\n guess_f, guess_ph, *_ = fft_based_freq_guess_complex(nd)\n guess_f *= self.sampling_rate\n\n nd_real_imag = np.hstack([nd.real, nd.imag])\n\n fit, err = so.curve_fit(sincos_model_real_imag,\n self.times, nd_real_imag,\n p0=[guess_f, guess_ph])\n\n if plot_fits:\n plt.figure()\n plt.plot(self.times, nd.real, \"-.b\")\n plt.plot(self.times, nd.imag, \".-r\")\n\n tt = np.linspace(self.times[0], self.times[-1], 300)\n plt.plot(tt, sincos_model_real_imag(tt, *fit)[:len(tt)], \"--b\")\n plt.plot(tt, sincos_model_real_imag(tt, *fit)[len(tt):], \"--r\")\n\n self.freqs.append(fit[0])\n\n self.freqs = np.array(self.freqs)\n if nyquist_calc == 'auto':\n self.nyquist = np.cumsum(self.freqs[1:] < self.freqs[:-1])\n self.nyquist = np.hstack(([0], self.nyquist))\n elif nyquist_calc == 'disabled':\n self.nyquist = np.zeros(len(self.freqs))\n else:\n raise NotImplementedError()\n # FIXME: proper support for auto nyquist with\n # a proper nyquist should be extracte\n\n self.freqs = self.freqs + self.nyquist * self.sampling_rate\n\n if invert_frequency_sign:\n self.freqs = -self.freqs\n\n # Exclude data from excludion indices\n self.filt_freqs = np.delete(self.freqs, self.exclusion_indices)\n self.filt_amps = np.delete(self.amps, self.exclusion_indices)\n self.excl_freqs = self.freqs[self.exclusion_indices]\n self.excl_amps = self.amps[self.exclusion_indices]\n\n self.poly_fit = np.polyfit(self.filt_amps, self.filt_freqs,\n self.poly_fit_order)\n\n self._inv_interpolation = None\n\n def amp_to_freq(self, amp):\n \"\"\"\n Find the frequency that corresponds to a given amplitude by\n evaluating the fit to the extracted data.\n \"\"\"\n return np.polyval(self.poly_fit, amp)\n\n def freq_to_amp(self, freq, kind='root_parabola', **kw):\n \"\"\"\n Find the amplitude that corresponds to a given frequency, by\n numerically inverting the fit.\n\n freq: The frequency or set of frequencies.\n kind: Which technique to use:\n \"interpolate\": Uses numerical interpolation to find the inverse.\n Only works if freq is in the range of measured dac values.\n \"root\": Finds the inverse of the model numerical. Slow, but can\n extrapolate.\n\n **kw : get passed on to methods that implement the different \"kind\"\n of calculations.\n \"\"\"\n\n if kind == 'interpolate':\n if self._inv_interpolation is None:\n no_samples = 50\n self.sampled_amps = np.linspace(\n np.min(\n self.amps), np.max(\n self.amps), no_samples)\n\n self.sampled_freqs = self.amp_to_freq(self.sampled_amps)\n\n self._inv_interpolation = si.interp1d(\n self.sampled_freqs, self.sampled_amps, kind='cubic',\n bounds_error=False,\n fill_value='extrapolate')\n return self._inv_interpolation(freq)\n if kind == 'root':\n return np.vectorize(self._freq_to_amp_root)(freq)\n\n if kind == 'root_parabola':\n # return self._freq_to_amp_root_parabola(freq, **kw)\n return freq_to_amp_root_parabola(freq=freq,\n poly_coeffs=self.poly_fit, **kw)\n\n raise ValueError(\"`kind` not understood\")\n\n # def _freq_to_amp_root_parabola(self, freq, positive_branch=True):\n # \"\"\"\n # Converts freq in Hz to amplitude.\n\n # Requires \"poly_fit\" to be set to the polynomial values\n # extracted from the cryoscope flux arc.\n\n # Assumes a parabola to find the roots but should also work for a higher\n # order polynomial, except that it will pick the wrong branch.\n\n # N.B. this method assumes that the polycoeffs are with respect to the\n # amplitude in units of V.\n # \"\"\"\n\n # # recursive allows dealing with an array of freqs\n # if isinstance(freq, (list, np.ndarray)):\n # return np.array([self._freq_to_amp_root_parabola(\n # f, positive_branch=positive_branch) for f in freq])\n\n # p = np.poly1d(self.poly_fit)\n # sols = (p-freq).roots\n\n # # sols returns 2 solutions (for a 2nd order polynomial)\n # if positive_branch:\n # sol = np.max(sols)\n # else:\n # sol = np.min(sols)\n\n # # imaginary part is ignored, instead sticking to closest real value\n # return np.real(sol)\n\n def _freq_to_amp_root(self, freq):\n \"\"\"\n Find the amplitude corresponding to a given frequency by numerically\n inverting the fit.\n \"\"\"\n\n poly = np.array(self.poly_fit)\n poly[-1] -= freq\n\n roots = np.roots(poly)\n\n # return the solution that is real and closest to the givenamp range\n\n real_mask = np.abs(roots.imag) < 1e-8\n\n if not any(real_mask):\n return None\n\n dist_from_range = np.abs(roots[real_mask] - np.mean(self.amps))\n\n return roots[real_mask][np.argmin(dist_from_range)].real\n\n def plot_freqs(self, ax=None, title='', **kw):\n if ax is None:\n ax = plt.gca()\n ax.set_title(title)\n\n amps_sorted = [x for x, _ in sorted(\n zip(self.filt_amps, self.filt_freqs))]\n freqs_sorted = [y for _, y in sorted(\n zip(self.filt_amps, self.filt_freqs))]\n\n ax.plot(amps_sorted, freqs_sorted, \".-\")\n ax.scatter(self.excl_amps, self.excl_freqs, marker='x', color='C3')\n aa = np.linspace(min(self.amps), max(self.amps), 50)\n ax.plot(aa, np.polyval(self.poly_fit, aa), label='fit')\n set_xlabel(ax, \"Amplitude\", 'V')\n set_ylabel(ax, 'Detuning', 'Hz')\n\n def plot_ffts(self, ax=None, title='', nyquist_unwrap=False, **kw):\n if ax is None:\n ax = plt.gca()\n if nyquist_unwrap:\n raise NotImplementedError\n ax.set_title(title)\n ffts = np.fft.fft(self.norm_data)\n\n freqs = np.arange(len(ffts[0])) * self.sampling_rate / len(ffts[0])\n\n flex_colormesh_plot_vs_xy(xvals=np.array(self.amps), yvals=freqs,\n zvals=np.abs(ffts).T,\n ax=ax)\n\n ax.scatter(self.filt_amps, self.filt_freqs % self.sampling_rate, color=\"C1\",\n facecolors='none', label='Dominant freqs.')\n\n ax.scatter(self.excl_amps, self.excl_freqs % self.sampling_rate,\n color=\"C3\",\n marker='x')\n aa = np.linspace(min(self.amps), max(self.amps), 300)\n\n ax.plot(aa, np.polyval(self.poly_fit, aa) % self.sampling_rate, \"r\",\n label='fit')\n set_xlabel(ax, \"Amplitude\", 'V') # a.u.\n set_ylabel(ax, 'Detuning', 'Hz')\n ax.legend()\n\n\ndef freq_to_amp_root_parabola(freq, poly_coeffs, positive_branch=True):\n \"\"\"\n Converts freq in Hz to amplitude in V.\n\n Requires \"poly_coeffs\" to be set to the polynomial values\n extracted from the cryoscope flux arc.\n\n Assumes a parabola to find the roots but should also work for a higher\n order polynomial, except that it will pick the wrong branch.\n\n N.B. this method assumes that the polycoeffs are with respect to the\n amplitude in units of V.\n \"\"\"\n # recursive allows dealing with an array of freqs\n if isinstance(freq, (list, np.ndarray)):\n return np.array([freq_to_amp_root_parabola(\n freq=f, poly_coeffs=poly_coeffs,\n positive_branch=positive_branch) for f in freq])\n\n p = np.poly1d(poly_coeffs)\n sols = (p-freq).roots\n\n # sols returns 2 solutions (for a 2nd order polynomial)\n if positive_branch:\n sol = np.max(sols)\n else:\n sol = np.min(sols)\n\n # imaginary part is ignored, instead sticking to closest real value\n return np.real(sol)\n" ]
[ [ "numpy.savetxt", "numpy.array", "numpy.sum" ], [ "numpy.imag", "numpy.reshape", "numpy.arange", "numpy.eye", "numpy.sin", "numpy.ndim", "numpy.ones", "numpy.real", "numpy.any", "numpy.ravel", "numpy.array", "numpy.zeros", "numpy.sum" ], [ "numpy.polyfit", "numpy.poly1d", "numpy.linspace", "scipy.signal.stft", "numpy.cumsum", "matplotlib.pyplot.plot", "numpy.max", "numpy.mean", "numpy.argmin", "numpy.exp", "numpy.polyval", "scipy.signal.savgol_filter", "scipy.optimize.curve_fit", "numpy.hstack", "matplotlib.pyplot.gca", "numpy.sin", "numpy.roots", "numpy.real", "scipy.interpolate.interp1d", "matplotlib.pyplot.figure", "numpy.min", "numpy.delete", "numpy.argsort", "numpy.array", "numpy.absolute", "numpy.abs", "numpy.fft.fft", "numpy.cos", "numpy.vectorize", "numpy.angle" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.10", "1.4", "1.3", "1.9", "0.19", "1.5", "1.7", "1.0", "1.2", "1.8" ], "tensorflow": [] } ]
PeterXingke/HugeCTR
[ "d7552c4c5f93ff18ded961645cac82d5d8b5b785" ]
[ "sparse_operation_kit/unit_test/test_scripts/tf2/test_sparse_emb_demo_model_multi_worker.py" ]
[ "\"\"\"\n Copyright (c) 2021, NVIDIA 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\nimport argparse\n\nimport sys, os\nsys.path.append(os.path.abspath(os.path.join(\n os.path.dirname(os.path.abspath(__file__)), r\"../../../\")))\nimport sparse_operation_kit as sok\nimport tensorflow as tf\n\nimport numpy as np\nimport os, json\nimport pickle\nimport utils\n\nfrom test_sparse_emb_demo_model_single_worker import SOKDemo, test_tf_demo, check_saved_embedding_variables\n\ndef test_sok_demo(args, init_tensors, *random_samples):\n port = 12345\n os.environ[\"TF_CONFIG\"] = json.dumps({\n 'cluster': {\"worker\": [args.ips[i] + \":\" + str(port + i) for i in range(args.worker_num)] },\n 'task': {\"type\": 'worker', \"index\": args.task_id}\n })\n strategy = tf.distribute.MultiWorkerMirroredStrategy()\n with strategy.scope():\n result = sok.Init(global_batch_size=args.global_batch_size)\n\n plugin_demo = SOKDemo(combiner=args.combiner, \n max_vocabulary_size_per_gpu=args.max_vocabulary_size_per_gpu,\n slot_num=args.slot_num, max_nnz=args.max_nnz,\n embedding_vec_size=args.embedding_vec_size)\n\n emb_opt = utils.get_embedding_optimizer(args.optimizer)(learning_rate=0.1)\n dense_opt = utils.get_dense_optimizer(args.optimizer)(learning_rate=0.1)\n\n plugin_saver = sok.Saver()\n if (1 == args.restore_params):\n filepath = r\"./embedding_variables\"\n plugin_saver.restore_from_file(plugin_demo.embedding_layer.embedding_variable, filepath)\n else:\n status = plugin_saver.load_embedding_values(plugin_demo.embedding_layer.embedding_variable, init_tensors)\n\n loss_fn = tf.keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)\n def _replica_loss(labels, logits):\n loss = loss_fn(labels, logits)\n return tf.nn.compute_average_loss(loss, global_batch_size=args.global_batch_size)\n\n @tf.function\n def _train_step(inputs, labels):\n with tf.GradientTape() as tape:\n logit, embedding_vector = plugin_demo(inputs, training=True)\n loss = _replica_loss(labels, logit)\n embedding_variables, other_variable = sok.split_embedding_variable_from_others(plugin_demo.trainable_variables)\n grads, emb_grads = tape.gradient(loss, [other_variable, embedding_variables])\n if \"plugin\" not in args.optimizer:\n with sok.OptimizerScope(embedding_variables):\n emb_opt.apply_gradients(zip(emb_grads, embedding_variables),\n experimental_aggregate_gradients=False)\n else:\n emb_opt.apply_gradients(zip(emb_grads, embedding_variables),\n experimental_aggregate_gradients=False)\n dense_opt.apply_gradients(zip(grads, other_variable))\n return logit, embedding_vector\n\n sok_results = list()\n\n def _dataset_fn(input_context):\n replica_batch_size = input_context.get_per_replica_batch_size(args.global_batch_size)\n dataset = utils.tf_dataset(*random_samples, batchsize=replica_batch_size, to_sparse_tensor=True, repeat=1)\n # because each worker has its own data source, so that no need to shard the dataset.\n return dataset\n\n dataset = strategy.distribute_datasets_from_function(_dataset_fn)\n\n for i, (sparse_tensors, replica_labels) in enumerate(dataset):\n print(\"-\" * 30, \"step \", str(i), \"-\" * 30)\n logit, embedding_vector = strategy.run(_train_step, args=(sparse_tensors, replica_labels))\n print(\"[INFO]: embedding_vector\\n\", embedding_vector)\n sok_results.append(embedding_vector)\n # FIXME: when the forward computation is too fast, there\n # may exist some conficts with datareader, which cause the program hang.\n import time\n time.sleep(0.2) # seconds\n\n # save params to file.\n if 1 == args.save_params:\n filepath = r\"./embedding_variables/\"\n utils.try_make_dirs(filepath, chief=(True if args.task_id == 0 else False))\n\n plugin_saver.dump_to_file(plugin_demo.embedding_layer.embedding_variable, filepath)\n\n return sok_results, plugin_demo.embedding_layer.embedding_variable.values[0].m_var_name\n\ndef compare_sok_with_tf(args):\n if (args.global_batch_size % args.local_gpu_num != 0):\n raise ValueError(\"global_batch_size: %d is not divisible by local_gpu_num: %d\"\n %(args.global_batch_size, args.local_gpu_num))\n if (args.global_batch_size % args.worker_num != 0):\n raise ValueError(\"global_batch_size: %d is not divisible by worker_num: %d\"\n %(args.global_batch_size, args.worker_num))\n\n # each worker generate different dataset\n if args.generate_new_datas:\n worker_batch_size = args.global_batch_size // args.worker_num\n random_samples_local = utils.generate_random_samples(num_of_samples=worker_batch_size * args.iter_num,\n vocabulary_size=args.local_gpu_num * args.max_vocabulary_size_per_gpu * args.worker_num,\n slot_num=args.slot_num,\n max_nnz=args.max_nnz)\n utils.save_to_file(r\"./random_samples_\" + str(args.task_id) + r\".file\", *random_samples_local)\n else:\n random_samples_local = utils.restore_from_file(r\"./random_samples_\" + str(args.task_id) + r\".file\")\n\n if (0 == args.restore_params):\n # each worker generate same init tensors, because each worker will do the filtering by itself.\n init_tensors = utils.get_ones_tensor(max_vocab_size_per_gpu=args.max_vocabulary_size_per_gpu,\n embedding_vec_size=args.embedding_vec_size,\n num=args.local_gpu_num * args.worker_num)\n else:\n filepath = r\"./embedding_variables\"\n tf_values_filename = os.path.join(filepath, r\"tf_variable.file\")\n init_tensors = utils.restore_from_file(tf_values_filename)\n\n sok_results_local, embedding_variable_name = test_sok_demo(args, init_tensors, *random_samples_local)\n # save the forward embedding vector from different worker to file\n utils.save_to_file(r\"./sok_embedding_vectors_\" + str(args.task_id) + r\".file\", *sok_results_local)\n\n # aggregate dataset from different worker\n dataset_filenames = [r\"./random_samples_\" + str(task_id) + r\".file\"\n for task_id in range(args.worker_num)]\n random_samples_total = [list() for _ in range(args.iter_num)]\n random_labels_total = [list() for _ in range(args.iter_num)]\n local_batch_size = args.global_batch_size // args.worker_num\n for work_id in range(args.worker_num):\n samples, labels = utils.restore_from_file(dataset_filenames[work_id])\n for i in range(args.iter_num):\n random_samples_total[i].extend(samples[i * local_batch_size : (i + 1) * local_batch_size])\n random_labels_total[i].extend(labels[i * local_batch_size : (i + 1) * local_batch_size])\n random_samples_total = np.concatenate(random_samples_total, axis=0)\n random_labels_total = np.concatenate(random_labels_total, axis=0)\n\n tf_results = test_tf_demo(args, init_tensors, random_samples_total, random_labels_total)\n\n # aggregate forward embedding vector from different worker\n sok_results_filenames = [r\"./sok_embedding_vectors_\" + str(task_id) + r\".file\"\n for task_id in range(args.worker_num)]\n sok_results_total = list()\n for file_name in sok_results_filenames:\n sok_results_local = utils.restore_from_file(file_name)\n sok_results_total.append(sok_results_local)\n\n if (len(sok_results_total[0]) != len(tf_results)):\n raise ValueError(\"The length of results obtained from sok: %d is not equal to that of tensorflow: %d.\"\n %(len(sok_results_total[0]), len(tf_results)))\n if (len(tf_results) != args.iter_num):\n raise ValueError(\"The length of embedding vectors: %d is not equal to iteration number: %d.\"\n %(len(tf_results), args.iter_num))\n\n # for i, sok_vector in enumerate(sok_results_total):\n for i in range(args.iter_num):\n if args.local_gpu_num != 1:\n sok_vector = tf.concat([tf.concat(sok_results_total[task_id][i].values, axis=0)\n for task_id in range(args.worker_num)], axis=0)\n else:\n sok_vector = tf.concat([sok_results_total[task_id][i]\n for task_id in range(args.worker_num)], axis=0)\n tf.debugging.assert_near(tf.reshape(sok_vector, \n shape=[-1, tf.shape(sok_vector)[-1]]),\n tf_results[i],\n atol=1e-4,\n rtol=1e-4)\n\n print(\"\\n[INFO]: With MultiWorkerMirroredStrategy, the embedding vector obtained from \" +\\\n \"sparse operation kit and tensorflow are consistent for %d iterations.\"\n %args.iter_num)\n \n if (1 == args.save_params):\n check_saved_embedding_variables(args, embedding_variable_name)\n\ndef get_task_id(ips):\n local_ip = utils.get_local_ip()\n for i in range(len(ips)):\n if ips[i] == local_ip:\n return i\n raise ValueError(\"Cannot find local_ip: %s in ips list: [%s]\"\n %(local_ip, \", \".join(ips)))\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='test demo model with single worker.')\n parser.add_argument('--local_gpu_num', type=int,\n help='the number of GPUs used to do paralell training.',\n required=False, default=8)\n parser.add_argument('--iter_num', type=int,\n help='the number of testing iterations.',\n required=False, default=100)\n parser.add_argument('--max_vocabulary_size_per_gpu', type=int,\n required=False, default=128)\n parser.add_argument('--slot_num', type=int,\n help='the number of feature fields',\n required=False, default=1)\n parser.add_argument('--max_nnz', type=int,\n help='the maximum number of keys in one slot',\n required=False, default=1)\n parser.add_argument('--embedding_vec_size', type=int,\n help='the dimention of embedding vector',\n required=False, default=1)\n parser.add_argument('--combiner', type=str,\n help='the combiner used to do reduction for sparse embedding layer. ' +\\\n 'It is only respected in sparse embedding layer.',\n required=False, default='mean', choices=['mean', 'sum'])\n parser.add_argument('--global_batch_size', type=int, required=False, default=16)\n parser.add_argument('--optimizer', type=str,\n help=\"use what optimizer\",\n required=False, default='plugin_adam',\n choices=['plugin_adam', 'adam', 'sgd'])\n parser.add_argument('--ips', type=str, nargs=\"+\",\n help=\"the ip address of each worker.\",\n required=False, default=\"0.0.0.0\")\n parser.add_argument('--generate_new_datas', type=int, choices=[0, 1],\n help='whether to generate new random samples',\n required=False, default=1)\n parser.add_argument('--save_params', type=int, choices=[0, 1],\n help='whether to save the trained parameters.',\n required=False, default=0)\n parser.add_argument('--restore_params', type=int, choices=[0, 1],\n help='whether to restore from saved files. '+\\\n 'By default, the testing program will generate random ' +\\\n 'initial value to initialize trainable parameters '+\\\n 'rather than restore trainable parameters from file.',\n required=False, default=0)\n args = parser.parse_args()\n\n if not isinstance(args.ips, list):\n args.ips = [args.ips]\n\n args.worker_num = len(args.ips)\n if utils.all_ips_in_local(args.ips):\n processes = list()\n for task_id in range(args.worker_num):\n available_gpus = \",\".join([str(args.local_gpu_num * task_id + i)\n for i in range(args.local_gpu_num)])\n print(\"[INFO]: on task: %d, its available GPUs are: %s\" %(task_id, available_gpus))\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = available_gpus\n process = utils.TestProcess(func=compare_sok_with_tf, task_id=task_id, arguments=args)\n process.start()\n processes.append(process)\n\n for process in processes:\n process.join()\n else:\n args.task_id = get_task_id(args.ips)\n\n os.environ['CUDA_VISIBLE_DEVICES'] = \",\".join([str(i) for i in range(args.local_gpu_num)])\n\n compare_sok_with_tf(args)\n \n \n " ]
[ [ "tensorflow.nn.compute_average_loss", "tensorflow.concat", "tensorflow.shape", "tensorflow.keras.losses.BinaryCrossentropy", "numpy.concatenate", "tensorflow.distribute.MultiWorkerMirroredStrategy", "tensorflow.GradientTape" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] } ]
avpak/okama
[ "b3c4f6b7dfcc314d3171f20b3bc95cfa04268c1a" ]
[ "tests/test_frontier.py" ]
[ "import pytest\nfrom pytest import approx\nfrom pytest import mark\n\nimport numpy as np\nfrom numpy.testing import assert_allclose\n\nfrom okama import EfficientFrontier\n\n\[email protected]\ndef test_init_efficient_frontier():\n with pytest.raises(Exception, match=r'The number of symbols cannot be less than two'):\n EfficientFrontier(symbols=['MCFTR.INDX'])\n\n\[email protected]\ndef test_bounds_setter_failing(init_efficient_frontier):\n with pytest.raises(Exception, match=r'The number of symbols \\(2\\) and the length of bounds \\(3\\) should be equal.'):\n init_efficient_frontier.bounds = ((0, 1.), (0.5, 1.), (0, 0.5))\n\n\[email protected]\ndef test_gmv(init_efficient_frontier):\n assert_allclose(init_efficient_frontier.gmv_weights, np.array([0.67501259, 0.32498741]), rtol=1e-2, atol=1e-2)\n\n\[email protected]\ndef test_gmv_monthly(init_efficient_frontier):\n assert init_efficient_frontier.gmv_monthly[0] == approx(0.026076618401825784, rel=1e-2)\n\n\[email protected]\ndef test_gmv_annualized(init_efficient_frontier):\n assert init_efficient_frontier.gmv_annualized[0] == approx(0.10198459385117883, rel=1e-2)\n\n\[email protected]\ndef test_optimize_return(init_efficient_frontier):\n assert init_efficient_frontier.optimize_return(option='max')['Mean_return_monthly'] == approx(0.015324, rel=1e-2)\n assert init_efficient_frontier.optimize_return(option='min')['Mean_return_monthly'] == approx(0.008803, rel=1e-2)\n\n\[email protected]\ndef test_minimize_risk(init_efficient_frontier):\n assert init_efficient_frontier.minimize_risk(target_return=0.015324, monthly_return=True)['SBMX.MOEX'] == approx(1, rel=1e-2)\n assert init_efficient_frontier.minimize_risk(target_return=0.139241, monthly_return=False)['SBMX.MOEX'] == approx(0.32498, rel=1e-2)\n\n\[email protected]\ndef test_minimize_risk_bounds(init_efficient_frontier_bounds):\n assert init_efficient_frontier_bounds.minimize_risk(target_return=0.015324, monthly_return=True)['SBMX.MOEX'] == approx(1, rel=1e-2)\n assert init_efficient_frontier_bounds.minimize_risk(target_return=0.1548, monthly_return=False)['SBMX.MOEX'] == approx(0.50030, rel=1e-2)\n\n\[email protected]\ndef test_mean_return_range(init_efficient_frontier):\n assert_allclose(init_efficient_frontier.mean_return_range, np.array([0.008803, 0.015325]), rtol=1e-2)\n\n\[email protected]\ndef test_mean_return_range_bounds(init_efficient_frontier_bounds):\n assert_allclose(init_efficient_frontier_bounds.mean_return_range, np.array([0.012064, 0.015325]), rtol=1e-2)\n\n\[email protected]\ndef test_ef_points(init_efficient_frontier):\n assert init_efficient_frontier.ef_points['Mean return'].iloc[-1] == approx(0.20007879286573038, rel=1e-2)\n\n\n\n\n\n\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
KKanda900/Model-Maker
[ "e73c6e1d47b9682657694e4f56ee96a34e3a29ea" ]
[ "Multi_Classification/Multi_Image_Classification.py" ]
[ "# Primary Python Files for Image Classification\nimport numpy as np \nimport pandas as pd \nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # dont show any tensorflow warning messages\nimport cv2\n\n# Keras libraries used for making the model and tensorflow\nimport tensorflow, keras\nfrom tensorflow.keras.utils import to_categorical\nfrom keras.layers import Dense,Conv2D,Flatten,MaxPool2D,Dropout\nfrom keras.models import Sequential\n\n# Sklearn library for splitting the data precisely\nfrom sklearn.model_selection import train_test_split\n\n'''\nMulti_Image_Classification Class\n\nDescription: \n1. Identify different sets of images based on the labels you provide.\n2. Works based off a sequential model.\n3. Uses a Convolutional Neural Network.\n'''\nclass Multi_Image_Classification:\n\n # ------------------------------ Generic Fields Needed for Training ---------------------------------- #\n shape = (200,200) # predefine a established shape for training and resizing the images (default)\n labels = [] # define the labels to train on\n \n # --------------------------- Training Tools ---------------------------------- #\n train_path = './Multi_Classification/train' # define the path where the training images are located\n train_labels = None # define the labels (same as testing)\n train_images = None # define the images with the training \n x_train = None # split the training images for training\n y_train = None # split the training labels for training\n \n # ------------------------- Testing Tools -------------------------------------- #\n test_path = './Multi_Classification/test' # define the path where the testing images are located\n x_val = None # split the training images for testing\n y_val = None # split the training labels for testing\n test_labels = None # define the testing labels (same as training)\n test_images = None # define the testing images \n \n # ----------------------------------- Main Model Tools ------------------------------- #\n epoch = 50 # default epoch \n batch_size = 10 # default batch size\n model = None # define the model (Sequential for Image Classification)\n\n # ------------------------- Define the Functions for Making the model ---------------------- #\n\n # define the labels and images depending on the directory path\n def set_data(self, directory_path):\n data_labels = [] # define the set of labels according to the name of the file\n data_images = [] # define the images\n \n # iterate through all the images in the directory\n for filename in os.listdir(directory_path): \n # Get the values of the images at the directory path\n img = cv2.imread(os.path.join(directory_path, filename))\n # Spliting file names and storing the labels for image in list\n data_labels.append(filename.split('_')[0])\n # Resize all images to a specific shape\n img = cv2.resize(img, self.shape)\n data_images.append(img) # append the image\n \n data_labels = pd.get_dummies(data_labels).values # Get the categorical data\n data_images = np.array(data_images) # Define the image array as a np array for fitting\n\n return data_labels, data_images # return the labels, images for the specific directory\n\n # define the tools for utilzing on creation of the object\n def __init__(self, create_model, labels, shape, epoch, batch_size):\n np.random.seed(1) # sets the random seed of the NumPy pseudo-random number generator\n\n self.shape = shape # let the user enter the shape of the images to be formed (default 200x200)\n\n # let the user define the labels for their model they want to create\n self.labels = labels # default values\n\n # define the training images and labels\n self.train_labels, self.train_images = self.set_data(self.train_path) \n\n # Splitting Training data into train and validation dataset\n self.x_train,self.x_val,self.y_train,self.y_val = train_test_split(self.train_images,self.train_labels,random_state=1)\n \n # define the test labels and images\n self.test_labels, self.test_images = self.set_data(self.test_path)\n \n # define the model for predicition \n if create_model == True:\n self.model = self.create_model(epoch, batch_size, self.x_train, self.y_train, self.x_val, self.y_val)\n\n # create the model to be used for predicition\n def create_model(self, epoch, batch_size, x_train, y_train, x_val, y_val):\n model = Sequential() # define the model as sequential\n \n model.add(Conv2D(kernel_size=(3,3), filters=32, activation='tanh', input_shape=(200,200,3,))) # define the first layer\n model.add(Conv2D(filters=30,kernel_size = (3,3),activation='tanh')) # define the second layer\n model.add(MaxPool2D(2,2)) # define the third layer\n model.add(Conv2D(filters=30,kernel_size = (3,3),activation='tanh')) # define the fourth layer\n model.add(MaxPool2D(2,2)) # define the fifth layer\n model.add(Conv2D(filters=30,kernel_size = (3,3),activation='tanh')) # define the sixth layer\n model.add(Flatten()) # define the seventh layer\n model.add(Dense(20,activation='relu')) # define the eigth layer\n model.add(Dense(15,activation='relu')) # define the ninth layer\n model.add(Dense(len(self.labels),activation = 'softmax')) # define the tenth layer (according to the number of labels for the model)\n \n model.compile(loss='categorical_crossentropy', metrics=['acc'], optimizer='adam') # compile the models with categorical because we are working with multiple labels\n history = model.fit(x_train,y_train,epochs=epoch,batch_size=batch_size,validation_data=(x_val,y_val)) # train the model\n \n # after the training is done, define a dictionary that holds the model and history from the training\n complete_model = {} # define the dictionary\n complete_model['model'] = model # define the model with its key\n complete_model['history'] = history # define the history with its key\n complete_model['labels'] = self.labels # save the labels into the dictionary\n \n return complete_model # return the model at the end\n\n # function to save the model that was created in the create_model function\n def save_model(self, model_name, model):\n model.save('./Models/{}.h5'.format(model_name)) # save the model in the models directory\n\n # function to save the model's labels to be used later\n def save_labels(self, labels, model_name):\n f = open('./Models/{}_Labels.txt'.format(model_name), 'a') # create the .txt file that will contain the labels of the model\n # iterate through the labels when the model was first created\n for i in range(len(labels)):\n f.write(\"{}\\n\".format(labels[i])) # write the labels to the file\n f.close() # after iterating through all the labels, close the file so the space can be free\n\n # ------------------------------------------------------ Define the functions used for classifiying --------------------------------------------- #\n \n # classifies images based on the model and the selected image\n def classify_image(self, image, model):\n \n checkImage = image[0] # get the image\n checklabel = image[0] # get the label of the image\n\n predict = model.predict(np.array(checkImage)) # get the predicition \n predicted_label = self.labels[np.argmax(predict)] # get the predicted label\n \n return predicted_label # return the predicted label from the labels provided by the user\n\n\n\n\n\n" ]
[ [ "numpy.random.seed", "sklearn.model_selection.train_test_split", "numpy.argmax", "numpy.array", "pandas.get_dummies" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
BeeQC/ANODE-reproducibility
[ "9d6b5a297302cdaa0bbc3908de1a94f3c28c0606" ]
[ "experiments/experiments_img.py" ]
[ "import json\nimport matplotlib\nmatplotlib.use('Agg') # This is hacky (useful for running on VMs)\nimport numpy as np\nimport os\nimport time\nimport torch\nfrom anode.models import ODENet\nfrom anode.conv_models import ConvODENet\nfrom anode.discrete_models import ResNet\nfrom anode.training import Trainer\nfrom experiments.dataloaders import mnist, cifar10, tiny_imagenet\nfrom viz.plots import histories_plt\n\n\ndef run_and_save_experiments_img(device, path_to_config):\n \"\"\"Runs and saves experiments as they are produced (so results are still\n saved even if NFEs become excessively large or underflow occurs).\n\n Parameters\n ----------\n device : torch.device\n\n path_to_config : string\n Path to config json file.\n \"\"\"\n # Open config file\n with open(path_to_config) as config_file:\n config = json.load(config_file)\n\n # Create a folder to store experiment results\n timestamp = time.strftime(\"%Y-%m-%d_%H-%M\")\n directory = \"img_results_{}_{}\".format(timestamp, config[\"id\"])\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n # Save config file in experiment directory\n with open(directory + '/config.json', 'w') as config_file:\n json.dump(config, config_file)\n\n num_reps = config[\"num_reps\"]\n dataset = config[\"dataset\"]\n model_configs = config[\"model_configs\"]\n training_config = config[\"training_config\"]\n\n results = {\"dataset\": dataset, \"model_info\": []}\n\n if dataset == 'mnist':\n data_loader, test_loader = mnist(training_config[\"batch_size\"])\n img_size = (1, 28, 28)\n output_dim = 10\n\n if dataset == 'cifar10':\n data_loader, test_loader = cifar10(training_config[\"batch_size\"])\n img_size = (3, 32, 32)\n output_dim = 10\n\n if dataset == 'imagenet':\n data_loader = tiny_imagenet(training_config[\"batch_size\"])\n img_size = (3, 64, 64)\n output_dim = 200\n\n only_success = True # Boolean to keep track of any experiments failing\n\n for i, model_config in enumerate(model_configs):\n results[\"model_info\"].append({})\n # Keep track of losses and nfes\n accuracy_histories = []\n epoch_accuracy_histories = []\n loss_histories = []\n nfe_histories = []\n bnfe_histories = []\n total_nfe_histories = []\n epoch_loss_histories = []\n epoch_nfe_histories = []\n epoch_bnfe_histories = []\n epoch_total_nfe_histories = []\n # Keep track of models potentially failing\n model_stats = {\n \"exceeded\": {\"count\": 0, \"final_losses\": [], \"final_nfes\": [],\n \"final_bnfes\": []},\n \"underflow\": {\"count\": 0, \"final_losses\": [], \"final_nfes\": [],\n \"final_bnfes\": []},\n \"success\": {\"count\": 0, \"final_losses\": [], \"final_nfes\": [],\n \"final_bnfes\": []}\n }\n\n if model_config[\"validation\"]:\n epoch_loss_val_histories = []\n\n is_ode = model_config[\"type\"] == \"odenet\" or model_config[\"type\"] == \"anode\"\n\n for j in range(num_reps):\n print(\"{}/{} model, {}/{} rep\".format(i + 1, len(model_configs), j + 1, num_reps))\n\n if is_ode:\n if model_config[\"type\"] == \"odenet\":\n augment_dim = 0\n else:\n augment_dim = model_config[\"augment_dim\"]\n\n model = ConvODENet(device, img_size, model_config[\"num_filters\"],\n output_dim=output_dim,\n augment_dim=augment_dim,\n time_dependent=model_config[\"time_dependent\"],\n non_linearity=model_config[\"non_linearity\"],\n adjoint=True)\n else:\n model = ResNet(data_dim, model_config[\"hidden_dim\"],\n model_config[\"num_layers\"],\n output_dim=output_dim,\n is_img=True)\n\n model.to(device)\n\n optimizer = torch.optim.Adam(model.parameters(),\n lr=model_config[\"lr\"],\n weight_decay=model_config[\"weight_decay\"])\n\n trainer = Trainer(model, optimizer, device,\n classification=True,\n print_freq=training_config[\"print_freq\"],\n record_freq=training_config[\"record_freq\"],\n verbose=True,\n save_dir=(directory, '{}_{}'.format(i, j)))\n\n accuracy_histories.append([])\n epoch_accuracy_histories.append([])\n loss_histories.append([])\n epoch_loss_histories.append([])\n nfe_histories.append([])\n epoch_nfe_histories.append([])\n bnfe_histories.append([])\n epoch_bnfe_histories.append([])\n total_nfe_histories.append([])\n epoch_total_nfe_histories.append([])\n\n if model_config[\"validation\"]:\n epoch_loss_val_histories.append([])\n\n # Train one epoch at a time, as NODEs can underflow or exceed the\n # maximum NFEs\n for epoch in range(training_config[\"epochs\"]):\n print(\"\\nEpoch {}\".format(epoch + 1))\n try:\n trainer.train(data_loader, 1)\n end_training = False\n except AssertionError as e:\n only_success = False\n # Assertion error means we either underflowed or exceeded\n # the maximum number of steps\n error_message = e.args[0]\n # Error message in torchdiffeq for max_num_steps starts\n # with 'max_num_steps'\n if error_message.startswith(\"max_num_steps\"):\n print(\"Maximum number of steps exceeded\")\n file_name_root = 'exceeded'\n elif error_message.startswith(\"underflow\"):\n print(\"Underflow\")\n file_name_root = 'underflow'\n else:\n print(\"Unknown assertion error\")\n file_name_root = 'unknown'\n\n model_stats[file_name_root][\"count\"] += 1\n\n if len(trainer.buffer['loss']):\n final_loss = np.mean(trainer.buffer['loss'])\n else:\n final_loss = None\n model_stats[file_name_root][\"final_losses\"].append(final_loss)\n\n if len(trainer.buffer['nfe']):\n final_nfes = np.mean(trainer.buffer['nfe'])\n else:\n final_nfes = None\n model_stats[file_name_root][\"final_nfes\"].append(final_nfes)\n\n if len(trainer.buffer['bnfe']):\n final_bnfes = np.mean(trainer.buffer['bnfe'])\n else:\n final_bnfes = None\n model_stats[file_name_root][\"final_bnfes\"].append(final_bnfes)\n\n # Save final NFEs before error happened\n with open(directory + '/{}_{}_{}.json'.format(file_name_root, i, j), 'w') as f:\n json.dump({\"forward\": trainer.nfe_buffer, \"backward\": trainer.bnfe_buffer}, f)\n\n end_training = True\n\n # Save info at every epoch\n accuracy_histories[-1] = trainer.histories['accuracy_history']\n epoch_accuracy_histories[-1] = trainer.histories['epoch_accuracy_history']\n loss_histories[-1] = trainer.histories['loss_history']\n epoch_loss_histories[-1] = trainer.histories['epoch_loss_history']\n if is_ode:\n nfe_histories[-1] = trainer.histories['nfe_history']\n epoch_nfe_histories[-1] = trainer.histories['epoch_nfe_history']\n bnfe_histories[-1] = trainer.histories['bnfe_history']\n epoch_bnfe_histories[-1] = trainer.histories['epoch_bnfe_history']\n total_nfe_histories[-1] = trainer.histories['total_nfe_history']\n epoch_total_nfe_histories[-1] = trainer.histories['epoch_total_nfe_history']\n\n if model_config[\"validation\"]:\n epoch_loss_val = dataset_mean_loss(trainer, test_loader, device)\n if epoch == 0:\n epoch_loss_val_histories[-1] = [epoch_loss_val]\n else:\n epoch_loss_val_histories[-1].append(epoch_loss_val)\n\n results[\"model_info\"][-1][\"type\"] = model_config[\"type\"]\n results[\"model_info\"][-1][\"loss_history\"] = loss_histories\n results[\"model_info\"][-1][\"accuracy_history\"] = accuracy_histories\n results[\"model_info\"][-1][\"epoch_accuracy_history\"] = epoch_accuracy_histories\n results[\"model_info\"][-1][\"epoch_loss_history\"] = epoch_loss_histories\n if model_config[\"validation\"]:\n results[\"model_info\"][-1][\"epoch_loss_val_history\"] = epoch_loss_val_histories\n\n if is_ode:\n results[\"model_info\"][-1][\"epoch_nfe_history\"] = epoch_nfe_histories\n results[\"model_info\"][-1][\"nfe_history\"] = nfe_histories\n results[\"model_info\"][-1][\"epoch_bnfe_history\"] = epoch_bnfe_histories\n results[\"model_info\"][-1][\"bnfe_history\"] = bnfe_histories\n results[\"model_info\"][-1][\"epoch_total_nfe_history\"] = epoch_total_nfe_histories\n results[\"model_info\"][-1][\"total_nfe_history\"] = total_nfe_histories\n\n # Save losses and nfes at every epoch\n with open(directory + '/losses_and_nfes.json', 'w') as f:\n json.dump(results['model_info'], f)\n\n # If training failed, move on to next rep\n if end_training:\n break\n\n # If we reached end of training, increment success counter\n if epoch == training_config[\"epochs\"] - 1:\n model_stats[\"success\"][\"count\"] += 1\n\n if len(trainer.buffer['loss']):\n final_loss = np.mean(trainer.buffer['loss'])\n else:\n final_loss = None\n model_stats[\"success\"][\"final_losses\"].append(final_loss)\n\n if len(trainer.buffer['nfe']):\n final_nfes = np.mean(trainer.buffer['nfe'])\n else:\n final_nfes = None\n model_stats[\"success\"][\"final_nfes\"].append(final_nfes)\n\n if len(trainer.buffer['bnfe']):\n final_bnfes = np.mean(trainer.buffer['bnfe'])\n else:\n final_bnfes = None\n model_stats[\"success\"][\"final_bnfes\"].append(final_bnfes)\n\n # Save model stats\n with open(directory + '/model_stats{}.json'.format(i), 'w') as f:\n json.dump(model_stats, f)\n\n # Create plots\n\n # Extract size of augmented dims\n augment_labels = ['p = 0' if model_config['type'] == 'odenet' else 'p = {}'.format(model_config['augment_dim'])\n for model_config in config['model_configs']]\n # Create losses figure\n # Note that we can only calculate mean loss if all models trained to\n # completion. Therefore we only include mean if only_success is True\n histories_plt(results[\"model_info\"], plot_type='loss', labels=augment_labels,\n include_mean=only_success, save_fig=directory + '/losses.png')\n histories_plt(results[\"model_info\"], plot_type='loss', labels=augment_labels,\n include_mean=only_success, shaded_err=True, save_fig=directory + '/losses_shaded.png')\n\n # Create NFE plots if ODE model is included\n contains_ode = False\n for model_config in config[\"model_configs\"]:\n if model_config[\"type\"] == \"odenet\" or model_config[\"type\"] == \"anode\":\n contains_ode = True\n break\n\n if contains_ode:\n # If adjoint method was used, plot forwards, backwards and total nfes\n if trainer.model.odeblock.adjoint:\n nfe_types = ['nfe', 'bnfe', 'total_nfe']\n else:\n nfe_types = ['nfe']\n\n for nfe_type in nfe_types:\n histories_plt(results[\"model_info\"], plot_type='nfe', labels=augment_labels,\n include_mean=only_success, nfe_type=nfe_type,\n save_fig=directory + '/{}s.png'.format(nfe_type))\n histories_plt(results[\"model_info\"], plot_type='nfe', labels=augment_labels,\n include_mean=only_success, shaded_err=True, nfe_type=nfe_type,\n save_fig=directory + '/{}s_shaded.png'.format(nfe_type))\n histories_plt(results[\"model_info\"], plot_type='nfe_vs_loss', labels=augment_labels,\n include_mean=only_success, nfe_type=nfe_type,\n save_fig=directory + '/{}_vs_loss.png'.format(nfe_type))\n histories_plt(results[\"model_info\"], plot_type='nfe_vs_loss', labels=augment_labels,\n include_mean=only_success, nfe_type=nfe_type,\n save_fig=directory + '/{}_vs_loss.png'.format(nfe_type))\n\n\ndef dataset_mean_loss(trainer, data_loader, device):\n \"\"\"Returns mean loss of model on a dataset. Useful for calculating\n validation loss.\n\n Parameters\n ----------\n trainer : training.Trainer instance\n Trainer instance for model we want to evaluate.\n\n data_loader : torch.utils.data.DataLoader\n\n device : torch.device\n \"\"\"\n epoch_loss = 0.\n for x_batch, y_batch in data_loader:\n x_batch = x_batch.to(device)\n y_batch = y_batch.to(device)\n y_pred = trainer.model(x_batch)\n loss = trainer._loss(y_pred, y_batch)\n epoch_loss += loss.item()\n return epoch_loss / len(data_loader)\n" ]
[ [ "matplotlib.use", "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
physwkim/silx
[ "e3f39babad34c97db8ec5dfbb8e92287ce059f70", "3f9bcda88c074438fdb30cde29fec314d26f471c", "3f9bcda88c074438fdb30cde29fec314d26f471c", "3f9bcda88c074438fdb30cde29fec314d26f471c", "e3f39babad34c97db8ec5dfbb8e92287ce059f70", "3f9bcda88c074438fdb30cde29fec314d26f471c", "e3f39babad34c97db8ec5dfbb8e92287ce059f70", "e3f39babad34c97db8ec5dfbb8e92287ce059f70" ]
[ "silx/gui/plot/actions/io.py", "silx/io/test/test_specfile.py", "silx/gui/data/_VolumeWindow.py", "silx/math/fft/fftw.py", "silx/gui/fit/FitWidget.py", "silx/math/test/test_HistogramndLut_nominal.py", "silx/image/_boundingbox.py", "silx/gui/widgets/LegendIconWidget.py" ]
[ "# coding: utf-8\n# /*##########################################################################\n#\n# Copyright (c) 2004-2020 European Synchrotron Radiation Facility\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n# ###########################################################################*/\n\"\"\"\n:mod:`silx.gui.plot.actions.io` provides a set of QAction relative of inputs\nand outputs for a :class:`.PlotWidget`.\n\nThe following QAction are available:\n\n- :class:`CopyAction`\n- :class:`PrintAction`\n- :class:`SaveAction`\n\"\"\"\n\nfrom __future__ import division\n\n__authors__ = [\"V.A. Sole\", \"T. Vincent\", \"P. Knobel\"]\n__license__ = \"MIT\"\n__date__ = \"25/09/2020\"\n\nfrom . import PlotAction\nfrom silx.io.utils import save1D, savespec, NEXUS_HDF5_EXT\nfrom silx.io.nxdata import save_NXdata\nimport logging\nimport sys\nimport os.path\nfrom collections import OrderedDict\nimport traceback\nimport numpy\nfrom silx.utils.deprecation import deprecated\nfrom silx.gui import qt, printer\nfrom silx.gui.dialog.GroupDialog import GroupDialog\nfrom silx.third_party.EdfFile import EdfFile\nfrom silx.third_party.TiffIO import TiffIO\nfrom ...utils.image import convertArrayToQImage\nif sys.version_info[0] == 3:\n from io import BytesIO\nelse:\n import cStringIO as _StringIO\n BytesIO = _StringIO.StringIO\n\n_logger = logging.getLogger(__name__)\n\n_NEXUS_HDF5_EXT_STR = ' '.join(['*' + ext for ext in NEXUS_HDF5_EXT])\n\n\ndef selectOutputGroup(h5filename):\n \"\"\"Open a dialog to prompt the user to select a group in\n which to output data.\n\n :param str h5filename: name of an existing HDF5 file\n :rtype: str\n :return: Name of output group, or None if the dialog was cancelled\n \"\"\"\n dialog = GroupDialog()\n dialog.addFile(h5filename)\n dialog.setWindowTitle(\"Select an output group\")\n if not dialog.exec_():\n return None\n return dialog.getSelectedDataUrl().data_path()\n\n\nclass SaveAction(PlotAction):\n \"\"\"QAction for saving Plot content.\n\n It opens a Save as... dialog.\n\n :param plot: :class:`.PlotWidget` instance on which to operate.\n :param parent: See :class:`QAction`.\n \"\"\"\n\n SNAPSHOT_FILTER_SVG = 'Plot Snapshot as SVG (*.svg)'\n SNAPSHOT_FILTER_PNG = 'Plot Snapshot as PNG (*.png)'\n\n DEFAULT_ALL_FILTERS = (SNAPSHOT_FILTER_PNG, SNAPSHOT_FILTER_SVG)\n\n # Dict of curve filters with CSV-like format\n # Using ordered dict to guarantee filters order\n # Note: '%.18e' is numpy.savetxt default format\n CURVE_FILTERS_TXT = OrderedDict((\n ('Curve as Raw ASCII (*.txt)',\n {'fmt': '%.18e', 'delimiter': ' ', 'header': False}),\n ('Curve as \";\"-separated CSV (*.csv)',\n {'fmt': '%.18e', 'delimiter': ';', 'header': True}),\n ('Curve as \",\"-separated CSV (*.csv)',\n {'fmt': '%.18e', 'delimiter': ',', 'header': True}),\n ('Curve as tab-separated CSV (*.csv)',\n {'fmt': '%.18e', 'delimiter': '\\t', 'header': True}),\n ('Curve as OMNIC CSV (*.csv)',\n {'fmt': '%.7E', 'delimiter': ',', 'header': False}),\n ('Curve as SpecFile (*.dat)',\n {'fmt': '%.10g', 'delimiter': '', 'header': False})\n ))\n\n CURVE_FILTER_NPY = 'Curve as NumPy binary file (*.npy)'\n\n CURVE_FILTER_NXDATA = 'Curve as NXdata (%s)' % _NEXUS_HDF5_EXT_STR\n\n DEFAULT_CURVE_FILTERS = list(CURVE_FILTERS_TXT.keys()) + [\n CURVE_FILTER_NPY, CURVE_FILTER_NXDATA]\n\n DEFAULT_ALL_CURVES_FILTERS = (\"All curves as SpecFile (*.dat)\",)\n\n IMAGE_FILTER_EDF = 'Image data as EDF (*.edf)'\n IMAGE_FILTER_TIFF = 'Image data as TIFF (*.tif)'\n IMAGE_FILTER_NUMPY = 'Image data as NumPy binary file (*.npy)'\n IMAGE_FILTER_ASCII = 'Image data as ASCII (*.dat)'\n IMAGE_FILTER_CSV_COMMA = 'Image data as ,-separated CSV (*.csv)'\n IMAGE_FILTER_CSV_SEMICOLON = 'Image data as ;-separated CSV (*.csv)'\n IMAGE_FILTER_CSV_TAB = 'Image data as tab-separated CSV (*.csv)'\n IMAGE_FILTER_RGB_PNG = 'Image as PNG (*.png)'\n IMAGE_FILTER_NXDATA = 'Image as NXdata (%s)' % _NEXUS_HDF5_EXT_STR\n\n DEFAULT_IMAGE_FILTERS = (IMAGE_FILTER_EDF,\n IMAGE_FILTER_TIFF,\n IMAGE_FILTER_NUMPY,\n IMAGE_FILTER_ASCII,\n IMAGE_FILTER_CSV_COMMA,\n IMAGE_FILTER_CSV_SEMICOLON,\n IMAGE_FILTER_CSV_TAB,\n IMAGE_FILTER_RGB_PNG,\n IMAGE_FILTER_NXDATA)\n\n SCATTER_FILTER_NXDATA = 'Scatter as NXdata (%s)' % _NEXUS_HDF5_EXT_STR\n DEFAULT_SCATTER_FILTERS = (SCATTER_FILTER_NXDATA,)\n\n # filters for which we don't want an \"overwrite existing file\" warning\n DEFAULT_APPEND_FILTERS = (CURVE_FILTER_NXDATA, IMAGE_FILTER_NXDATA,\n SCATTER_FILTER_NXDATA)\n\n def __init__(self, plot, parent=None):\n self._filters = {\n 'all': OrderedDict(),\n 'curve': OrderedDict(),\n 'curves': OrderedDict(),\n 'image': OrderedDict(),\n 'scatter': OrderedDict()}\n\n self._appendFilters = list(self.DEFAULT_APPEND_FILTERS)\n\n # Initialize filters\n for nameFilter in self.DEFAULT_ALL_FILTERS:\n self.setFileFilter(\n dataKind='all', nameFilter=nameFilter, func=self._saveSnapshot)\n\n for nameFilter in self.DEFAULT_CURVE_FILTERS:\n self.setFileFilter(\n dataKind='curve', nameFilter=nameFilter, func=self._saveCurve)\n\n for nameFilter in self.DEFAULT_ALL_CURVES_FILTERS:\n self.setFileFilter(\n dataKind='curves', nameFilter=nameFilter, func=self._saveCurves)\n\n for nameFilter in self.DEFAULT_IMAGE_FILTERS:\n self.setFileFilter(\n dataKind='image', nameFilter=nameFilter, func=self._saveImage)\n\n for nameFilter in self.DEFAULT_SCATTER_FILTERS:\n self.setFileFilter(\n dataKind='scatter', nameFilter=nameFilter, func=self._saveScatter)\n\n super(SaveAction, self).__init__(\n plot, icon='document-save', text='Save as...',\n tooltip='Save curve/image/plot snapshot dialog',\n triggered=self._actionTriggered,\n checkable=False, parent=parent)\n self.setShortcut(qt.QKeySequence.Save)\n self.setShortcutContext(qt.Qt.WidgetShortcut)\n\n @staticmethod\n def _errorMessage(informativeText='', parent=None):\n \"\"\"Display an error message.\"\"\"\n # TODO issue with QMessageBox size fixed and too small\n msg = qt.QMessageBox(parent)\n msg.setIcon(qt.QMessageBox.Critical)\n msg.setInformativeText(informativeText + ' ' + str(sys.exc_info()[1]))\n msg.setDetailedText(traceback.format_exc())\n msg.exec_()\n\n def _saveSnapshot(self, plot, filename, nameFilter):\n \"\"\"Save a snapshot of the :class:`PlotWindow` widget.\n\n :param str filename: The name of the file to write\n :param str nameFilter: The selected name filter\n :return: False if format is not supported or save failed,\n True otherwise.\n \"\"\"\n if nameFilter == self.SNAPSHOT_FILTER_PNG:\n fileFormat = 'png'\n elif nameFilter == self.SNAPSHOT_FILTER_SVG:\n fileFormat = 'svg'\n else: # Format not supported\n _logger.error(\n 'Saving plot snapshot failed: format not supported')\n return False\n\n plot.saveGraph(filename, fileFormat=fileFormat)\n return True\n\n def _getAxesLabels(self, item):\n # If curve has no associated label, get the default from the plot\n xlabel = item.getXLabel() or self.plot.getXAxis().getLabel()\n ylabel = item.getYLabel() or self.plot.getYAxis().getLabel()\n return xlabel, ylabel\n\n def _get1dData(self, item):\n \"provide xdata, [ydata], xlabel, [ylabel] and manages error bars\"\n xlabel, ylabel = self._getAxesLabels(item)\n x_data = item.getXData(copy=False)\n y_data = item.getYData(copy=False)\n x_err = item.getXErrorData(copy=False)\n y_err = item.getYErrorData(copy=False)\n labels = [ylabel]\n data = [y_data]\n\n if x_err is not None:\n if numpy.isscalar(x_err):\n data.append(numpy.zeros_like(y_data) + x_err)\n labels.append(xlabel + \"_errors\")\n elif x_err.ndim == 1:\n data.append(x_err)\n labels.append(xlabel + \"_errors\")\n elif x_err.ndim == 2:\n data.append(x_err[0])\n labels.append(xlabel + \"_errors_below\")\n data.append(x_err[1])\n labels.append(xlabel + \"_errors_above\")\n\n if y_err is not None:\n if numpy.isscalar(y_err):\n data.append(numpy.zeros_like(y_data) + y_err)\n labels.append(ylabel + \"_errors\")\n elif y_err.ndim == 1:\n data.append(y_err)\n labels.append(ylabel + \"_errors\")\n elif y_err.ndim == 2:\n data.append(y_err[0])\n labels.append(ylabel + \"_errors_below\")\n data.append(y_err[1])\n labels.append(ylabel + \"_errors_above\")\n return x_data, data, xlabel, labels\n\n @staticmethod\n def _selectWriteableOutputGroup(filename, parent):\n if os.path.exists(filename) and os.path.isfile(filename) \\\n and os.access(filename, os.W_OK):\n entryPath = selectOutputGroup(filename)\n if entryPath is None:\n _logger.info(\"Save operation cancelled\")\n return None\n return entryPath\n elif not os.path.exists(filename):\n # create new entry in new file\n return \"/entry\"\n else:\n SaveAction._errorMessage('Save failed (file access issue)\\n', parent=parent)\n return None\n\n def _saveCurveAsNXdata(self, curve, filename):\n entryPath = self._selectWriteableOutputGroup(filename, parent=self.plot)\n if entryPath is None:\n return False\n\n xlabel, ylabel = self._getAxesLabels(curve)\n\n return save_NXdata(\n filename,\n nxentry_name=entryPath,\n signal=curve.getYData(copy=False),\n axes=[curve.getXData(copy=False)],\n signal_name=\"y\",\n axes_names=[\"x\"],\n signal_long_name=ylabel,\n axes_long_names=[xlabel],\n signal_errors=curve.getYErrorData(copy=False),\n axes_errors=[curve.getXErrorData(copy=True)],\n title=self.plot.getGraphTitle())\n\n def _saveCurve(self, plot, filename, nameFilter):\n \"\"\"Save a curve from the plot.\n\n :param str filename: The name of the file to write\n :param str nameFilter: The selected name filter\n :return: False if format is not supported or save failed,\n True otherwise.\n \"\"\"\n if nameFilter not in self.DEFAULT_CURVE_FILTERS:\n return False\n\n # Check if a curve is to be saved\n curve = plot.getActiveCurve()\n # before calling _saveCurve, if there is no selected curve, we\n # make sure there is only one curve on the graph\n if curve is None:\n curves = plot.getAllCurves()\n if not curves:\n self._errorMessage(\"No curve to be saved\", parent=self.plot)\n return False\n curve = curves[0]\n\n if nameFilter in self.CURVE_FILTERS_TXT:\n filter_ = self.CURVE_FILTERS_TXT[nameFilter]\n fmt = filter_['fmt']\n csvdelim = filter_['delimiter']\n autoheader = filter_['header']\n else:\n # .npy or nxdata\n fmt, csvdelim, autoheader = (\"\", \"\", False)\n\n if nameFilter == self.CURVE_FILTER_NXDATA:\n return self._saveCurveAsNXdata(curve, filename)\n\n xdata, data, xlabel, labels = self._get1dData(curve)\n\n try:\n save1D(filename,\n xdata, data,\n xlabel, labels,\n fmt=fmt, csvdelim=csvdelim,\n autoheader=autoheader)\n except IOError:\n self._errorMessage('Save failed\\n', parent=self.plot)\n return False\n\n return True\n\n def _saveCurves(self, plot, filename, nameFilter):\n \"\"\"Save all curves from the plot.\n\n :param str filename: The name of the file to write\n :param str nameFilter: The selected name filter\n :return: False if format is not supported or save failed,\n True otherwise.\n \"\"\"\n if nameFilter not in self.DEFAULT_ALL_CURVES_FILTERS:\n return False\n\n curves = plot.getAllCurves()\n if not curves:\n self._errorMessage(\"No curves to be saved\", parent=self.plot)\n return False\n\n curve = curves[0]\n scanno = 1\n try:\n xdata, data, xlabel, labels = self._get1dData(curve)\n\n specfile = savespec(filename,\n xdata, data,\n xlabel, labels,\n fmt=\"%.7g\", scan_number=1, mode=\"w\",\n write_file_header=True,\n close_file=False)\n except IOError:\n self._errorMessage('Save failed\\n', parent=self.plot)\n return False\n\n for curve in curves[1:]:\n try:\n scanno += 1\n xdata, data, xlabel, labels = self._get1dData(curve)\n specfile = savespec(specfile,\n xdata, data,\n xlabel, labels,\n fmt=\"%.7g\", scan_number=scanno,\n write_file_header=False,\n close_file=False)\n except IOError:\n self._errorMessage('Save failed\\n', parent=self.plot)\n return False\n specfile.close()\n\n return True\n\n def _saveImage(self, plot, filename, nameFilter):\n \"\"\"Save an image from the plot.\n\n :param str filename: The name of the file to write\n :param str nameFilter: The selected name filter\n :return: False if format is not supported or save failed,\n True otherwise.\n \"\"\"\n if nameFilter not in self.DEFAULT_IMAGE_FILTERS:\n return False\n\n image = plot.getActiveImage()\n if image is None:\n qt.QMessageBox.warning(\n plot, \"No Data\", \"No image to be saved\")\n return False\n\n data = image.getData(copy=False)\n\n # TODO Use silx.io for writing files\n if nameFilter == self.IMAGE_FILTER_EDF:\n edfFile = EdfFile(filename, access=\"w+\")\n edfFile.WriteImage({}, data, Append=0)\n return True\n\n elif nameFilter == self.IMAGE_FILTER_TIFF:\n tiffFile = TiffIO(filename, mode='w')\n tiffFile.writeImage(data, software='silx')\n return True\n\n elif nameFilter == self.IMAGE_FILTER_NUMPY:\n try:\n numpy.save(filename, data)\n except IOError:\n self._errorMessage('Save failed\\n', parent=self.plot)\n return False\n return True\n\n elif nameFilter == self.IMAGE_FILTER_NXDATA:\n entryPath = self._selectWriteableOutputGroup(filename, parent=self.plot)\n if entryPath is None:\n return False\n xorigin, yorigin = image.getOrigin()\n xscale, yscale = image.getScale()\n xaxis = xorigin + xscale * numpy.arange(data.shape[1])\n yaxis = yorigin + yscale * numpy.arange(data.shape[0])\n xlabel, ylabel = self._getAxesLabels(image)\n interpretation = \"image\" if len(data.shape) == 2 else \"rgba-image\"\n\n return save_NXdata(filename,\n nxentry_name=entryPath,\n signal=data,\n axes=[yaxis, xaxis],\n signal_name=\"image\",\n axes_names=[\"y\", \"x\"],\n axes_long_names=[ylabel, xlabel],\n title=plot.getGraphTitle(),\n interpretation=interpretation)\n\n elif nameFilter in (self.IMAGE_FILTER_ASCII,\n self.IMAGE_FILTER_CSV_COMMA,\n self.IMAGE_FILTER_CSV_SEMICOLON,\n self.IMAGE_FILTER_CSV_TAB):\n csvdelim, filetype = {\n self.IMAGE_FILTER_ASCII: (' ', 'txt'),\n self.IMAGE_FILTER_CSV_COMMA: (',', 'csv'),\n self.IMAGE_FILTER_CSV_SEMICOLON: (';', 'csv'),\n self.IMAGE_FILTER_CSV_TAB: ('\\t', 'csv'),\n }[nameFilter]\n\n height, width = data.shape\n rows, cols = numpy.mgrid[0:height, 0:width]\n try:\n save1D(filename, rows.ravel(), (cols.ravel(), data.ravel()),\n filetype=filetype,\n xlabel='row',\n ylabels=['column', 'value'],\n csvdelim=csvdelim,\n autoheader=True)\n\n except IOError:\n self._errorMessage('Save failed\\n', parent=self.plot)\n return False\n return True\n\n elif nameFilter == self.IMAGE_FILTER_RGB_PNG:\n # Get displayed image\n rgbaImage = image.getRgbaImageData(copy=False)\n # Convert RGB QImage\n qimage = convertArrayToQImage(rgbaImage[:, :, :3])\n\n if qimage.save(filename, 'PNG'):\n return True\n else:\n _logger.error('Failed to save image as %s', filename)\n qt.QMessageBox.critical(\n self.parent(),\n 'Save image as',\n 'Failed to save image')\n\n return False\n\n def _saveScatter(self, plot, filename, nameFilter):\n \"\"\"Save an image from the plot.\n\n :param str filename: The name of the file to write\n :param str nameFilter: The selected name filter\n :return: False if format is not supported or save failed,\n True otherwise.\n \"\"\"\n if nameFilter not in self.DEFAULT_SCATTER_FILTERS:\n return False\n\n if nameFilter == self.SCATTER_FILTER_NXDATA:\n entryPath = self._selectWriteableOutputGroup(filename, parent=self.plot)\n if entryPath is None:\n return False\n scatter = plot.getScatter()\n\n x = scatter.getXData(copy=False)\n y = scatter.getYData(copy=False)\n z = scatter.getValueData(copy=False)\n\n xerror = scatter.getXErrorData(copy=False)\n if isinstance(xerror, float):\n xerror = xerror * numpy.ones(x.shape, dtype=numpy.float32)\n\n yerror = scatter.getYErrorData(copy=False)\n if isinstance(yerror, float):\n yerror = yerror * numpy.ones(x.shape, dtype=numpy.float32)\n\n xlabel = plot.getGraphXLabel()\n ylabel = plot.getGraphYLabel()\n\n return save_NXdata(\n filename,\n nxentry_name=entryPath,\n signal=z,\n axes=[x, y],\n signal_name=\"values\",\n axes_names=[\"x\", \"y\"],\n axes_long_names=[xlabel, ylabel],\n axes_errors=[xerror, yerror],\n title=plot.getGraphTitle())\n\n def setFileFilter(self, dataKind, nameFilter, func, index=None, appendToFile=False):\n \"\"\"Set a name filter to add/replace a file format support\n\n :param str dataKind:\n The kind of data for which the provided filter is valid.\n One of: 'all', 'curve', 'curves', 'image', 'scatter'\n :param str nameFilter: The name filter in the QFileDialog.\n See :meth:`QFileDialog.setNameFilters`.\n :param callable func: The function to call to perform saving.\n Expected signature is:\n bool func(PlotWidget plot, str filename, str nameFilter)\n :param bool appendToFile: True to append the data into the selected\n file.\n :param integer index: Index of the filter in the final list (or None)\n \"\"\"\n assert dataKind in ('all', 'curve', 'curves', 'image', 'scatter')\n\n if appendToFile:\n self._appendFilters.append(nameFilter)\n\n # first append or replace the new filter to prevent colissions\n self._filters[dataKind][nameFilter] = func\n if index is None:\n # we are already done\n return\n\n # get the current ordered list of keys\n keyList = list(self._filters[dataKind].keys())\n\n # deal with negative indices\n if index < 0:\n index = len(keyList) + index\n if index < 0:\n index = 0\n\n if index >= len(keyList):\n # nothing to be done, already at the end\n txt = 'Requested index %d impossible, already at the end' % index\n _logger.info(txt)\n return\n\n # get the new ordered list\n oldIndex = keyList.index(nameFilter)\n del keyList[oldIndex]\n keyList.insert(index, nameFilter)\n\n # build the new filters\n newFilters = OrderedDict()\n for key in keyList:\n newFilters[key] = self._filters[dataKind][key]\n\n # and update the filters\n self._filters[dataKind] = newFilters\n return\n\n def getFileFilters(self, dataKind):\n \"\"\"Returns the nameFilter and associated function for a kind of data.\n\n :param str dataKind:\n The kind of data for which the provided filter is valid.\n On of: 'all', 'curve', 'curves', 'image', 'scatter'\n :return: {nameFilter: function} associations.\n :rtype: collections.OrderedDict\n \"\"\"\n assert dataKind in ('all', 'curve', 'curves', 'image', 'scatter')\n\n return self._filters[dataKind].copy()\n\n def _actionTriggered(self, checked=False):\n \"\"\"Handle save action.\"\"\"\n # Set-up filters\n filters = OrderedDict()\n\n # Add image filters if there is an active image\n if self.plot.getActiveImage() is not None:\n filters.update(self._filters['image'].items())\n\n # Add curve filters if there is a curve to save\n if (self.plot.getActiveCurve() is not None or\n len(self.plot.getAllCurves()) == 1):\n filters.update(self._filters['curve'].items())\n if len(self.plot.getAllCurves()) >= 1:\n filters.update(self._filters['curves'].items())\n\n # Add scatter filters if there is a scatter\n # todo: CSV\n if self.plot.getScatter() is not None:\n filters.update(self._filters['scatter'].items())\n\n filters.update(self._filters['all'].items())\n\n # Create and run File dialog\n dialog = qt.QFileDialog(self.plot)\n dialog.setOption(dialog.DontUseNativeDialog)\n dialog.setWindowTitle(\"Output File Selection\")\n dialog.setModal(1)\n dialog.setNameFilters(list(filters.keys()))\n\n dialog.setFileMode(dialog.AnyFile)\n dialog.setAcceptMode(dialog.AcceptSave)\n\n def onFilterSelection(filt_):\n # disable overwrite confirmation for NXdata types,\n # because we append the data to existing files\n if filt_ in self._appendFilters:\n dialog.setOption(dialog.DontConfirmOverwrite)\n else:\n dialog.setOption(dialog.DontConfirmOverwrite, False)\n\n dialog.filterSelected.connect(onFilterSelection)\n\n if not dialog.exec_():\n return False\n\n nameFilter = dialog.selectedNameFilter()\n filename = dialog.selectedFiles()[0]\n dialog.close()\n\n if '(' in nameFilter and ')' == nameFilter.strip()[-1]:\n # Check for correct file extension\n # Extract file extensions as .something\n extensions = [ext[ext.find('.'):] for ext in\n nameFilter[nameFilter.find('(') + 1:-1].split()]\n for ext in extensions:\n if (len(filename) > len(ext) and\n filename[-len(ext):].lower() == ext.lower()):\n break\n else: # filename has no extension supported in nameFilter, add one\n if len(extensions) >= 1:\n filename += extensions[0]\n\n # Handle save\n func = filters.get(nameFilter, None)\n if func is not None:\n return func(self.plot, filename, nameFilter)\n else:\n _logger.error('Unsupported file filter: %s', nameFilter)\n return False\n\n\ndef _plotAsPNG(plot):\n \"\"\"Save a :class:`Plot` as PNG and return the payload.\n\n :param plot: The :class:`Plot` to save\n \"\"\"\n pngFile = BytesIO()\n plot.saveGraph(pngFile, fileFormat='png')\n pngFile.flush()\n pngFile.seek(0)\n data = pngFile.read()\n pngFile.close()\n return data\n\n\nclass PrintAction(PlotAction):\n \"\"\"QAction for printing the plot.\n\n It opens a Print dialog.\n\n Current implementation print a bitmap of the plot area and not vector\n graphics, so printing quality is not great.\n\n :param plot: :class:`.PlotWidget` instance on which to operate.\n :param parent: See :class:`QAction`.\n \"\"\"\n\n def __init__(self, plot, parent=None):\n super(PrintAction, self).__init__(\n plot, icon='document-print', text='Print...',\n tooltip='Open print dialog',\n triggered=self.printPlot,\n checkable=False, parent=parent)\n self.setShortcut(qt.QKeySequence.Print)\n self.setShortcutContext(qt.Qt.WidgetShortcut)\n\n def getPrinter(self):\n \"\"\"The QPrinter instance used by the PrintAction.\n\n :rtype: QPrinter\n \"\"\"\n return printer.getDefaultPrinter()\n\n @property\n @deprecated(replacement=\"getPrinter()\", since_version=\"0.8.0\")\n def printer(self):\n return self.getPrinter()\n\n def printPlotAsWidget(self):\n \"\"\"Open the print dialog and print the plot.\n\n Use :meth:`QWidget.render` to print the plot\n\n :return: True if successful\n \"\"\"\n dialog = qt.QPrintDialog(self.getPrinter(), self.plot)\n dialog.setWindowTitle('Print Plot')\n if not dialog.exec_():\n return False\n\n # Print a snapshot of the plot widget at the top of the page\n widget = self.plot.centralWidget()\n\n painter = qt.QPainter()\n if not painter.begin(self.getPrinter()):\n return False\n\n pageRect = self.getPrinter().pageRect()\n xScale = pageRect.width() / widget.width()\n yScale = pageRect.height() / widget.height()\n scale = min(xScale, yScale)\n\n painter.translate(pageRect.width() / 2., 0.)\n painter.scale(scale, scale)\n painter.translate(-widget.width() / 2., 0.)\n widget.render(painter)\n painter.end()\n\n return True\n\n def printPlot(self):\n \"\"\"Open the print dialog and print the plot.\n\n Use :meth:`Plot.saveGraph` to print the plot.\n\n :return: True if successful\n \"\"\"\n # Init printer and start printer dialog\n dialog = qt.QPrintDialog(self.getPrinter(), self.plot)\n dialog.setWindowTitle('Print Plot')\n if not dialog.exec_():\n return False\n\n # Save Plot as PNG and make a pixmap from it with default dpi\n pngData = _plotAsPNG(self.plot)\n\n pixmap = qt.QPixmap()\n pixmap.loadFromData(pngData, 'png')\n\n xScale = self.getPrinter().pageRect().width() / pixmap.width()\n yScale = self.getPrinter().pageRect().height() / pixmap.height()\n scale = min(xScale, yScale)\n\n # Draw pixmap with painter\n painter = qt.QPainter()\n if not painter.begin(self.getPrinter()):\n return False\n\n painter.drawPixmap(0, 0,\n pixmap.width() * scale,\n pixmap.height() * scale,\n pixmap)\n painter.end()\n\n return True\n\n\nclass CopyAction(PlotAction):\n \"\"\"QAction to copy :class:`.PlotWidget` content to clipboard.\n\n :param plot: :class:`.PlotWidget` instance on which to operate\n :param parent: See :class:`QAction`\n \"\"\"\n\n def __init__(self, plot, parent=None):\n super(CopyAction, self).__init__(\n plot, icon='edit-copy', text='Copy plot',\n tooltip='Copy a snapshot of the plot into the clipboard',\n triggered=self.copyPlot,\n checkable=False, parent=parent)\n self.setShortcut(qt.QKeySequence.Copy)\n self.setShortcutContext(qt.Qt.WidgetShortcut)\n\n def copyPlot(self):\n \"\"\"Copy plot content to the clipboard as a bitmap.\"\"\"\n # Save Plot as PNG and make a QImage from it with default dpi\n pngData = _plotAsPNG(self.plot)\n image = qt.QImage.fromData(pngData, 'png')\n qt.QApplication.clipboard().setImage(image)\n", "# coding: utf-8\n# /*##########################################################################\n# Copyright (C) 2016-2019 European Synchrotron Radiation Facility\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n# ############################################################################*/\n\"\"\"Tests for specfile wrapper\"\"\"\n\n__authors__ = [\"P. Knobel\", \"V.A. Sole\"]\n__license__ = \"MIT\"\n__date__ = \"17/01/2018\"\n\n\nimport locale\nimport logging\nimport numpy\nimport os\nimport sys\nimport tempfile\nimport unittest\n\nfrom silx.utils import testutils\n\nfrom ..specfile import SpecFile, Scan\nfrom .. import specfile\n\n\nlogger1 = logging.getLogger(__name__)\n\nsftext = \"\"\"#F /tmp/sf.dat\n#E 1455180875\n#D Thu Feb 11 09:54:35 2016\n#C imaging User = opid17\n#U00 user comment first line\n#U01 This is a dummy file to test SpecFile parsing\n#U02\n#U03 last line\n\n#O0 Pslit HGap MRTSlit UP MRTSlit DOWN\n#O1 Sslit1 VOff Sslit1 HOff Sslit1 VGap\n#o0 pshg mrtu mrtd\n#o2 ss1vo ss1ho ss1vg\n\n#J0 Seconds IA ion.mono Current\n#J1 xbpmc2 idgap1 Inorm\n\n#S 1 ascan ss1vo -4.55687 -0.556875 40 0.2\n#D Thu Feb 11 09:55:20 2016\n#T 0.2 (Seconds)\n#G0 0\n#G1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n#G3 0 0 0 0 0 0 0 0 0\n#G4 0\n#Q\n#P0 180.005 -0.66875 0.87125\n#P1 14.74255 16.197579 12.238283\n#UMI0 Current AutoM Shutter\n#UMI1 192.51 OFF FE open\n#UMI2 Refill in 39883 sec, Fill Mode: uniform multibunch / Message: Feb 11 08:00 Delivery:Next Refill at 21:00;\n#N 4\n#L first column second column 3rd_col\n-1.23 5.89 8\n8.478100E+01 5 1.56\n3.14 2.73 -3.14\n1.2 2.3 3.4\n\n#S 25 ascan c3th 1.33245 1.52245 40 0.15\n#D Thu Feb 11 10:00:31 2016\n#P0 80.005 -1.66875 1.87125\n#P1 4.74255 6.197579 2.238283\n#N 5\n#L column0 column1 col2 col3\n0.0 0.1 0.2 0.3\n1.0 1.1 1.2 1.3\n2.0 2.1 2.2 2.3\n3.0 3.1 3.2 3.3\n\n#S 26 yyyyyy\n#D Thu Feb 11 09:55:20 2016\n#P0 80.005 -1.66875 1.87125\n#P1 4.74255 6.197579 2.238283\n#N 4\n#L first column second column 3rd_col\n#C Sat Oct 31 15:51:47 1998. Scan aborted after 0 points.\n\n#F /tmp/sf.dat\n#E 1455180876\n#D Thu Feb 11 09:54:36 2016\n\n#S 1 aaaaaa\n#U first duplicate line\n#U second duplicate line\n#@MCADEV 1\n#@MCA %16C\n#@CHANN 3 0 2 1\n#@CALIB 1 2 3\n#N 3\n#L uno duo\n1 2\n@A 0 1 2\n3 4\n@A 3.1 4 5\n5 6\n@A 6 7.7 8\n\"\"\"\n\n\nloc = locale.getlocale(locale.LC_NUMERIC)\ntry:\n locale.setlocale(locale.LC_NUMERIC, 'de_DE.utf8')\nexcept locale.Error:\n try_DE = False\nelse:\n try_DE = True\n locale.setlocale(locale.LC_NUMERIC, loc)\n\n\nclass TestSpecFile(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n fd, cls.fname1 = tempfile.mkstemp(text=False)\n if sys.version_info < (3, ):\n os.write(fd, sftext)\n else:\n os.write(fd, bytes(sftext, 'ascii'))\n os.close(fd)\n\n fd2, cls.fname2 = tempfile.mkstemp(text=False)\n if sys.version_info < (3, ):\n os.write(fd2, sftext[370:923])\n else:\n os.write(fd2, bytes(sftext[370:923], 'ascii'))\n os.close(fd2)\n\n fd3, cls.fname3 = tempfile.mkstemp(text=False)\n txt = sftext[371:923]\n if sys.version_info < (3, ):\n os.write(fd3, txt)\n else:\n os.write(fd3, bytes(txt, 'ascii'))\n os.close(fd3)\n\n @classmethod\n def tearDownClass(cls):\n os.unlink(cls.fname1)\n os.unlink(cls.fname2)\n os.unlink(cls.fname3)\n\n def setUp(self):\n self.sf = SpecFile(self.fname1)\n self.scan1 = self.sf[0]\n self.scan1_2 = self.sf[\"1.2\"]\n self.scan25 = self.sf[\"25.1\"]\n self.empty_scan = self.sf[\"26.1\"]\n\n self.sf_no_fhdr = SpecFile(self.fname2)\n self.scan1_no_fhdr = self.sf_no_fhdr[0]\n\n self.sf_no_fhdr_crash = SpecFile(self.fname3)\n self.scan1_no_fhdr_crash = self.sf_no_fhdr_crash[0]\n\n def tearDown(self):\n self.sf.close()\n self.sf_no_fhdr.close()\n self.sf_no_fhdr_crash.close()\n\n def test_open(self):\n self.assertIsInstance(self.sf, SpecFile)\n with self.assertRaises(specfile.SfErrFileOpen):\n SpecFile(\"doesnt_exist.dat\")\n\n # test filename types unicode and bytes\n if sys.version_info[0] < 3:\n try:\n SpecFile(self.fname1)\n except TypeError:\n self.fail(\"failed to handle filename as python2 str\")\n try:\n SpecFile(unicode(self.fname1))\n except TypeError:\n self.fail(\"failed to handle filename as python2 unicode\")\n else:\n try:\n SpecFile(self.fname1)\n except TypeError:\n self.fail(\"failed to handle filename as python3 str\")\n try:\n SpecFile(bytes(self.fname1, 'utf-8'))\n except TypeError:\n self.fail(\"failed to handle filename as python3 bytes\")\n\n def test_number_of_scans(self):\n self.assertEqual(4, len(self.sf))\n\n def test_list_of_scan_indices(self):\n self.assertEqual(self.sf.list(),\n [1, 25, 26, 1])\n self.assertEqual(self.sf.keys(),\n [\"1.1\", \"25.1\", \"26.1\", \"1.2\"])\n\n def test_index_number_order(self):\n self.assertEqual(self.sf.index(1, 2), 3) # sf[\"1.2\"]==sf[3]\n self.assertEqual(self.sf.number(1), 25) # sf[1]==sf[\"25\"]\n self.assertEqual(self.sf.order(3), 2) # sf[3]==sf[\"1.2\"]\n with self.assertRaises(specfile.SfErrScanNotFound):\n self.sf.index(3, 2)\n with self.assertRaises(specfile.SfErrScanNotFound):\n self.sf.index(99)\n\n def assertRaisesRegex(self, *args, **kwargs):\n # Python 2 compatibility\n if sys.version_info.major >= 3:\n return super(TestSpecFile, self).assertRaisesRegex(*args, **kwargs)\n else:\n return self.assertRaisesRegexp(*args, **kwargs)\n\n def test_getitem(self):\n self.assertIsInstance(self.sf[2], Scan)\n self.assertIsInstance(self.sf[\"1.2\"], Scan)\n # int out of range\n with self.assertRaisesRegex(IndexError, 'Scan index must be in ran'):\n self.sf[107]\n # float indexing not allowed\n with self.assertRaisesRegex(TypeError, 'The scan identification k'):\n self.sf[1.2]\n # non existant scan with \"N.M\" indexing\n with self.assertRaises(KeyError):\n self.sf[\"3.2\"]\n\n def test_specfile_iterator(self):\n i = 0\n for scan in self.sf:\n if i == 1:\n self.assertEqual(scan.motor_positions,\n self.sf[1].motor_positions)\n i += 1\n # number of returned scans\n self.assertEqual(i, len(self.sf))\n\n def test_scan_index(self):\n self.assertEqual(self.scan1.index, 0)\n self.assertEqual(self.scan1_2.index, 3)\n self.assertEqual(self.scan25.index, 1)\n\n def test_scan_headers(self):\n self.assertEqual(self.scan25.scan_header_dict['S'],\n \"25 ascan c3th 1.33245 1.52245 40 0.15\")\n self.assertEqual(self.scan1.header[17], '#G0 0')\n self.assertEqual(len(self.scan1.header), 29)\n # parsing headers with long keys\n self.assertEqual(self.scan1.scan_header_dict['UMI0'],\n 'Current AutoM Shutter')\n # parsing empty headers\n self.assertEqual(self.scan1.scan_header_dict['Q'], '')\n # duplicate headers: concatenated (with newline)\n self.assertEqual(self.scan1_2.scan_header_dict[\"U\"],\n \"first duplicate line\\nsecond duplicate line\")\n\n def test_file_headers(self):\n self.assertEqual(self.scan1.header[1],\n '#E 1455180875')\n self.assertEqual(self.scan1.file_header_dict['F'],\n '/tmp/sf.dat')\n\n def test_multiple_file_headers(self):\n \"\"\"Scan 1.2 is after the second file header, with a different\n Epoch\"\"\"\n self.assertEqual(self.scan1_2.header[1],\n '#E 1455180876')\n\n def test_scan_labels(self):\n self.assertEqual(self.scan1.labels,\n ['first column', 'second column', '3rd_col'])\n\n def test_data(self):\n # data_line() and data_col() take 1-based indices as arg\n self.assertAlmostEqual(self.scan1.data_line(1)[2],\n 1.56)\n # tests for data transposition between original file and .data attr\n self.assertAlmostEqual(self.scan1.data[2, 0],\n 8)\n self.assertEqual(self.scan1.data.shape, (3, 4))\n self.assertAlmostEqual(numpy.sum(self.scan1.data), 113.631)\n\n def test_data_column_by_name(self):\n self.assertAlmostEqual(self.scan25.data_column_by_name(\"col2\")[1],\n 1.2)\n # Scan.data is transposed after readinq, so column is the first index\n self.assertAlmostEqual(numpy.sum(self.scan25.data_column_by_name(\"col2\")),\n numpy.sum(self.scan25.data[2, :]))\n with self.assertRaises(specfile.SfErrColNotFound):\n self.scan25.data_column_by_name(\"ygfxgfyxg\")\n\n def test_motors(self):\n self.assertEqual(len(self.scan1.motor_names), 6)\n self.assertEqual(len(self.scan1.motor_positions), 6)\n self.assertAlmostEqual(sum(self.scan1.motor_positions),\n 223.385912)\n self.assertEqual(self.scan1.motor_names[1], 'MRTSlit UP')\n self.assertAlmostEqual(\n self.scan25.motor_position_by_name('MRTSlit UP'),\n -1.66875)\n\n def test_absence_of_file_header(self):\n \"\"\"We expect Scan.file_header to be an empty list in the absence\n of a file header.\n \"\"\"\n self.assertEqual(len(self.scan1_no_fhdr.motor_names), 0)\n # motor positions can still be read in the scan header\n # even in the absence of motor names\n self.assertAlmostEqual(sum(self.scan1_no_fhdr.motor_positions),\n 223.385912)\n self.assertEqual(len(self.scan1_no_fhdr.header), 15)\n self.assertEqual(len(self.scan1_no_fhdr.scan_header), 15)\n self.assertEqual(len(self.scan1_no_fhdr.file_header), 0)\n\n def test_crash_absence_of_file_header(self):\n \"\"\"Test no crash in absence of file header and no leading newline\n character\n \"\"\"\n self.assertEqual(len(self.scan1_no_fhdr_crash.motor_names), 0)\n # motor positions can still be read in the scan header\n # even in the absence of motor names\n self.assertAlmostEqual(sum(self.scan1_no_fhdr_crash.motor_positions),\n 223.385912)\n self.assertEqual(len(self.scan1_no_fhdr_crash.scan_header), 15)\n self.assertEqual(len(self.scan1_no_fhdr_crash.file_header), 0)\n\n def test_mca(self):\n self.assertEqual(len(self.scan1.mca), 0)\n self.assertEqual(len(self.scan1_2.mca), 3)\n self.assertEqual(self.scan1_2.mca[1][2], 5)\n self.assertEqual(sum(self.scan1_2.mca[2]), 21.7)\n\n # Negative indexing\n self.assertEqual(sum(self.scan1_2.mca[len(self.scan1_2.mca) - 1]),\n sum(self.scan1_2.mca[-1]))\n\n # Test iterator\n line_count, total_sum = (0, 0)\n for mca_line in self.scan1_2.mca:\n line_count += 1\n total_sum += sum(mca_line)\n self.assertEqual(line_count, 3)\n self.assertAlmostEqual(total_sum, 36.8)\n\n def test_mca_header(self):\n self.assertEqual(self.scan1.mca_header_dict, {})\n self.assertEqual(len(self.scan1_2.mca_header_dict), 4)\n self.assertEqual(self.scan1_2.mca_header_dict[\"CALIB\"], \"1 2 3\")\n self.assertEqual(self.scan1_2.mca.calibration,\n [[1., 2., 3.]])\n # default calib in the absence of #@CALIB\n self.assertEqual(self.scan25.mca.calibration,\n [[0., 1., 0.]])\n self.assertEqual(self.scan1_2.mca.channels,\n [[0, 1, 2]])\n # absence of #@CHANN and spectra\n self.assertEqual(self.scan25.mca.channels,\n [])\n\n @testutils.test_logging(specfile._logger.name, warning=1)\n def test_empty_scan(self):\n \"\"\"Test reading a scan with no data points\"\"\"\n self.assertEqual(len(self.empty_scan.labels),\n 3)\n col1 = self.empty_scan.data_column_by_name(\"second column\")\n self.assertEqual(col1.shape, (0, ))\n\n\nclass TestSFLocale(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n fd, cls.fname = tempfile.mkstemp(text=False)\n if sys.version_info < (3, ):\n os.write(fd, sftext)\n else:\n os.write(fd, bytes(sftext, 'ascii'))\n os.close(fd)\n\n @classmethod\n def tearDownClass(cls):\n os.unlink(cls.fname)\n locale.setlocale(locale.LC_NUMERIC, loc) # restore saved locale\n\n def crunch_data(self):\n self.sf3 = SpecFile(self.fname)\n self.assertAlmostEqual(self.sf3[0].data_line(1)[2],\n 1.56)\n self.sf3.close()\n\n @unittest.skipIf(not try_DE, \"de_DE.utf8 locale not installed\")\n def test_locale_de_DE(self):\n locale.setlocale(locale.LC_NUMERIC, 'de_DE.utf8')\n self.crunch_data()\n\n def test_locale_user(self):\n locale.setlocale(locale.LC_NUMERIC, '') # use user's preferred locale\n self.crunch_data()\n\n def test_locale_C(self):\n locale.setlocale(locale.LC_NUMERIC, 'C') # use default (C) locale\n self.crunch_data()\n\n\ndef suite():\n test_suite = unittest.TestSuite()\n test_suite.addTest(\n unittest.defaultTestLoader.loadTestsFromTestCase(TestSpecFile))\n test_suite.addTest(\n unittest.defaultTestLoader.loadTestsFromTestCase(TestSFLocale))\n return test_suite\n\n\nif __name__ == '__main__':\n unittest.main(defaultTest=\"suite\")\n", "# coding: utf-8\n# /*##########################################################################\n#\n# Copyright (c) 2019 European Synchrotron Radiation Facility\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n# ###########################################################################*/\n\"\"\"This module provides a widget to visualize 3D arrays\"\"\"\n\n__authors__ = [\"T. Vincent\"]\n__license__ = \"MIT\"\n__date__ = \"22/03/2019\"\n\n\nimport numpy\n\nfrom .. import qt\nfrom ..plot3d.SceneWindow import SceneWindow\nfrom ..plot3d.items import ScalarField3D, ComplexField3D, ItemChangedType\n\n\nclass VolumeWindow(SceneWindow):\n \"\"\"Extends SceneWindow with a convenient API for 3D array\n\n :param QWidget: parent\n \"\"\"\n\n def __init__(self, parent):\n super(VolumeWindow, self).__init__(parent)\n self.__firstData = True\n # Hide global parameter dock\n self.getGroupResetWidget().parent().setVisible(False)\n\n def setAxesLabels(self, xlabel=None, ylabel=None, zlabel=None):\n \"\"\"Set the text labels of the axes.\n\n :param Union[str,None] xlabel: Label of the X axis\n :param Union[str,None] ylabel: Label of the Y axis\n :param Union[str,None] zlabel: Label of the Z axis\n \"\"\"\n sceneWidget = self.getSceneWidget()\n sceneWidget.getSceneGroup().setAxesLabels(\n 'X' if xlabel is None else xlabel,\n 'Y' if ylabel is None else ylabel,\n 'Z' if zlabel is None else zlabel)\n\n def clear(self):\n \"\"\"Clear any currently displayed data\"\"\"\n sceneWidget = self.getSceneWidget()\n items = sceneWidget.getItems()\n if (len(items) == 1 and\n isinstance(items[0], (ScalarField3D, ComplexField3D))):\n items[0].setData(None)\n else: # Safety net\n sceneWidget.clearItems()\n\n @staticmethod\n def __computeIsolevel(data):\n \"\"\"Returns a suitable isolevel value for data\n\n :param numpy.ndarray data:\n :rtype: float\n \"\"\"\n data = data[numpy.isfinite(data)]\n if len(data) == 0:\n return 0\n else:\n return numpy.mean(data) + numpy.std(data)\n\n def setData(self, data, offset=(0., 0., 0.), scale=(1., 1., 1.)):\n \"\"\"Set the 3D array data to display.\n\n :param numpy.ndarray data: 3D array of float or complex\n :param List[float] offset: (tx, ty, tz) coordinates of the origin\n :param List[float] scale: (sx, sy, sz) scale for each dimension\n \"\"\"\n sceneWidget = self.getSceneWidget()\n dataMaxCoords = numpy.array(list(reversed(data.shape))) - 1\n\n previousItems = sceneWidget.getItems()\n if (len(previousItems) == 1 and\n isinstance(previousItems[0], (ScalarField3D, ComplexField3D)) and\n numpy.iscomplexobj(data) == isinstance(previousItems[0], ComplexField3D)):\n # Reuse existing volume item\n volume = sceneWidget.getItems()[0]\n volume.setData(data, copy=False)\n # Make sure the plane goes through the dataset\n for plane in volume.getCutPlanes():\n point = numpy.array(plane.getPoint())\n if numpy.any(point < (0, 0, 0)) or numpy.any(point > dataMaxCoords):\n plane.setPoint(dataMaxCoords // 2)\n else:\n # Add a new volume\n sceneWidget.clearItems()\n volume = sceneWidget.addVolume(data, copy=False)\n volume.setLabel('Volume')\n for plane in volume.getCutPlanes():\n # Make plane going through the center of the data\n plane.setPoint(dataMaxCoords // 2)\n plane.setVisible(False)\n plane.sigItemChanged.connect(self.__cutPlaneUpdated)\n volume.addIsosurface(self.__computeIsolevel, '#FF0000FF')\n\n # Expand the parameter tree\n model = self.getParamTreeView().model()\n index = qt.QModelIndex() # Invalid index for top level\n while 1:\n rowCount = model.rowCount(parent=index)\n if rowCount == 0:\n break\n index = model.index(rowCount - 1, 0, parent=index)\n self.getParamTreeView().setExpanded(index, True)\n if not index.isValid():\n break\n\n volume.setTranslation(*offset)\n volume.setScale(*scale)\n\n if self.__firstData: # Only center for first dataset\n self.__firstData = False\n sceneWidget.centerScene()\n\n def __cutPlaneUpdated(self, event):\n \"\"\"Handle the change of visibility of the cut plane\n\n :param event: Kind of update\n \"\"\"\n if event == ItemChangedType.VISIBLE:\n plane = self.sender()\n if plane.isVisible():\n self.getSceneWidget().selection().setCurrentItem(plane)\n", "#!/usr/bin/env python\n# coding: utf-8\n# /*##########################################################################\n#\n# Copyright (c) 2018-2019 European Synchrotron Radiation Facility\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n# ###########################################################################*/\nimport numpy as np\n\nfrom .basefft import BaseFFT, check_version\ntry:\n import pyfftw\n __have_fftw__ = True\nexcept ImportError:\n __have_fftw__ = False\n\n\n# Check pyfftw version\n__required_pyfftw_version__ = \"0.10.0\"\nif __have_fftw__:\n __have_fftw__ = check_version(pyfftw, __required_pyfftw_version__)\n\n\nclass FFTW(BaseFFT):\n \"\"\"Initialize a FFTW plan.\n\n Please see FFT class for parameters help.\n\n FFTW-specific parameters\n -------------------------\n\n :param bool check_alignment:\n If set to True and \"data\" is provided, this will enforce the input data\n to be \"byte aligned\", which might imply extra memory usage.\n :param int num_threads:\n Number of threads for computing FFT.\n \"\"\"\n def __init__(\n self,\n shape=None,\n dtype=None,\n template=None,\n shape_out=None,\n axes=None,\n normalize=\"rescale\",\n check_alignment=False,\n num_threads=1,\n ):\n if not(__have_fftw__):\n raise ImportError(\"Please install pyfftw >= %s to use the FFTW back-end\" % __required_pyfftw_version__)\n super(FFTW, self).__init__(\n shape=shape,\n dtype=dtype,\n template=template,\n shape_out=shape_out,\n axes=axes,\n normalize=normalize,\n )\n self.check_alignment = check_alignment\n self.num_threads = num_threads\n self.backend = \"fftw\"\n\n self.allocate_arrays()\n self.set_fftw_flags()\n self.compute_forward_plan()\n self.compute_inverse_plan()\n self.refs = {\n \"data_in\": self.data_in,\n \"data_out\": self.data_out,\n }\n\n def set_fftw_flags(self):\n self.fftw_flags = ('FFTW_MEASURE', ) # TODO\n self.fftw_planning_timelimit = None # TODO\n self.fftw_norm_modes = {\n \"rescale\": {\"ortho\": False, \"normalize\": True},\n \"ortho\": {\"ortho\": True, \"normalize\": False},\n \"none\": {\"ortho\": False, \"normalize\": False},\n }\n if self.normalize not in self.fftw_norm_modes:\n raise ValueError(\"Unknown normalization mode %s. Possible values are %s\" %\n (self.normalize, self.fftw_norm_modes.keys())\n )\n self.fftw_norm_mode = self.fftw_norm_modes[self.normalize]\n\n def _allocate(self, shape, dtype):\n return pyfftw.zeros_aligned(shape, dtype=dtype)\n\n def check_array(self, array, shape, dtype, copy=True):\n if array.shape != shape:\n raise ValueError(\"Invalid data shape: expected %s, got %s\" %\n (shape, array.shape)\n )\n if array.dtype != dtype:\n raise ValueError(\"Invalid data type: expected %s, got %s\" %\n (dtype, array.dtype)\n )\n\n def set_data(self, self_array, array, shape, dtype, copy=True, name=None):\n \"\"\"\n :param self_array: array owned by the current instance\n (either self.data_in or self.data_out).\n :type: numpy.ndarray\n :param self_array: data to set\n :type: numpy.ndarray\n :type tuple shape: shape of the array\n :param dtype: type of the array\n :type: numpy.dtype\n :param bool copy: should we copy the array\n :param str name: name of the array\n\n Copies are avoided when possible.\n \"\"\"\n self.check_array(array, shape, dtype)\n if id(self.refs[name]) == id(array):\n # nothing to do: fft is performed on self.data_in or self.data_out\n arr_to_use = self.refs[name]\n if self.check_alignment and not(pyfftw.is_byte_aligned(array)):\n # If the array is not properly aligned,\n # create a temp. array copy it to self.data_in or self.data_out\n self_array[:] = array[:]\n arr_to_use = self_array\n else:\n # If the array is properly aligned, use it directly\n if copy:\n arr_to_use = np.copy(array)\n else:\n arr_to_use = array\n return arr_to_use\n\n def compute_forward_plan(self):\n self.plan_forward = pyfftw.FFTW(\n self.data_in,\n self.data_out,\n axes=self.axes,\n direction='FFTW_FORWARD',\n flags=self.fftw_flags,\n threads=self.num_threads,\n planning_timelimit=self.fftw_planning_timelimit,\n # the following seems to be taken into account only when using __call__\n ortho=self.fftw_norm_mode[\"ortho\"],\n normalise_idft=self.fftw_norm_mode[\"normalize\"],\n )\n\n def compute_inverse_plan(self):\n self.plan_inverse = pyfftw.FFTW(\n self.data_out,\n self.data_in,\n axes=self.axes,\n direction='FFTW_BACKWARD',\n flags=self.fftw_flags,\n threads=self.num_threads,\n planning_timelimit=self.fftw_planning_timelimit,\n # the following seem to be taken into account only when using __call__\n ortho=self.fftw_norm_mode[\"ortho\"],\n normalise_idft=self.fftw_norm_mode[\"normalize\"],\n )\n\n def fft(self, array, output=None):\n \"\"\"\n Perform a (forward) Fast Fourier Transform.\n\n :param numpy.ndarray array:\n Input data. Must be consistent with the current context.\n :param numpy.ndarray output:\n Optional output data.\n \"\"\"\n data_in = self.set_input_data(array, copy=False)\n data_out = self.set_output_data(output, copy=False)\n self.plan_forward.update_arrays(data_in, data_out)\n # execute.__call__ does both update_arrays() and normalization\n self.plan_forward(\n ortho=self.fftw_norm_mode[\"ortho\"],\n )\n self.plan_forward.update_arrays(self.refs[\"data_in\"], self.refs[\"data_out\"])\n return data_out\n\n def ifft(self, array, output=None):\n \"\"\"\n Perform a (inverse) Fast Fourier Transform.\n\n :param numpy.ndarray array:\n Input data. Must be consistent with the current context.\n :param numpy.ndarray output:\n Optional output data.\n \"\"\"\n data_in = self.set_output_data(array, copy=False)\n data_out = self.set_input_data(output, copy=False)\n self.plan_inverse.update_arrays(data_in, data_out)\n # execute.__call__ does both update_arrays() and normalization\n self.plan_inverse(\n ortho=self.fftw_norm_mode[\"ortho\"],\n normalise_idft=self.fftw_norm_mode[\"normalize\"]\n )\n self.plan_inverse.update_arrays(self.refs[\"data_out\"], self.refs[\"data_in\"])\n return data_out\n", "# coding: utf-8\n# /*##########################################################################\n#\n# Copyright (c) 2004-2020 European Synchrotron Radiation Facility\n#\n# This file is part of the PyMca X-ray Fluorescence Toolkit developed at\n# the ESRF by the Software group.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n# ######################################################################### */\n\"\"\"This module provides a widget designed to configure and run a fitting\nprocess with constraints on parameters.\n\nThe main class is :class:`FitWidget`. It relies on\n:mod:`silx.math.fit.fitmanager`, which relies on :func:`silx.math.fit.leastsq`.\n\nThe user can choose between functions before running the fit. These function can\nbe user defined, or by default are loaded from\n:mod:`silx.math.fit.fittheories`.\n\"\"\"\n\n__authors__ = [\"V.A. Sole\", \"P. Knobel\"]\n__license__ = \"MIT\"\n__date__ = \"17/07/2018\"\n\nimport logging\nimport sys\nimport traceback\n\nfrom silx.math.fit import fittheories\nfrom silx.math.fit import fitmanager, functions\nfrom silx.gui import qt\nfrom .FitWidgets import (FitActionsButtons, FitStatusLines,\n FitConfigWidget, ParametersTab)\nfrom .FitConfig import getFitConfigDialog\nfrom .BackgroundWidget import getBgDialog, BackgroundDialog\nfrom ...utils.deprecation import deprecated\n\nQTVERSION = qt.qVersion()\nDEBUG = 0\n_logger = logging.getLogger(__name__)\n\n\n__authors__ = [\"V.A. Sole\", \"P. Knobel\"]\n__license__ = \"MIT\"\n__date__ = \"30/11/2016\"\n\n\nclass FitWidget(qt.QWidget):\n \"\"\"This widget can be used to configure, run and display results of a\n fitting process.\n\n The standard steps for using this widget is to initialize it, then load\n the data to be fitted.\n\n Optionally, you can also load user defined fit theories. If you skip this\n step, a series of default fit functions will be presented (gaussian-like\n functions), and you can later load your custom fit theories from an\n external file using the GUI.\n\n A fit theory is a fit function and its associated features:\n\n - estimation function,\n - list of parameter names\n - numerical derivative algorithm\n - configuration widget\n\n Once the widget is up and running, the user may select a fit theory and a\n background theory, change configuration parameters specific to the theory\n run the estimation, set constraints on parameters and run the actual fit.\n\n The results are displayed in a table.\n\n .. image:: img/FitWidget.png\n \"\"\"\n sigFitWidgetSignal = qt.Signal(object)\n \"\"\"This signal is emitted by the estimation and fit methods.\n It carries a dictionary with two items:\n\n - *event*: one of the following strings\n\n - *EstimateStarted*,\n - *FitStarted*\n - *EstimateFinished*,\n - *FitFinished*\n - *EstimateFailed*\n - *FitFailed*\n\n - *data*: None, or fit/estimate results (see documentation for\n :attr:`silx.math.fit.fitmanager.FitManager.fit_results`)\n \"\"\"\n\n def __init__(self, parent=None, title=None, fitmngr=None,\n enableconfig=True, enablestatus=True, enablebuttons=True):\n \"\"\"\n\n :param parent: Parent widget\n :param title: Window title\n :param fitmngr: User defined instance of\n :class:`silx.math.fit.fitmanager.FitManager`, or ``None``\n :param enableconfig: If ``True``, activate widgets to modify the fit\n configuration (select between several fit functions or background\n functions, apply global constraints, peak search parameters…)\n :param enablestatus: If ``True``, add a fit status widget, to display\n a message when fit estimation is available and when fit results\n are available, as well as a measure of the fit error.\n :param enablebuttons: If ``True``, add buttons to run estimation and\n fitting.\n \"\"\"\n if title is None:\n title = \"FitWidget\"\n qt.QWidget.__init__(self, parent)\n\n self.setWindowTitle(title)\n layout = qt.QVBoxLayout(self)\n\n self.fitmanager = self._setFitManager(fitmngr)\n \"\"\"Instance of :class:`FitManager`.\n This is the underlying data model of this FitWidget.\n\n If no custom theories are defined, the default ones from\n :mod:`silx.math.fit.fittheories` are imported.\n \"\"\"\n\n # reference fitmanager.configure method for direct access\n self.configure = self.fitmanager.configure\n self.fitconfig = self.fitmanager.fitconfig\n\n self.configdialogs = {}\n \"\"\"This dictionary defines the fit configuration widgets\n associated with the fit theories in :attr:`fitmanager.theories`\n\n Keys must correspond to existing theory names, i.e. existing keys\n in :attr:`fitmanager.theories`.\n\n Values must be instances of QDialog widgets with an additional\n *output* attribute, a dictionary storing configuration parameters\n interpreted by the corresponding fit theory.\n\n The dialog can also define a *setDefault* method to initialize the\n widget values with values in a dictionary passed as a parameter.\n This will be executed first.\n\n In case the widget does not actually inherit :class:`QDialog`, it\n must at least implement the following methods (executed in this\n particular order):\n\n - :meth:`show`: should cause the widget to become visible to the\n user)\n - :meth:`exec_`: should run while the user is interacting with the\n widget, interrupting the rest of the program. It should\n typically end (*return*) when the user clicks an *OK*\n or a *Cancel* button.\n - :meth:`result`: must return ``True`` if the new configuration in\n attribute :attr:`output` is to be accepted (user clicked *OK*),\n or return ``False`` if :attr:`output` is to be rejected (user\n clicked *Cancel*)\n\n To associate a custom configuration widget with a fit theory, use\n :meth:`associateConfigDialog`. E.g.::\n\n fw = FitWidget()\n my_config_widget = MyGaussianConfigWidget(parent=fw)\n fw.associateConfigDialog(theory_name=\"Gaussians\",\n config_widget=my_config_widget)\n \"\"\"\n\n self.bgconfigdialogs = {}\n \"\"\"Same as :attr:`configdialogs`, except that the widget is associated\n with a background theory in :attr:`fitmanager.bgtheories`\"\"\"\n\n self._associateDefaultConfigDialogs()\n\n self.guiConfig = None\n \"\"\"Configuration widget at the top of FitWidget, to select\n fit function, background function, and open an advanced\n configuration dialog.\"\"\"\n\n self.guiParameters = ParametersTab(self)\n \"\"\"Table widget for display of fit parameters and constraints\"\"\"\n\n if enableconfig:\n self.guiConfig = FitConfigWidget(self)\n \"\"\"Function selector and configuration widget\"\"\"\n\n self.guiConfig.FunConfigureButton.clicked.connect(\n self.__funConfigureGuiSlot)\n self.guiConfig.BgConfigureButton.clicked.connect(\n self.__bgConfigureGuiSlot)\n\n self.guiConfig.WeightCheckBox.setChecked(\n self.fitconfig.get(\"WeightFlag\", False))\n self.guiConfig.WeightCheckBox.stateChanged[int].connect(self.weightEvent)\n\n self.guiConfig.BkgComBox.activated[str].connect(self.bkgEvent)\n self.guiConfig.FunComBox.activated[str].connect(self.funEvent)\n self._populateFunctions()\n\n layout.addWidget(self.guiConfig)\n\n layout.addWidget(self.guiParameters)\n\n if enablestatus:\n self.guistatus = FitStatusLines(self)\n \"\"\"Status bar\"\"\"\n layout.addWidget(self.guistatus)\n\n if enablebuttons:\n self.guibuttons = FitActionsButtons(self)\n \"\"\"Widget with estimate, start fit and dismiss buttons\"\"\"\n self.guibuttons.EstimateButton.clicked.connect(self.estimate)\n self.guibuttons.EstimateButton.setEnabled(False)\n self.guibuttons.StartFitButton.clicked.connect(self.startFit)\n self.guibuttons.StartFitButton.setEnabled(False)\n self.guibuttons.DismissButton.clicked.connect(self.dismiss)\n layout.addWidget(self.guibuttons)\n\n def _setFitManager(self, fitinstance):\n \"\"\"Initialize a :class:`FitManager` instance, to be assigned to\n :attr:`fitmanager`, or use a custom FitManager instance.\n\n :param fitinstance: Existing instance of FitManager, possibly\n customized by the user, or None to load a default instance.\"\"\"\n if isinstance(fitinstance, fitmanager.FitManager):\n # customized\n fitmngr = fitinstance\n else:\n # initialize default instance\n fitmngr = fitmanager.FitManager()\n\n # initialize the default fitting functions in case\n # none is present\n if not len(fitmngr.theories):\n fitmngr.loadtheories(fittheories)\n\n return fitmngr\n\n def _associateDefaultConfigDialogs(self):\n \"\"\"Fill :attr:`bgconfigdialogs` and :attr:`configdialogs` by calling\n :meth:`associateConfigDialog` with default config dialog widgets.\n \"\"\"\n # associate silx.gui.fit.FitConfig with all theories\n # Users can later associate their own custom dialogs to\n # replace the default.\n configdialog = getFitConfigDialog(parent=self,\n default=self.fitconfig)\n for theory in self.fitmanager.theories:\n self.associateConfigDialog(theory, configdialog)\n for bgtheory in self.fitmanager.bgtheories:\n self.associateConfigDialog(bgtheory, configdialog,\n theory_is_background=True)\n\n # associate silx.gui.fit.BackgroundWidget with Strip and Snip\n bgdialog = getBgDialog(parent=self,\n default=self.fitconfig)\n for bgtheory in [\"Strip\", \"Snip\"]:\n if bgtheory in self.fitmanager.bgtheories:\n self.associateConfigDialog(bgtheory, bgdialog,\n theory_is_background=True)\n\n def _populateFunctions(self):\n \"\"\"Fill combo-boxes with fit theories and background theories\n loaded by :attr:`fitmanager`.\n Run :meth:`fitmanager.configure` to ensure the custom configuration\n of the selected theory has been loaded into :attr:`fitconfig`\"\"\"\n for theory_name in self.fitmanager.bgtheories:\n self.guiConfig.BkgComBox.addItem(theory_name)\n self.guiConfig.BkgComBox.setItemData(\n self.guiConfig.BkgComBox.findText(theory_name),\n self.fitmanager.bgtheories[theory_name].description,\n qt.Qt.ToolTipRole)\n\n for theory_name in self.fitmanager.theories:\n self.guiConfig.FunComBox.addItem(theory_name)\n self.guiConfig.FunComBox.setItemData(\n self.guiConfig.FunComBox.findText(theory_name),\n self.fitmanager.theories[theory_name].description,\n qt.Qt.ToolTipRole)\n\n # - activate selected fit theory (if any)\n # - activate selected bg theory (if any)\n configuration = self.fitmanager.configure()\n if self.fitmanager.selectedtheory is None:\n # take the first one by default\n self.guiConfig.FunComBox.setCurrentIndex(1)\n self.funEvent(list(self.fitmanager.theories.keys())[0])\n else:\n idx = list(self.fitmanager.theories).index(self.fitmanager.selectedtheory)\n self.guiConfig.FunComBox.setCurrentIndex(idx + 1)\n self.funEvent(self.fitmanager.selectedtheory)\n\n if self.fitmanager.selectedbg is None:\n self.guiConfig.BkgComBox.setCurrentIndex(1)\n self.bkgEvent(list(self.fitmanager.bgtheories.keys())[0])\n else:\n idx = list(self.fitmanager.bgtheories).index(self.fitmanager.selectedbg)\n self.guiConfig.BkgComBox.setCurrentIndex(idx + 1)\n self.bkgEvent(self.fitmanager.selectedbg)\n\n configuration.update(self.configure())\n\n @deprecated(replacement='setData', since_version='0.3.0')\n def setdata(self, x, y, sigmay=None, xmin=None, xmax=None):\n self.setData(x, y, sigmay, xmin, xmax)\n\n def setData(self, x=None, y=None, sigmay=None, xmin=None, xmax=None):\n \"\"\"Set data to be fitted.\n\n :param x: Abscissa data. If ``None``, :attr:`xdata`` is set to\n ``numpy.array([0.0, 1.0, 2.0, ..., len(y)-1])``\n :type x: Sequence or numpy array or None\n :param y: The dependant data ``y = f(x)``. ``y`` must have the same\n shape as ``x`` if ``x`` is not ``None``.\n :type y: Sequence or numpy array or None\n :param sigmay: The uncertainties in the ``ydata`` array. These are\n used as weights in the least-squares problem.\n If ``None``, the uncertainties are assumed to be 1.\n :type sigmay: Sequence or numpy array or None\n :param xmin: Lower value of x values to use for fitting\n :param xmax: Upper value of x values to use for fitting\n \"\"\"\n if y is None:\n self.guibuttons.EstimateButton.setEnabled(False)\n self.guibuttons.StartFitButton.setEnabled(False)\n else:\n self.guibuttons.EstimateButton.setEnabled(True)\n self.guibuttons.StartFitButton.setEnabled(True)\n self.fitmanager.setdata(x=x, y=y, sigmay=sigmay,\n xmin=xmin, xmax=xmax)\n for config_dialog in self.bgconfigdialogs.values():\n if isinstance(config_dialog, BackgroundDialog):\n config_dialog.setData(x, y, xmin=xmin, xmax=xmax)\n\n def associateConfigDialog(self, theory_name, config_widget,\n theory_is_background=False):\n \"\"\"Associate an instance of custom configuration dialog widget to\n a fit theory or to a background theory.\n\n This adds or modifies an item in the correspondence table\n :attr:`configdialogs` or :attr:`bgconfigdialogs`.\n\n :param str theory_name: Name of fit theory. This must be a key of dict\n :attr:`fitmanager.theories`\n :param config_widget: Custom configuration widget. See documentation\n for :attr:`configdialogs`\n :param bool theory_is_background: If flag is *True*, add dialog to\n :attr:`bgconfigdialogs` rather than :attr:`configdialogs`\n (default).\n :raise: KeyError if parameter ``theory_name`` does not match an\n existing fit theory or background theory in :attr:`fitmanager`.\n :raise: AttributeError if the widget does not implement the mandatory\n methods (*show*, *exec_*, *result*, *setDefault*) or the mandatory\n attribute (*output*).\n \"\"\"\n theories = self.fitmanager.bgtheories if theory_is_background else\\\n self.fitmanager.theories\n\n if theory_name not in theories:\n raise KeyError(\"%s does not match an existing fitmanager theory\")\n\n if config_widget is not None:\n for mandatory_attr in [\"show\", \"exec_\", \"result\", \"output\"]:\n if not hasattr(config_widget, mandatory_attr):\n raise AttributeError(\n \"Custom configuration widget must define \" +\n \"attribute or method \" + mandatory_attr)\n\n if theory_is_background:\n self.bgconfigdialogs[theory_name] = config_widget\n else:\n self.configdialogs[theory_name] = config_widget\n\n def _emitSignal(self, ddict):\n \"\"\"Emit pyqtSignal after estimation completed\n (``ddict = {'event': 'EstimateFinished', 'data': fit_results}``)\n and after fit completed\n (``ddict = {'event': 'FitFinished', 'data': fit_results}``)\"\"\"\n self.sigFitWidgetSignal.emit(ddict)\n\n def __funConfigureGuiSlot(self):\n \"\"\"Open an advanced configuration dialog widget\"\"\"\n self.__configureGui(dialog_type=\"function\")\n\n def __bgConfigureGuiSlot(self):\n \"\"\"Open an advanced configuration dialog widget\"\"\"\n self.__configureGui(dialog_type=\"background\")\n\n def __configureGui(self, newconfiguration=None, dialog_type=\"function\"):\n \"\"\"Open an advanced configuration dialog widget to get a configuration\n dictionary, or use a supplied configuration dictionary. Call\n :meth:`configure` with this dictionary as a parameter. Update the gui\n accordingly. Reinitialize the fit results in the table and in\n :attr:`fitmanager`.\n\n :param newconfiguration: User supplied configuration dictionary. If ``None``,\n open a dialog widget that returns a dictionary.\"\"\"\n configuration = self.configure()\n # get new dictionary\n if newconfiguration is None:\n newconfiguration = self.configureDialog(configuration, dialog_type)\n # update configuration\n configuration.update(self.configure(**newconfiguration))\n # set fit function theory\n try:\n i = 1 + \\\n list(self.fitmanager.theories.keys()).index(\n self.fitmanager.selectedtheory)\n self.guiConfig.FunComBox.setCurrentIndex(i)\n self.funEvent(self.fitmanager.selectedtheory)\n except ValueError:\n _logger.error(\"Function not in list %s\",\n self.fitmanager.selectedtheory)\n self.funEvent(list(self.fitmanager.theories.keys())[0])\n # current background\n try:\n i = 1 + \\\n list(self.fitmanager.bgtheories.keys()).index(\n self.fitmanager.selectedbg)\n self.guiConfig.BkgComBox.setCurrentIndex(i)\n self.bkgEvent(self.fitmanager.selectedbg)\n except ValueError:\n _logger.error(\"Background not in list %s\",\n self.fitmanager.selectedbg)\n self.bkgEvent(list(self.fitmanager.bgtheories.keys())[0])\n\n # update the Gui\n self.__initialParameters()\n\n def configureDialog(self, oldconfiguration, dialog_type=\"function\"):\n \"\"\"Display a dialog, allowing the user to define fit configuration\n parameters.\n\n By default, a common dialog is used for all fit theories. But if the\n defined a custom dialog using :meth:`associateConfigDialog`, it is\n used instead.\n\n :param dict oldconfiguration: Dictionary containing previous configuration\n :param str dialog_type: \"function\" or \"background\"\n :return: User defined parameters in a dictionary\n \"\"\"\n newconfiguration = {}\n newconfiguration.update(oldconfiguration)\n\n if dialog_type == \"function\":\n theory = self.fitmanager.selectedtheory\n configdialog = self.configdialogs[theory]\n elif dialog_type == \"background\":\n theory = self.fitmanager.selectedbg\n configdialog = self.bgconfigdialogs[theory]\n\n # this should only happen if a user specifically associates None\n # with a theory, to have no configuration option\n if configdialog is None:\n return {}\n\n # update state of configdialog before showing it\n if hasattr(configdialog, \"setDefault\"):\n configdialog.setDefault(newconfiguration)\n configdialog.show()\n configdialog.exec_()\n if configdialog.result():\n newconfiguration.update(configdialog.output)\n\n return newconfiguration\n\n def estimate(self):\n \"\"\"Run parameter estimation function then emit\n :attr:`sigFitWidgetSignal` with a dictionary containing a status\n message and a list of fit parameters estimations\n in the format defined in\n :attr:`silx.math.fit.fitmanager.FitManager.fit_results`\n\n The emitted dictionary has an *\"event\"* key that can have\n following values:\n\n - *'EstimateStarted'*\n - *'EstimateFailed'*\n - *'EstimateFinished'*\n \"\"\"\n try:\n theory_name = self.fitmanager.selectedtheory\n estimation_function = self.fitmanager.theories[theory_name].estimate\n if estimation_function is not None:\n ddict = {'event': 'EstimateStarted',\n 'data': None}\n self._emitSignal(ddict)\n self.fitmanager.estimate(callback=self.fitStatus)\n else:\n msg = qt.QMessageBox(self)\n msg.setIcon(qt.QMessageBox.Information)\n text = \"Function does not define a way to estimate\\n\"\n text += \"the initial parameters. Please, fill them\\n\"\n text += \"yourself in the table and press Start Fit\\n\"\n msg.setText(text)\n msg.setWindowTitle('FitWidget Message')\n msg.exec_()\n return\n except Exception as e: # noqa (we want to catch and report all errors)\n _logger.warning('Estimate error: %s', traceback.format_exc())\n msg = qt.QMessageBox(self)\n msg.setIcon(qt.QMessageBox.Critical)\n msg.setWindowTitle(\"Estimate Error\")\n msg.setText(\"Error on estimate: %s\" % e)\n msg.exec_()\n ddict = {\n 'event': 'EstimateFailed',\n 'data': None}\n self._emitSignal(ddict)\n return\n\n self.guiParameters.fillFromFit(\n self.fitmanager.fit_results, view='Fit')\n self.guiParameters.removeAllViews(keep='Fit')\n ddict = {\n 'event': 'EstimateFinished',\n 'data': self.fitmanager.fit_results}\n self._emitSignal(ddict)\n\n @deprecated(replacement='startFit', since_version='0.3.0')\n def startfit(self):\n self.startFit()\n\n def startFit(self):\n \"\"\"Run fit, then emit :attr:`sigFitWidgetSignal` with a dictionary\n containing a status message and a list of fit\n parameters results in the format defined in\n :attr:`silx.math.fit.fitmanager.FitManager.fit_results`\n\n The emitted dictionary has an *\"event\"* key that can have\n following values:\n\n - *'FitStarted'*\n - *'FitFailed'*\n - *'FitFinished'*\n \"\"\"\n self.fitmanager.fit_results = self.guiParameters.getFitResults()\n try:\n ddict = {'event': 'FitStarted',\n 'data': None}\n self._emitSignal(ddict)\n self.fitmanager.runfit(callback=self.fitStatus)\n except Exception as e: # noqa (we want to catch and report all errors)\n _logger.warning('Estimate error: %s', traceback.format_exc())\n msg = qt.QMessageBox(self)\n msg.setIcon(qt.QMessageBox.Critical)\n msg.setWindowTitle(\"Fit Error\")\n msg.setText(\"Error on Fit: %s\" % e)\n msg.exec_()\n ddict = {\n 'event': 'FitFailed',\n 'data': None\n }\n self._emitSignal(ddict)\n return\n\n self.guiParameters.fillFromFit(\n self.fitmanager.fit_results, view='Fit')\n self.guiParameters.removeAllViews(keep='Fit')\n ddict = {\n 'event': 'FitFinished',\n 'data': self.fitmanager.fit_results\n }\n self._emitSignal(ddict)\n return\n\n def bkgEvent(self, bgtheory):\n \"\"\"Select background theory, then reinitialize parameters\"\"\"\n bgtheory = str(bgtheory)\n if bgtheory in self.fitmanager.bgtheories:\n self.fitmanager.setbackground(bgtheory)\n else:\n functionsfile = qt.QFileDialog.getOpenFileName(\n self, \"Select python module with your function(s)\", \"\",\n \"Python Files (*.py);;All Files (*)\")\n\n if len(functionsfile):\n try:\n self.fitmanager.loadbgtheories(functionsfile)\n except ImportError:\n qt.QMessageBox.critical(self, \"ERROR\",\n \"Function not imported\")\n return\n else:\n # empty the ComboBox\n while self.guiConfig.BkgComBox.count() > 1:\n self.guiConfig.BkgComBox.removeItem(1)\n # and fill it again\n for key in self.fitmanager.bgtheories:\n self.guiConfig.BkgComBox.addItem(str(key))\n\n i = 1 + \\\n list(self.fitmanager.bgtheories.keys()).index(\n self.fitmanager.selectedbg)\n self.guiConfig.BkgComBox.setCurrentIndex(i)\n self.__initialParameters()\n\n def funEvent(self, theoryname):\n \"\"\"Select a fit theory to be used for fitting. If this theory exists\n in :attr:`fitmanager`, use it. Then, reinitialize table.\n\n :param theoryname: Name of the fit theory to use for fitting. If this theory\n exists in :attr:`fitmanager`, use it. Else, open a file dialog to open\n a custom fit function definition file with\n :meth:`fitmanager.loadtheories`.\n \"\"\"\n theoryname = str(theoryname)\n if theoryname in self.fitmanager.theories:\n self.fitmanager.settheory(theoryname)\n else:\n # open a load file dialog\n functionsfile = qt.QFileDialog.getOpenFileName(\n self, \"Select python module with your function(s)\", \"\",\n \"Python Files (*.py);;All Files (*)\")\n\n if len(functionsfile):\n try:\n self.fitmanager.loadtheories(functionsfile)\n except ImportError:\n qt.QMessageBox.critical(self, \"ERROR\",\n \"Function not imported\")\n return\n else:\n # empty the ComboBox\n while self.guiConfig.FunComBox.count() > 1:\n self.guiConfig.FunComBox.removeItem(1)\n # and fill it again\n for key in self.fitmanager.theories:\n self.guiConfig.FunComBox.addItem(str(key))\n\n i = 1 + \\\n list(self.fitmanager.theories.keys()).index(\n self.fitmanager.selectedtheory)\n self.guiConfig.FunComBox.setCurrentIndex(i)\n self.__initialParameters()\n\n def weightEvent(self, flag):\n \"\"\"This is called when WeightCheckBox is clicked, to configure the\n *WeightFlag* field in :attr:`fitmanager.fitconfig` and set weights\n in the least-square problem.\"\"\"\n self.configure(WeightFlag=flag)\n if flag:\n self.fitmanager.enableweight()\n else:\n # set weights back to 1\n self.fitmanager.disableweight()\n\n def __initialParameters(self):\n \"\"\"Fill the fit parameters names with names of the parameters of\n the selected background theory and the selected fit theory.\n Initialize :attr:`fitmanager.fit_results` with these names, and\n initialize the table with them. This creates a view called \"Fit\"\n in :attr:`guiParameters`\"\"\"\n self.fitmanager.parameter_names = []\n self.fitmanager.fit_results = []\n for pname in self.fitmanager.bgtheories[self.fitmanager.selectedbg].parameters:\n self.fitmanager.parameter_names.append(pname)\n self.fitmanager.fit_results.append({'name': pname,\n 'estimation': 0,\n 'group': 0,\n 'code': 'FREE',\n 'cons1': 0,\n 'cons2': 0,\n 'fitresult': 0.0,\n 'sigma': 0.0,\n 'xmin': None,\n 'xmax': None})\n if self.fitmanager.selectedtheory is not None:\n theory = self.fitmanager.selectedtheory\n for pname in self.fitmanager.theories[theory].parameters:\n self.fitmanager.parameter_names.append(pname + \"1\")\n self.fitmanager.fit_results.append({'name': pname + \"1\",\n 'estimation': 0,\n 'group': 1,\n 'code': 'FREE',\n 'cons1': 0,\n 'cons2': 0,\n 'fitresult': 0.0,\n 'sigma': 0.0,\n 'xmin': None,\n 'xmax': None})\n\n self.guiParameters.fillFromFit(\n self.fitmanager.fit_results, view='Fit')\n\n def fitStatus(self, data):\n \"\"\"Set *status* and *chisq* in status bar\"\"\"\n if 'chisq' in data:\n if data['chisq'] is None:\n self.guistatus.ChisqLine.setText(\" \")\n else:\n chisq = data['chisq']\n self.guistatus.ChisqLine.setText(\"%6.2f\" % chisq)\n\n if 'status' in data:\n status = data['status']\n self.guistatus.StatusLine.setText(str(status))\n\n def dismiss(self):\n \"\"\"Close FitWidget\"\"\"\n self.close()\n\n\nif __name__ == \"__main__\":\n import numpy\n\n x = numpy.arange(1500).astype(numpy.float64)\n constant_bg = 3.14\n\n p = [1000, 100., 30.0,\n 500, 300., 25.,\n 1700, 500., 35.,\n 750, 700., 30.0,\n 1234, 900., 29.5,\n 302, 1100., 30.5,\n 75, 1300., 21.]\n y = functions.sum_gauss(x, *p) + constant_bg\n\n a = qt.QApplication(sys.argv)\n w = FitWidget()\n w.setData(x=x, y=y)\n w.show()\n a.exec_()\n", "# coding: utf-8\n# /*##########################################################################\n# Copyright (C) 2016-2019 European Synchrotron Radiation Facility\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n# ############################################################################*/\n\"\"\"\nNominal tests of the HistogramndLut function.\n\"\"\"\n\nimport unittest\n\nimport numpy as np\n\nfrom silx.math import HistogramndLut\n\n\ndef _get_bin_edges(histo_range, n_bins, n_dims):\n edges = []\n for i_dim in range(n_dims):\n edges.append(histo_range[i_dim, 0] +\n np.arange(n_bins[i_dim] + 1) *\n (histo_range[i_dim, 1] - histo_range[i_dim, 0]) /\n n_bins[i_dim])\n return tuple(edges)\n\n\n# ==============================================================\n# ==============================================================\n# ==============================================================\n\n\nclass _TestHistogramndLut_nominal(unittest.TestCase):\n \"\"\"\n Unit tests of the HistogramndLut class.\n \"\"\"\n\n ndims = None\n\n def setUp(self):\n ndims = self.ndims\n self.tested_dim = ndims-1\n\n if ndims is None:\n raise ValueError('ndims class member not set.')\n\n sample = np.array([5.5, -3.3,\n 0., -0.5,\n 3.3, 8.8,\n -7.7, 6.0,\n -4.0])\n\n weights = np.array([500.5, -300.3,\n 0.01, -0.5,\n 300.3, 800.8,\n -700.7, 600.6,\n -400.4])\n\n n_elems = len(sample)\n\n if ndims == 1:\n shape = (n_elems,)\n else:\n shape = (n_elems, ndims)\n\n self.sample = np.zeros(shape=shape, dtype=sample.dtype)\n if ndims == 1:\n self.sample = sample\n else:\n self.sample[..., ndims-1] = sample\n\n self.weights = weights\n\n # the tests are performed along one dimension,\n # all the other bins indices along the other dimensions\n # are expected to be 2\n # (e.g : when testing a 2D sample : [0, x] will go into\n # bin [2, y] because of the bin ranges [-2, 2] and n_bins = 4\n # for the first dimension)\n self.other_axes_index = 2\n self.histo_range = np.repeat([[-2., 2.]], ndims, axis=0)\n self.histo_range[ndims-1] = [-4., 6.]\n\n self.n_bins = np.array([4]*ndims)\n self.n_bins[ndims-1] = 5\n\n if ndims == 1:\n def fill_histo(h, v, dim, op=None):\n if op:\n h[:] = op(h[:], v)\n else:\n h[:] = v\n self.fill_histo = fill_histo\n else:\n def fill_histo(h, v, dim, op=None):\n idx = [self.other_axes_index]*len(h.shape)\n idx[dim] = slice(0, None)\n idx = tuple(idx)\n if op:\n h[idx] = op(h[idx], v)\n else:\n h[idx] = v\n self.fill_histo = fill_histo\n\n def test_nominal_bin_edges(self):\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins)\n\n bin_edges = instance.bins_edges\n\n expected_edges = _get_bin_edges(self.histo_range,\n self.n_bins,\n self.ndims)\n\n for i_edges, edges in enumerate(expected_edges):\n self.assertTrue(np.array_equal(bin_edges[i_edges],\n expected_edges[i_edges]),\n msg='Testing bin_edges for dim {0}'\n ''.format(i_edges+1))\n\n def test_nominal_histo_range(self):\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins)\n\n histo_range = instance.histo_range\n\n self.assertTrue(np.array_equal(histo_range, self.histo_range))\n\n def test_nominal_last_bin_closed(self):\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins)\n\n last_bin_closed = instance.last_bin_closed\n\n self.assertEqual(last_bin_closed, False)\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins,\n last_bin_closed=True)\n\n last_bin_closed = instance.last_bin_closed\n\n self.assertEqual(last_bin_closed, True)\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins,\n last_bin_closed=False)\n\n last_bin_closed = instance.last_bin_closed\n\n self.assertEqual(last_bin_closed, False)\n\n def test_nominal_n_bins_array(self):\n\n test_n_bins = np.arange(self.ndims) + 10\n instance = HistogramndLut(self.sample,\n self.histo_range,\n test_n_bins)\n\n n_bins = instance.n_bins\n\n self.assertTrue(np.array_equal(test_n_bins, n_bins))\n\n def test_nominal_n_bins_scalar(self):\n\n test_n_bins = 10\n expected_n_bins = np.array([test_n_bins] * self.ndims)\n instance = HistogramndLut(self.sample,\n self.histo_range,\n test_n_bins)\n\n n_bins = instance.n_bins\n\n self.assertTrue(np.array_equal(expected_n_bins, n_bins))\n\n def test_nominal_histo_ref(self):\n \"\"\"\n \"\"\"\n expected_h_tpl = np.array([2, 1, 1, 1, 1])\n expected_c_tpl = np.array([-700.7, -0.5, 0.01, 300.3, 500.5])\n\n expected_h = np.zeros(shape=self.n_bins, dtype=np.double)\n expected_c = np.zeros(shape=self.n_bins, dtype=np.double)\n\n self.fill_histo(expected_h, expected_h_tpl, self.ndims-1)\n self.fill_histo(expected_c, expected_c_tpl, self.ndims-1)\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins)\n\n instance.accumulate(self.weights)\n\n histo = instance.histo()\n w_histo = instance.weighted_histo()\n histo_ref = instance.histo(copy=False)\n w_histo_ref = instance.weighted_histo(copy=False)\n\n self.assertTrue(np.array_equal(histo, expected_h))\n self.assertTrue(np.array_equal(w_histo, expected_c))\n self.assertTrue(np.array_equal(histo_ref, expected_h))\n self.assertTrue(np.array_equal(w_histo_ref, expected_c))\n\n histo_ref[0, ...] = histo_ref[0, ...] + 10\n w_histo_ref[0, ...] = w_histo_ref[0, ...] + 20\n\n self.assertTrue(np.array_equal(histo, expected_h))\n self.assertTrue(np.array_equal(w_histo, expected_c))\n self.assertFalse(np.array_equal(histo_ref, expected_h))\n self.assertFalse(np.array_equal(w_histo_ref, expected_c))\n\n histo_2 = instance.histo()\n w_histo_2 = instance.weighted_histo()\n\n self.assertFalse(np.array_equal(histo_2, expected_h))\n self.assertFalse(np.array_equal(w_histo_2, expected_c))\n self.assertTrue(np.array_equal(histo_2, histo_ref))\n self.assertTrue(np.array_equal(w_histo_2, w_histo_ref))\n\n def test_nominal_accumulate_once(self):\n \"\"\"\n \"\"\"\n expected_h_tpl = np.array([2, 1, 1, 1, 1])\n expected_c_tpl = np.array([-700.7, -0.5, 0.01, 300.3, 500.5])\n\n expected_h = np.zeros(shape=self.n_bins, dtype=np.double)\n expected_c = np.zeros(shape=self.n_bins, dtype=np.double)\n\n self.fill_histo(expected_h, expected_h_tpl, self.ndims-1)\n self.fill_histo(expected_c, expected_c_tpl, self.ndims-1)\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins)\n\n instance.accumulate(self.weights)\n\n histo = instance.histo()\n w_histo = instance.weighted_histo()\n\n self.assertEqual(w_histo.dtype, np.float64)\n self.assertEqual(histo.dtype, np.uint32)\n self.assertTrue(np.array_equal(histo, expected_h))\n self.assertTrue(np.array_equal(w_histo, expected_c))\n self.assertTrue(np.array_equal(instance.histo(), expected_h))\n self.assertTrue(np.array_equal(instance.weighted_histo(),\n expected_c))\n\n def test_nominal_accumulate_twice(self):\n \"\"\"\n \"\"\"\n expected_h_tpl = np.array([2, 1, 1, 1, 1])\n expected_c_tpl = np.array([-700.7, -0.5, 0.01, 300.3, 500.5])\n\n expected_h = np.zeros(shape=self.n_bins, dtype=np.double)\n expected_c = np.zeros(shape=self.n_bins, dtype=np.double)\n\n self.fill_histo(expected_h, expected_h_tpl, self.ndims-1)\n self.fill_histo(expected_c, expected_c_tpl, self.ndims-1)\n\n # calling accumulate twice\n expected_h *= 2\n expected_c *= 2\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins)\n\n instance.accumulate(self.weights)\n\n instance.accumulate(self.weights)\n\n histo = instance.histo()\n w_histo = instance.weighted_histo()\n\n self.assertEqual(w_histo.dtype, np.float64)\n self.assertEqual(histo.dtype, np.uint32)\n self.assertTrue(np.array_equal(histo, expected_h))\n self.assertTrue(np.array_equal(w_histo, expected_c))\n self.assertTrue(np.array_equal(instance.histo(), expected_h))\n self.assertTrue(np.array_equal(instance.weighted_histo(),\n expected_c))\n\n def test_nominal_apply_lut_once(self):\n \"\"\"\n \"\"\"\n expected_h_tpl = np.array([2, 1, 1, 1, 1])\n expected_c_tpl = np.array([-700.7, -0.5, 0.01, 300.3, 500.5])\n\n expected_h = np.zeros(shape=self.n_bins, dtype=np.double)\n expected_c = np.zeros(shape=self.n_bins, dtype=np.double)\n\n self.fill_histo(expected_h, expected_h_tpl, self.ndims-1)\n self.fill_histo(expected_c, expected_c_tpl, self.ndims-1)\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins)\n\n histo, w_histo = instance.apply_lut(self.weights)\n\n self.assertEqual(w_histo.dtype, np.float64)\n self.assertEqual(histo.dtype, np.uint32)\n self.assertTrue(np.array_equal(histo, expected_h))\n self.assertTrue(np.array_equal(w_histo, expected_c))\n self.assertEqual(instance.histo(), None)\n self.assertEqual(instance.weighted_histo(), None)\n\n def test_nominal_apply_lut_twice(self):\n \"\"\"\n \"\"\"\n expected_h_tpl = np.array([2, 1, 1, 1, 1])\n expected_c_tpl = np.array([-700.7, -0.5, 0.01, 300.3, 500.5])\n\n expected_h = np.zeros(shape=self.n_bins, dtype=np.double)\n expected_c = np.zeros(shape=self.n_bins, dtype=np.double)\n\n self.fill_histo(expected_h, expected_h_tpl, self.ndims-1)\n self.fill_histo(expected_c, expected_c_tpl, self.ndims-1)\n\n # calling apply_lut twice\n expected_h *= 2\n expected_c *= 2\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins)\n\n histo, w_histo = instance.apply_lut(self.weights)\n histo_2, w_histo_2 = instance.apply_lut(self.weights,\n histo=histo,\n weighted_histo=w_histo)\n\n self.assertEqual(id(histo), id(histo_2))\n self.assertEqual(id(w_histo), id(w_histo_2))\n self.assertEqual(w_histo.dtype, np.float64)\n self.assertEqual(histo.dtype, np.uint32)\n self.assertTrue(np.array_equal(histo, expected_h))\n self.assertTrue(np.array_equal(w_histo, expected_c))\n self.assertEqual(instance.histo(), None)\n self.assertEqual(instance.weighted_histo(), None)\n\n def test_nominal_accumulate_last_bin_closed(self):\n \"\"\"\n \"\"\"\n expected_h_tpl = np.array([2, 1, 1, 1, 2])\n expected_c_tpl = np.array([-700.7, -0.5, 0.01, 300.3, 1101.1])\n\n expected_h = np.zeros(shape=self.n_bins, dtype=np.double)\n expected_c = np.zeros(shape=self.n_bins, dtype=np.double)\n\n self.fill_histo(expected_h, expected_h_tpl, self.ndims-1)\n self.fill_histo(expected_c, expected_c_tpl, self.ndims-1)\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins,\n last_bin_closed=True)\n\n instance.accumulate(self.weights)\n\n histo = instance.histo()\n w_histo = instance.weighted_histo()\n\n self.assertEqual(w_histo.dtype, np.float64)\n self.assertEqual(histo.dtype, np.uint32)\n self.assertTrue(np.array_equal(histo, expected_h))\n self.assertTrue(np.array_equal(w_histo, expected_c))\n\n def test_nominal_accumulate_weight_min_max(self):\n \"\"\"\n \"\"\"\n weight_min = -299.9\n weight_max = 499.9\n\n expected_h_tpl = np.array([0, 1, 1, 1, 0])\n expected_c_tpl = np.array([0., -0.5, 0.01, 300.3, 0.])\n\n expected_h = np.zeros(shape=self.n_bins, dtype=np.double)\n expected_c = np.zeros(shape=self.n_bins, dtype=np.double)\n\n self.fill_histo(expected_h, expected_h_tpl, self.ndims-1)\n self.fill_histo(expected_c, expected_c_tpl, self.ndims-1)\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins)\n\n instance.accumulate(self.weights,\n weight_min=weight_min,\n weight_max=weight_max)\n\n histo = instance.histo()\n w_histo = instance.weighted_histo()\n\n self.assertEqual(w_histo.dtype, np.float64)\n self.assertEqual(histo.dtype, np.uint32)\n self.assertTrue(np.array_equal(histo, expected_h))\n self.assertTrue(np.array_equal(w_histo, expected_c))\n\n def test_nominal_accumulate_forced_int32(self):\n \"\"\"\n double weights, int32 weighted_histogram\n \"\"\"\n expected_h_tpl = np.array([2, 1, 1, 1, 1])\n expected_c_tpl = np.array([-700, 0, 0, 300, 500])\n\n expected_h = np.zeros(shape=self.n_bins, dtype=np.double)\n expected_c = np.zeros(shape=self.n_bins, dtype=np.double)\n\n self.fill_histo(expected_h, expected_h_tpl, self.ndims-1)\n self.fill_histo(expected_c, expected_c_tpl, self.ndims-1)\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins,\n dtype=np.int32)\n\n instance.accumulate(self.weights)\n\n histo = instance.histo()\n w_histo = instance.weighted_histo()\n\n self.assertEqual(w_histo.dtype, np.int32)\n self.assertEqual(histo.dtype, np.uint32)\n self.assertTrue(np.array_equal(histo, expected_h))\n self.assertTrue(np.array_equal(w_histo, expected_c))\n\n def test_nominal_accumulate_forced_float32(self):\n \"\"\"\n int32 weights, float32 weighted_histogram\n \"\"\"\n expected_h_tpl = np.array([2, 1, 1, 1, 1])\n expected_c_tpl = np.array([-700., 0., 0., 300., 500.])\n\n expected_h = np.zeros(shape=self.n_bins, dtype=np.double)\n expected_c = np.zeros(shape=self.n_bins, dtype=np.float32)\n\n self.fill_histo(expected_h, expected_h_tpl, self.ndims-1)\n self.fill_histo(expected_c, expected_c_tpl, self.ndims-1)\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins,\n dtype=np.float32)\n\n instance.accumulate(self.weights.astype(np.int32))\n\n histo = instance.histo()\n w_histo = instance.weighted_histo()\n\n self.assertEqual(w_histo.dtype, np.float32)\n self.assertEqual(histo.dtype, np.uint32)\n self.assertTrue(np.array_equal(histo, expected_h))\n self.assertTrue(np.array_equal(w_histo, expected_c))\n\n def test_nominal_accumulate_int32(self):\n \"\"\"\n int32 weights\n \"\"\"\n expected_h_tpl = np.array([2, 1, 1, 1, 1])\n expected_c_tpl = np.array([-700, 0, 0, 300, 500])\n\n expected_h = np.zeros(shape=self.n_bins, dtype=np.double)\n expected_c = np.zeros(shape=self.n_bins, dtype=np.int32)\n\n self.fill_histo(expected_h, expected_h_tpl, self.ndims-1)\n self.fill_histo(expected_c, expected_c_tpl, self.ndims-1)\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins)\n\n instance.accumulate(self.weights.astype(np.int32))\n\n histo = instance.histo()\n w_histo = instance.weighted_histo()\n\n self.assertEqual(w_histo.dtype, np.int32)\n self.assertEqual(histo.dtype, np.uint32)\n self.assertTrue(np.array_equal(histo, expected_h))\n self.assertTrue(np.array_equal(w_histo, expected_c))\n\n def test_nominal_accumulate_int32_double(self):\n \"\"\"\n int32 weights\n \"\"\"\n expected_h_tpl = np.array([2, 1, 1, 1, 1])\n expected_c_tpl = np.array([-700, 0, 0, 300, 500])\n\n expected_h = np.zeros(shape=self.n_bins, dtype=np.double)\n expected_c = np.zeros(shape=self.n_bins, dtype=np.int32)\n\n self.fill_histo(expected_h, expected_h_tpl, self.ndims-1)\n self.fill_histo(expected_c, expected_c_tpl, self.ndims-1)\n\n instance = HistogramndLut(self.sample,\n self.histo_range,\n self.n_bins)\n\n instance.accumulate(self.weights.astype(np.int32))\n instance.accumulate(self.weights)\n\n histo = instance.histo()\n w_histo = instance.weighted_histo()\n\n expected_h *= 2\n expected_c *= 2\n\n self.assertEqual(w_histo.dtype, np.int32)\n self.assertEqual(histo.dtype, np.uint32)\n self.assertTrue(np.array_equal(histo, expected_h))\n self.assertTrue(np.array_equal(w_histo, expected_c))\n\n def testNoneNativeTypes(self):\n type = self.sample.dtype.newbyteorder(\"B\")\n sampleB = self.sample.astype(type)\n\n type = self.sample.dtype.newbyteorder(\"L\")\n sampleL = self.sample.astype(type)\n\n histo_inst = HistogramndLut(sampleB,\n self.histo_range,\n self.n_bins)\n\n histo_inst = HistogramndLut(sampleL,\n self.histo_range,\n self.n_bins)\n\n\nclass TestHistogramndLut_nominal_1d(_TestHistogramndLut_nominal):\n ndims = 1\n\n\nclass TestHistogramndLut_nominal_2d(_TestHistogramndLut_nominal):\n ndims = 2\n\n\nclass TestHistogramndLut_nominal_3d(_TestHistogramndLut_nominal):\n ndims = 3\n\n\n# ==============================================================\n# ==============================================================\n# ==============================================================\n\n\ntest_cases = (TestHistogramndLut_nominal_1d,\n TestHistogramndLut_nominal_2d,\n TestHistogramndLut_nominal_3d,)\n\n\ndef suite():\n loader = unittest.defaultTestLoader\n test_suite = unittest.TestSuite()\n for test_class in test_cases:\n tests = loader.loadTestsFromTestCase(test_class)\n test_suite.addTests(tests)\n return test_suite\n\nif __name__ == '__main__':\n unittest.main(defaultTest=\"suite\")\n", "# coding: utf-8\n# /*##########################################################################\n#\n# Copyright (c) 2018 European Synchrotron Radiation Facility\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n# ###########################################################################*/\n\"\"\"offer some generic 2D bounding box features\n\"\"\"\n\n__authors__ = [\"H. Payno\"]\n__license__ = \"MIT\"\n__date__ = \"07/09/2019\"\n\nfrom silx.math.combo import min_max\nimport numpy\n\n\nclass _BoundingBox:\n \"\"\"\n Simple 2D bounding box\n\n :param tuple bottom_left: (y, x) bottom left point\n :param tuple top_right: (y, x) top right point\n \"\"\"\n def __init__(self, bottom_left, top_right):\n self.bottom_left = bottom_left\n self.top_right = top_right\n self.min_x = bottom_left[1]\n self.min_y = bottom_left[0]\n self.max_x = top_right[1]\n self.max_y = top_right[0]\n\n def contains(self, item):\n \"\"\"\n\n :param item: bouding box or point. If it is bounding check check if the\n bottom_left and top_right corner of the given bounding box\n are inside the current bounding box\n :type: Union[BoundingBox, tuple]\n :return:\n \"\"\"\n if isinstance(item, _BoundingBox):\n return self.contains(item.bottom_left) and self.contains(item.top_right)\n else:\n return (\n (self.min_x <= item[1] <= self.max_x) and\n (self.min_y <= item[0] <= self.max_y)\n )\n\n def collide(self, bb):\n \"\"\"\n Check if the two bounding box collide\n\n :param bb: bounding box to compare with\n :type: :class:BoundingBox\n :return: True if the two boxes collides\n :rtype: bool\n \"\"\"\n assert isinstance(bb, _BoundingBox)\n return (\n (self.min_x < bb.max_x and self.max_x > bb.min_x) and\n (self.min_y < bb.max_y and self.max_y > bb.min_y)\n )\n\n @staticmethod\n def from_points(points):\n \"\"\"\n\n :param numpy.array tuple points: list of points. Should be 2D:\n [(y1, x1), (y2, x2), (y3, x3), ...]\n :return: bounding box from two points\n :rtype: _BoundingBox\n \"\"\"\n if not isinstance(points, numpy.ndarray):\n points_ = numpy.ndarray(points)\n else:\n points_ = points\n x = points_[:, 1]\n y = points_[:, 0]\n x_min, x_max = min_max(x)\n y_min, y_max = min_max(y)\n return _BoundingBox(bottom_left=(y_min, x_min), top_right=(y_max, x_max))\n", "# coding: utf-8\n# /*##########################################################################\n#\n# Copyright (c) 2004-2018 European Synchrotron Radiation Facility\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n# ###########################################################################*/\n\"\"\"Widget displaying a symbol (marker symbol, line style and color) to identify\nan item displayed by a plot.\n\"\"\"\n\n__authors__ = [\"V.A. Sole\", \"T. Rueter\", \"T. Vincent\"]\n__license__ = \"MIT\"\n__data__ = \"11/11/2019\"\n\n\nimport logging\n\nimport numpy\n\nfrom .. import qt, colors\n\n\n_logger = logging.getLogger(__name__)\n\n\n# Build all symbols\n# Courtesy of the pyqtgraph project\n\n_Symbols = None\n\"\"\"\"Cache supported symbols as Qt paths\"\"\"\n\n\n_NoSymbols = (None, 'None', 'none', '', ' ')\n\"\"\"List of values resulting in no symbol being displayed for a curve\"\"\"\n\n\n_LineStyles = {\n None: qt.Qt.NoPen,\n 'None': qt.Qt.NoPen,\n 'none': qt.Qt.NoPen,\n '': qt.Qt.NoPen,\n ' ': qt.Qt.NoPen,\n '-': qt.Qt.SolidLine,\n '--': qt.Qt.DashLine,\n ':': qt.Qt.DotLine,\n '-.': qt.Qt.DashDotLine\n}\n\"\"\"Conversion from matplotlib-like linestyle to Qt\"\"\"\n\n_NoLineStyle = (None, 'None', 'none', '', ' ')\n\"\"\"List of style values resulting in no line being displayed for a curve\"\"\"\n\n\n_colormapImage = {}\n\"\"\"Store cached pixmap\"\"\"\n# FIXME: Could be better to use a LRU dictionary\n\n_COLORMAP_PIXMAP_SIZE = 32\n\"\"\"Size of the cached pixmaps for the colormaps\"\"\"\n\n\ndef _initSymbols():\n \"\"\"Init the cached symbol structure if not yet done.\"\"\"\n global _Symbols\n if _Symbols is not None:\n return\n\n symbols = dict([(name, qt.QPainterPath())\n for name in ['o', 's', 't', 'd', '+', 'x', '.', ',']])\n symbols['o'].addEllipse(qt.QRectF(.1, .1, .8, .8))\n symbols['.'].addEllipse(qt.QRectF(.3, .3, .4, .4))\n symbols[','].addEllipse(qt.QRectF(.4, .4, .2, .2))\n symbols['s'].addRect(qt.QRectF(.1, .1, .8, .8))\n\n coords = {\n 't': [(0.5, 0.), (.1, .8), (.9, .8)],\n 'd': [(0.1, 0.5), (0.5, 0.), (0.9, 0.5), (0.5, 1.)],\n '+': [(0.0, 0.40), (0.40, 0.40), (0.40, 0.), (0.60, 0.),\n (0.60, 0.40), (1., 0.40), (1., 0.60), (0.60, 0.60),\n (0.60, 1.), (0.40, 1.), (0.40, 0.60), (0., 0.60)],\n 'x': [(0.0, 0.40), (0.40, 0.40), (0.40, 0.), (0.60, 0.),\n (0.60, 0.40), (1., 0.40), (1., 0.60), (0.60, 0.60),\n (0.60, 1.), (0.40, 1.), (0.40, 0.60), (0., 0.60)]\n }\n for s, c in coords.items():\n symbols[s].moveTo(*c[0])\n for x, y in c[1:]:\n symbols[s].lineTo(x, y)\n symbols[s].closeSubpath()\n tr = qt.QTransform()\n tr.rotate(45)\n symbols['x'].translate(qt.QPointF(-0.5, -0.5))\n symbols['x'] = tr.map(symbols['x'])\n symbols['x'].translate(qt.QPointF(0.5, 0.5))\n\n _Symbols = symbols\n\n\nclass LegendIconWidget(qt.QWidget):\n \"\"\"Object displaying linestyle and symbol of plots.\n\n :param QWidget parent: See :class:`QWidget`\n \"\"\"\n\n def __init__(self, parent=None):\n super(LegendIconWidget, self).__init__(parent)\n _initSymbols()\n\n # Visibilities\n self.showLine = True\n self.showSymbol = True\n self.showColormap = True\n\n # Line attributes\n self.lineStyle = qt.Qt.NoPen\n self.lineWidth = 1.\n self.lineColor = qt.Qt.green\n\n self.symbol = ''\n # Symbol attributes\n self.symbolStyle = qt.Qt.SolidPattern\n self.symbolColor = qt.Qt.green\n self.symbolOutlineBrush = qt.QBrush(qt.Qt.white)\n self.symbolColormap = None\n \"\"\"Name or array of colors\"\"\"\n\n self.colormap = None\n \"\"\"Name or array of colors\"\"\"\n\n # Control widget size: sizeHint \"is the only acceptable\n # alternative, so the widget can never grow or shrink\"\n # (c.f. Qt Doc, enum QSizePolicy::Policy)\n self.setSizePolicy(qt.QSizePolicy.Fixed,\n qt.QSizePolicy.Fixed)\n\n def sizeHint(self):\n return qt.QSize(50, 15)\n\n def setSymbol(self, symbol):\n \"\"\"Set the symbol\"\"\"\n symbol = str(symbol)\n if symbol not in _NoSymbols:\n if symbol not in _Symbols:\n raise ValueError(\"Unknown symbol: <%s>\" % symbol)\n self.symbol = symbol\n self.update()\n\n def setSymbolColor(self, color):\n \"\"\"\n :param color: determines the symbol color\n :type style: qt.QColor\n \"\"\"\n self.symbolColor = qt.QColor(color)\n self.update()\n\n # Modify Line\n\n def setLineColor(self, color):\n self.lineColor = qt.QColor(color)\n self.update()\n\n def setLineWidth(self, width):\n self.lineWidth = float(width)\n self.update()\n\n def setLineStyle(self, style):\n \"\"\"Set the linestyle.\n\n Possible line styles:\n\n - '', ' ', 'None': No line\n - '-': solid\n - '--': dashed\n - ':': dotted\n - '-.': dash and dot\n\n :param str style: The linestyle to use\n \"\"\"\n if style not in _LineStyles:\n raise ValueError('Unknown style: %s', style)\n self.lineStyle = _LineStyles[style]\n self.update()\n\n def _toLut(self, colormap):\n \"\"\"Returns an internal LUT object used by this widget to manage\n a colormap LUT.\n\n If the argument is a `Colormap` object, only the current state will be\n displayed. The object itself will not be stored, and further changes\n of this `Colormap` will not update this widget.\n\n :param Union[str,numpy.ndarray,Colormap] colormap: The colormap to\n display\n :rtype: Union[None,str,numpy.ndarray]\n \"\"\"\n if isinstance(colormap, colors.Colormap):\n # Helper to allow to support Colormap objects\n c = colormap.getName()\n if c is None:\n c = colormap.getNColors()\n colormap = c\n\n return colormap\n\n def setColormap(self, colormap):\n \"\"\"Set the colormap to display\n\n If the argument is a `Colormap` object, only the current state will be\n displayed. The object itself will not be stored, and further changes\n of this `Colormap` will not update this widget.\n\n :param Union[str,numpy.ndarray,Colormap] colormap: The colormap to\n display\n \"\"\"\n colormap = self._toLut(colormap)\n\n if colormap is None:\n if self.colormap is None:\n return\n self.colormap = None\n self.update()\n return\n\n if numpy.array_equal(self.colormap, colormap):\n # This also works with strings\n return\n\n self.colormap = colormap\n self.update()\n\n def getColormap(self):\n \"\"\"Returns the used colormap.\n\n If the argument was set with a `Colormap` object, this function will\n returns the LUT, represented by a string name or by an array or colors.\n\n :returns: Union[None,str,numpy.ndarray,Colormap]\n \"\"\"\n return self.colormap\n\n def setSymbolColormap(self, colormap):\n \"\"\"Set the colormap to display a symbol\n\n If the argument is a `Colormap` object, only the current state will be\n displayed. The object itself will not be stored, and further changes\n of this `Colormap` will not update this widget.\n\n :param Union[str,numpy.ndarray,Colormap] colormap: The colormap to\n display\n \"\"\"\n colormap = self._toLut(colormap)\n\n if colormap is None:\n if self.colormap is None:\n return\n self.symbolColormap = None\n self.update()\n return\n\n if numpy.array_equal(self.symbolColormap, colormap):\n # This also works with strings\n return\n\n self.symbolColormap = colormap\n self.update()\n\n def getSymbolColormap(self):\n \"\"\"Returns the used symbol colormap.\n\n If the argument was set with a `Colormap` object, this function will\n returns the LUT, represented by a string name or by an array or colors.\n\n :returns: Union[None,str,numpy.ndarray,Colormap]\n \"\"\"\n return self.colormap\n\n # Paint\n\n def paintEvent(self, event):\n \"\"\"\n :param event: event\n :type event: QPaintEvent\n \"\"\"\n painter = qt.QPainter(self)\n self.paint(painter, event.rect(), self.palette())\n\n def paint(self, painter, rect, palette):\n painter.save()\n painter.setRenderHint(qt.QPainter.Antialiasing)\n # Scale painter to the icon height\n # current -> width = 2.5, height = 1.0\n scale = float(self.height())\n ratio = float(self.width()) / scale\n symbolOffset = qt.QPointF(.5 * (ratio - 1.), 0.)\n # Determine and scale offset\n offset = qt.QPointF(float(rect.left()) / scale, float(rect.top()) / scale)\n\n # Override color when disabled\n if self.isEnabled():\n overrideColor = None\n else:\n overrideColor = palette.color(qt.QPalette.Disabled,\n qt.QPalette.WindowText)\n\n # Draw BG rectangle (for debugging)\n # bottomRight = qt.QPointF(\n # float(rect.right())/scale,\n # float(rect.bottom())/scale)\n # painter.fillRect(qt.QRectF(offset, bottomRight),\n # qt.QBrush(qt.Qt.green))\n\n if self.showColormap:\n if self.colormap is not None:\n if self.isEnabled():\n image = self.getColormapImage(self.colormap)\n else:\n image = self.getGrayedColormapImage(self.colormap)\n pixmapRect = qt.QRect(0, 0, _COLORMAP_PIXMAP_SIZE, 1)\n widthMargin = 0\n halfHeight = 4\n widgetRect = self.rect()\n dest = qt.QRect(\n widgetRect.left() + widthMargin,\n widgetRect.center().y() - halfHeight + 1,\n widgetRect.width() - widthMargin * 2,\n halfHeight * 2,\n )\n painter.drawImage(dest, image, pixmapRect)\n\n painter.scale(scale, scale)\n\n llist = []\n if self.showLine:\n linePath = qt.QPainterPath()\n linePath.moveTo(0., 0.5)\n linePath.lineTo(ratio, 0.5)\n # linePath.lineTo(2.5, 0.5)\n lineBrush = qt.QBrush(\n self.lineColor if overrideColor is None else overrideColor)\n linePen = qt.QPen(\n lineBrush,\n (self.lineWidth / self.height()),\n self.lineStyle,\n qt.Qt.FlatCap\n )\n llist.append((linePath, linePen, lineBrush))\n\n isValidSymbol = (len(self.symbol) and\n self.symbol not in _NoSymbols)\n if self.showSymbol and isValidSymbol:\n if self.symbolColormap is None:\n # PITFALL ahead: Let this be a warning to others\n # symbolPath = Symbols[self.symbol]\n # Copy before translate! Dict is a mutable type\n symbolPath = qt.QPainterPath(_Symbols[self.symbol])\n symbolPath.translate(symbolOffset)\n symbolBrush = qt.QBrush(\n self.symbolColor if overrideColor is None else overrideColor,\n self.symbolStyle)\n symbolPen = qt.QPen(\n self.symbolOutlineBrush, # Brush\n 1. / self.height(), # Width\n qt.Qt.SolidLine # Style\n )\n llist.append((symbolPath,\n symbolPen,\n symbolBrush))\n else:\n nbSymbols = int(ratio + 2)\n for i in range(nbSymbols):\n if self.isEnabled():\n image = self.getColormapImage(self.symbolColormap)\n else:\n image = self.getGrayedColormapImage(self.symbolColormap)\n pos = int((_COLORMAP_PIXMAP_SIZE / nbSymbols) * i)\n pos = numpy.clip(pos, 0, _COLORMAP_PIXMAP_SIZE-1)\n color = image.pixelColor(pos, 0)\n delta = qt.QPointF(ratio * ((i - (nbSymbols-1)/2) / nbSymbols), 0)\n\n symbolPath = qt.QPainterPath(_Symbols[self.symbol])\n symbolPath.translate(symbolOffset + delta)\n symbolBrush = qt.QBrush(color, self.symbolStyle)\n symbolPen = qt.QPen(\n self.symbolOutlineBrush, # Brush\n 1. / self.height(), # Width\n qt.Qt.SolidLine # Style\n )\n llist.append((symbolPath,\n symbolPen,\n symbolBrush))\n\n # Draw\n for path, pen, brush in llist:\n path.translate(offset)\n painter.setPen(pen)\n painter.setBrush(brush)\n painter.drawPath(path)\n\n painter.restore()\n\n # Helpers\n\n @staticmethod\n def isEmptySymbol(symbol):\n \"\"\"Returns True if this symbol description will result in an empty\n symbol.\"\"\"\n return symbol in _NoSymbols\n\n @staticmethod\n def isEmptyLineStyle(lineStyle):\n \"\"\"Returns True if this line style description will result in an empty\n line.\"\"\"\n return lineStyle in _NoLineStyle\n\n @staticmethod\n def _getColormapKey(colormap):\n \"\"\"\n Returns the key used to store the image in the data storage\n \"\"\"\n if isinstance(colormap, numpy.ndarray):\n key = tuple(colormap)\n else:\n key = colormap\n return key\n\n @staticmethod\n def getGrayedColormapImage(colormap):\n \"\"\"Return a grayed version image preview from a LUT name.\n\n This images are cached into a global structure.\n\n :param Union[str,numpy.ndarray] colormap: Description of the LUT\n :rtype: qt.QImage\n \"\"\"\n key = LegendIconWidget._getColormapKey(colormap)\n grayKey = (key, \"gray\")\n image = _colormapImage.get(grayKey, None)\n if image is None:\n image = LegendIconWidget.getColormapImage(colormap)\n image = image.convertToFormat(qt.QImage.Format_Grayscale8)\n _colormapImage[grayKey] = image\n return image\n\n @staticmethod\n def getColormapImage(colormap):\n \"\"\"Return an image preview from a LUT name.\n\n This images are cached into a global structure.\n\n :param Union[str,numpy.ndarray] colormap: Description of the LUT\n :rtype: qt.QImage\n \"\"\"\n key = LegendIconWidget._getColormapKey(colormap)\n image = _colormapImage.get(key, None)\n if image is None:\n image = LegendIconWidget.createColormapImage(colormap)\n _colormapImage[key] = image\n return image\n\n @staticmethod\n def createColormapImage(colormap):\n \"\"\"Create and return an icon preview from a LUT name.\n\n This icons are cached into a global structure.\n\n :param Union[str,numpy.ndarray] colormap: Description of the LUT\n :rtype: qt.QImage\n \"\"\"\n size = _COLORMAP_PIXMAP_SIZE\n if isinstance(colormap, numpy.ndarray):\n lut = colormap\n if len(lut) > size:\n # Down sample\n step = int(len(lut) / size)\n lut = lut[::step]\n elif len(lut) < size:\n # Over sample\n indexes = numpy.arange(size) / float(size) * (len(lut) - 1)\n indexes = indexes.astype(\"int\")\n lut = lut[indexes]\n else:\n colormap = colors.Colormap(colormap)\n lut = colormap.getNColors(size)\n\n if lut is None or len(lut) == 0:\n return qt.QIcon()\n\n pixmap = qt.QPixmap(size, 1)\n painter = qt.QPainter(pixmap)\n for i in range(size):\n rgb = lut[i]\n r, g, b = rgb[0], rgb[1], rgb[2]\n painter.setPen(qt.QColor(r, g, b))\n painter.drawPoint(qt.QPoint(i, 0))\n painter.end()\n return pixmap.toImage()\n" ]
[ [ "numpy.arange", "numpy.save", "numpy.ones", "numpy.zeros_like", "numpy.isscalar" ], [ "numpy.sum" ], [ "numpy.isfinite", "numpy.std", "numpy.mean", "numpy.any", "numpy.iscomplexobj" ], [ "numpy.copy" ], [ "numpy.arange" ], [ "numpy.array_equal", "numpy.arange", "numpy.repeat", "numpy.array", "numpy.zeros" ], [ "numpy.ndarray" ], [ "numpy.arange", "numpy.array_equal", "numpy.clip" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Nijta/project-NN-Pytorch-scripts
[ "06a50ab072613fb60b8b8e1cea85c4aa8e75549d", "06a50ab072613fb60b8b8e1cea85c4aa8e75549d" ]
[ "project/03-asvspoof-mega/03_fuse_score_evaluate.py", "sandbox/dynamic_prog.py" ]
[ "#!/usr/bin/python\n\"\"\" \nWrapper to fuse score and compute EER and min tDCF\nSimple score averaging.\n\nUsage:\npython 03_fuse_score_evaluate.py log_output_testset_1 log_output_testset_2 ...\n\nThe log_output_testset is produced by the pytorch code, for\nexample, ./lfcc-lcnn-lstmsum-am/01/__pretrained/log_output_testset\n\nIt has information like:\n...\nGenerating 71230,LA_E_9999427,0,43237,0, time: 0.005s\nOutput, LA_E_9999487, 0, 0.172325\n...\n(See README for the format of this log)\n\nThis script will extract the line starts with \"Output, ...\"\n\n\"\"\"\n\nimport os\nimport sys\nimport numpy as np\nfrom sandbox import eval_asvspoof\n\ndef parse_txt(file_path):\n bonafide = []\n bonafide_file_name = []\n spoofed = []\n spoofed_file_name = []\n with open(file_path, 'r') as file_ptr:\n for line in file_ptr:\n if line.startswith('Output,'):\n #Output, LA_E_9999487, 0, 0.172325\n temp = line.split(',')\n flag = int(temp[2])\n name = temp[1]\n if flag:\n bonafide_file_name.append(name)\n bonafide.append(float(temp[-1]))\n else:\n spoofed.append(float(temp[-1]))\n spoofed_file_name.append(name)\n bonafide = np.array(bonafide)\n spoofed = np.array(spoofed)\n return bonafide, spoofed, bonafide_file_name, spoofed_file_name\n\n\ndef fuse_score(file_path_lists):\n bonafide_score = {}\n spoofed_score = {}\n for data_path in file_path_lists:\n bonafide, spoofed, bona_name, spoof_name = parse_txt(data_path)\n for score, name in zip(bonafide, bona_name):\n if name in bonafide_score:\n bonafide_score[name].append(score)\n else:\n bonafide_score[name] = [score]\n for score, name in zip(spoofed, spoof_name):\n if name in spoofed_score:\n spoofed_score[name].append(score)\n else:\n spoofed_score[name] = [score]\n fused_bonafide = np.array([np.mean(y) for x, y in bonafide_score.items()])\n fused_spoofed = np.array([np.mean(y) for x, y in spoofed_score.items()])\n return fused_bonafide, fused_spoofed\n \n\nif __name__ == \"__main__\":\n \n data_paths = sys.argv[1:]\n bonafide, spoofed = fuse_score(data_paths)\n mintDCF, eer, threshold = eval_asvspoof.tDCF_wrapper(bonafide, spoofed)\n print(\"Score file: {:s}\".format(str(data_paths)))\n print(\"mintDCF: {:1.4f}\".format(mintDCF))\n print(\"EER: {:2.3f}%\".format(eer * 100))\n print(\"Threshold: {:f}\".format(threshold))\n", "#!/usr/bin/env python\n\"\"\"\nFunctions for dynamic programming\n\n\"\"\"\nfrom __future__ import print_function\nimport os\nimport sys\nimport numpy as np\nimport torch\nimport torch.nn as torch_nn\nimport torch.nn.functional as torch_nn_func\n\nimport core_scripts.other_tools.debug as nii_debug\n\n__author__ = \"Xin Wang\"\n__email__ = \"[email protected]\"\n__copyright__ = \"Copyright 2020, Xin Wang\"\n\n#############################################################\ndef viterbi_decode(init_prob, trans_prob, obser_prob, \n eps=torch.finfo(torch.float32).eps, return_more=False):\n \"\"\" Routine to do Viterbi decoding\n \n viterbi_decode(init_prob, trans_prob, obser_prob, \n eps=torch.finfo(torch.float32).eps, return_more=False):\n \n Input:\n init_prob: initialia state probability\n tensor or np.arrary, in shape (N), for N states\n trans_prob: transition probability\n tensor or np.array, in shape (N, N)\n trans_prob(i, j): P(state=j | prev_state=i)\n obser_prob: observation probability\n tensor or np.array, in shape (T, N), for T time sptes\n \n return_more: True: return best_states, prob_mat, state_trace\n False: return best_states\n Output:\n best_states: best state sequence tensor or np.array, in shape (T)\n prob_mat: probablity matrix in shape (T, N), where (t, j) denotes\n max_{s_1:t-1} P(o_1:t, s_1:t-1, s_t=j)\n state_mat: in shape (T, N), where (t, j) denotes\n argmax_i P(o_1:t, s_1:t-2, s_t-1=i, s_t=j)\n \"\"\" \n \n if type(init_prob) is torch.Tensor:\n _log_func = torch.log\n _torch_flag = True\n else:\n _log_func = np.log\n _torch_flag = False\n log_init_prob = _log_func(init_prob + eps)\n log_trans_prob = _log_func(trans_prob + eps) \n log_obser_prob = _log_func(obser_prob + eps) \n \n n_time, n_state = log_obser_prob.shape\n if log_trans_prob.shape[0] != n_state or log_trans_prob.shape[0] != n_state:\n print(\"Viterbi decoding: transition prob matrix invalid\")\n sys.exit(1)\n if log_init_prob.shape[0] != n_state:\n print(\"Viterbi decoding: init prob matrix invalid\")\n sys.exit(1)\n \n if _torch_flag:\n prob_mat = torch.zeros_like(log_obser_prob)\n state_mat = torch.zeros_like(log_obser_prob, dtype=torch.int)\n best_states = torch.zeros([n_time], dtype=torch.int, \n device = init_prob.device)\n _argmax = torch.argmax\n tmp_idx = torch.arange(0, n_state, dtype=torch.long)\n else:\n prob_mat = np.zeros(log_obser_prob.shape)\n state_mat = np.zeros(log_obser_prob.shape, dtype=np.int)\n best_states = np.zeros([n_time], dtype=np.int)\n _argmax = np.argmax\n tmp_idx = np.arange(0, n_state, dtype=np.int)\n \n\n prob_mat[0, :] = log_init_prob + log_obser_prob[0, :]\n for time_idx in np.arange(1, n_time):\n trout_prob = prob_mat[time_idx - 1] + log_trans_prob.T\n\n # this version is faster?\n #print(time_idx)\n tmp_best = _argmax(trout_prob, axis=1)\n state_mat[time_idx] = tmp_best\n prob_mat[time_idx] = trout_prob[tmp_idx, tmp_best] \\\n + log_obser_prob[time_idx]\n \n # seems to be too slow\n #for state_idx in np.arange(n_state):\n # tmp_best = _argmax(trout_prob[state_idx])\n # state_mat[time_idx, state_idx] = tmp_best\n # prob_mat[time_idx, state_idx] = trout_prob[state_idx, tmp_best] \\\n # +log_obser_prob[time_idx, state_idx]\n \n best_states[-1] = _argmax(prob_mat[-1, :])\n for time_idx in np.arange(n_time-2, -1, -1):\n best_states[time_idx] = state_mat[time_idx+1, best_states[time_idx+1]]\n if return_more:\n return best_states, prob_mat, state_mat\n else:\n return best_states\n" ]
[ [ "numpy.array", "numpy.mean" ], [ "torch.zeros", "numpy.arange", "torch.zeros_like", "torch.arange", "torch.finfo", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
onsabbatical/PoET-BiN
[ "5226cf7e8e34316a3ced73ce30528ac49730ecf4", "5226cf7e8e34316a3ced73ce30528ac49730ecf4", "5226cf7e8e34316a3ced73ce30528ac49730ecf4", "5226cf7e8e34316a3ced73ce30528ac49730ecf4" ]
[ "mnist/storage.py", "mnist/main.py", "svhn/rinc/lvl_wise_copy2.py", "mnist/classifier/my_pool_multi_1.py" ]
[ "import torch \nimport numpy as np\n\ndef store_value(main_array,cu_fl,i,name):\n\n\tcu_uint8 = cu_fl.type(torch.ByteTensor)\n\tmain_array = torch.cat((main_array,cu_uint8),0)\n\t#print(i)\n\n\tif (i + 1)%100 == 0:\n\t\tmain_array_np = main_array.cpu().numpy()\n\t\tnp.save(name + str(int(i/100)) + '.npy',main_array[1:,:,:,:])\n\t\tmain_array = torch.ByteTensor(1,np.shape(main_array)[1],np.shape(main_array)[2],np.shape(main_array)[3])\n\treturn main_array\n\n\ndef store_value_3d(main_array,cu_fl,i,name):\n\n\tcu_uint8 = cu_fl.type(torch.ByteTensor)\n\tcu_uint8 = torch.reshape(cu_uint8,(cu_fl.size()[0],cu_fl.size()[2],cu_fl.size()[3]))\n\tmain_array = torch.cat((main_array,cu_uint8),0)\n\t#print(i)\n\n\tif (i + 1)%100 == 0:\n\t\tmain_array_np = main_array.cpu().numpy()\n\t\tnp.save(name + str(int(i/100)) + '.npy',main_array[1:,:,:])\n\t\tmain_array = torch.ByteTensor(1,np.shape(main_array)[1],np.shape(main_array)[2])\n\treturn main_array\n\ndef store_value_2d(main_array,cu_fl,i,name):\n\n\tcu_uint8 = cu_fl.type(torch.ByteTensor)\n\tmain_array = torch.cat((main_array,cu_uint8),0)\n\t#print(i)\n\n\tif (i + 1)%100 == 0:\n\t\tmain_array_np = main_array.cpu().numpy()\n\t\tnp.save(name + str(int(i/100)) + '.npy',main_array[1:,:])\n\t\tmain_array = torch.ByteTensor(1,np.shape(main_array)[1])\n\treturn main_array\n\ndef store_value2(main_array,cu_fl,i,name):\n\n\tcu_uint8 = cu_fl.type(torch.ByteTensor)\n\tmain_array = torch.cat((main_array,cu_uint8),0)\n\t#print(i)\n\n\tif (i + 1)%100 == 0:\n\t\tmain_array_np = main_array.cpu().numpy()\n\t\tnp.save(name + str(int(i/100)) + '.npy',main_array[1:])\n\t\tmain_array = torch.ByteTensor(1)\n\treturn main_array\n\ndef store_all_weights(dict_wb):\n\tweight_matrix = torch.Tensor(1,8).type(torch.cuda.FloatTensor)\n\tbias_matrix = torch.Tensor(1).type(torch.cuda.FloatTensor)\n\n\tfor items in dict_wb:\n\t\tprint(weight_matrix.size())\n\t\tif 'weight' in items:\n\t\t\tprint(dict_wb[items].size())\n\t\t\tweight_matrix = torch.cat((weight_matrix,dict_wb[items]),0)\n\n\t\tif 'bias' in items:\n\t\t\tbias_matrix = torch.cat((bias_matrix,dict_wb[items]),0)\n\tnp.save('weight_matrix.npy',weight_matrix[1:,:].cpu().numpy())\n\tnp.save('bias_matrix.npy',bias_matrix[1:].cpu().numpy())", "'''Train CIFAR10 with PyTorch.'''\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.backends.cudnn as cudnn\n\nimport torchvision\nimport torchvision.transforms as transforms\n\nimport os\nimport argparse\nos.environ['CUDA_VISIBLE_DEVICES']='0'\nfrom models import *\nfrom utils import progress_bar\n\nfrom storage import *\n\n\nparser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')\nparser.add_argument('--lr', default=0.01, type=float, help='learning rate')\nparser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint')\nargs = parser.parse_args()\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nbest_acc = 0 # best test accuracy\nstart_epoch = 0 # start from epoch 0 or last checkpoint epoch\n\n# Data\nprint('==> Preparing data..')\ntransform_train = transforms.Compose([\n #transforms.RandomCrop(32, padding=4),\n #transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\ntransform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\ntrainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform_train)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=100, shuffle=True, num_workers=2)\n\ntestset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform_test)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)\n\nclasses = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n# Model\nprint('==> Building model..')\nnet = VGG('VGG11')\n# net = ResNet18()\n# net = PreActResNet18()\n# net = GoogLeNet()\n# net = DenseNet121()\n# net = ResNeXt29_2x64d()\n# net = MobileNet()\n# net = MobileNetV2()\n# net = DPN92()\n# net = ShuffleNetG2()\n# net = SENet18()\n#net = ShuffleNetV2(1)\nnet = net.to(device)\nif device == 'cuda':\n net = torch.nn.DataParallel(net)\n cudnn.benchmark = True\n\nif args.resume:\n # Load checkpoint.\n print('==> Resuming from checkpoint..')\n assert os.path.isdir('checkpoint'), 'Error: no checkpoint directory found!'\n checkpoint = torch.load('./checkpoint/ckpt.t7')\n net.load_state_dict(checkpoint['net'])\n best_acc = checkpoint['acc']\n start_epoch = checkpoint['epoch']\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=0.9, weight_decay=5e-4)\n\n# Training\ndef train(epoch):\n print('\\nEpoch: %d' % epoch)\n net.train()\n train_loss = 0\n correct = 0\n total = 0\n for batch_idx, (inputs, targets) in enumerate(trainloader):\n inputs, targets = inputs.to(device), targets.to(device)\n optimizer.zero_grad()\n outputs,sec_out,sec_in = net(inputs)\n loss = criterion(outputs, targets)\n loss.backward()\n optimizer.step()\n\n train_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n progress_bar(batch_idx, len(trainloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))\n\ndef test(epoch):\n global best_acc\n net.eval()\n test_loss = 0\n correct = 0\n total = 0\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(testloader):\n inputs, targets = inputs.to(device), targets.to(device)\n outputs,sec_out,sec_in = net(inputs)\n loss = criterion(outputs, targets)\n\n test_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n progress_bar(batch_idx, len(testloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))\n\n # Save checkpoint.\n acc = 100.*correct/total\n if acc > best_acc:\n print('Saving..')\n state = {\n 'net': net.state_dict(),\n 'acc': acc,\n 'epoch': epoch,\n }\n if not os.path.isdir('checkpoint'):\n os.mkdir('checkpoint')\n torch.save(state, './checkpoint/ckpt.t7')\n best_acc = acc\n if acc > 98:\n storage(trainloader,'train')\n storage(testloader,'test')\n\n\ndef storage(loader_v,nme):\n net.eval()\n main_array1 = torch.ByteTensor(1,512)\n main_array2 = torch.ByteTensor(1,80)\n out_label = torch.ByteTensor(1)\n with torch.no_grad():\n for ct,(inputs,targets) in enumerate(loader_v):\n inputs, targets = inputs.to(device), targets.to(device)\n outputs,sec_out,sec_in = net(inputs)\n main_array1 = store_value_2d(main_array1,sec_in.data,ct,nme + '_input_')\n main_array2 = store_value_2d(main_array2,sec_out.data,ct,nme + '_output_')\n out_label = store_value2(out_label,targets,ct, nme + '_labels_')\n\n\n \n\n\nfor epoch in range(start_epoch, start_epoch+50):\n train(epoch)\n test(epoch)\n", "import numpy as np\n\n'''\nimport gzip,pickle\nf=gzip.open(r'D:\\siva\\Masters\\Thesis\\04_ETE_18\\W1\\mnist.pkl.gz')\nMNIST=pickle.load(f)\n\nlogFile=r'D:\\siva\\Masters\\Thesis\\06_AUT_18\\W3\\Mec\\logFile.log'\nlogFile2=r'D:\\siva\\Masters\\Thesis\\06_AUT_18\\W3\\Mec\\logFile2.log'\nlog=open(logFile,'w')\nlog2=open(logFile2,'w')\n'''\n#%%\n\ndef best_feature(X,y,feature_list,lists,lvl,weights):\n\n\tif lvl == 0:\n\t\tmin_entropy = 1\n\n\telse:\n\t\tmin_entropy = 2 ** (lvl)\n\tbest_feat = feature_list[0]\n\n\tfor j,cur_feature in enumerate(feature_list):\n\t\tentropy_lvl = 0\n\t\t#print('feat' + str(cur_feature))\n\n\t\tfor cur_node in range(np.shape(lists)[0]):\n\t\t\tent1 = 0\n\t\t\tent2 = 0\n\n\t\t\t#node_list = np.array(np.sum(cur_node != -1))\n\t\t\tnode_list = lists[cur_node, lists[cur_node] != -1 ]\n\t\t\t#print('node_list' + str(node_list))\n\t\t\t#y_int = y_train[node_list]\n\t\t\t#ln = np.sum(y[X[node_list,cur_feature] == 0] == 0) \n\t\t\t#a = node_list[X[node_list,cur_feature] == 0]\n\t\t\t#print('a ' + str(a))\n\t\t\tsubl_nodelist = node_list[X[node_list,cur_feature] == 0]\n\t\t\tln = np.sum(weights[subl_nodelist[y[subl_nodelist] == 0]])\n\t\t\t#print('ln : ' + str(ln))\n\t\t\t#lp = np.sum(y[X[node_list,cur_feature] == 0] == 1)\n\t\t\tlp = np.sum(weights[subl_nodelist[y[subl_nodelist] == 1]])\n\t\t\t#print('lp : ' + str(lp))\n\n\t\t\ttotal_l = (ln + lp).astype(float)\n\n\t\t\t#rn = np.sum(y[X[node_list,cur_feature] == 1] == 0)\n\t\t\tsubr_nodelist = node_list[X[node_list,cur_feature] == 1]\n\t\t\trn = np.sum(weights[subr_nodelist[y[subr_nodelist] == 0]])\n\t\t\t#rp = np.sum(y[X[node_list,cur_feature] == 1] == 1)\n\t\t\trp = np.sum(weights[subr_nodelist[y[subr_nodelist] == 1]])\n\n\t\t\ttotal_r = (rn + rp).astype(float)\n\n\t\t\tif total_l == 0:\n\t\t\t\tent1 = 0\n\t\t\telif ln == 0:\n\t\t\t\tent1 = 0\n\t\t\telif lp ==0:\n\t\t\t\tent1 = 0\n\t\t\telse:\n\t\t\t\tent1 = -1 / (total_l + total_r ) *(ln*np.log2(ln/total_l) + lp * np.log2(lp/total_l))\n\t\t\t\t#print('hi_l' + str(ent1))\n\n\t\t\tif total_r == 0:\n\t\t\t\tent2 = 0\n\t\t\telif rn == 0:\n\t\t\t\tent2 = 0\n\t\t\telif rp == 0:\n\t\t\t\tent2 = 0\n\t\t\telse:\t\n\t\t\t\tent2 = -1 / ( total_l + total_r )*(rn*np.log2(rn/total_r) + rp * np.log2(rp/total_r))\n\t\t\t\t#print('hi_r' + str(ent2))\n\n\t\t\tentropy_node = ent1 + ent2\n\n\t\t\tentropy_lvl += entropy_node\n\n\n\t\tif entropy_lvl < min_entropy:\n\n\t\t\tmin_entropy = entropy_lvl\n\t\t\tbest_feat = cur_feature\n\t\t\t#print(best_feat)\n\n\n\n\tlist_new = np.ones((2*np.shape(lists)[0],np.shape(X)[0])).astype(int)\n\tlist_new = -1 * list_new\n\n\tfor cur_node in range(np.shape(lists)[0]):\n\t\tnode_list = lists[ cur_node, lists[cur_node] != -1 ]\n\t\tlist_new[2*cur_node,:np.sum(X[node_list,best_feat] == 0) ] = node_list[X[node_list,best_feat] == 0]\n\t\tlist_new[2*cur_node + 1,:np.sum(X[node_list,best_feat] == 1) ] = node_list[X[node_list,best_feat] == 1]\n\n\t#print('lvl = ' + str(lvl) + ', best_feat = ' + str(best_feat))\n\t\t\n\n\treturn (best_feat,list_new)\n\ndef assign_class(X,y,lists,weights):\n\n\tlabel_class = np.zeros(np.shape(lists)[0])\n\n\tfor cur_node in range(np.shape(lists)[0]):\n\t\tnode_list = lists[cur_node, lists[cur_node] != -1 ]\n\t\tif np.sum(weights[node_list[y[node_list] == 1]]) > np.sum(weights[node_list[y[node_list] == 0]]):\n\t\t\tlabel_class[cur_node] = 1\n\n\t\n\treturn label_class\t\t\n\n#%%\n\n\ndef construct_lut(X,y,max_features,weights):\n\n\tfeature_list = np.arange(np.size(X,1))\n\tlists = np.arange(np.size(X,0))\n\tlists_new = np.zeros((1,len(lists))).astype(int)\n\tlists_new[0] = lists\n\n\tfeature_array = np.zeros(max_features)\n\n\tfor i in range(max_features):\n\t\tfeature_list_new = feature_list[feature_list >=0]\n\t\t(best_feat2,lists_new) = best_feature(X,y,feature_list_new,lists_new,i,weights)\n\t\tfeature_array[i] = best_feat2.astype(int)\n\t\tfeature_list[best_feat2] = -1 \n\n\n\tlabel_class = assign_class(X,y,lists_new,weights)\n\t#print(label_class)\n\treturn (feature_array, lists_new, label_class)\n\n\n#%%\n\n\ndef predict(X_train,y_train,feature_array,label_class,lvl):\n\tm=lvl\n\tindices_my = np.arange(2**lvl)\n\tsel_ind = indices_my[label_class == 1]\n\tsparse_mat = np.flip((((sel_ind[:,None] & (1 << np.arange(m)))) > 0).astype(int),1)\n\tfeature_array = feature_array.astype(int)\n\ty_predicted = np.zeros(np.shape(X_train)[0])\n\tfor i in range(np.shape(X_train)[0]):\n\t\tX_t = (X_train[i,feature_array] == sparse_mat)\n\t\ty_predicted[i] = np.any(np.sum(X_t,axis = 1) == lvl).astype(int)\n\n\taccuracy = np.sum(y_predicted == y_train).astype(float) / np.shape(X_train)[0]\n\n\treturn accuracy\n\ndef predict_out_lut(X_train,y_train,feature_array,label_class,lvl):\n\tm=lvl\n\tindices_my = np.arange(2**lvl)\n\tsel_ind = indices_my[label_class == 1]\n\tsparse_mat = np.flip((((sel_ind[:,None] & (1 << np.arange(m)))) > 0).astype(int),1)\n\tfeature_array = feature_array.astype(int)\n\ty_predicted = np.zeros(np.shape(X_train)[0])\n\tfor i in range(np.shape(X_train)[0]):\n\t\tX_t = (X_train[i,feature_array] == sparse_mat)\n\t\ty_predicted[i] = np.any(np.sum(X_t,axis = 1) == lvl).astype(int)\n\n\treturn y_predicted\n'''\ndef vhdl_gen(feature_array,label_class):\n\tdict1 = {'1' : ' ', '0' : ' not('}\n\tdict2 = {'1' : ' ', '0' : ' ) '}\n\tpos = np.where(label_class == 1)\n\tfor i in range(len(pos)):\n\n\t\tnot_pos = '{0:06b}'.format(pos[i])\n\t\tlog.write('tree_0_' + 'path_' + str(i) + ' = ')\n\t\tfor j in range(5):\n\t\t\tlog.write(dict1[not_pos[j]] 'feat_' + str(j) + dict2[not_pos[j]] + ' and ')\n\t\tlog.write(dict1[not_pos[5]] 'feat_' + str(5) + dict2[not_pos[5]] + '; \\n')\n\n\n\tlog2.write('lut_0 = ')\n\tfor i in range(len(pos) - 1):\n\t\tlog2.write('tree_0_' + 'path_' + str(i) + ' or ')\n\n\tlog2.write('tree_0_' + 'path_' + str(len(pos)) + ' ; ')\n\n'''\n\n'''\ntrain_set = np.append(MNIST[0][0],MNIST[0][1].reshape(-1,1),axis=1)\nvalid_set = np.append(MNIST[1][0],MNIST[1][1].reshape(-1,1),axis=1)\ntest_set = np.append(MNIST[2][0],MNIST[2][1].reshape(-1,1),axis=1)\n\ntrain_set = np.append (train_set,valid_set,axis = 0)\n\nX_train, y_train = train_set[:,:-1], train_set[:,-1]\nX_test, y_test = test_set[:,:-1], test_set[:,-1]\n\nX_train[X_train >= 0.4] = 1 \nX_train[X_train < 0.4] = 0\n\nX_test[X_test >= 0.4] = 1 \nX_test[X_test < 0.4] = 0\n\ny_train[y_train != 1 ] = 0\ny_train[ y_train == 1] = 1\n\n\ny_test[ y_test != 1 ] = 0\ny_test[ y_test == 1] = 1\n\nweights = np.ones(np.shape(X_train)[0])/np.shape(X_train)[0]\n \nlvl = 6\n(feature_array, lists_new, label_class) = construct_lut(X_train,y_train,lvl,weights)\n\naccuracy = predict(X_train,y_train,feature_array,label_class,lvl)\n\nvhdl_gen(feature_array,label_class)\n\nprint('VHDL Generated')\n\nprint( 'Training Accuracy is : ' + str(accuracy))\n\naccuracy = predict(X_test,y_test,feature_array,label_class,lvl)\nprint( 'Test Accuracy is : ' + str(accuracy))\n'''\n\n'''\n\nX_train = np.zeros((7,3))\ny_train = np.zeros(7)\n\nX_train[1,2] = X_train[2,1] = X_train[3,1] = X_train[3,2] = X_train[4,0] = X_train[5,0] = X_train[5,2] = X_train[6,0] = X_train[6,1] = y_train[1] = y_train[3] = y_train[6] = 1\n''' ", "import numpy as np\nfrom multiprocessing import Pool\nimport adaboost_v1\n\nX_train = np.load('dt_train_inp.npy')\ny_train = np.load('dt_train_out.npy')\n\nX_test = np.load('dt_test_inp.npy')\ny_test = np.load('dt_test_out.npy')\n\n#X_train = np.append(X_train,X_test,axis=0)\n#y_train = np.append(y_train,y_test,axis=0)\n\n#X_test = np.append(X_test,X_train[320000:,:],axis=0)\n#y_test = np.append(y_test,y_train[320000:,:],axis=0)\n\n#X_train = X_train[:32000,:]\n#y_train = y_train[:32000,:]\n\nprint(np.shape(X_train))\nprint(np.shape(X_test))\nprint(np.shape(y_train))\nprint(np.shape(y_test))\n\ncur_pred_y_train_store = np.zeros((np.shape(y_train)[0],np.shape(y_train)[1])).astype(bool)\ncur_pred_y_test_store = np.zeros((np.shape(y_test)[0],np.shape(y_test)[1])).astype(bool)\n\n\ntot_est = 32 \nhyp_inp = 8\ntotal_estimators = tot_est\nc_feats_store = np.zeros((10*hyp_inp,int(total_estimators/hyp_inp),hyp_inp,hyp_inp))\nc_weights_store = np.zeros((10*hyp_inp,int(total_estimators/hyp_inp) + 1,hyp_inp))\ndef adaboost_train_req(cur_y_train,cur_y_test):\n Features_next_level_test = np.zeros((np.shape(cur_y_test)[0],int(total_estimators/hyp_inp)))\n Features_next_level_train = np.zeros((np.shape(cur_y_train)[0],int(total_estimators/hyp_inp)))\n alpha_next_level = np.zeros(int(total_estimators/hyp_inp))\n new_init_weights = np.ones(np.shape(X_train)[0])/np.shape(X_train)[0]\n init_weights = np.ones(np.shape(X_train)[0])/np.shape(X_train)[0]\n c_label_array = np.zeros((int(total_estimators/hyp_inp),hyp_inp,2**hyp_inp))\n c_feats_array = np.zeros((int(total_estimators/hyp_inp),hyp_inp,hyp_inp))\n c_weights_array = np.zeros((int(total_estimators/hyp_inp) + 1,hyp_inp))\n\n for i in range(int(total_estimators/hyp_inp)):\n BNNout_temp,BNNout_train_temp,alpha,label_array,feats_array = adaboost_v1.adaboost_train(X_train,cur_y_train,X_test,cur_y_test,hyp_inp,hyp_inp,init_weights)\n c_label_array[i,:,:] = label_array\n c_feats_array[i,:,:] = feats_array\n BNNout = np.transpose(BNNout_temp)\n c_weights_array[i,:] = alpha \n BNNout_train = np.transpose(BNNout_train_temp)\n cur_weights = np.zeros((hyp_inp,1))\n cur_weights[:,0] = alpha\n sum_cur = np.sum(cur_weights)\n th = sum_cur * 0.5\n Features_next_level_test[:,i] = np.matmul(BNNout,cur_weights)[:,0] > th\n Features_next_level_train[:,i] = np.matmul(BNNout_train,cur_weights)[:,0] > th\n cur_error = np.sum(init_weights[cur_y_train != Features_next_level_train[:,i]])\n new_init_weights[np.where(Features_next_level_train[:,i] != cur_y_train)] = 0.5 * init_weights[np.where(Features_next_level_train[:,i] != cur_y_train)] / cur_error\n new_init_weights[np.where(Features_next_level_train[:,i] == cur_y_train)] = 0.5 * init_weights[np.where(Features_next_level_train[:,i] == cur_y_train)] / (1 - cur_error)\n if cur_error <= 0:\n alpha_next_level[i] = 10.36\n else:\n alpha_next_level[i] = 0.5 * np.log2((1-cur_error)/cur_error)\n init_weights = new_init_weights\n\n all_weights = np.zeros((int(total_estimators/hyp_inp),1))\n all_weights[:,0] = alpha_next_level\n c_weights_array[-1,:int(total_estimators/hyp_inp)] = alpha_next_level\n sum_aw = np.sum(all_weights)\n th = sum_aw / 2\n #all_weights[:,0] = all_weights[:,0] / sum_aw\n BNNout_f = np.matmul(Features_next_level_test,all_weights)\n BNNout_f_train = np.matmul(Features_next_level_train,all_weights)\n BNNout_f_bin = BNNout_f > th \n BNNout_f_train_bin = BNNout_f_train > th\n BNNacc = np.sum((cur_y_test == BNNout_f_bin[:,0].astype(int)).astype(int)).astype(float) / np.shape(BNNout_f_bin)[0] *100.0;\n print (\"Accuracy of pixel is \", BNNacc,\" Sum is : \" , sum_aw)\n\n return BNNout_f_train_bin[:,0],BNNout_f_bin[:,0],c_label_array,c_feats_array,c_weights_array\n'''\ndef adaboost_train_req(cur_y_train,cur_y_test):\n\n\tfor i in range(int(total_estimators/6)):\n\t\tcur_pred_y_train1,cur_pred_y_test1 = adaboost_v1.adaboost_train(X_train,cur_y_train,X_test,cur_y_test,6,6)\n\treturn cur_pred_y_train1,cur_pred_y_test1 \n'''\nif __name__ == '__main__':\n p = Pool(30)\n c_label_store = np.zeros((10*hyp_inp,int(total_estimators/hyp_inp),hyp_inp,2**hyp_inp))\n\n cur_y_train_list = [y_train[:,0]]\n cur_y_test_list = [y_test[:,0]]\n\n for i in range(79):\n cur_y_train_list.append(y_train[:,i+1])\n cur_y_test_list.append(y_test[:,i+1])\n\n cur_pred_y_train_list ,cur_pred_y_test_list,c_label_array_list,c_feats_array_list,c_weights_array_list = zip(*p.starmap(adaboost_train_req,zip(cur_y_train_list, cur_y_test_list)))\n\n for i in range(80):\n cur_pred_y_train_store[:,i] = cur_pred_y_train_list[i]\n cur_pred_y_test_store[:,i] = cur_pred_y_test_list[i]\n c_label_store[i,:,:,:] = c_label_array_list[i]\n c_feats_store[i,:,:,:] = c_feats_array_list[i]\n c_weights_store[i,:,:] = c_weights_array_list[i]\n\n #print('current_output : ' , i)\n np.save(\"predicted_train_outputs.npy\",cur_pred_y_train_store)\n np.save(\"predicted_test_outputs.npy\",cur_pred_y_test_store)\n np.save(\"label_store.npy\",c_label_store)\n np.save(\"feats_store.npy\",c_feats_store)\n np.save(\"weights_store.npy\",c_weights_store)\n" ]
[ [ "torch.ByteTensor", "numpy.shape", "torch.Tensor", "torch.cat" ], [ "torch.ByteTensor", "torch.nn.CrossEntropyLoss", "torch.load", "torch.utils.data.DataLoader", "torch.no_grad", "torch.cuda.is_available", "torch.nn.DataParallel", "torch.save" ], [ "numpy.log2", "numpy.arange", "numpy.size", "numpy.shape", "numpy.zeros", "numpy.sum" ], [ "numpy.log2", "numpy.matmul", "numpy.save", "numpy.shape", "numpy.where", "numpy.transpose", "numpy.load", "numpy.zeros", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
keadwen/CFU-Playground
[ "74c79158e85e1365170ececd1d91ea3fa48faba0" ]
[ "third_party/tflite-micro/tensorflow/lite/micro/tools/metrics/create_size_log.py" ]
[ "# Copyright 2021 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\"\"\"Script to build the required binaries, profile their size and generate log.\n\"\"\"\n\nimport argparse\nimport datetime\nimport os\nimport pandas as pd\nimport subprocess\n\n\ndef _build_a_binary(root_dir, binary_name, makefile_options):\n os.chdir(root_dir)\n\n params_list = [\n \"make\", \"-f\", \"tensorflow/lite/micro/tools/make/Makefile\", binary_name\n ] + [\"%s=%s\" % (key, value) for (key, value) in makefile_options.items()]\n\n process = subprocess.Popen(params_list,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n if process.returncode != 0:\n raise RuntimeError(\"Building %s failed with \\n\\n %s\" %\n (\" \".join(params_list), stderr.decode()))\n\n\ndef _profile_a_binary(root_dir, binary_name, makefile_options, build_info):\n target_dir = \"%s_%s_%s\" % (makefile_options[\"TARGET\"],\n makefile_options[\"TARGET_ARCH\"],\n makefile_options[\"BUILD_TYPE\"])\n binary_path = os.path.join(root_dir, 'tensorflow/lite/micro/tools/make/gen/',\n target_dir, 'bin', binary_name)\n csv_path = os.path.join(root_dir, 'data/continuous_builds/size_profiling',\n target_dir, \"%s.csv\" % binary_name)\n\n # Run size command and extract the output\n process = subprocess.Popen([\"size\", binary_path],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n if process.returncode != 0:\n raise RuntimeError(\"size %s failed with \\n\\n %s\" %\n (binary_name, stderr.decode()))\n\n output_str = stdout.decode()\n df = pd.DataFrame([line.split() for line in output_str.split('\\n')[1:]],\n columns=list(output_str.split('\\n')[0].split()))\n\n # Append the output from the size to the CSV file\n report = _create_or_read_csv(csv_path)\n report.loc[len(report.index)] = [\n build_info[\"date\"], build_info['sha'], df['text'][0], df['data'][0],\n df['bss'][0], df['dec'][0]\n ]\n\n report.to_csv(csv_path, index=False, header=False, mode='a')\n\n\ndef _create_or_read_csv(csv_file_name):\n if os.path.exists(csv_file_name) is not True:\n csv_df = pd.DataFrame(\n columns=['date', 'sha', 'text', 'data', 'bss', 'total'])\n csv_df.to_csv(csv_file_name, index=False, mode='w')\n\n csv_head = pd.read_csv(csv_file_name, index_col=False, nrows=0)\n return csv_head\n\n\ndef _get_build_info(root_dir):\n os.chdir(root_dir)\n\n current_time = str(datetime.datetime.now())\n\n git_process = subprocess.Popen([\"git\", \"rev-parse\", \"HEAD\"],\n stdout=subprocess.PIPE,\n cwd=root_dir)\n sha, err = git_process.communicate()\n if git_process.returncode != 0:\n raise RuntimeError(\"Git failed with %s\" % err.decode())\n\n return {'date': current_time, 'sha': sha.decode().strip('\\n')}\n\n\ndef _build_and_profile(root_dir, makefile_options, binary_names):\n build_info = _get_build_info(root_dir)\n\n for binary_name in binary_names:\n _build_a_binary(root_dir, binary_name, makefile_options)\n _profile_a_binary(root_dir, binary_name, makefile_options, build_info)\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n default_binary_list_string = 'keyword_benchmark,baseline_memory_footprint,interpreter_memory_footprint'\n parser.add_argument(\n '--binary_list',\n nargs='?',\n const=default_binary_list_string,\n default=default_binary_list_string,\n help=\n 'binary list separated by comma (e.g. keyword_benchmark,baseline_memory_footprint)'\n )\n parser.add_argument('--build_type',\n nargs='?',\n const='release',\n default='release',\n help='build type (e.g. release)')\n parser.add_argument('--target',\n nargs='?',\n const='linux',\n default='linux',\n help='host target (e.g. linux)')\n parser.add_argument('--target_arch',\n nargs='?',\n const='x86_64',\n default='x86_64',\n help='target architecture (e.g x86_64)')\n args = parser.parse_args()\n\n makefile_options = {\n \"BUILD_TYPE\": args.build_type,\n \"TARGET\": args.target,\n \"TARGET_ARCH\": args.target_arch\n }\n binary_names = args.binary_list.split(',')\n\n script_path = os.path.dirname(os.path.realpath(__file__))\n root_dir = os.path.join(script_path, '../../../../..')\n\n _build_and_profile(root_dir, makefile_options, binary_names)\n" ]
[ [ "pandas.read_csv", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
chandar-lab/IIRC
[ "ae6ffcfc0a42274bcda66e2288e09118604620e4" ]
[ "experiments/utils.py" ]
[ "import numpy as np\nimport torch.nn as nn\nimport json\n\n\ndef log(epoch, task_id, log_dict, logbook):\n log_dict[\"message\"] = f\"task_{task_id}_metrics\"\n log_dict[\"task_id\"] = task_id\n log_dict[\"task_epoch\"] = epoch\n log_dict[\"step\"] = epoch\n logbook.write_metric(log_dict)\n\n\ndef log_task(task_id, log_dict, logbook):\n log_dict[\"message\"] = f\"incremental_metrics\"\n log_dict[\"task_id\"] = task_id\n log_dict[\"step\"] = task_id\n logbook.write_metric(log_dict)\n\n\ndef pad_random_crop(tensor_img, per_direction_padding=0):\n pad_left = pad_right = pad_top = pad_bottom = per_direction_padding\n tensor_width = tensor_img.shape[-1]\n tensor_height = tensor_img.shape[-2]\n tensor_img = nn.functional.pad(tensor_img,\n [pad_left, pad_right, pad_top, pad_bottom])\n\n start_index_width = np.random.randint(0, pad_left + pad_right)\n start_index_height = np.random.randint(0, pad_top + pad_bottom)\n end_index_width = start_index_width + tensor_width\n end_index_height = start_index_height + tensor_height\n\n return tensor_img[..., start_index_height:end_index_height, start_index_width:end_index_width]\n\n\ndef random_horizontal_flip(tensor_img, flip_prop=0.5):\n do_flip = np.random.random() >= (1 - flip_prop)\n if do_flip:\n return tensor_img.flip((-1))\n else:\n return tensor_img\n\n\ndef remove_extra_logs(cur_task_id, cur_epoch, file):\n logs_to_keep = []\n remove_task_summary = False\n with open(file, 'r') as logs_file:\n for line in logs_file:\n json_line = json.loads(line)\n if not (json_line['logbook_type'] == \"metric\"):\n logs_to_keep.append(json_line)\n elif json_line[\"task_id\"] < cur_task_id:\n logs_to_keep.append(json_line)\n elif json_line[\"task_id\"] == cur_task_id:\n if \"task_epoch\" in json_line.keys() and json_line[\"task_epoch\"] < cur_epoch:\n logs_to_keep.append(json_line)\n elif \"task_epoch\" in json_line.keys() and json_line[\"task_epoch\"] >= cur_epoch:\n remove_task_summary = True\n elif not remove_task_summary:\n logs_to_keep.append(json_line)\n with open(file, 'w') as logs_file:\n for json_line in logs_to_keep:\n logs_file.write(json.dumps(json_line))\n logs_file.write(\"\\n\")\n\n\ndef extend_list(input_, output_length):\n if isinstance(input_, int):\n output = [input_ for _ in range(output_length)]\n elif hasattr(input_, '__iter__'):\n if len(input_) < output_length:\n output = input_\n output.extend([input_[-1] for _ in range(output_length - len(input_))])\n elif len(input_) > output_length:\n output = input_[:output_length]\n else:\n output = input_\n else:\n raise TypeError(\"Neither an integer nor an iterable was provided\")\n return output" ]
[ [ "numpy.random.random", "torch.nn.functional.pad", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
carlo-/RNNet
[ "995fcce1da58ac2c840afd865bde88d11d81006f" ]
[ "experiments.py" ]
[ "#\n# KTH Royal Institute of Technology\n# DD2424: Deep Learning in Data Science\n# Assignment 4\n#\n# Carlo Rapisarda ([email protected])\n#\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport dataset as dt\nfrom os.path import exists\nfrom model import RNNet\nfrom utilities import compute_grads_numerical, compare_grads, unpickle, pickle, eprint, simple_smooth_1d\n\nGOBLET_RESULTS_PATH = '../goblet_results.pkl'\n\n\ndef check_gradients():\n\n book = dt.load_goblet_of_fire()\n seq_len = 25\n m = 5\n\n X, Y, _ = book.get_labeled_data(0, seq_len)\n h0 = np.zeros((m, 1))\n\n np.random.seed(42)\n net = RNNet(m=m, K=book.K)\n\n print('===> Computing numerical gradients...')\n num_grads = compute_grads_numerical(X, Y, h0, net)\n\n print('===> Computing analytical gradients...')\n grads = net._backward(X, Y, h0, *net._forward(X, h0))\n\n errors = compare_grads(num_grads, grads, m, book.K)\n errors_v = vars(errors)\n for k in errors_v:\n v = errors_v[k]\n print(f'MSEs for {k} -> max: {v.max()},\\t avg: {v.mean()},\\t std: {v.std()}')\n\n\ndef train_with_goblet_of_fire(results_path=None):\n\n book = dt.load_goblet_of_fire()\n\n np.random.seed(42)\n net = RNNet(m=100, K=book.K)\n\n # optimizer = RNNet.AdaGrad(net, eta=0.1)\n optimizer = RNNet.RMSProp(net, eta=0.001, gamma=0.9)\n\n config = {\n 'epochs': 10,\n 'output_folder': '../out',\n 'optimizer': optimizer,\n 'sequence_length': 25,\n 'record_interval': 1_000,\n 'test_length': 200\n }\n\n res = net.train(book, config)\n\n if results_path is not None:\n pickle(res, results_path)\n\n return res\n\n\ndef plot_results(res, fig_path=None):\n\n interval = res['interval']\n smooth_losses_by_interval = res['smooth_losses_by_interval']\n smooth_losses_by_epoch = res['smooth_losses_by_epoch']\n\n epochs = len(smooth_losses_by_epoch)\n iters_per_epoch = 1.0 * len(smooth_losses_by_interval) * interval / epochs\n\n smoother = np.array(smooth_losses_by_interval)\n smoother = simple_smooth_1d(smoother, 0.95)\n\n fig = plt.figure(figsize=(9, 4))\n\n ax1 = fig.add_subplot(111)\n ax1.plot(np.arange(len(smooth_losses_by_interval)) * interval, smooth_losses_by_interval)\n ax1.plot(np.arange(smoother.size) * interval, smoother)\n ax1.set_xlabel('step')\n ax1.set_ylabel('loss')\n\n ax2 = ax1.twiny()\n ax2.set_xlabel('epoch')\n ax2.set_xlim(ax1.get_xlim())\n ax2.set_xticks(np.arange(1,epochs+1) * iters_per_epoch)\n ax2.set_xticklabels(np.arange(1,epochs+1))\n\n ax2.grid()\n ax1.grid(axis='y')\n\n fig.tight_layout()\n fig.legend(['training loss', 'smoothed'], bbox_to_anchor=(0.98, 0.86), bbox_transform=fig.transFigure)\n\n if fig_path is not None:\n fig.savefig(fig_path, bbox_inches='tight')\n\n fig.show()\n\n\ndef print_evolution(res, interval, limit=None):\n smooth_losses = res['smooth_losses_by_interval']\n synth_samples = res['synthesized_text_by_interval']\n res_interval = res['interval']\n assert interval % res_interval == 0, 'Print interval must be a multiple of the recorded interval'\n selected_indexes = [x for x in range(0, len(synth_samples), interval // res_interval)]\n if limit is not None:\n selected_indexes = selected_indexes[:limit]\n # last_step = selected_indexes[-1] * res_interval\n # print(f'\\nModel evolution from step 1 to {last_step}:\\n')\n print('\\n')\n for i in selected_indexes:\n step = max(i * res_interval, 1)\n text = synth_samples[i]\n smooth_loss = smooth_losses[i]\n print(f'===> Step: {step}, smooth_loss: {round(smooth_loss, 4)}, synthesized:\\n{text}\\n\\n')\n\n\ndef synthesize_with_best_model():\n model_path = '../trained_models/2018-06-12-2205-e10.pkl'\n if exists(model_path):\n book = dt.load_goblet_of_fire()\n net = RNNet.import_model(model_path)\n np.random.seed(50)\n print(net.synthesize(1000, book.char_to_one_hot, book.index_to_char))\n else:\n eprint('Best trained model found!')\n\n\ndef main():\n\n check_gradients()\n\n if not exists(GOBLET_RESULTS_PATH):\n train_with_goblet_of_fire(GOBLET_RESULTS_PATH)\n\n results = unpickle(GOBLET_RESULTS_PATH)\n\n plot_results(results, '../Report/Figs/training_goblet.eps')\n\n print_evolution(results, 10_000, 11)\n\n print(f'===> Passage from the final model (smooth_loss: {results[\"smooth_losses_by_epoch\"][-1]}):')\n synthesize_with_best_model()\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.random.seed", "numpy.arange", "numpy.array", "numpy.zeros", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mpekalski/Y8M
[ "24b61107a0f482fdb36ab8b15b768cea24e5808a", "24b61107a0f482fdb36ab8b15b768cea24e5808a" ]
[ "video_level_code/xp_frame_level_models.py", "bstnet/readers.py" ]
[ "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Contains a collection of models which operate on variable-length sequences.\n\"\"\"\nimport math\n\nimport models\nimport video_level_models\nimport tensorflow as tf\nimport model_utils as utils\n\nimport tensorflow.contrib.slim as slim\nfrom tensorflow import flags\nfrom tensorflow import logging\n\nFLAGS = flags.FLAGS\n\n\nclass RangeLogisticModel(models.BaseModel):\n\n def create_model(self, model_input, vocab_size, num_frames, **unused_params):\n \"\"\"Creates a model which uses a logistic classifier over the average of the\n frame-level features.\n\n This class is intended to be an example for implementors of frame level\n models. If you want to train a model over averaged features it is more\n efficient to average them beforehand rather than on the fly.\n\n Args:\n model_input: A 'batch_size' x 'max_frames' x 'num_features' matrix of\n input features.\n vocab_size: The number of classes in the dataset.\n num_frames: A vector of length 'batch' which indicates the number of\n frames for each video (before padding).\n\n Returns:\n A dictionary with a tensor containing the probability predictions of the\n model in the 'predictions' key. The dimensions of the tensor are\n 'batch_size' x 'num_classes'.\n \"\"\"\n# num_frames = tf.cast(tf.expand_dims(num_frames, 1), tf.float32)\n# feature_size = model_input.get_shape().as_list()[2]\n\n# denominators = tf.reshape(\n# tf.tile(num_frames, [1, feature_size]), [-1, feature_size])\n# avg_pooled = tf.reduce_sum(model_input,\n# axis=[1]) / denominators\n range_pooled = tf.reduce_max(model_input, axis=[1]) - \\\n tf.reduce_min(model_input, axis=[1])\n output = slim.fully_connected(\n range_pooled, vocab_size, activation_fn=tf.nn.sigmoid,\n weights_regularizer=slim.l2_regularizer(1e-4))\n return {\"predictions\": output}\n\nclass FNN_mvt_Model(models.BaseModel):\n\n def create_model(self, model_input, vocab_size, num_frames,\n l2_penalty=1e-4, is_training=True, **unused_params):\n \"\"\"Creates a model which uses a logistic classifier over the average of the\n frame-level features.\n\n This class is intended to be an example for implementors of frame level\n models. If you want to train a model over averaged features it is more\n efficient to average them beforehand rather than on the fly.\n\n Args:\n model_input: A 'batch_size' x 'max_frames' x 'num_features' matrix of\n input features.\n vocab_size: The number of classes in the dataset.\n num_frames: A vector of length 'batch' which indicates the number of\n frames for each video (before padding).\n\n Returns:\n A dictionary with a tensor containing the probability predictions of the\n model in the 'predictions' key. The dimensions of the tensor are\n 'batch_size' x 'num_classes'.\n \"\"\"\n \n inter_f_mean, inter_f_var = tf.nn.moments(model_input, [1])\n inter_f_std = tf.sqrt(inter_f_var)\n \n kk = 3\n xt = tf.transpose(model_input, perm=[0,2,1])\n tk = tf.nn.top_k(xt, kk).values \n\n logging.info( 'xt: {}'.format(xt.get_shape().as_list() ))\n logging.info( 'tk: {}'.format(tk.get_shape().as_list() )) \n \n topk = tf.reshape(tk, [-1, kk * tk.get_shape().as_list()[1]])\n logging.info( 'topk: {}'.format(topk.get_shape().as_list() )) \n \n# inter_f_feats = tf.concat([inter_f_mean, inter_f_std], 1)\n inter_f_feats = tf.concat([inter_f_mean, inter_f_std, topk], 1)\n \n logging.info('inter_f_mean: {}'.format(inter_f_mean.get_shape().as_list()))\n logging.info( 'feats: {}'.format(inter_f_feats.get_shape().as_list() )) \n \n tf.summary.histogram(\"inter_f_mean\", inter_f_mean)\n tf.summary.histogram(\"inter_f_std\", inter_f_std)\n \n with tf.name_scope('FNN_mvt_Model'):\n A0 = slim.batch_norm(\n inter_f_feats,\n center=True,\n scale=True,\n is_training=is_training,\n scope=\"BN\")\n \n h1Units = 3600\n A1 = slim.fully_connected(\n A0, h1Units, activation_fn=tf.nn.relu,\n weights_regularizer=slim.l2_regularizer(l2_penalty),\n scope='FC_H1')\n output = slim.fully_connected(\n A1, vocab_size, activation_fn=tf.nn.sigmoid,\n weights_regularizer=slim.l2_regularizer(l2_penalty),\n scope='FC_P')\n return {\"predictions\": output}\n\nclass DbofModel2(models.BaseModel):\n \"\"\"Creates a Deep Bag of Frames model.\n\n The model projects the features for each frame into a higher dimensional\n 'clustering' space, pools across frames in that space, and then\n uses a configurable video-level model to classify the now aggregated features.\n\n The model will randomly sample either frames or sequences of frames during\n training to speed up convergence.\n\n Args:\n model_input: A 'batch_size' x 'max_frames' x 'num_features' matrix of\n input features.\n vocab_size: The number of classes in the dataset.\n num_frames: A vector of length 'batch' which indicates the number of\n frames for each video (before padding).\n\n Returns:\n A dictionary with a tensor containing the probability predictions of the\n model in the 'predictions' key. The dimensions of the tensor are\n 'batch_size' x 'num_classes'.\n \"\"\"\n\n def create_model(self,\n model_input,\n vocab_size,\n num_frames,\n iterations=None,\n add_batch_norm=None,\n sample_random_frames=None,\n cluster_size=None,\n hidden_size=None,\n is_training=True,\n **unused_params):\n iterations = iterations or FLAGS.iterations\n add_batch_norm = add_batch_norm or FLAGS.dbof_add_batch_norm\n random_frames = sample_random_frames or FLAGS.sample_random_frames\n cluster_size = cluster_size or FLAGS.dbof_cluster_size\n hidden1_size = hidden_size or FLAGS.dbof_hidden_size\n\n num_frames = tf.cast(tf.expand_dims(num_frames, 1), tf.float32)\n if random_frames:\n model_input = utils.SampleRandomFrames(model_input, num_frames,\n iterations)\n else:\n model_input = utils.SampleRandomSequence(model_input, num_frames,\n iterations)\n max_frames = model_input.get_shape().as_list()[1]\n feature_size = model_input.get_shape().as_list()[2]\n reshaped_input = tf.reshape(model_input, [-1, feature_size])\n tf.summary.histogram(\"input_hist\", reshaped_input)\n\n if add_batch_norm:\n reshaped_input = slim.batch_norm(\n reshaped_input,\n center=True,\n scale=True,\n is_training=is_training,\n scope=\"input_bn\")\n\n cluster_weights = tf.get_variable(\"cluster_weights\",\n [feature_size, cluster_size],\n initializer = tf.random_normal_initializer(stddev=1 / math.sqrt(feature_size)))\n tf.summary.histogram(\"cluster_weights\", cluster_weights)\n activation = tf.matmul(reshaped_input, cluster_weights)\n if add_batch_norm:\n activation = slim.batch_norm(\n activation,\n center=True,\n scale=True,\n is_training=is_training,\n scope=\"cluster_bn\")\n else:\n cluster_biases = tf.get_variable(\"cluster_biases\",\n [cluster_size],\n initializer = tf.random_normal(stddev=1 / math.sqrt(feature_size)))\n tf.summary.histogram(\"cluster_biases\", cluster_biases)\n activation += cluster_biases\n activation = tf.nn.relu6(activation)\n tf.summary.histogram(\"cluster_output\", activation)\n\n activation = tf.reshape(activation, [-1, max_frames, cluster_size])\n activation = utils.FramePooling(activation, FLAGS.dbof_pooling_method)\n\n hidden1_weights = tf.get_variable(\"hidden1_weights\",\n [cluster_size, hidden1_size],\n initializer=tf.random_normal_initializer(stddev=1 / math.sqrt(cluster_size)))\n tf.summary.histogram(\"hidden1_weights\", hidden1_weights)\n activation = tf.matmul(activation, hidden1_weights)\n if add_batch_norm:\n activation = slim.batch_norm(\n activation,\n center=True,\n scale=True,\n is_training=is_training,\n scope=\"hidden1_bn\")\n else:\n hidden1_biases = tf.get_variable(\"hidden1_biases\",\n [hidden1_size],\n initializer = tf.random_normal_initializer(stddev=0.01))\n tf.summary.histogram(\"hidden1_biases\", hidden1_biases)\n activation += hidden1_biases\n activation = tf.nn.relu6(activation)\n tf.summary.histogram(\"hidden1_output\", activation)\n\n aggregated_model = getattr(video_level_models,\n FLAGS.video_level_classifier_model)\n return aggregated_model().create_model(\n model_input=activation,\n vocab_size=vocab_size,\n **unused_params)\n\nclass LstmModel2(models.BaseModel):\n\n def create_model(self, model_input, vocab_size, num_frames, **unused_params):\n \"\"\"Creates a model which uses a stack of LSTMs to represent the video.\n\n Args:\n model_input: A 'batch_size' x 'max_frames' x 'num_features' matrix of\n input features.\n vocab_size: The number of classes in the dataset.\n num_frames: A vector of length 'batch' which indicates the number of\n frames for each video (before padding).\n\n Returns:\n A dictionary with a tensor containing the probability predictions of the\n model in the 'predictions' key. The dimensions of the tensor are\n 'batch_size' x 'num_classes'.\n \"\"\"\n lstm_size = FLAGS.lstm_cells\n number_of_layers = FLAGS.lstm_layers\n\n ## Batch normalize the input\n stacked_lstm = tf.contrib.rnn.MultiRNNCell(\n [\n tf.contrib.rnn.BasicLSTMCell(\n lstm_size, forget_bias=1.0, state_is_tuple=False)\n for _ in range(number_of_layers)\n ], state_is_tuple=False)\n\n #loss = 0.0\n with tf.variable_scope(\"RNN\"):\n outputs, state = tf.nn.dynamic_rnn(stacked_lstm, model_input,\n sequence_length=num_frames,\n dtype=tf.float32)\n\n aggregated_model = getattr(video_level_models,\n FLAGS.video_level_classifier_model)\n return aggregated_model().create_model(\n model_input=state,\n vocab_size=vocab_size,\n num_mixtures=2,\n **unused_params)\n\nclass FMoeModel1(models.BaseModel):\n\n def create_model(self, model_input, vocab_size, num_frames,\n l2_penalty=1e-4, is_training=True, **unused_params):\n \"\"\"Creates a model which uses a logistic classifier over the average of the\n frame-level features.\n\n This class is intended to be an example for implementors of frame level\n models. If you want to train a model over averaged features it is more\n efficient to average them beforehand rather than on the fly.\n\n Args:\n model_input: A 'batch_size' x 'max_frames' x 'num_features' matrix of\n input features.\n vocab_size: The number of classes in the dataset.\n num_frames: A vector of length 'batch' which indicates the number of\n frames for each video (before padding).\n\n Returns:\n A dictionary with a tensor containing the probability predictions of the\n model in the 'predictions' key. The dimensions of the tensor are\n 'batch_size' x 'num_classes'.\n \"\"\"\n\n \n inter_f_mean, inter_f_var = tf.nn.moments(model_input, [1])\n inter_f_std = tf.sqrt(inter_f_var)\n \n kk = 5\n xt = tf.transpose(model_input, perm=[0,2,1])\n tk = tf.nn.top_k(xt, kk).values \n\n logging.info( 'xt: {}'.format(xt.get_shape().as_list() ))\n logging.info( 'tk: {}'.format(tk.get_shape().as_list() )) \n \n topk = tf.reshape(tk, [-1, kk * tk.get_shape().as_list()[1]])\n logging.info( 'topk: {}'.format(topk.get_shape().as_list() )) \n \n# inter_f_feats = tf.concat([inter_f_mean, inter_f_std], 1)\n inter_f_feats = tf.concat([inter_f_mean, inter_f_std, topk], 1)\n \n logging.info('inter_f_mean: {}'.format(inter_f_mean.get_shape().as_list()))\n logging.info( 'feats: {}'.format(inter_f_feats.get_shape().as_list() )) \n \n tf.summary.histogram(\"inter_f_mean\", inter_f_mean)\n tf.summary.histogram(\"inter_f_std\", inter_f_std)\n \n A0 = slim.batch_norm(\n inter_f_feats,\n center=True,\n scale=True,\n is_training=is_training,\n scope=\"BN\")\n \n aggregated_model = getattr(video_level_models,\n FLAGS.video_level_classifier_model)\n return aggregated_model().create_model(\n model_input=A0,\n vocab_size=vocab_size,\n num_mixtures=2,\n **unused_params)\n \nclass FMoeModel2(models.BaseModel):\n\n def create_model(self, model_input, vocab_size, num_frames,\n l2_penalty=1e-4, **unused_params):\n \"\"\"Creates a model which uses a logistic classifier over the average of the\n frame-level features.\n\n This class is intended to be an example for implementors of frame level\n models. If you want to train a model over averaged features it is more\n efficient to average them beforehand rather than on the fly.\n\n Args:\n model_input: A 'batch_size' x 'max_frames' x 'num_features' matrix of\n input features.\n vocab_size: The number of classes in the dataset.\n num_frames: A vector of length 'batch' which indicates the number of\n frames for each video (before padding).\n\n Returns:\n A dictionary with a tensor containing the probability predictions of the\n model in the 'predictions' key. The dimensions of the tensor are\n 'batch_size' x 'num_classes'.\n \"\"\"\n# num_frames = tf.cast(tf.expand_dims(num_frames, 1), tf.float32)\n# feature_size = model_input.get_shape().as_list()[2]\n# \n# logging.info('model_input shape: {}'.format(\n# model_input.get_shape().as_list()))\n#\n# denominators = tf.reshape(\n# tf.tile(num_frames, [1, feature_size]), [-1, feature_size])\n# avg_pooled = tf.reduce_sum(model_input, axis=[1]) / denominators\n \n avg_pooled = utils.FramePooling(model_input, 'average')\n \n logging.info( 'avg_pooled shape: {}'.format(\n avg_pooled.get_shape().as_list() )) \n \n aggregated_model = getattr(video_level_models,\n FLAGS.video_level_classifier_model)\n return aggregated_model().create_model(\n model_input=avg_pooled,\n vocab_size=vocab_size,\n num_mixtures=2,\n **unused_params)\n", "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Provides readers configured for different datasets.\"\"\"\n\nimport tensorflow as tf\nimport utils\nimport re\nfrom tensorflow import logging\ndef resize_axis(tensor, axis, new_size, fill_value=0):\n \"\"\"Truncates or pads a tensor to new_size on on a given axis.\n\n Truncate or extend tensor such that tensor.shape[axis] == new_size. If the\n size increases, the padding will be performed at the end, using fill_value.\n\n Args:\n tensor: The tensor to be resized.\n axis: An integer representing the dimension to be sliced.\n new_size: An integer or 0d tensor representing the new value for\n tensor.shape[axis].\n fill_value: Value to use to fill any new entries in the tensor. Will be\n cast to the type of tensor.\n\n Returns:\n The resized tensor.\n \"\"\"\n tensor = tf.convert_to_tensor(tensor)\n shape = tf.unstack(tf.shape(tensor))\n\n pad_shape = shape[:]\n pad_shape[axis] = tf.maximum(0, new_size - shape[axis])\n\n shape[axis] = tf.minimum(shape[axis], new_size)\n shape = tf.stack(shape)\n\n resized = tf.concat([\n tf.slice(tensor, tf.zeros_like(shape), shape),\n tf.fill(tf.stack(pad_shape), tf.cast(fill_value, tensor.dtype))\n ], axis)\n\n # Update shape.\n new_shape = tensor.get_shape().as_list() # A copy is being made.\n new_shape[axis] = new_size\n resized.set_shape(new_shape)\n return resized\n\nclass BaseReader(object):\n \"\"\"Inherit from this class when implementing new readers.\"\"\"\n\n def prepare_reader(self, unused_filename_queue):\n \"\"\"Create a thread for generating prediction and label tensors.\"\"\"\n raise NotImplementedError()\n\n\nclass YT8MAggregatedFeatureReader(BaseReader):\n \"\"\"Reads TFRecords of pre-aggregated Examples.\n\n The TFRecords must contain Examples with a sparse int64 'labels' feature and\n a fixed length float32 feature, obtained from the features in 'feature_name'.\n The float features are assumed to be an average of dequantized values.\n \"\"\"\n\n def __init__(self,\n num_classes=4716,\n feature_sizes=[1024],\n feature_names=[\"mean_inc3\"],\n feature_calcs=\"\",\n feature_remove=\"\",\n decode_zlib=True):\n \"\"\"Construct a YT8MAggregatedFeatureReader.\n\n Args:\n num_classes: a positive integer for the number of classes.\n feature_sizes: positive integer(s) for the feature dimensions as a list.\n feature_names: the feature name(s) in the tensorflow record as a list.\n \"\"\"\n assert len(feature_names) == len(feature_sizes), \\\n \"length of feature_names (={}) != length of feature_sizes (={})\".format( \\\n len(feature_names), len(feature_sizes))\n new_feature_names = None\n self.num_classes = num_classes\n self.feature_sizes = feature_sizes\n self.feature_names = feature_names\n self.decode_zlib = decode_zlib\n self.feature_remove = feature_remove.replace(' ','').split(',')\n #\n # New features' names\n #\n new_feature_names = []\n if feature_calcs != \"\":\n new_feature_names = [x.replace(' ','') for x in feature_calcs.split(',')]\n #\n # Determine new features' sizes\n #\n new_feature_sizes = [] \n if feature_calcs != \"\":\n for feat in new_feature_names:\n if re.findall('audio$', feat) != []:\n new_feature_sizes = new_feature_sizes + [128]\n elif re.findall('rgb$', feat) != []:\n new_feature_sizes = new_feature_sizes + [1024]\n elif feat[:14] == 'c_interaction_' or feat[:7] == 'c_diff_':\n x = -1\n for g in re.findall('(\\d+):(\\d+)',feat):\n if x < int(g[1])-int(g[0]):\n x = int(g[1])-int(g[0])\n new_feature_sizes = new_feature_sizes + [x]\n #\n # Update old with new\n #\n if new_feature_sizes != []:\n self.feature_sizes = self.feature_sizes + new_feature_sizes\n if new_feature_names != []:\n self.feature_names = self.feature_names + new_feature_names\n #\n # Remove features\n #\n #if feature_remove != '':\n # for feat in feature_remove.replace(' ','').split(','):\n # i = self.feature_names.index(feat)\n # print(' removing: ' + str(self.feature_names[i]))\n # del self.feature_names[i]\n # del self.feature_sizes[i] \n\n print('Identified features: ' + str(len(self.feature_names)) + \" | \" + str(self.feature_names))\n print(' lengths: ' + str(len(self.feature_sizes)) + \" | \" + str(self.feature_sizes))\n print(' removed: ' + str(len(self.feature_remove))+ \" | \" + str(self.feature_remove))\n\n\n def prepare_reader(self, filename_queue, batch_size=1024):\n \"\"\"Creates a single reader thread for pre-aggregated YouTube 8M Examples.\n\n Args:\n filename_queue: A tensorflow queue of filename locations.\n\n Returns:\n A tuple of video indexes, features, labels, and padding data.\n \"\"\"\n opts = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.ZLIB)\n if self.decode_zlib:\n reader = tf.TFRecordReader(options=opts)\n else:\n reader = tf.TFRecordReader()\n\n _, serialized_examples = reader.read_up_to(filename_queue, batch_size)\n\n tf.add_to_collection(\"serialized_examples\", serialized_examples)\n return self.prepare_serialized_examples(serialized_examples)\n\n def prepare_serialized_examples(self, serialized_examples):\n # set the mapping from the fields to data types in the proto\n num_features = len(self.feature_names)\n assert num_features > 0, \"self.feature_names is empty!\"\n assert len(self.feature_names) == len(self.feature_sizes), \\\n \"length of feature_names (={}) != length of feature_sizes (={})\".format( \\\n len(self.feature_names), len(self.feature_sizes))\n\n # 2017-04-28 - now num_frames is float so I had to change it from int64\n feature_map = {\"video_id\": tf.FixedLenFeature([], tf.string),\n \"labels\": tf.VarLenFeature(tf.int64), \n \"num_frames\": tf.VarLenFeature(tf.float32)}\n \n for feature_index in range(num_features):\n if self.feature_names[feature_index][:2] != 'c_':\n feature_map[self.feature_names[feature_index]] = tf.FixedLenFeature(\n [self.feature_sizes[feature_index]], tf.float32)\n\n #ssert False, feature_map\n features = tf.parse_example(serialized_examples, features=feature_map)\n labels = tf.sparse_to_indicator(features[\"labels\"], 4716)\n labels.set_shape([None, 4716])\n labels = resize_axis(labels, 1, self.num_classes)\n\n #assert False, features['mean_rgb']\n #assert False, tf.slice(features['mean_rgb'],[?,0],[?,self.num_interactions])\n #assert False, self.feature_names\n for feature_name in self.feature_names:\n if feature_name[:5] == 'c_sq_':\n features[feature_name] = features[feature_name[5:]] * features[feature_name[5:]]\n elif feature_name[:6] == 'c_log_':\n features[feature_name] = tf.log1p(tf.abs(features[feature_name[6:]]))\n elif feature_name[:6] == 'c_inv_':\n features[feature_name] = 1/features[feature_name[6:]]\n elif feature_name[:6] == 'c_abs_':\n features[feature_name] = tf.abs(features[feature_name[6:]])\n elif feature_name[:6] == 'c_sin_':\n features[feature_name] = tf.sin(features[feature_name[6:]])\n elif feature_name[:6] == 'c_cos_':\n features[feature_name] = tf.cos(features[feature_name[6:]])\n elif feature_name[:7] == 'c_sqrt_':\n features[feature_name] = tf.sqrt(features[feature_name[7:]])\n elif feature_name[:8] == 'c_rsqrt_':\n features[feature_name] = tf.rsqrt(features[feature_name[8:]])\n elif feature_name[:7] == 'c_diff_':\n x = re.findall('c_diff_([^_]+)_([^_]+)_([^_]+)_([^_]+)_([^_]+)_([^_]+)', feature_name)[0]\n feat_1 = x[0]+'_'+x[1]\n feat_2 = x[3]+'_'+x[4]\n y_1 = [int(y) for y in x[2].split(':')]\n y_2 = [int(y) for y in x[5].split(':')]\n features[feature_name] = tf.subtract(features[feat_1][:,y_1[0]:y_1[1]], features[feat_2][:,y_2[0]:y_2[1]])\n elif feature_name[:8] == 'c_over_':\n x = re.findall('c_over_([^_]+)_([^_]+)_(.+)', feature_name)[0]\n feat_1 = x[0]+'_'+x[2]\n feat_2 = x[1]+'_'+x[2]\n features[feature_name] = tf.divide(features[feat_1], features[feat_2])\n elif feature_name[:14] == 'c_interaction_':\n # example: c_interaction_mean_rgb_0:128_mean_audio_0:128\n # that is mean_rgb*mean_audio for the first 128 coordinates of both of them\n x = re.findall('c_interaction_([^_]+)_([^_]+)_([^_]+)_([^_]+)_([^_]+)_([^_]+)', feature_name)[0]\n feat_1 = x[0]+'_'+x[1]\n feat_2 = x[3]+'_'+x[4] \n y_1 = [int(y) for y in x[2].split(':')]\n y_2 = [int(y) for y in x[5].split(':')]\n features[feature_name] = tf.multiply(features[feat_1][:,y_1[0]:y_1[1]], features[feat_2][:,y_2[0]:y_2[1]])\n #elif feature_name == 'num_frames':\n # features[feature_name] = tf.cast(features[feature_name], tf.float32)\n\n #assert False, features\n #assert False, [self.feature_sizes, self.feature_names, features]\n #if self.feature_remove != '':\n # for feat in self.feature_remove.replace(' ','').split(','):\n # i = self.feature_names.index(feat)\n # print(' removing: ' + str(self.feature_names[i]))\n # del self.feature_names[i]\n # del self.feature_sizes[i]\n # del features[self.feature_names[i]]\n\n concatenated_features = tf.concat([\n features[feature_name] for feature_name in self.feature_names if feature_name not in self.feature_remove]\n , 1)\n return features[\"video_id\"], concatenated_features, labels, tf.ones([tf.shape(serialized_examples)[0]])\n\nclass YT8MFrameFeatureReader(BaseReader):\n \"\"\"Reads TFRecords of SequenceExamples.\n\n The TFRecords must contain SequenceExamples with the sparse in64 'labels'\n context feature and a fixed length byte-quantized feature vector, obtained\n from the features in 'feature_names'. The quantized features will be mapped\n back into a range between min_quantized_value and max_quantized_value.\n \"\"\"\n\n def __init__(self,\n num_classes=4716,\n feature_sizes=[1024],\n feature_names=[\"inc3\"],\n max_frames=300):\n \"\"\"Construct a YT8MFrameFeatureReader.\n\n Args:\n num_classes: a positive integer for the number of classes.\n feature_sizes: positive integer(s) for the feature dimensions as a list.\n feature_names: the feature name(s) in the tensorflow record as a list.\n max_frames: the maximum number of frames to process.\n \"\"\"\n\n assert len(feature_names) == len(feature_sizes), \\\n \"length of feature_names (={}) != length of feature_sizes (={})\".format( \\\n len(feature_names), len(feature_sizes))\n\n self.num_classes = num_classes\n self.feature_sizes = feature_sizes\n self.feature_names = feature_names\n self.max_frames = max_frames\n\n def get_video_matrix(self,\n features,\n feature_size,\n max_frames,\n max_quantized_value,\n min_quantized_value):\n \"\"\"Decodes features from an input string and quantizes it.\n\n Args:\n features: raw feature values\n feature_size: length of each frame feature vector\n max_frames: number of frames (rows) in the output feature_matrix\n max_quantized_value: the maximum of the quantized value.\n min_quantized_value: the minimum of the quantized value.\n\n Returns:\n feature_matrix: matrix of all frame-features\n num_frames: number of frames in the sequence\n \"\"\"\n decoded_features = tf.reshape(\n tf.cast(tf.decode_raw(features, tf.uint8), tf.float32),\n [-1, feature_size])\n\n num_frames = tf.minimum(tf.shape(decoded_features)[0], max_frames)\n feature_matrix = utils.Dequantize(decoded_features,\n max_quantized_value,\n min_quantized_value)\n feature_matrix = resize_axis(feature_matrix, 0, max_frames)\n return feature_matrix, num_frames\n\n def prepare_reader(self,\n filename_queue,\n max_quantized_value=2,\n min_quantized_value=-2):\n \"\"\"Creates a single reader thread for YouTube8M SequenceExamples.\n\n Args:\n filename_queue: A tensorflow queue of filename locations.\n max_quantized_value: the maximum of the quantized value.\n min_quantized_value: the minimum of the quantized value.\n\n Returns:\n A tuple of video indexes, video features, labels, and padding data.\n \"\"\"\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue)\n\n return self.prepare_serialized_examples(serialized_example,\n max_quantized_value, min_quantized_value)\n\n def prepare_serialized_examples(self, serialized_example,\n max_quantized_value=2, min_quantized_value=-2):\n\n contexts, features = tf.parse_single_sequence_example(\n serialized_example,\n context_features={\"video_id\": tf.FixedLenFeature(\n [], tf.string),\n \"labels\": tf.VarLenFeature(tf.int64)},\n sequence_features={\n feature_name : tf.FixedLenSequenceFeature([], dtype=tf.string)\n for feature_name in self.feature_names\n })\n\n # read ground truth labels\n labels = (tf.cast(\n tf.sparse_to_dense(contexts[\"labels\"].values, (4716,), 1,\n validate_indices=False),\n tf.bool))\n \n # loads (potentially) different types of features and concatenates them\n num_features = len(self.feature_names)\n assert num_features > 0, \"No feature selected: feature_names is empty!\"\n\n assert len(self.feature_names) == len(self.feature_sizes), \\\n \"length of feature_names (={}) != length of feature_sizes (={})\".format( \\\n len(self.feature_names), len(self.feature_sizes))\n\n num_frames = -1 # the number of frames in the video\n feature_matrices = [None] * num_features # an array of different features\n for feature_index in range(num_features):\n feature_matrix, num_frames_in_this_feature = self.get_video_matrix(\n features[self.feature_names[feature_index]],\n self.feature_sizes[feature_index],\n self.max_frames,\n max_quantized_value,\n min_quantized_value)\n if num_frames == -1:\n num_frames = num_frames_in_this_feature\n else:\n tf.assert_equal(num_frames, num_frames_in_this_feature)\n\n feature_matrices[feature_index] = feature_matrix\n\n # cap the number of frames at self.max_frames\n num_frames = tf.minimum(num_frames, self.max_frames)\n\n # concatenate different features\n video_matrix = tf.concat(feature_matrices, 1)\n\n # convert to batch format.\n # TODO: Do proper batch reads to remove the IO bottleneck.\n batch_video_ids = tf.expand_dims(contexts[\"video_id\"], 0)\n batch_video_matrix = tf.expand_dims(video_matrix, 0)\n batch_labels = tf.expand_dims(labels, 0)\n batch_frames = tf.expand_dims(num_frames, 0)\n\n return batch_video_ids, batch_video_matrix, batch_labels, batch_frames\n\n" ]
[ [ "tensorflow.nn.dynamic_rnn", "tensorflow.concat", "tensorflow.contrib.slim.l2_regularizer", "tensorflow.nn.moments", "tensorflow.nn.top_k", "tensorflow.name_scope", "tensorflow.random_normal_initializer", "tensorflow.matmul", "tensorflow.contrib.slim.batch_norm", "tensorflow.summary.histogram", "tensorflow.reduce_max", "tensorflow.transpose", "tensorflow.nn.relu6", "tensorflow.contrib.rnn.BasicLSTMCell", "tensorflow.reshape", "tensorflow.expand_dims", "tensorflow.reduce_min", "tensorflow.variable_scope", "tensorflow.sqrt" ], [ "tensorflow.convert_to_tensor", "tensorflow.concat", "tensorflow.FixedLenFeature", "tensorflow.stack", "tensorflow.minimum", "tensorflow.cast", "tensorflow.TFRecordReader", "tensorflow.python_io.TFRecordOptions", "tensorflow.sparse_to_dense", "tensorflow.decode_raw", "tensorflow.subtract", "tensorflow.divide", "tensorflow.rsqrt", "tensorflow.shape", "tensorflow.parse_example", "tensorflow.assert_equal", "tensorflow.zeros_like", "tensorflow.FixedLenSequenceFeature", "tensorflow.VarLenFeature", "tensorflow.add_to_collection", "tensorflow.sin", "tensorflow.cos", "tensorflow.multiply", "tensorflow.maximum", "tensorflow.expand_dims", "tensorflow.sparse_to_indicator", "tensorflow.sqrt", "tensorflow.abs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
MaZhanyu007/MSDGAN
[ "037ad33025c29869dbc9cb233a45b8762d31179d" ]
[ "decoder.py" ]
[ "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n# In[2]:\n\n\nclass Decoder(nn.Module):\n def __init__(self, output_dim, emb_dim, enc_hid_dim, dec_hid_dim, dropout_rate, attention):\n super().__init__()\n \n self.output_dim = output_dim\n self.emb_dim = emb_dim\n self.enc_hid_dim = enc_hid_dim\n self.dec_hid_dim = dec_hid_dim\n self.dropout_rate = dropout_rate\n self.attention = attention\n \n self.embedding = nn.Embedding(output_dim, emb_dim)\n self.gru = nn.GRU(enc_hid_dim + emb_dim, dec_hid_dim, batch_first=True)\n self.fc = nn.Linear(enc_hid_dim + dec_hid_dim + emb_dim, output_dim)\n self.dropout = nn.Dropout(dropout_rate)\n \n def forward(self, input, hidden, encoder_outputs):\n # input = [batch_size]\n # hidden = [batch_size, dec_hid_dim]\n # encoder_outputs = [batch_size, seq_len, enc_hid_dim * 2]\n\n input = input.unsqueeze(1)\n # input = [batch_size, 1]\n \n embedded = self.dropout(self.embedding(input))\n # embedded = [batch_size, 1, emb_dim]\n \n a = self.attention(hidden, encoder_outputs)\n # a = [batch_size, seq_len]\n a = a.unsqueeze(1)\n # a = [batch_size, 1, seq_len]\n \n context = torch.bmm(a, encoder_outputs)\n # context = [batch_size, 1, enc_hid_dim * 2]\n \n gru_input = torch.cat((embedded, context), dim=2)\n # gru_input = [batch_size, 1, (enc hid dim * 2) + emb dim]\n \n output, hidden = self.gru(gru_input, hidden.unsqueeze(0))\n # output = [batch_size, seq_len, dec hid dim * n directions]\n # hidden = [n layers * n directions, batch size, dec hid dim]\n \n #seq_len, n layers and n directions will always be 1 in this decoder, therefore:\n #output = [batch_size, 1, dec_hid_dim]\n #hidden = [1, batch_size, dec_hid_dim]\n #this also means that output == hidden\n \n #assert (output == hidden).all()\n \n embedded = embedded.squeeze(1) #[batch_size, emb_dim]\n output = output.squeeze(1) #[batch_size, dec_hid_dim * n directions]??????????\n context = context.squeeze(1) #[batch_size, enc_hid_dim * 2]\n \n output = self.fc(torch.cat((output, context, embedded), dim=1))\n # output = [batch_size, output_dim]\n \n return output, hidden.squeeze(0)" ]
[ [ "torch.nn.Dropout", "torch.cat", "torch.nn.GRU", "torch.nn.Embedding", "torch.nn.Linear", "torch.bmm" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
opesci/seigen
[ "7d12eab05ed5a857601babe2933aa804c853de66" ]
[ "tests/tiling/explosive_source.py" ]
[ "\"\"\"\nThis is an explicit DG method: we invert the mass matrix and perform\na matrix-vector multiplication to get the solution in a time step\n\"\"\"\n\nfrom math import *\nimport mpi4py\nimport numpy as np\nfrom time import time\nimport sys\nimport os\nimport cProfile\n\nfrom firedrake import *\nfrom firedrake.petsc import PETSc\n\nfrom pyop2.utils import cached_property\nfrom pyop2.profiling import timed_region\nfrom pyop2.base import _trace, Dat, DataSet\nfrom pyop2.fusion.interface import loop_chain\nfrom pyop2.logger import info, set_log_level, INFO\n\nimport coffee.base as ast\n\nfrom utils import parser, output_time, calculate_sdepth, FusionSchemes\n\n\nclass ElasticLF4(object):\n r\"\"\"An elastic wave equation solver, using the finite element method\n for spatial discretisation, and a fourth-order leap-frog time-stepping scheme.\"\"\"\n\n loop_chain_length = 28\n num_solves = 8\n\n def __init__(self, mesh, family, degree, dimension, output=1, params=None):\n r\"\"\" Initialise a new elastic wave simulation.\n\n :param mesh: The underlying computational mesh of vertices and edges.\n :param str family: Specify whether CG or DG should be used.\n :param int degree: Use polynomial basis functions of this degree.\n :param int dimension: The spatial dimension of the problem (1, 2 or 3).\n :param int output: period, in timesteps, to write solution fields to a file.\n :param dict params: simulation and optimisation parameters\n :returns: None\n \"\"\"\n self.degree = degree\n self.mesh = mesh\n self.dimension = dimension\n self.output = output\n\n self.tofile = params['tofile']\n\n self.S = TensorFunctionSpace(mesh, family, degree, name='S')\n self.U = VectorFunctionSpace(mesh, family, degree, name='U')\n # Assumes that the S and U function spaces are the same.\n self.S_tot_dofs = op2.MPI.COMM_WORLD.allreduce(self.S.dof_count, op=mpi4py.MPI.SUM)\n self.U_tot_dofs = op2.MPI.COMM_WORLD.allreduce(self.U.dof_count, op=mpi4py.MPI.SUM)\n info(\"Number of degrees of freedom (Velocity): %d\" % self.U_tot_dofs)\n info(\"Number of degrees of freedom (Stress): %d\" % self.S_tot_dofs)\n\n self.s = TrialFunction(self.S)\n self.v = TestFunction(self.S)\n self.u = TrialFunction(self.U)\n self.w = TestFunction(self.U)\n\n self.s0 = Function(self.S, name=\"StressOld\")\n self.sh1 = Function(self.S, name=\"StressHalf1\")\n self.stemp = Function(self.S, name=\"StressTemp\")\n self.sh2 = Function(self.S, name=\"StressHalf2\")\n self.s1 = Function(self.S, name=\"StressNew\")\n\n self.u0 = Function(self.U, name=\"VelocityOld\")\n self.uh1 = Function(self.U, name=\"VelocityHalf1\")\n self.utemp = Function(self.U, name=\"VelocityTemp\")\n self.uh2 = Function(self.U, name=\"VelocityHalf2\")\n self.u1 = Function(self.U, name=\"VelocityNew\")\n\n self.absorption_function = None\n self.source_function = None\n self.source_expression = None\n self._dt = None\n self._density = None\n self._mu = None\n self._l = None\n\n self.n = FacetNormal(self.mesh)\n self.I = Identity(self.dimension)\n\n # Tiling options\n self.tiling_size = params['tile_size']\n self.tiling_uf = params['num_unroll']\n self.tiling_mode = params['mode']\n self.tiling_halo = params['extra_halo']\n self.tiling_explicit = params['explicit_mode']\n self.tiling_explicit_id = params['explicit_mode_id']\n self.tiling_log = params['log']\n self.tiling_sdepth = params['s_depth']\n self.tiling_part = params['partitioning']\n self.tiling_coloring = params['coloring']\n self.tiling_glb_maps = params['use_glb_maps']\n self.tiling_prefetch = params['use_prefetch']\n\n # Mat-vec AST cache\n self.asts = {}\n\n if self.tofile:\n # File output streams\n platform = os.environ.get('NODENAME', 'unknown')\n tmpdir = os.environ['TMPDIR']\n base = os.path.join(tmpdir, 'output', platform,\n 'p%d' % self.degree, 'uf%d' % self.tiling_uf)\n if op2.MPI.COMM_WORLD.rank == 0:\n if not os.path.exists(base):\n os.makedirs(base)\n sub_dirs = [d for d in os.listdir(base)\n if os.path.isdir(os.path.join(base, d))]\n sub_dir = \"%d_em%d_part%s_tile%s\" % (len(sub_dirs),\n self.tiling_explicit_id,\n self.tiling_size if self.tiling_uf else 0,\n self.tiling_part if self.tiling_uf else 'None')\n base = os.path.join(base, sub_dir)\n os.makedirs(base)\n op2.MPI.COMM_WORLD.barrier()\n base = op2.MPI.COMM_WORLD.bcast(base, root=0)\n self.u_stream = File(os.path.join(base, 'velocity.pvd'))\n self.s_stream = File(os.path.join(base, 'stress.pvd'))\n\n @property\n def absorption(self):\n r\"\"\" The absorption coefficient :math:`\\sigma` for the absorption term\n\n .. math:: \\sigma\\mathbf{u}\n\n where :math:`\\mathbf{u}` is the velocity field.\n \"\"\"\n return self.absorption_function\n\n @absorption.setter\n def absorption(self, expression):\n r\"\"\" Setter function for the absorption field.\n :param firedrake.Expression expression: The expression to interpolate onto the absorption field.\n \"\"\"\n self.absorption_function.interpolate(expression)\n\n # Source term\n @property\n def source(self):\n r\"\"\" The source term on the RHS of the velocity (or stress) equation. \"\"\"\n return self.source_function\n\n @source.setter\n def source(self, expression):\n r\"\"\" Setter function for the source field.\n :param firedrake.Expression expression: The expression to interpolate onto the source field.\n \"\"\"\n self.source_function.interpolate(expression)\n\n def assemble_inverse_mass(self):\n r\"\"\" Compute the inverse of the consistent mass matrix for the velocity and stress equations.\n :returns: None\n \"\"\"\n # Inverse of the (consistent) mass matrix for the velocity equation.\n self.inverse_mass_velocity = assemble(inner(self.w, self.u)*dx, inverse=True)\n self.inverse_mass_velocity.assemble()\n self.imass_velocity = self.inverse_mass_velocity.M\n # Inverse of the (consistent) mass matrix for the stress equation.\n self.inverse_mass_stress = assemble(inner(self.v, self.s)*dx, inverse=True)\n self.inverse_mass_stress.assemble()\n self.imass_stress = self.inverse_mass_stress.M\n\n def copy_massmatrix_into_dat(self):\n\n # Copy the velocity mass matrix into a Dat\n vmat = self.imass_velocity.handle\n dofs_per_entity = self.U.fiat_element.entity_dofs()\n dofs_per_entity = sum(self.mesh.make_dofs_per_plex_entity(dofs_per_entity))\n arity = dofs_per_entity*self.U.topological.dim\n self.velocity_mass_asdat = Dat(DataSet(self.mesh.cell_set, arity*arity), dtype='double')\n istart, iend = vmat.getOwnershipRange()\n idxs = [PETSc.IS().createGeneral(np.arange(i, i+arity, dtype=np.int32),\n comm=PETSc.COMM_SELF)\n for i in range(istart, iend, arity)]\n submats = vmat.getSubMatrices(idxs, idxs)\n for i, m in enumerate(submats):\n self.velocity_mass_asdat.data[i] = m[:, :].flatten()\n info(\"Computed velocity mass matrix\")\n\n # Copy the stress mass matrix into a Dat\n smat = self.imass_stress.handle\n dofs_per_entity = self.S.fiat_element.entity_dofs()\n dofs_per_entity = sum(self.mesh.make_dofs_per_plex_entity(dofs_per_entity))\n arity = dofs_per_entity*self.S.topological.dim\n self.stress_mass_asdat = Dat(DataSet(self.mesh.cell_set, arity*arity), dtype='double')\n istart, iend = smat.getOwnershipRange()\n idxs = [PETSc.IS().createGeneral(np.arange(i, i+arity, dtype=np.int32),\n comm=PETSc.COMM_SELF)\n for i in range(istart, iend, arity)]\n submats = smat.getSubMatrices(idxs, idxs)\n for i, m in enumerate(submats):\n self.stress_mass_asdat.data[i] = m[:, :].flatten()\n info(\"Computed stress mass matrix\")\n\n @property\n def form_uh1(self):\n \"\"\" UFL for uh1 equation. \"\"\"\n F = inner(self.w, self.u)*dx - self.f(self.w, self.s0, self.u0, self.n, self.absorption)\n return F\n\n @cached_property\n def rhs_uh1(self):\n \"\"\" RHS for uh1 equation. \"\"\"\n return rhs(self.form_uh1)\n\n @property\n def form_stemp(self):\n \"\"\" UFL for stemp equation. \"\"\"\n F = inner(self.v, self.s)*dx - self.g(self.v, self.uh1, self.I, self.n, self.l, self.mu, self.source)\n return F\n\n @cached_property\n def rhs_stemp(self):\n \"\"\" RHS for stemp equation. \"\"\"\n return rhs(self.form_stemp)\n\n @property\n def form_uh2(self):\n \"\"\" UFL for uh2 equation. \"\"\"\n F = inner(self.w, self.u)*dx - self.f(self.w, self.stemp, self.u0, self.n, self.absorption)\n return F\n\n @cached_property\n def rhs_uh2(self):\n \"\"\" RHS for uh2 equation. \"\"\"\n return rhs(self.form_uh2)\n\n @property\n def form_u1(self):\n \"\"\" UFL for u1 equation. \"\"\"\n # Note that we have multiplied through by dt here.\n F = self.density*inner(self.w, self.u)*dx - self.density*inner(self.w, self.u0)*dx - self.dt*inner(self.w, self.uh1)*dx - ((self.dt**3)/24.0)*inner(self.w, self.uh2)*dx\n return F\n\n @cached_property\n def rhs_u1(self):\n \"\"\" RHS for u1 equation. \"\"\"\n return rhs(self.form_u1)\n\n @property\n def form_sh1(self):\n \"\"\" UFL for sh1 equation. \"\"\"\n F = inner(self.v, self.s)*dx - self.g(self.v, self.u1, self.I, self.n, self.l, self.mu, self.source)\n return F\n\n @cached_property\n def rhs_sh1(self):\n \"\"\" RHS for sh1 equation. \"\"\"\n return rhs(self.form_sh1)\n\n @property\n def form_utemp(self):\n \"\"\" UFL for utemp equation. \"\"\"\n F = inner(self.w, self.u)*dx - self.f(self.w, self.sh1, self.u1, self.n, self.absorption)\n return F\n\n @cached_property\n def rhs_utemp(self):\n \"\"\" RHS for utemp equation. \"\"\"\n return rhs(self.form_utemp)\n\n @property\n def form_sh2(self):\n \"\"\" UFL for sh2 equation. \"\"\"\n F = inner(self.v, self.s)*dx - self.g(self.v, self.utemp, self.I, self.n, self.l, self.mu, self.source)\n return F\n\n @cached_property\n def rhs_sh2(self):\n \"\"\" RHS for sh2 equation. \"\"\"\n return rhs(self.form_sh2)\n\n @property\n def form_s1(self):\n \"\"\" UFL for s1 equation. \"\"\"\n # Note that we have multiplied through by dt here.\n F = inner(self.v, self.s)*dx - inner(self.v, self.s0)*dx - self.dt*inner(self.v, self.sh1)*dx - ((self.dt**3)/24.0)*inner(self.v, self.sh2)*dx\n return F\n\n @cached_property\n def rhs_s1(self):\n \"\"\" RHS for s1 equation. \"\"\"\n return rhs(self.form_s1)\n\n def f(self, w, s0, u0, n, absorption=None):\n \"\"\" The RHS of the velocity equation. \"\"\"\n f = -inner(grad(w), s0)*dx + inner(avg(s0)*n('+'), w('+'))*dS + inner(avg(s0)*n('-'), w('-'))*dS\n if(absorption):\n f += -inner(w, absorption*u0)*dx\n return f\n\n def g(self, v, u1, I, n, l, mu, source=None):\n \"\"\" The RHS of the stress equation. \"\"\"\n g = - l*(v[i, j]*I[i, j]).dx(k)*u1[k]*dx + l*(jump(v[i, j], n[k])*I[i, j]*avg(u1[k]))*dS + l*(v[i, j]*I[i, j]*u1[k]*n[k])*ds - mu*inner(div(v), u1)*dx + mu*inner(avg(u1), jump(v, n))*dS - mu*inner(div(v.T), u1)*dx + mu*inner(avg(u1), jump(v.T, n))*dS + mu*inner(u1, dot(v, n))*ds + mu*inner(u1, dot(v.T, n))*ds\n if(source):\n g += inner(v, source)*dx\n return g\n\n def ast_matmul(self, F_a, implementation='optimized'):\n \"\"\"Generate an AST for a PyOP2 kernel performing a matrix-vector multiplication.\"\"\"\n\n # The number of dofs on each element is /ndofs*cdim/\n F_a_fs = F_a.function_space()\n ndofs = F_a_fs.fiat_element.entity_dofs()\n ndofs = sum(self.mesh.make_dofs_per_plex_entity(ndofs))\n cdim = F_a_fs.dim\n name = 'mat_vec_mul_kernel_%s' % F_a_fs.name\n\n identifier = (ndofs, cdim, name, implementation)\n if identifier in self.asts:\n return self.asts[identifier]\n\n from coffee import isa, options\n if cdim and cdim % isa['dp_reg'] == 0:\n simd_pragma = '#pragma simd reduction(+:sum)'\n else:\n simd_pragma = ''\n\n # Craft the AST\n if implementation == 'optimized' and cdim >= 4:\n body = ast.Incr(ast.Symbol('sum'),\n ast.Prod(ast.Symbol('A', ('i',), ((ndofs*cdim, 'j*%d + k' % cdim),)),\n ast.Symbol('B', ('j', 'k'))))\n body = ast.c_for('k', cdim, body, simd_pragma).children[0]\n body = [ast.Decl('const int', ast.Symbol('index'), init=ast.Symbol('i%%%d' % cdim)),\n ast.Decl('double', ast.Symbol('sum'), init=ast.Symbol('0.0')),\n ast.c_for('j', ndofs, body).children[0],\n ast.Assign(ast.Symbol('C', ('i/%d' % cdim, 'index')), 'sum')]\n body = ast.Block([ast.c_for('i', ndofs*cdim, body).children[0]])\n funargs = [ast.Decl('double* restrict', 'A'),\n ast.Decl('double *restrict *restrict', 'B'),\n ast.Decl('double *restrict *', 'C')]\n fundecl = ast.FunDecl('void', name, funargs, body, ['static', 'inline'])\n else:\n body = ast.Incr(ast.Symbol('C', ('i/%d' % cdim, 'index')),\n ast.Prod(ast.Symbol('A', ('i',), ((ndofs*cdim, 'j*%d + k' % cdim),)),\n ast.Symbol('B', ('j', 'k'))))\n body = ast.c_for('k', cdim, body).children[0]\n body = [ast.Decl('const int', ast.Symbol('index'), init=ast.Symbol('i%%%d' % cdim)),\n ast.Assign(ast.Symbol('C', ('i/%d' % cdim, 'index' % cdim)), '0.0'),\n ast.c_for('j', ndofs, body).children[0]]\n body = ast.Block([ast.c_for('i', ndofs*cdim, body).children[0]])\n funargs = [ast.Decl('double* restrict', 'A'),\n ast.Decl('double *restrict *restrict', 'B'),\n ast.Decl('double *restrict *', 'C')]\n fundecl = ast.FunDecl('void', name, funargs, body, ['static', 'inline'])\n\n # Track the AST for later fast retrieval\n self.asts[identifier] = fundecl\n\n return fundecl\n\n def solve(self, rhs, matrix_asdat, result):\n F_a = assemble(rhs)\n ast_matmul = self.ast_matmul(F_a)\n\n # Create the par loop (automatically added to the trace of loops to be executed)\n kernel = op2.Kernel(ast_matmul, ast_matmul.name)\n op2.par_loop(kernel, self.mesh.cell_set,\n matrix_asdat(op2.READ),\n F_a.dat(op2.READ, F_a.cell_node_map()),\n result.dat(op2.WRITE, result.cell_node_map()))\n\n def write(self, u=None, s=None, output=True):\n r\"\"\" Write the velocity and/or stress fields to file.\n :param firedrake.Function u: The velocity field.\n :param firedrake.Function s: The stress field.\n :returns: None\n \"\"\"\n _trace.evaluate_all()\n if output:\n with timed_region('i/o'):\n if(u):\n self.u_stream.write(u)\n if(s):\n # FIXME: Cannot currently write tensor valued fields to a VTU file.\n # See https://github.com/firedrakeproject/firedrake/issues/538\n #self.s_stream << s\n pass\n\n def run(self, T, TS=0):\n \"\"\" Run the elastic wave simulation until t = T or ntimesteps = TS.\n :param float T: The finish time of the simulation.\n :param float TS: The maximum number of timesteps performed; ignored if = 0.\n :returns: The final solution fields for velocity and stress.\n \"\"\"\n\n # Write out the initial condition.\n self.write(self.u1, self.s1, self.tofile)\n\n info(\"Generating inverse mass matrix\")\n # Pre-assemble the inverse mass matrices, which should stay\n # constant throughout the simulation (assuming no mesh adaptivity).\n start = time()\n self.assemble_inverse_mass()\n end = time()\n info(\"DONE! (Elapsed: %f s)\" % round(end - start, 3))\n op2.MPI.COMM_WORLD.barrier()\n info(\"Copying inverse mass matrix into a dat...\")\n start = time()\n self.copy_massmatrix_into_dat()\n end = time()\n info(\"DONE! (Elapsed: %f s)\" % round(end - start, 3))\n op2.MPI.COMM_WORLD.barrier()\n\n start = time()\n t = self.dt\n timestep = 0\n ntimesteps = sys.maxint if TS == 0 else TS\n\n while t <= T + 1e-12 and timestep < ntimesteps:\n if op2.MPI.COMM_WORLD.rank == 0 and timestep % self.output == 0:\n info(\"t = %f, (timestep = %d)\" % (t, timestep))\n with loop_chain(\"main1\",\n tile_size=self.tiling_size,\n num_unroll=self.tiling_uf,\n mode=self.tiling_mode,\n extra_halo=self.tiling_halo,\n explicit=self.tiling_explicit,\n use_glb_maps=self.tiling_glb_maps,\n use_prefetch=self.tiling_prefetch,\n coloring=self.tiling_coloring,\n ignore_war=True,\n log=self.tiling_log):\n # In case the source is time-dependent, update the time 't' here.\n if(self.source):\n with timed_region('source term update'):\n self.source_expression.t = t\n self.source = self.source_expression\n\n # Solve for the velocity vector field.\n self.solve(self.rhs_uh1, self.velocity_mass_asdat, self.uh1)\n self.solve(self.rhs_stemp, self.stress_mass_asdat, self.stemp)\n self.solve(self.rhs_uh2, self.velocity_mass_asdat, self.uh2)\n self.solve(self.rhs_u1, self.velocity_mass_asdat, self.u1)\n\n # Solve for the stress tensor field.\n self.solve(self.rhs_sh1, self.stress_mass_asdat, self.sh1)\n self.solve(self.rhs_utemp, self.velocity_mass_asdat, self.utemp)\n self.solve(self.rhs_sh2, self.stress_mass_asdat, self.sh2)\n self.solve(self.rhs_s1, self.stress_mass_asdat, self.s1)\n\n self.u0.assign(self.u1)\n self.s0.assign(self.s1)\n\n # Write out the new fields\n self.write(self.u1, self.s1, self.tofile and timestep % self.output == 0)\n\n # Move onto next timestep\n t += self.dt\n timestep += 1\n\n # Write out the final state of the fields\n self.write(self.u1, self.s1, self.tofile)\n\n end = time()\n\n return start, end, timestep, self.u1, self.s1\n\n\n# Helper stuff\n\ndef Vp(mu, l, density):\n r\"\"\" Calculate the P-wave velocity, given by\n\n .. math:: \\sqrt{\\frac{(\\lambda + 2\\mu)}{\\rho}}\n\n where :math:`\\rho` is the density, and :math:`\\lambda` and :math:`\\mu` are\n the first and second Lame parameters, respectively.\n\n :param mu: The second Lame parameter.\n :param l: The first Lame parameter.\n :param density: The density.\n :returns: The P-wave velocity.\n :rtype: float\n \"\"\"\n return sqrt((l + 2*mu)/density)\n\n\ndef Vs(mu, density):\n r\"\"\" Calculate the S-wave velocity, given by\n\n .. math:: \\sqrt{\\frac{\\mu}{\\rho}}\n\n where :math:`\\rho` is the density, and :math:`\\mu` is the second Lame parameter.\n\n :param mu: The second Lame parameter.\n :param density: The density.\n :returns: The P-wave velocity.\n :rtype: float\n \"\"\"\n return sqrt(mu/density)\n\n\ndef cfl_dt(dx, Vp, courant_number):\n r\"\"\" Computes the maximum permitted value for the timestep math:`\\delta t`.\n :param float dx: The characteristic element length.\n :param float Vp: The P-wave velocity.\n :param float courant_number: The desired Courant number\n :returns: The maximum permitted timestep, math:`\\delta t`.\n :rtype: float\n \"\"\"\n return (courant_number*dx)/Vp\n\n\nclass ExplosiveSourceLF4(object):\n\n def explosive_source_lf4(self, T=2.5, TS=0, Lx=300.0, Ly=150.0, h=2.5, cn=0.05,\n mesh_file=None, output=1, poly_order=2, params=None):\n\n tile_size = params['tile_size']\n num_unroll = params['num_unroll']\n extra_halo = params['extra_halo']\n part_mode = params['partitioning']\n explicit_mode = params['explicit_mode']\n\n if explicit_mode:\n fusion_scheme = FusionSchemes.get(explicit_mode, part_mode, tile_size)\n num_solves, params['explicit_mode'] = fusion_scheme\n else:\n num_solves = ElasticLF4.num_solves\n\n if mesh_file:\n mesh = Mesh(mesh_file)\n else:\n mesh = RectangleMesh(int(Lx/h), int(Ly/h), Lx, Ly)\n\n set_log_level(INFO)\n\n kwargs = {}\n if params['mode'] in ['tile', 'only_tile']:\n s_depth = calculate_sdepth(num_solves, num_unroll, extra_halo)\n if part_mode == 'metis':\n kwargs['reorder'] = ('metis-rcm', mesh.num_cells() / tile_size)\n else:\n s_depth = 1\n # FIXME: need s_depth in firedrake to be able to use this\n # kwargs['s_depth'] = s_depth\n params['s_depth'] = s_depth\n\n mesh.topology.init(**kwargs)\n slope(mesh, debug=True)\n\n # Instantiate the model\n self.elastic = ElasticLF4(mesh, \"DG\", poly_order, 2, output, params)\n\n info(\"S-depth used: %d\" % s_depth)\n info(\"Polynomial order: %d\" % poly_order)\n\n # Constants\n self.elastic.density = 1.0\n self.elastic.mu = 3600.0\n self.elastic.l = 3599.3664\n\n self.Vp = Vp(self.elastic.mu, self.elastic.l, self.elastic.density)\n self.Vs = Vs(self.elastic.mu, self.elastic.density)\n info(\"P-wave velocity: %f\" % self.Vp)\n info(\"S-wave velocity: %f\" % self.Vs)\n\n self.dx = h\n self.courant_number = cn\n self.elastic.dt = cfl_dt(self.dx, self.Vp, self.courant_number)\n info(\"Using a timestep of %f\" % self.elastic.dt)\n\n # Source\n exp_area = (44.5, 45.5, Ly - 1.5, Ly - 0.5)\n if poly_order == 1:\n # Adjust explosion area\n exp_area = (149.5, 150.5, Ly - 1.5, Ly - 0.5)\n a = 159.42\n self.elastic.source_expression = Expression(((\"x[0] >= %f && x[0] <= %f && x[1] >= %f && x[1] <= %f ? (-1.0 + 2*a*pow(t - 0.3, 2))*exp(-a*pow(t - 0.3, 2)) : 0.0\" % exp_area, \"0.0\"),\n (\"0.0\", \"x[0] >= %f && x[0] <= %f && x[1] >= %f && x[1] <= %f ? (-1.0 + 2*a*pow(t - 0.3, 2))*exp(-a*pow(t - 0.3, 2)) : 0.0\" % exp_area)), a=a, t=0)\n self.elastic.source_function = Function(self.elastic.S)\n self.elastic.source = self.elastic.source_expression\n\n # Absorption\n F = FunctionSpace(mesh, \"DG\", poly_order, name='F')\n self.elastic.absorption_function = Function(F)\n self.elastic.absorption = Expression(\"x[0] <= 20 || x[0] >= %f || x[1] <= 20.0 ? 1000 : 0\" % (Lx - 20,))\n\n # Initial conditions\n uic = Expression(('0.0', '0.0'))\n self.elastic.u0.assign(Function(self.elastic.U).interpolate(uic))\n sic = Expression((('0', '0'), ('0', '0')))\n self.elastic.s0.assign(Function(self.elastic.S).interpolate(sic))\n\n # Run the simulation\n start, end, ntimesteps, u1, s1 = self.elastic.run(T, TS=TS)\n\n # Print runtime summary\n output_time(start, end,\n tofile=params['tofile'],\n verbose=params['verbose'],\n meshid=(\"h%s\" % h).replace('.', ''),\n ntimesteps=ntimesteps,\n nloops=ElasticLF4.loop_chain_length*num_unroll,\n partitioning=part_mode,\n tile_size=tile_size,\n extra_halo=extra_halo,\n explicit_mode=explicit_mode,\n glb_maps=params['use_glb_maps'],\n prefetch=params['use_prefetch'],\n coloring=params['coloring'],\n poly_order=poly_order,\n domain=os.path.splitext(os.path.basename(mesh.name))[0],\n function_spaces=[self.elastic.S, self.elastic.U])\n\n return u1, s1\n\n\nif __name__ == '__main__':\n set_log_level(INFO)\n\n # Parse the input\n args = parser()\n params = {\n 'num_unroll': args.num_unroll,\n 'tile_size': args.tile_size,\n 'mode': args.fusion_mode,\n 'partitioning': args.part_mode,\n 'coloring': args.coloring,\n 'extra_halo': args.extra_halo,\n 'explicit_mode': args.explicit_mode,\n 'explicit_mode_id': args.explicit_mode,\n 'use_glb_maps': args.glb_maps,\n 'use_prefetch': args.prefetch,\n 'log': args.log,\n 'tofile': args.tofile,\n 'verbose': args.verbose\n }\n\n # Set the kernel optimizaation level (default: O2)\n parameters['coffee']['optlevel'] = args.coffee_opt\n\n # Is it just a run to check correctness?\n if args.check:\n Lx, Ly, h, time_max, tolerance = 20, 20, 2.5, 0.01, 1e-10\n info(\"Checking correctness of original and tiled versions, with:\")\n info(\" (Lx, Ly, T, tolerance)=%s\" % str((Lx, Ly, time_max, tolerance)))\n info(\" %s\" % params)\n # Run the tiled variant\n u1, s1 = ExplosiveSourceLF4().explosive_source_lf4(time_max, Lx, Ly, h,\n sys.maxint, params)\n # Run the original code\n original = {'num_unroll': 0, 'tile_size': 0, 'mode': None,\n 'partitioning': 'chunk', 'extra_halo': 0}\n u1_orig, s1_orig = ExplosiveSourceLF4().explosive_source_lf4(time_max, Lx, Ly, h,\n sys.maxint, original)\n # Check output\n info(\"Checking output...\")\n assert np.allclose(u1.dat.data, u1_orig.dat.data, rtol=1e-10)\n assert np.allclose(s1.dat.data, s1_orig.dat.data, rtol=1e-10)\n info(\"Results OK!\")\n sys.exit(0)\n\n # Set the input mesh\n if args.mesh_file:\n info(\"Using the unstructured mesh %s\" % args.mesh_file)\n kwargs = {'T': args.time_max, 'TS': args.timesteps_max, 'mesh_file': args.mesh_file,\n 'h': args.ms, 'cn': args.cn, 'output': args.output, 'poly_order': args.poly_order,\n 'params': params}\n else:\n Lx, Ly = eval(args.mesh_size)\n info(\"Using the structured mesh with values (Lx,Ly,h)=%s\" % str((Lx, Ly, args.ms)))\n kwargs = {'T': args.time_max, 'TS': args.timesteps_max, 'Lx': Lx, 'Ly': Ly, 'h': args.ms,\n 'output': args.output, 'poly_order': args.poly_order, 'params': params}\n\n info(\"h=%f, courant number=%f\" % (args.ms, args.cn))\n\n if args.profile:\n cProfile.run('ExplosiveSourceLF4().explosive_source_lf4(**kwargs)',\n 'log_rank%d.cprofile' % op2.MPI.COMM_WORLD.rank)\n else:\n u1, s1 = ExplosiveSourceLF4().explosive_source_lf4(**kwargs)\n" ]
[ [ "numpy.arange", "numpy.allclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
isabella232/gps_building_blocks
[ "86ef8be60a42cd12e27696007589388b7b053f4f", "86ef8be60a42cd12e27696007589388b7b053f4f" ]
[ "py/gps_building_blocks/analysis/exp_design/ab_testing_design_test.py", "py/gps_building_blocks/ml/data_prep/data_visualizer/viz_utils_test.py" ]
[ "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# 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\"\"\"Tests for gps_building_blocks.analysis.exp_design.ab_testing_design.\"\"\"\n\nfrom absl.testing import absltest\nimport numpy as np\nfrom gps_building_blocks.analysis.exp_design import ab_testing_design\n\nBASELINE_CONVERSION_RATE_PERCENTAGE = 5\nEXPECTED_UPLIFT_PERCENTAGE = 10\nLABELS = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\nPREDICTIONS = np.array([\n 0.7, 0.63, 0.4, 0.77, 0.45, 0.8, 0.41, 0.82, 0.7, 0.6, 0.5, 0.45, 0.74,\n 0.11, 0.21, 0.05, 0.67, 0.79, 0.60, 0.10\n])\n\n\nclass ABTestingExperimentalDesignTest(absltest.TestCase):\n\n def test_calc_chisquared_sample_size_returns_correct_values(self):\n result_sample_size = ab_testing_design.calc_chisquared_sample_size(\n baseline_conversion_rate_percentage=BASELINE_CONVERSION_RATE_PERCENTAGE,\n expected_uplift_percentage=EXPECTED_UPLIFT_PERCENTAGE)\n\n self.assertEqual(result_sample_size, 14913.0)\n\n def test_calc_chisquared_sample_size_change_power_and_confidence(self):\n result_sample_size = ab_testing_design.calc_chisquared_sample_size(\n baseline_conversion_rate_percentage=BASELINE_CONVERSION_RATE_PERCENTAGE,\n expected_uplift_percentage=EXPECTED_UPLIFT_PERCENTAGE,\n power_percentage=90,\n confidence_level_percentage=99)\n\n self.assertEqual(result_sample_size, 28271.0)\n\n def test_calc_chisquared_sample_sizes_for_bins_returns_correct_values(self):\n results = ab_testing_design.calc_chisquared_sample_sizes_for_bins(\n labels=LABELS, probability_predictions=PREDICTIONS, number_bins=3)\n\n self.assertEqual(results.shape, (24, 7))\n self.assertListEqual(\n list(results.columns), [\n 'bin_number', 'bin_size', 'conv_rate_percentage',\n 'uplift_percentage', 'power_percentage',\n 'confidence_level_percentage', 'sample_size'\n ])\n self.assertListEqual(\n list(results['sample_size']), [\n 248.0, 314.0, 343.0, 421.0, 62.0, 79.0, 86.0, 106.0, 928.0, 1178.0,\n 1285.0, 1577.0, 232.0, 295.0, 322.0, 395.0, 1031.0, 1309.0, 1428.0,\n 1752.0, 258.0, 328.0, 357.0, 438.0\n ])\n\n def test_resulted_bin_metrics_does_not_contain_nas(self):\n results = ab_testing_design.calc_chisquared_sample_sizes_for_bins(\n labels=LABELS, probability_predictions=PREDICTIONS, number_bins=3)\n\n self.assertFalse(results.isna().values.any())\n\n def test_calc_chisquared_sample_sizes_for_cumulative_bins_returns_right_vals(\n self):\n results = ab_testing_design.calc_chisquared_sample_sizes_for_cumulative_bins(\n labels=LABELS, probability_predictions=PREDICTIONS, number_bins=5)\n\n self.assertEqual(results.shape, (40, 8))\n self.assertListEqual(\n list(results.columns), [\n 'cumulative_bin_number', 'bin_size', 'bin_size_percentage',\n 'conv_rate_percentage', 'uplift_percentage', 'power_percentage',\n 'confidence_level_percentage', 'sample_size'\n ])\n self.assertListEqual(\n list(results['sample_size']), [\n 207.0, 262.0, 286.0, 351.0, 52.0, 66.0, 72.0, 88.0, 371.0, 471.0,\n 514.0, 631.0, 93.0, 118.0, 129.0, 158.0, 442.0, 561.0, 612.0, 751.0,\n 111.0, 141.0, 153.0, 188.0, 371.0, 471.0, 514.0, 631.0, 93.0, 118.0,\n 129.0, 158.0, 619.0, 785.0, 857.0, 1051.0, 155.0, 197.0, 215.0,\n 263.0\n ])\n\n\nif __name__ == '__main__':\n absltest.main()\n", "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# 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# python3\n\"\"\"Tests for google3.corp.gtech.ads.data_catalyst.components.data_preparation.data_visualizer.plot_data_creation_utils.\"\"\"\n\nfrom absl.testing import absltest\nfrom google.cloud import bigquery\nfrom matplotlib import pyplot as plt\nimport pandas as pd\nfrom gps_building_blocks.ml.data_prep.data_visualizer import viz_utils\n\nTESTDATA_1 = pd.DataFrame({\n 'snapshot_date': ['2019-10-01', '2019-10-02', '2019-10-03'],\n 'pos_count': [326, 312, 300],\n 'neg_count': [321061, 320396, 320200],\n 'tot_count': [321387, 320708, 320500],\n 'rate': [0.001014, 0.000973, 0.0009]\n})\n\nTESTDATA_2 = pd.DataFrame({\n 'days_since_first_activity': [120, 150, 200, 60, 100, 130, 20, 50, 450, 38],\n 'days_since_latest_activity': [30, 100, 35, 23, 45, 100, 14, 7, 20, 6],\n 'has_positive_label': [\n 'True', 'False', 'False', 'True', 'False', 'True', 'False', 'False',\n 'True', 'True'\n ]\n})\n\n\nclass VizUtilsTest(absltest.TestCase):\n\n def setUp(self):\n self.addCleanup(absltest.mock.patch.stopall)\n super(VizUtilsTest, self).setUp()\n\n self.mock_bq_client = absltest.mock.create_autospec(bigquery.client.Client)\n\n def test_execute_sql_returns_pd_dataframe(self):\n fake_sql_query = 'SELECT * FROM project.dataset.table;'\n\n self.mock_bq_client.query.return_value.to_dataframe.return_value = TESTDATA_1\n\n results = viz_utils.execute_sql(self.mock_bq_client, fake_sql_query)\n\n self.mock_bq_client.query.return_value.result.assert_called_once()\n pd.testing.assert_frame_equal(results, TESTDATA_1)\n\n def test_plot_bar_returns_a_bar_plot_with_correct_elements(self):\n plot_data = TESTDATA_1\n x_var = 'snapshot_date'\n y_var = 'pos_count'\n title = '# positive examples over time'\n subplot_index = 0\n\n _, axes = plt.subplots(nrows=2, ncols=1)\n viz_utils.plot_bar(\n plot_data=plot_data,\n x_variable=x_var,\n y_variable=y_var,\n title=title,\n axes=axes,\n subplot_index=subplot_index)\n\n bar_plot = axes[subplot_index]\n x_data = list(plot_data[x_var])\n y_data = [float(y) for y in list(plot_data[y_var])]\n\n with self.subTest(name='test x axis variable is equal'):\n self.assertEqual(x_var, bar_plot.get_xlabel())\n with self.subTest(name='test x axis data is equal'):\n self.assertListEqual(\n x_data,\n [tick.get_text() for tick in bar_plot.get_xticklabels(which='major')])\n with self.subTest(name='test y axis variable is equal'):\n self.assertEqual(y_var, bar_plot.get_ylabel())\n with self.subTest(name='test y axis data is equal'):\n self.assertListEqual(y_data, [h.get_height() for h in bar_plot.patches])\n with self.subTest(name='test title is equal'):\n self.assertEqual(title, bar_plot.get_title())\n\n def test_plot_class_densities_returns_plot_with_correct_elements(self):\n plot_data = TESTDATA_2\n plot_variable = 'days_since_first_activity'\n title = 'Class distribution of days_since_first_activity'\n class1_label = 'True'\n class2_label = 'False'\n label_variable = 'has_positive_label'\n subplot_index = 0\n\n _, axes = plt.subplots(nrows=2, ncols=1)\n viz_utils.plot_class_densities(\n plot_data=plot_data,\n plot_variable=plot_variable,\n class1_label='True',\n class2_label='False',\n label_variable=label_variable,\n title=title,\n axes=axes,\n subplot_index=subplot_index)\n\n plot = axes[subplot_index]\n\n with self.subTest(name='test labels of two clases are equal'):\n self.assertListEqual([\n label_variable + '=' + class1_label,\n label_variable + '=' + class2_label\n ], [l.get_text() for l in plot.get_legend().get_texts()])\n with self.subTest(name='test title is equal'):\n self.assertEqual(title, plot.title.get_text())\n\n def test_plot_line_returns_a_line_plot_with_correct_elements(self):\n plot_data = TESTDATA_1\n x_var = 'snapshot_date'\n y_var = 'tot_count'\n title = 'Total examples over time'\n subplot_index = 0\n\n _, axes = plt.subplots(nrows=2, ncols=1)\n viz_utils.plot_line(\n plot_data=plot_data,\n x_variable=x_var,\n y_variable=y_var,\n title=title,\n axes=axes,\n subplot_index=subplot_index)\n\n line_plot = axes[subplot_index]\n y_data = list(plot_data[y_var])\n\n with self.subTest(name='test x axis variable is equal'):\n self.assertEqual(x_var, line_plot.get_xlabel())\n with self.subTest(name='test y axis variable is equal'):\n self.assertEqual(y_var, line_plot.get_ylabel())\n with self.subTest(name='test y axis data is equal'):\n self.assertListEqual(y_data, list(line_plot.get_lines()[0].get_data()[1]))\n with self.subTest(name='test title is equal'):\n self.assertEqual(title, line_plot.get_title())\n\n\nif __name__ == '__main__':\n absltest.main()\n" ]
[ [ "numpy.array" ], [ "pandas.testing.assert_frame_equal", "matplotlib.pyplot.subplots", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
ashishpatel26/mealpy
[ "69e8dc727e15527e31ac5ace1debe92a0bc7d828", "69e8dc727e15527e31ac5ace1debe92a0bc7d828", "69e8dc727e15527e31ac5ace1debe92a0bc7d828", "69e8dc727e15527e31ac5ace1debe92a0bc7d828" ]
[ "mealpy/fake/RHO.py", "mealpy/swarm_based/BES.py", "mealpy/bio_based/IWO.py", "mealpy/physics_based/WDO.py" ]
[ "#!/usr/bin/env python\n# ------------------------------------------------------------------------------------------------------%\n# Created by \"Thieu Nguyen\" at 14:53, 17/03/2020 %\n# %\n# Email: [email protected] %\n# Homepage: https://www.researchgate.net/profile/Thieu_Nguyen6 %\n# Github: https://github.com/thieu1995 %\n#-------------------------------------------------------------------------------------------------------%\n\nfrom numpy.random import uniform, normal\nfrom numpy.linalg import norm\nfrom numpy import exp, power, pi, zeros, array, mean, ones, dot\nfrom math import gamma\nfrom copy import deepcopy\nfrom mealpy.root import Root\n\n\nclass OriginalRHO(Root):\n \"\"\"\n The original version of: Rhino Herd Optimization (RHO)\n (A Novel Metaheuristic Algorithm inspired by Rhino Herd Behavior)\n Link:\n https://doi.org/10.3384/ecp171421026\n \"\"\"\n\n def __init__(self, obj_func=None, lb=None, ub=None, problem_size=50, batch_size=10, verbose=True,\n epoch=750, pop_size=100, c=0.53, a=2831, r=0.04, A=1):\n Root.__init__(self, obj_func, lb, ub, problem_size, batch_size, verbose)\n self.epoch = epoch\n self.pop_size = pop_size\n self.c = c # shape parameter - default = 0.53 > 0\n self.a = a # scale parameter - default = 2831 > 0\n self.r = r # default = 0.04\n self.A = A # the area of each grid cell - default = 1\n\n def train(self):\n pop = [self.create_solution() for _ in range(self.pop_size)]\n g_best = self.get_global_best_solution(pop=pop, id_fit=self.ID_FIT, id_best=self.ID_MIN_PROB)\n\n # Epoch loop\n for epoch in range(self.epoch):\n\n pos_list = array([item[self.ID_POS] for item in pop])\n fit_list = array([item[self.ID_FIT] for item in pop])\n fx_list = deepcopy(fit_list)\n pos_center = mean(pos_list, axis=0)\n\n ## Each individual loop\n for i in range(0, self.pop_size):\n # Eq. 1\n exp_component = -1 * power(norm(pop[i][self.ID_POS] - pos_center) / self.a, 2.0 / self.c)\n fx = 2 * exp(exp_component) / (self.c ** 2 * pi * self.a ** 2 * gamma(self.c))\n fx_list[i] = fx\n\n # Eq. 7\n s_component = ones(self.problem_size)\n for j in range(0, self.problem_size):\n sum_temp = 0\n for i in range(0, self.pop_size):\n sum_temp += fx_list[i] * (1 + pop[i][self.ID_POS][j] / (self.EPSILON + pop[i][self.ID_FIT]))\n s_component[j] = self.A * sum_temp\n\n for i in range(0, self.pop_size):\n x_new = pop[i][self.ID_POS]\n for j in range(0, self.problem_size):\n # Eq. 7\n s_x = fx_list[i] * (1 + pop[i][self.ID_FIT] * pop[i][self.ID_POS][j]) / s_component[j]\n\n # Eq. 9\n if uniform() <= 0.5:\n x_new[j] = pop[i][self.ID_POS][j] - uniform() * s_x * pop[i][self.ID_POS][j]\n else:\n x_new[j] = pop[i][self.ID_POS][j] + uniform() * s_x * pop[i][self.ID_POS][j]\n x_new = self.amend_position_faster(x_new)\n fit = self.get_fitness_position(x_new)\n if fit < pop[i][self.ID_FIT]:\n pop[i] = [x_new, fit]\n\n g_best = self.update_global_best_solution(pop, self.ID_MIN_PROB, g_best)\n self.loss_train.append(g_best[self.ID_FIT])\n if self.verbose:\n print(\"> Epoch: {}, Best fit: {}\".format(epoch + 1, g_best[self.ID_FIT]))\n self.solution = g_best\n return g_best[self.ID_POS], g_best[self.ID_FIT], self.loss_train\n\n\nclass BaseRHO(Root):\n \"\"\"\n My version of: Rhino Herd Optimization (RHO)\n (A Novel Metaheuristic Algorithm inspired by Rhino Herd Behavior)\n Notes:\n + Remove third loop\n \"\"\"\n\n def __init__(self, obj_func=None, lb=None, ub=None, problem_size=50, batch_size=10, verbose=True,\n epoch=750, pop_size=100, c=0.53, a=2831, r=0.04, A=1):\n Root.__init__(self, obj_func, lb, ub, problem_size, batch_size, verbose)\n self.epoch = epoch\n self.pop_size = pop_size\n self.c = c # shape parameter - default = 0.53 > 0\n self.a = a # scale parameter - default = 2831 > 0\n self.r = r # default = 0.04\n self.A = A # the area of each grid cell - default = 1\n\n def train(self):\n pop = [self.create_solution() for _ in range(self.pop_size)]\n g_best = self.get_global_best_solution(pop=pop, id_fit=self.ID_FIT, id_best=self.ID_MIN_PROB)\n pop_size = self.pop_size\n\n # Epoch loop\n for epoch in range(self.epoch):\n pop_new = deepcopy(pop)\n\n pos_list = array([item[self.ID_POS] for item in pop])\n fit_list = array([item[self.ID_FIT] for item in pop])\n fx_list = deepcopy(fit_list)\n pos_center = mean(pos_list, axis=0)\n\n ## Calculate the fx for each individual\n for i in range(0, pop_size):\n # Eq. 1\n exp_component = -1 * power(norm(pop[i][self.ID_POS] - pos_center) / self.a , 2.0/self.c )\n fx = 2 * exp(exp_component) / (self.c ** 2 * pi * self.a ** 2 * gamma(self.c))\n fx_list[i] = fx\n\n # print(fx_list)\n\n # Eq. 7\n sum_temp = zeros(self.problem_size)\n for i in range(0, pop_size):\n sum_temp += fx_list[i] * (1 + pop[i][self.ID_POS] * pop[i][self.ID_FIT])\n sum_temp = self.A * sum_temp\n\n for i in range(0, pop_size):\n s_x = fx_list[i] * (1 + pop[i][self.ID_POS]/pop[i][self.ID_FIT]) / sum_temp\n if uniform() <= 0.5:\n x_new = pop[i][self.ID_POS] - uniform() * dot(s_x, pop[i][self.ID_POS])\n else:\n x_new = pop[i][self.ID_POS] + uniform() * dot(s_x, pop[i][self.ID_POS])\n x_new = self.amend_position_faster(x_new)\n fit = self.get_fitness_position(x_new)\n if fit < pop[i][self.ID_FIT]:\n pop_new[i] = [x_new, fit]\n\n if epoch % 100 == 0:\n pop_size = self.pop_size\n pop_new = sorted(pop_new, key=lambda item: item[self.ID_FIT])\n pop = deepcopy(pop_new[:pop_size])\n else:\n pop_size = pop_size + int(self.r * pop_size)\n n_new = pop_size - len(pop)\n for i in range(0, n_new):\n pop_new.extend([self.create_solution()])\n pop = deepcopy(pop_new)\n\n g_best = self.update_global_best_solution(pop, self.ID_MIN_PROB, g_best)\n self.loss_train.append(g_best[self.ID_FIT])\n if self.verbose:\n print(\"> Epoch: {}, Best fit: {}\".format(epoch + 1, g_best[self.ID_FIT]))\n self.solution = g_best\n return g_best[self.ID_POS], g_best[self.ID_FIT], self.loss_train\n\n\nclass LevyRHO(BaseRHO):\n \"\"\"\n My modified version of: Rhino Herd Optimization (RH)\n (A Novel Metaheuristic Algorithm inspired by Rhino Herd Behavior)\n Notes:\n + Change the flow of algorithm\n + Uses normal in equation instead of uniform\n + Uses levy-flight instead of uniform-equation\n \"\"\"\n\n def __init__(self, obj_func=None, lb=None, ub=None, problem_size=50, batch_size=10, verbose=True,\n epoch=750, pop_size=100, c=0.53, a=2831, r=0.04, A=1):\n BaseRHO.__init__(self, obj_func, lb, ub, problem_size, batch_size, verbose, epoch, pop_size, c, a, r, A)\n\n\n def train(self):\n pop = [self.create_solution(minmax=0) for _ in range(self.pop_size)]\n g_best = self.get_global_best_solution(pop=pop, id_fit=self.ID_FIT, id_best=self.ID_MIN_PROB)\n pop_size = self.pop_size\n\n # Epoch loop\n for epoch in range(self.epoch):\n pop_new = deepcopy(pop)\n\n pos_list = array([item[self.ID_POS] for item in pop])\n pos_center = mean(pos_list, axis=0)\n fx_list = zeros(pop_size)\n\n ## Calculate the fx for each individual\n for i in range(0, pop_size):\n # Eq. 1\n exp_component = -1 * power( norm(pop[i][self.ID_POS] - pos_center) / self.a , 2.0/self.c )\n fx = 2 * exp(exp_component) / (self.c ** 2 * pi * self.a ** 2 * gamma(self.c))\n fx_list[i] = fx\n #print(fx_list)\n # Eq. 7\n sum_temp = zeros(self.problem_size)\n for i in range(0, self.pop_size):\n sum_temp += fx_list[i] * (1 + pop[i][self.ID_POS] / pop[i][self.ID_FIT] + self.EPSILON)\n sum_temp = self.A * sum_temp\n\n for i in range(0, pop_size):\n s_x = fx_list[i] * (1 + pop[i][self.ID_FIT] * pop[i][self.ID_POS]) / sum_temp\n if uniform() < 0.5:\n x_new = pop[i][self.ID_POS] - normal() * dot(s_x, pop[i][self.ID_POS])\n else:\n x_new = self.levy_flight(epoch+1, pop[i][self.ID_POS], g_best[self.ID_POS])\n x_new = self.amend_position_faster(x_new)\n fit = self.get_fitness_position(x_new)\n if fit < pop[i][self.ID_FIT]:\n pop_new[i] = [x_new, fit]\n\n if epoch % 100 == 0:\n pop_size = self.pop_size\n pop_new = sorted(pop_new, key=lambda item: item[self.ID_FIT])\n pop = deepcopy(pop_new[:pop_size])\n else:\n pop_size = pop_size + int(self.r * pop_size)\n n_new = pop_size - len(pop)\n for i in range(0, n_new):\n pop_new.extend([self.create_solution()])\n pop = deepcopy(pop_new)\n\n ## Make sure the population does not have duplicates.\n new_set = set()\n for idx, obj in enumerate(pop):\n if tuple(obj[self.ID_POS].tolist()) in new_set:\n pop[idx] = self.create_solution()\n else:\n new_set.add(tuple(obj[self.ID_POS].tolist()))\n\n g_best = self.update_global_best_solution(pop, self.ID_MIN_PROB, g_best)\n self.loss_train.append(g_best[self.ID_FIT])\n if self.verbose:\n print(\"> Epoch: {}, Pop Size: {}, Best Fit: {}\".format(epoch+1, pop_size, g_best[self.ID_FIT]))\n self.solution = g_best\n return g_best[self.ID_POS], g_best[self.ID_FIT], self.loss_train\n\n", "#!/usr/bin/env python\n# ------------------------------------------------------------------------------------------------------%\n# Created by \"Thieu Nguyen\" at 14:52, 17/03/2020 %\n# %\n# Email: [email protected] %\n# Homepage: https://www.researchgate.net/profile/Thieu_Nguyen6 %\n# Github: https://github.com/thieu1995 %\n#-------------------------------------------------------------------------------------------------------%\n\nfrom numpy.random import uniform, choice\nfrom numpy import array, mean, pi, sin, cos, max, sinh, cosh\nfrom mealpy.root import Root\n\n\nclass BaseBES(Root):\n \"\"\"\n Original version of: Bald Eagle Search (BES)\n (Novel meta-heuristic bald eagle search optimisation algorithm)\n Link:\n DOI: https://doi.org/10.1007/s10462-019-09732-5\n \"\"\"\n\n def __init__(self, obj_func=None, lb=None, ub=None, problem_size=50, batch_size=10, verbose=True,\n epoch=750, pop_size=100, a=10, R=1.5, alpha=2, c1=2, c2=2):\n Root.__init__(self, obj_func, lb, ub, problem_size, batch_size, verbose)\n self.epoch = epoch\n self.pop_size = pop_size\n self.a = a # default: 10, determining the corner between point search in the central point, in [5, 10]\n self.R = R # default: 1.5, determining the number of search cycles, in [0.5, 2]\n self.alpha = alpha # default: 2, parameter for controlling the changes in position, in [1.5, 2]\n self.c1 = c1 # default: 2, in [1, 2]\n self.c2 = c2 # c1 and c2 increase the movement intensity of bald eagles towards the best and centre points\n\n def _create_x_y_x1_y1_(self):\n \"\"\" Using numpy vector for faster computational time \"\"\"\n ## Eq. 2\n phi = self.a * pi * uniform(0, 1, self.pop_size)\n r = phi + self.R * uniform(0, 1, self.pop_size)\n xr, yr = r * sin(phi), r * cos(phi)\n\n ## Eq. 3\n r1 = phi1 = self.a * pi * uniform(0, 1, self.pop_size)\n xr1, yr1 = r1 * sinh(phi1), r1 * cosh(phi1)\n\n x_list = xr / max(xr)\n y_list = yr / max(yr)\n x1_list = xr1 / max(xr1)\n y1_list = yr1 / max(yr1)\n return x_list, y_list, x1_list, y1_list\n\n def train(self):\n # Initialization population and fitness\n pop = [self.create_solution() for _ in range(self.pop_size)]\n g_best = self.get_global_best_solution(pop, self.ID_FIT, self.ID_MIN_PROB)\n\n for epoch in range(self.epoch):\n ## 0. Pre-definded\n x_list, y_list, x1_list, y1_list = self._create_x_y_x1_y1_()\n\n # Three parts: selecting the search space, searching within the selected search space and swooping.\n ## 1. Select space\n pos_list = array([individual[self.ID_POS] for individual in pop])\n pos_mean = mean(pos_list, axis=0)\n for i in range(0, self.pop_size):\n pos_new = g_best[self.ID_POS] + self.alpha * uniform() * (pos_mean - pop[i][self.ID_POS])\n pos_new = self.amend_position_faster(pos_new)\n fit = self.get_fitness_position(pos_new)\n if fit < pop[i][self.ID_FIT]:\n pop[i] = [pos_new, fit]\n if pop[i][self.ID_FIT] < g_best[self.ID_FIT]:\n g_best = [pos_new, fit]\n\n ## 2. Search in space\n pos_list = array([individual[self.ID_POS] for individual in pop])\n pos_mean = mean(pos_list, axis=0)\n for i in range(0, self.pop_size):\n idx_rand = choice(list(set(range(0, self.pop_size)) - {i}))\n pos_new = pop[i][self.ID_POS] + y_list[i] * (pop[i][self.ID_POS] - pop[idx_rand][self.ID_POS]) + x_list[i] * (pop[i][self.ID_POS] - pos_mean)\n pos_new = self.amend_position_faster(pos_new)\n fit = self.get_fitness_position(pos_new)\n if fit < pop[i][self.ID_FIT]:\n pop[i] = [pos_new, fit]\n if pop[i][self.ID_FIT] < g_best[self.ID_FIT]:\n g_best = [pos_new, fit]\n\n ## 3. Swoop\n pos_list = array([individual[self.ID_POS] for individual in pop])\n pos_mean = mean(pos_list, axis=0)\n for i in range(0, self.pop_size):\n pos_new = uniform() * g_best[self.ID_POS] + x1_list[i] * (pop[i][self.ID_POS] - self.c1 * pos_mean) \\\n + y1_list[i] * (pop[i][self.ID_POS] - self.c2 * g_best[self.ID_POS])\n pos_new = self.amend_position_faster(pos_new)\n fit = self.get_fitness_position(pos_new)\n if fit < pop[i][self.ID_FIT]:\n pop[i] = [pos_new, fit]\n if pop[i][self.ID_FIT] < g_best[self.ID_FIT]:\n g_best = [pos_new, fit]\n\n self.loss_train.append(g_best[self.ID_FIT])\n if self.verbose:\n print(\"> Epoch: {}, Best fit: {}\".format(epoch + 1, g_best[self.ID_FIT]))\n self.solution = g_best\n return g_best[self.ID_POS], g_best[self.ID_FIT], self.loss_train\n", "#!/usr/bin/env python\n# ------------------------------------------------------------------------------------------------------%\n# Created by \"Thieu Nguyen\" at 12:17, 18/03/2020 %\n# %\n# Email: [email protected] %\n# Homepage: https://www.researchgate.net/profile/Thieu_Nguyen6 %\n# Github: https://github.com/thieu1995 %\n#-------------------------------------------------------------------------------------------------------%\n\nfrom numpy.random import uniform\nfrom numpy import ceil\nfrom copy import deepcopy\nfrom mealpy.root import Root\n\n\nclass BaseIWO(Root):\n \"\"\"\n My version of: weed colonization (IWO)\n A novel numerical optimization algorithm inspired from weed colonization\n Noted:\n https://pdfs.semanticscholar.org/734c/66e3757620d3d4016410057ee92f72a9853d.pdf\n \"\"\"\n\n def __init__(self, obj_func=None, lb=None, ub=None, problem_size=50, batch_size=10, verbose=True,\n epoch=750, pop_size=100, seeds=(2, 10), exponent=2, sigma=(0.5, 0.001)):\n Root.__init__(self, obj_func, lb, ub, problem_size, batch_size, verbose)\n self.epoch = epoch\n self.pop_size = pop_size\n self.seeds = seeds # (Min, Max) Number of Seeds\n self.exponent = exponent # Variance Reduction Exponent\n self.sigma = sigma # (Initial, Final) Value of Standard Deviation\n\n def train(self):\n pop = [self.create_solution() for _ in range(self.pop_size)]\n pop, g_best = self.get_sorted_pop_and_global_best_solution(pop, self.ID_FIT, self.ID_MIN_PROB)\n fit_best = g_best[self.ID_FIT]\n fit_worst = pop[self.ID_MAX_PROB][self.ID_FIT]\n for epoch in range(self.epoch):\n # Update Standard Deviation\n sigma = ((self.epoch - epoch) / (self.epoch - 1)) ** self.exponent * (self.sigma[0] - self.sigma[1]) + self.sigma[1]\n # Reproduction\n pop_new = []\n for item in pop:\n ratio = (item[self.ID_FIT] - fit_worst) / (fit_best - fit_worst + self.EPSILON)\n s = int(ceil(self.seeds[0] + (self.seeds[1] - self.seeds[0]) * ratio))\n for j in range(s):\n # Initialize Offspring and Generate Random Location\n pos_new = item[self.ID_POS] + sigma * uniform(self.lb, self.ub)\n pos_new = self.amend_position_faster(pos_new)\n fit = self.get_fitness_position(pos_new)\n pop_new.append([pos_new, fit])\n\n # Re-calculate best train and worst train\n pop = pop + pop_new\n pop, g_best = self.update_sorted_population_and_global_best_solution(pop, self.ID_MIN_PROB, g_best)\n pop = pop[:self.pop_size]\n fit_worst = pop[self.ID_MAX_PROB][self.ID_FIT]\n fit_best = pop[self.ID_MIN_PROB][self.ID_FIT]\n\n self.loss_train.append(g_best[self.ID_FIT])\n if self.verbose:\n print(\"> Epoch: {}, Best fit: {}\".format(epoch + 1, g_best[self.ID_FIT]))\n self.solution = g_best\n return g_best[self.ID_POS], g_best[self.ID_FIT], self.loss_train\n\n\nclass OriginalIWO(Root):\n \"\"\"\n Original version of: weed colonization (IWO)\n A novel numerical optimization algorithm inspired from weed colonization\n Link:\n https://pdfs.semanticscholar.org/734c/66e3757620d3d4016410057ee92f72a9853d.pdf\n \"\"\"\n\n def __init__(self, obj_func=None, lb=None, ub=None, problem_size=50, batch_size=10, verbose=True,\n epoch=750, pop_size=100, seeds=(2, 10), exponent=2, sigma=(0.5, 0.001)):\n Root.__init__(self, obj_func, lb, ub, problem_size, batch_size, verbose)\n self.epoch = epoch\n self.pop_size = pop_size\n self.seeds = seeds # (Min, Max) Number of Seeds\n self.exponent = exponent # Variance Reduction Exponent\n self.sigma = sigma # (Initial, Final) Value of Standard Deviation\n\n def train(self):\n pop = [self.create_solution() for _ in range(self.pop_size)]\n pop_sorted, g_best = self.get_sorted_pop_and_global_best_solution(pop, self.ID_FIT, self.ID_MIN_PROB)\n cost_best = g_best[self.ID_FIT]\n cost_worst = pop_sorted[self.ID_MAX_PROB][self.ID_FIT]\n for epoch in range(self.epoch):\n # Update Standard Deviation\n sigma = ((self.epoch - epoch) / (self.epoch - 1)) ** self.exponent * (self.sigma[0] - self.sigma[1]) + self.sigma[1]\n # Reproduction\n pop_new = []\n for item in pop:\n ratio = (item[self.ID_FIT] - cost_worst) / (cost_best - cost_worst)\n S = int(ceil(self.seeds[0] + (self.seeds[1] - self.seeds[0]) * ratio))\n for j in range(S):\n # Initialize Offspring and Generate Random Location\n pos_new = item[self.ID_POS] + sigma * uniform(self.lb, self.ub)\n pos_new = self.amend_position_faster(pos_new)\n fit = self.get_fitness_position(pos_new)\n pop_new.append([pos_new, fit])\n\n # Merge Populations\n pop = pop + pop_new\n pop = sorted(pop, key=lambda temp: temp[self.ID_FIT])\n pop = pop[:self.pop_size]\n\n # Re-calculate best train and worst train\n cost_worst = pop[self.ID_MAX_PROB][self.ID_FIT]\n if cost_best > pop[self.ID_MIN_PROB][self.ID_FIT]:\n g_best = deepcopy(pop[self.ID_MIN_PROB])\n cost_best = g_best[self.ID_FIT]\n self.loss_train.append(g_best[self.ID_FIT])\n if self.verbose:\n print(\"> Epoch: {}, Best fit: {}\".format(epoch + 1, g_best[self.ID_FIT]))\n self.solution = g_best\n return g_best[self.ID_POS], g_best[self.ID_FIT], self.loss_train\n", "#!/usr/bin/env python\n# ------------------------------------------------------------------------------------------------------%\n# Created by \"Thieu Nguyen\" at 21:18, 17/03/2020 %\n# %\n# Email: [email protected] %\n# Homepage: https://www.researchgate.net/profile/Thieu_Nguyen6 %\n# Github: https://github.com/thieu1995 %\n#-------------------------------------------------------------------------------------------------------%\n\nfrom numpy.random import uniform, randint\nfrom numpy import ones, clip\nfrom mealpy.root import Root\n\n\nclass BaseWDO(Root):\n \"\"\"\n The original version of : Wind Driven Optimization (WDO)\n The Wind Driven Optimization Technique and its Application in Electromagnetics\n \"\"\"\n\n def __init__(self, obj_func=None, lb=None, ub=None, problem_size=50, batch_size=10, verbose=True,\n epoch=750, pop_size=100, RT=3, g=0.2, alp=0.4, c=0.4, max_v=0.3):\n Root.__init__(self, obj_func, lb, ub, problem_size, batch_size, verbose)\n self.epoch = epoch\n self.pop_size = pop_size\n self.RT = RT # RT coefficient\n self.g = g # gravitational constant\n self.alp = alp # constants in the update equation\n self.c = c # coriolis effect\n self.max_v = max_v # maximum allowed speed\n\n def train(self):\n \"\"\"\n # pop is the set of \"air parcel\" - \"position\"\n # air parcel: is the set of gas atoms . Each atom represents a dimension in position and has its own velocity\n # pressure represented by fitness value\n \"\"\"\n pop = [self.create_solution() for _ in range(self.pop_size)]\n g_best = self.get_global_best_solution(pop, self.ID_FIT, self.ID_MIN_PROB)\n list_velocity = self.max_v * uniform(self.lb, self.ub, (self.pop_size, self.problem_size))\n\n for epoch in range(self.epoch):\n\n # Update velocity based on random dimensions and position of global best\n for i in range(self.pop_size):\n\n rand_dim = randint(0, self.problem_size)\n temp = list_velocity[i][rand_dim] * ones(self.problem_size)\n vel = (1 - self.alp)*list_velocity[i] - self.g * pop[i][self.ID_POS] + \\\n (1 - 1.0/(i+1)) * self.RT * (g_best[self.ID_POS] - pop[i][self.ID_POS]) + self.c * temp / (i+1)\n vel = clip(vel, -self.max_v, self.max_v)\n\n # Update air parcel positions, check the bound and calculate pressure (fitness)\n pos = pop[i][self.ID_POS] + vel\n pos = self.amend_position_faster(pos)\n fit = self.get_fitness_position(pos)\n pop[i] = [pos, fit]\n list_velocity[i] = vel\n\n ## batch size idea\n if i % self.batch_size:\n g_best = self.update_global_best_solution(pop, self.ID_MIN_PROB, g_best)\n self.loss_train.append(g_best[self.ID_FIT])\n if self.verbose:\n print(\">Epoch: {}, Best fit: {}\".format(epoch + 1, g_best[self.ID_FIT]))\n self.solution = g_best\n return g_best[self.ID_POS], g_best[self.ID_FIT], self.loss_train\n\n" ]
[ [ "numpy.dot", "numpy.linalg.norm", "numpy.ones", "numpy.random.normal", "numpy.mean", "numpy.exp", "numpy.random.uniform", "numpy.array", "numpy.zeros" ], [ "numpy.cosh", "numpy.cos", "numpy.sinh", "numpy.sin", "numpy.max", "numpy.mean", "numpy.random.uniform", "numpy.array" ], [ "numpy.ceil", "numpy.random.uniform" ], [ "numpy.random.uniform", "numpy.ones", "numpy.clip", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
intel-isl/MetaLearningTradeoffs
[ "bb1b849742a959310f3b9b630bb76ae3509a5d4a", "bb1b849742a959310f3b9b630bb76ae3509a5d4a", "bb1b849742a959310f3b9b630bb76ae3509a5d4a" ]
[ "maml_zoo/baselines/zero_baseline.py", "experiments/benchmark/summary.py", "maml_zoo/meta_trainer.py" ]
[ "from maml_zoo.baselines.base import Baseline\nimport numpy as np\n\n\nclass ZeroBaseline(Baseline):\n \"\"\"\n Dummy baseline\n \"\"\"\n\n def __init__(self):\n super(ZeroBaseline, self).__init__()\n\n def get_param_values(self, **kwargs):\n \"\"\"\n Returns the parameter values of the baseline object\n\n Returns:\n (None): coefficients of the baseline\n\n \"\"\"\n return None\n\n def set_param_values(self, value, **kwargs):\n \"\"\"\n Sets the parameter values of the baseline object\n\n Args:\n value (None): coefficients of the baseline\n\n \"\"\"\n pass\n\n def fit(self, paths, **kwargs):\n \"\"\"\n Improves the quality of zeroes output by baseline\n\n Args:\n paths: list of paths\n\n \"\"\"\n pass\n\n def predict(self, path):\n \"\"\"\n Produces some zeroes\n\n Args:\n path (dict): dict of lists/numpy array containing trajectory / path information\n such as \"observations\", \"rewards\", ...\n\n Returns:\n (np.ndarray): numpy array of the same length as paths[\"observations\"] specifying the reward baseline\n \n \"\"\"\n return np.zeros_like(path[\"rewards\"])", "import numpy as np\nimport os\nimport json\nimport joblib\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom scipy.special import betainc\n\nDIR = os.getcwd()+'/data'\nOUTPUT = os.getcwd()+'/results'\nif os.path.exists(OUTPUT):\n os.makedirs(OUTPUT)\n\nalgos = ['ppo', 'promp', 'trpo', 'trpomaml']\nenvironment_mode_pairs = [['walker', 'params-interpolate'], ['walker', 'goal-interpolate'],\n ['cheetah', 'goal-interpolate'], ['hopper', 'params-interpolate'],\n ['metaworld', 'ml1-push'], ['metaworld', 'ml1-reach'],\n ['metaworld', 'ml10'], ['metaworld', 'ml45']]\nseeds = [1, 2, 3, 4, 5]\ncheckpoints = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\nupdates = [0, 1, 2, 3, 4, 5]\n\nreward_means = np.zeros((len(algos), len(environment_mode_pairs), len(seeds), len(checkpoints), len(updates)))\nreward_stderrs = np.zeros((len(algos), len(environment_mode_pairs), len(seeds), len(checkpoints), len(updates)))\n\nfor a in range(len(algos)):\n alg = algos[a]\n alg_dir = os.path.join(DIR, alg)\n if os.path.isdir(alg_dir):\n for b in range(len(environment_mode_pairs)):\n pair = environment_mode_pairs[b]\n environment = pair[0]\n mode = pair[1]\n mode_dir = os.path.join(alg_dir, mode)\n env_dir = os.path.join(mode_dir, environment)\n if os.path.isdir(env_dir):\n for c in range(len(seeds)):\n run = seeds[c]\n run_dir = os.path.join(env_dir, 'run_'+str(run))\n if os.path.isdir(run_dir):\n hyperparam_file = os.path.join(run_dir, 'params.json')\n\n # Extract hyperparams\n if os.path.exists(hyperparam_file):\n with open(hyperparam_file, 'r') as hyperparams:\n try:\n hyperparam_dict = json.load(hyperparams)\n checkpoint_gap = hyperparam_dict['checkpoint_gap']\n except (ValueError, json.decoder.JSONDecodeError) as e:\n print(\"WARNING: exception reading params.json at %s\" % run_dir)\n pass\n else:\n print(\"WARNING: Missing hyperparameters file at %s, skipping\" % run_dir)\n continue\n\n # Get evaluation stats\n for d in range(len(checkpoints)):\n checkpoint = checkpoints[d]\n checkpoint_dir = os.path.join(run_dir, 'checkpoint_'+str(checkpoint))\n if os.path.isdir(checkpoint_dir):\n evaluation_file = os.path.join(checkpoint_dir, 'evaluation.json')\n print(\"Reading %s\" % evaluation_file)\n if os.path.exists(evaluation_file):\n with open(evaluation_file, 'r') as evaluation:\n trials = []\n for line in evaluation:\n try:\n trials.append(json.loads(line))\n except (ValueError, json.decode.JSONDecodeError) as e:\n print(\"WARNING: exception reading line %s; \\n%s\" % (line, e))\n pass\n\n for f in range(len(updates)):\n reward_means[a,b,c,d,f] = float(np.mean(np.asarray([data['avg_update_reward'][f] for data in trials])))\n reward_stderrs[a,b,c,d,f] = float(np.std(np.asarray([data['avg_update_reward'][f] for data in trials])))/np.sqrt(len(trials))\n else:\n print(\"WARNING: Evaluation file is missing at %s, skipping\" % checkpoint_dir)\n else:\n print(\"WARNING: Unexpected file at %s\" % checkpoint_dir)\n else:\n print(\"WARNING: Unexpected file at %s\" % run_dir)\n else:\n print(\"WARNING: Unexpected file at %s\" % env_dir)\n else:\n print(\"WARNING: Unexpected file at %s\" % alg_dir)\n\n\n# Average the results over seeds\n\nprint(\"Computing average test rewards over seeds\")\navg_reward_means = np.zeros((len(algos), len(environment_mode_pairs), len(checkpoints), len(updates)))\nfor a in range(len(algos)):\n for b in range(len(environment_mode_pairs)):\n for d in range(len(checkpoints)):\n for f in range(len(updates)):\n avg_reward_means[a,b,d,f] = np.mean(reward_means[a,b,:,d,f])\n with open(os.path.join(OUTPUT, 'output.txt'), 'a') as result:\n result.write(\"Average rewards for {} environment {} mode {} at checkpoint {}\".format(algos[a], environment_mode_pairs[b][0], environment_mode_pairs[b][1], checkpoints[d]))\n result.write(\"\\n\")\n result.write(str(avg_reward_means[a,b,d,:]))\n result.write(\"\\n\")\n\nprint(\"Computing standard errors of average test rewards over seeds\")\navg_reward_stderrs = np.zeros((len(algos), len(environment_mode_pairs), len(checkpoints), len(updates)))\nfor a in range(len(algos)):\n for b in range(len(environment_mode_pairs)):\n for d in range(len(checkpoints)):\n for f in range(len(updates)):\n varest = np.var(reward_means[a,b,:,d,f])\n varest += np.mean(reward_stderrs[a,b,:,d,f]**2)\n avg_reward_stderrs[a,b,d,f] = np.sqrt(varest/len(seeds))\n\n# Construct contour plots\n\nprint(\"Contour plots of whether MAML is better than DRS, as functions of the checkpoint and update\")\n\ndef welch_test(target_mean, target_std, target_n, comparison_mean, comparison_std, comparison_n):\n # Computes a Welch test to see if the comparitor sample is larger than the target\n # sample. This is a one-sided test.\n # Modified from https://nbviewer.jupyter.org/url/argmin.net/code/atari_performance_profiles.ipynb\n\n nu = ((target_std**2/target_n + comparison_std**2/comparison_n)**2/\n (target_std**4/target_n/(target_n-1)+ comparison_std**4/comparison_n/(comparison_n-1)))\n t_stat = ((target_mean-comparison_mean)\n /np.sqrt(target_std**2/target_n+comparison_std**2/comparison_n))\n\n return 0.5*betainc(nu/2,1/2,nu/(t_stat**2+nu))\n\ndef get_tradeoff_map(task_avg_reward_means, task_avg_reward_stderrs):\n\n num_checkpoints = task_avg_reward_means.shape[2]\n num_updates = task_avg_reward_means.shape[3]\n num_seeds = 5 # From above\n bin_table = np.zeros((num_checkpoints, num_updates))\n fin_table = np.zeros((num_checkpoints, num_updates))\n\n for c in range(num_checkpoints):\n for u in range(num_updates):\n fin_table[c,u] = welch_test(task_avg_reward_means[1,c,u], np.sqrt(num_seeds)*task_avg_reward_stderrs[1,c,u], num_seeds, task_avg_reward_means[0,c,u], np.sqrt(num_seeds)*task_avg_reward_stderrs[0,c,u], num_seeds)\n\n if avg_reward_means[0,task,c,u] > avg_reward_means[1,task,c,u]:\n bin_table[c,u] = 1\n else:\n bin_table[c,u] = -1\n return bin_table*(1-2*fin_table), bin_table\n\nyint = range(0,21,2)\nfor b in range(len(environment_mode_pairs)):\n mm, bt = get_tradeoff_map(avg_reward_means[0:2,b,:,:], avg_reward_stderrs[0:2,b,:,:])\n plt.figure(figsize=(5,2.5))\n plt.contourf(np.array(checkpoints).astype(int), np.array(updates).astype(int), mm.T, np.linspace(-1.01, 1.01, 50),vmin=-1,vmax=1, cmap='RdBu_r')\n plt.xticks(yint)\n plt.xlabel('Meta-Training Budget')\n plt.ylabel('Test Updates')\n plt.tight_layout()\n plt.savefig('ppo_promp_{}.pdf'.format('-'.join(environment_mode_pairs[b])))\n plt.close(fig)\n\n mm, bt = get_tradeoff_map(avg_reward_means[2:4,b,:,:], avg_reward_stderrs[2:4,b,:,:])\n plt.figure(figsize=(5,2.5))\n plt.contourf(np.array(checkpoints).astype(int), np.array(updates).astype(int), mm.T, np.linspace(-1.01, 1.01, 50),vmin=-1,vmax=1, cmap='RdBu_r')\n plt.xticks(yint)\n plt.xlabel('Meta-Training Budget')\n plt.ylabel('Test Updates')\n plt.tight_layout()\n plt.savefig('trpo_trpomaml_{}.pdf'.format('-'.join(environment_mode_pairs[b])))\n plt.close(fig)\n\n# Construct reward plots\n\nprint(\"Plotting rewards as function of checkpoint, after one update\")\nfor b in range(len(environment_mode_pairs)):\n environment = environment_mode_pairs[b][0]\n mode = environment_mode_pairs[b][1]\n if environment == 'metaworld':\n gap = 1000*20*10*150 # Number of time steps between each checkpoint\n else:\n gap = 100*40*20*200\n\n fig = plt.figure()\n plt.plot(gap*np.asarray(checkpoints), avg_reward_means[0,b,:,1], 'r') # DRS+PPO\n plt.fill_between(gap*np.asarray(checkpoints), avg_reward_means[0,b,:,1]-1.96*avg_reward_stderrs[0,b,:,1], avg_reward_means[0,b,:,1]+1.96*avg_reward_stderrs[0,b,:,1], facecolor='r', alpha=0.25)\n plt.plot(gap*np.asarray(checkpoints), avg_reward_means[1,b,:,1], 'b') # ProMP\n plt.fill_between(gap*np.asarray(checkpoints), avg_reward_means[1,b,:,1]-1.96*avg_reward_stderrs[1,b,:,1], avg_reward_means[1,b,:,1]+1.96*avg_reward_stderrs[1,b,:,1], facecolor='b', alpha=0.25)\n plt.xlabel('Training Timesteps')\n plt.ylabel('Test Reward')\n plt.savefig(os.path.join(OUTPUT, 'ppo_promp_{}_{}_reward_update_1.png'.format(environment, mode)))\n plt.close(fig)\n\n fig = plt.figure()\n plt.plot(gap*np.asarray(checkpoints), avg_reward_means[2,b,:,1], 'r') # DRS+TRPO\n plt.fill_between(gap*np.asarray(checkpoints), avg_reward_means[2,b,:,1]-1.96*avg_reward_stderrs[2,b,:,1], avg_reward_means[2,b,:,1]+1.96*avg_reward_stderrs[2,b,:,1], facecolor='r', alpha=0.25)\n plt.plot(gap*np.asarray(checkpoints), avg_reward_means[3,b,:,1], 'b') # ProMP\n plt.fill_between(gap*np.asarray(checkpoints), avg_reward_means[3,b,:,1]-1.96*avg_reward_stderrs[3,b,:,1], avg_reward_means[3,b,:,1]+1.96*avg_reward_stderrs[3,b,:,1], facecolor='b', alpha=0.25)\n plt.xlabel('Training Timesteps')\n plt.ylabel('Test Reward')\n plt.savefig(os.path.join(OUTPUT, 'trpo_trpomaml_{}_{}_reward_update_1.png'.format(environment, mode)))\n plt.close(fig)\n\n", "import tensorflow as tf\nimport numpy as np\nimport time\nfrom maml_zoo.logger import logger\n\n\nclass Trainer(object):\n \"\"\"\n Performs steps for MAML\n\n Args:\n algo (Algo) :\n env (Env) :\n sampler (Sampler) : \n sample_processor (SampleProcessor) : \n baseline (Baseline) : \n policy (Policy) : \n n_itr (int) : Number of iterations to train for\n start_itr (int) : Number of iterations policy has already trained for, if reloading\n num_inner_grad_steps (int) : Number of inner steps per maml iteration\n sess (tf.Session) : current tf session (if we loaded policy, for example)\n \"\"\"\n def __init__(\n self,\n algo,\n env,\n sampler,\n sample_processor,\n policy,\n n_itr,\n start_itr=0,\n num_inner_grad_steps=1,\n sess=None,\n ):\n self.algo = algo\n self.env = env\n self.sampler = sampler\n self.sample_processor = sample_processor\n self.baseline = sample_processor.baseline\n self.policy = policy\n self.n_itr = n_itr\n self.start_itr = start_itr\n self.num_inner_grad_steps = num_inner_grad_steps\n if sess is None:\n sess = tf.Session()\n self.sess = sess\n\n def train(self):\n \"\"\"\n Trains policy on env using algo\n\n Pseudocode:\n for itr in n_itr:\n for step in num_inner_grad_steps:\n sampler.sample()\n algo.compute_updated_dists()\n algo.optimize_policy()\n sampler.update_goals()\n \"\"\"\n with self.sess.as_default() as sess:\n\n # initialize uninitialized vars (only initialize vars that were not loaded)\n uninit_vars = [var for var in tf.global_variables() if not sess.run(tf.is_variable_initialized(var))]\n sess.run(tf.variables_initializer(uninit_vars))\n\n start_time = time.time()\n for itr in range(self.start_itr, self.n_itr):\n itr_start_time = time.time()\n logger.log(\"\\n ---------------- Iteration %d ----------------\" % itr)\n logger.log(\"Sampling set of tasks/goals for this meta-batch...\")\n\n self.sampler.update_tasks()\n self.policy.switch_to_pre_update() # Switch to pre-update policy\n\n all_samples_data, all_paths = [], []\n list_sampling_time, list_inner_step_time, list_outer_step_time, list_proc_samples_time = [], [], [], []\n start_total_inner_time = time.time()\n for step in range(self.num_inner_grad_steps+1):\n logger.log('** Step ' + str(step) + ' **')\n\n \"\"\" -------------------- Sampling --------------------------\"\"\"\n\n logger.log(\"Obtaining samples...\")\n time_env_sampling_start = time.time()\n paths = self.sampler.obtain_samples(log=True, log_prefix='Step_%d-' % step)\n list_sampling_time.append(time.time() - time_env_sampling_start)\n all_paths.append(paths)\n\n \"\"\" ----------------- Processing Samples ---------------------\"\"\"\n\n logger.log(\"Processing samples...\")\n time_proc_samples_start = time.time()\n samples_data = self.sample_processor.process_samples(paths, log='all', log_prefix='Step_%d-' % step)\n all_samples_data.append(samples_data)\n list_proc_samples_time.append(time.time() - time_proc_samples_start)\n\n self.log_diagnostics(sum(list(paths.values()), []), prefix='Step_%d-' % step)\n\n \"\"\" ------------------- Inner Policy Update --------------------\"\"\"\n\n time_inner_step_start = time.time()\n if step < self.num_inner_grad_steps:\n logger.log(\"Computing inner policy updates...\")\n self.algo._adapt(samples_data)\n # train_writer = tf.summary.FileWriter('/home/ignasi/Desktop/maml_zoo_graph',\n # sess.graph)\n list_inner_step_time.append(time.time() - time_inner_step_start)\n total_inner_time = time.time() - start_total_inner_time\n\n time_maml_opt_start = time.time()\n \"\"\" ------------------ Outer Policy Update ---------------------\"\"\"\n\n logger.log(\"Optimizing policy...\")\n # This needs to take all samples_data so that it can construct graph for meta-optimization.\n time_outer_step_start = time.time()\n self.algo.optimize_policy(all_samples_data)\n\n \"\"\" ------------------- Logging Stuff --------------------------\"\"\"\n logger.logkv('Itr', itr)\n logger.logkv('n_timesteps', self.sampler.total_timesteps_sampled)\n\n logger.logkv('Time-OuterStep', time.time() - time_outer_step_start)\n logger.logkv('Time-TotalInner', total_inner_time)\n logger.logkv('Time-InnerStep', np.sum(list_inner_step_time))\n logger.logkv('Time-SampleProc', np.sum(list_proc_samples_time))\n logger.logkv('Time-Sampling', np.sum(list_sampling_time))\n\n logger.logkv('Time', time.time() - start_time)\n logger.logkv('ItrTime', time.time() - itr_start_time)\n logger.logkv('Time-MAMLSteps', time.time() - time_maml_opt_start)\n\n logger.log(\"Saving snapshot...\")\n params = self.get_itr_snapshot(itr)\n logger.save_itr_params(itr, params)\n logger.log(\"Saved\")\n\n logger.dumpkvs()\n if itr == 0:\n sess.graph.finalize()\n\n logger.log(\"Training finished\")\n self.sess.close() \n\n def get_itr_snapshot(self, itr):\n \"\"\"\n Gets the current policy and env for storage\n \"\"\"\n return dict(itr=itr, policy=self.policy, env=self.env, baseline=self.baseline)\n\n def log_diagnostics(self, paths, prefix):\n # TODO: we aren't using it so far\n self.env.log_diagnostics(paths, prefix)\n self.policy.log_diagnostics(paths, prefix)\n self.baseline.log_diagnostics(paths, prefix)\n" ]
[ [ "numpy.zeros_like" ], [ "matplotlib.pyplot.tight_layout", "numpy.sqrt", "numpy.linspace", "numpy.asarray", "matplotlib.use", "matplotlib.pyplot.ylabel", "scipy.special.betainc", "numpy.mean", "matplotlib.pyplot.close", "numpy.var", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks", "numpy.array", "numpy.zeros", "matplotlib.pyplot.figure" ], [ "tensorflow.global_variables", "tensorflow.variables_initializer", "tensorflow.is_variable_initialized", "tensorflow.Session", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
ouyangyike/Inference-Algorithm
[ "ac3470e2fbc4415174b32ecc2e2f3f101da1ca38", "ac3470e2fbc4415174b32ecc2e2f3f101da1ca38" ]
[ "logistic regression/logistic_adam/adam_train_loss .py", "logistic regression/softmax/soft_test_accuracy .py" ]
[ "import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom logistic_adam import *\n\n\n#learing rate = 1,batch_size = 500, epoch=15, lamda = 0.01\nlogging = runLogistic(1,500,15,0.01)\n#print(logging)\nplt.plot(logging[:,0],marker='+',label='learning rate = 1')\n\n#learing rate = 0.1,batch_size = 500, epoch=15, lamda = 0.01\nlogging = runLogistic(0.1,500,15,0.01)\n#print(logging)\nplt.plot(logging[:,0],marker='*',label='learning rate = 0.1')\n\n#learing rate = 0.01,batch_size = 500, epoch=15, lamda = 0.01\nlogging = runLogistic(0.01,500,15,0.01)\n#print(logging)\nplt.plot(logging[:,0],marker='h',label='learning rate = 0.01')\n\n#learing rate = 0.001,batch_size = 500, epoch=15, lamda = 0.01\nlogging = runLogistic(0.001,500,15,0.01)\n#print(logging)\nplt.plot(logging[:,0],marker='d',label='learning rate = 0.001')\n\n\nplt.legend(loc='upper right')\nplt.title('Plot of Train_CrossEntropy vs. Iterations with batch_size=500')\nplt.xlabel('Iterations')\nplt.ylabel('Train_CrossEntropy')\nplt.show()\n\n\n", "import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom softmax import *\n\n\n#learing rate = 0.1,batch_size = 500, epoch=30, lamda = 0.01\nlogging = runSoftmax(0.01,500,30,0.01)\nplt.plot(logging[:,3],marker='+',label='learning rate = 0.1')\n\n\nplt.legend(loc='lower right')\nplt.title('Plot of Test_Accuracy vs. Iterations with batch_size=500')\nplt.xlabel('Iterations')\nplt.ylabel('Test_Accuracy')\nplt.ylim(0,1)\nplt.show()\n\n\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.title", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ], [ "matplotlib.pyplot.legend", "matplotlib.pyplot.title", "matplotlib.pyplot.ylim", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
NinaTian98369/HypoGen
[ "14f192ecc1ef0c6fc5864f0816ef61885dc9e864" ]
[ "Code/HypoBertClas/pybert/test/predicter.py" ]
[ "#encoding:utf-8\nimport torch\nimport numpy as np\nfrom ..utils.utils import model_device,load_bert\n\nclass Predicter(object):\n def __init__(self,\n model,\n logger,\n n_gpu,\n model_path\n ):\n self.model = model\n self.logger = logger\n self.width = 30\n self.model, self.device = model_device(n_gpu= n_gpu, model=self.model, logger=self.logger)\n loads = load_bert(model_path=model_path,model = self.model)\n self.model = loads[0]\n\n def show_info(self,batch_id,n_batch):\n recv_per = int(100 * (batch_id + 1) / n_batch)\n if recv_per >= 100:\n recv_per = 100\n # show bar\n show_bar = f\"\\r[predict]{batch_id+1}/{n_batch}[{int(self.width * recv_per / 100) * '>':<{self.width}s}]{recv_per}%\"\n print(show_bar,end='')\n\n def predict(self,data):\n all_logits = None\n self.model.eval()\n n_batch = len(data)\n with torch.no_grad():\n for step, (input_ids, input_mask, segment_ids, label_ids) in enumerate(data):\n input_ids = input_ids.to(self.device)\n input_mask = input_mask.to(self.device)\n segment_ids = segment_ids.to(self.device)\n logits = self.model(input_ids, segment_ids, input_mask)\n logits = logits.sigmoid()\n self.show_info(step,n_batch)\n if all_logits is None:\n all_logits = logits.detach().cpu().numpy()\n else:\n all_logits = np.concatenate([all_logits,logits.detach().cpu().numpy()],axis = 0)\n return all_logits\n\n\n\n\n\n\n" ]
[ [ "torch.no_grad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
StarWang/detext
[ "66f071ec2cebf5e54e7d1de40936b5f281c2a69b", "66f071ec2cebf5e54e7d1de40936b5f281c2a69b" ]
[ "src/smart_compose/train/data_fn.py", "test/detext/layers/test_vocab_layer.py" ]
[ "import tensorflow as tf\nfrom functools import partial\n\nfrom smart_compose.utils.parsing_utils import get_input_files, InputFtrType, iterate_items_with_list_val\n\n\ndef _read_specified_features(inputs, feature_type2name):\n \"\"\"Only reads in features specified in the DeText arguments\"\"\"\n required_inputs = {}\n for _, ftr_name_list in iterate_items_with_list_val(feature_type2name):\n for ftr_name in ftr_name_list:\n required_inputs[ftr_name] = inputs[ftr_name]\n return required_inputs\n\n\n_FTR_TYPE_TO_SCHEMA = {\n InputFtrType.TARGET_COLUMN_NAME: tf.io.FixedLenFeature(shape=[], dtype=tf.string)\n}\n\n\ndef _get_tfrecord_feature_parsing_schema(feature_type_2_name: dict):\n \"\"\"Returns parsing schema for input TFRecord\n\n :param feature_type_2_name: Features mapping from feature types to feature names\n \"\"\"\n ftr_name_2_schema = dict()\n for ftr_type, ftr_name_lst in iterate_items_with_list_val(feature_type_2_name):\n for ftr_name in ftr_name_lst:\n ftr_name_2_schema[ftr_name] = _FTR_TYPE_TO_SCHEMA[ftr_type]\n\n return ftr_name_2_schema\n\n\ndef _cast_features_to_smaller_dtype(example, feature_type_2_names: dict):\n \"\"\"Casts tensor to smaller storage dtype. int64 -> int32, float64 -> float32\"\"\"\n\n def _cast_to_dtype_of_smaller_size(t):\n if t.dtype == tf.int64:\n return tf.cast(t, dtype=tf.int32)\n elif t.dtype == tf.float64:\n return tf.cast(t, dtype=tf.float32)\n else:\n return t\n\n for ftr_type, ftr_name_lst in iterate_items_with_list_val(feature_type_2_names):\n for ftr_name in ftr_name_lst:\n example[ftr_name] = _cast_to_dtype_of_smaller_size(example[ftr_name])\n return example\n\n\n_FTR_TYPE_TO_DENSE_DEFAULT_VAL = {\n InputFtrType.TARGET_COLUMN_NAME: '',\n}\n\n\ndef input_fn_tfrecord(input_pattern,\n batch_size,\n mode,\n feature_type_2_name: dict,\n block_length=100,\n prefetch_size=tf.data.experimental.AUTOTUNE,\n num_parallel_calls=tf.data.experimental.AUTOTUNE,\n input_pipeline_context=None):\n \"\"\"\n Data input function for training given TFRecord\n \"\"\"\n output_buffer_size = 1000\n\n input_files = get_input_files(input_pattern)\n feature_type_2_name = feature_type_2_name.copy()\n if len(input_files) > 1: # Multiple input files\n # Preprocess files concurrently, and interleave blocks of block_length records from each file\n dataset = tf.data.Dataset.from_tensor_slices(tf.constant(input_files))\n # Shard input when using distributed training strategy\n if mode == tf.estimator.ModeKeys.TRAIN and input_pipeline_context and input_pipeline_context.num_input_pipelines > 1:\n dataset = dataset.shard(input_pipeline_context.num_input_pipelines,\n input_pipeline_context.input_pipeline_id)\n\n dataset = dataset.shuffle(buffer_size=len(input_files))\n\n dataset = dataset.interleave(tf.data.TFRecordDataset, block_length=block_length,\n num_parallel_calls=num_parallel_calls)\n else:\n dataset = tf.data.TFRecordDataset(input_files[0])\n\n # Parse and preprocess data\n dataset = tfrecord_transform_fn(dataset,\n batch_size,\n mode,\n feature_type_2_name,\n output_buffer_size,\n prefetch_size)\n return dataset\n\n\ndef _split_features_and_labels(example, feature_type_2_name: dict):\n \"\"\"Split inputs into two parts: features and label\"\"\"\n target_ftr_name = feature_type_2_name[InputFtrType.TARGET_COLUMN_NAME]\n labels = {\n target_ftr_name: example.pop(target_ftr_name)\n }\n\n return example, labels\n\n\ndef tfrecord_transform_fn(dataset,\n batch_size,\n mode,\n feature_type_2_name,\n output_buffer_size,\n prefetch_size=tf.data.experimental.AUTOTUNE,\n num_parallel_calls=tf.data.experimental.AUTOTUNE):\n \"\"\" Preprocesses datasets including\n 1. dataset shuffling\n 2. record parsing\n 3. padding and batching\n \"\"\"\n if mode == tf.estimator.ModeKeys.TRAIN:\n dataset = dataset.shuffle(output_buffer_size)\n dataset = dataset.repeat()\n\n def _process_data(record, features_schema):\n example = tf.io.parse_single_example(serialized=record, features=features_schema)\n example = _cast_features_to_smaller_dtype(example, feature_type_2_name)\n features, labels = _split_features_and_labels(example, feature_type_2_name)\n return features, labels\n\n features_schema = _get_tfrecord_feature_parsing_schema(feature_type_2_name)\n dataset = dataset.map(partial(_process_data, features_schema=features_schema),\n num_parallel_calls=num_parallel_calls)\n\n dataset = (dataset\n .batch(batch_size, drop_remainder=True)\n .prefetch(prefetch_size))\n return dataset\n", "import copy\nimport shutil\n\nimport tensorflow as tf\nimport tensorflow_hub as hub\n\nfrom detext.layers import vocab_layer\nfrom detext.utils.layer_utils import get_sorted_dict\nfrom detext.utils.parsing_utils import InternalFtrType\nfrom detext.utils.testing.data_setup import DataSetup\n\n\nclass TestVocabLayer(tf.test.TestCase, DataSetup):\n num_cls_sep = 1\n sentences = tf.constant(['hello sent1', 'build build build build sent2'])\n inputs = get_sorted_dict({InternalFtrType.SENTENCES: sentences,\n InternalFtrType.NUM_CLS: tf.constant(num_cls_sep, dtype=tf.dtypes.int32),\n InternalFtrType.NUM_SEP: tf.constant(num_cls_sep, dtype=tf.dtypes.int32),\n InternalFtrType.MIN_LEN: tf.constant(DataSetup.min_len, dtype=tf.dtypes.int32),\n InternalFtrType.MAX_LEN: tf.constant(DataSetup.max_len, dtype=tf.dtypes.int32)})\n\n def testAddClsSep(self):\n vocab_layer_param = copy.copy(self.vocab_layer_param)\n inputs = copy.copy(self.inputs)\n inputs['min_len'] = 6\n inputs['max_len'] = 7\n inputs['num_cls'] = 2\n inputs['num_sep'] = 2\n\n layer = vocab_layer.create_vocab_layer(vocab_layer_param, '')\n outputs = layer(inputs)\n\n self.assertAllEqual(outputs[InternalFtrType.TOKENIZED_IDS][0],\n tf.constant([self.CLS_ID, self.CLS_ID, self.UNK_ID, self.UNK_ID, self.SEP_ID, self.SEP_ID, self.PAD_ID]))\n\n def testAdjustLen(self):\n vocab_layer_param = copy.copy(self.vocab_layer_param)\n inputs = copy.copy(self.inputs)\n inputs['min_len'] = 12\n inputs['max_len'] = 16\n\n layer = vocab_layer.create_vocab_layer(vocab_layer_param, '')\n outputs = layer(inputs)\n shape = tf.shape(outputs[InternalFtrType.TOKENIZED_IDS])\n self.assertAllEqual(shape, tf.constant([2, 12]))\n\n inputs['min_len'] = 0\n inputs['max_len'] = 1\n outputs = layer(inputs)\n shape = tf.shape(outputs[InternalFtrType.TOKENIZED_IDS])\n self.assertAllEqual(shape, tf.constant([2, 1]))\n\n def testLength(self):\n vocab_layer_param = copy.copy(self.vocab_layer_param)\n inputs = copy.copy(self.inputs)\n inputs['min_len'] = 1\n inputs['max_len'] = 16\n inputs['num_cls'] = 0\n inputs['num_sep'] = 0\n\n layer = vocab_layer.create_vocab_layer(vocab_layer_param, '')\n outputs = layer(inputs)\n self.assertAllEqual(outputs[InternalFtrType.LENGTH], tf.constant([2, 5]))\n\n inputs['num_cls'] = 1\n inputs['num_sep'] = 1\n layer = vocab_layer.create_vocab_layer(vocab_layer_param, '')\n outputs = layer(inputs)\n self.assertAllEqual(outputs[InternalFtrType.LENGTH], tf.constant([4, 7]))\n\n def testVocabLayerApi(self):\n \"\"\"Checks whether a given layer conforms to the DeText vocab layer API\"\"\"\n layer = hub.load(self.vocab_hub_url)\n layer: vocab_layer.VocabLayerBase\n\n self.assertEqual(layer.vocab_size(), self.vocab_size)\n self.assertEqual(layer.pad_id(), self.PAD_ID)\n\n inputs = self.inputs\n outputs = layer(inputs)\n expected_outputs = {InternalFtrType.LENGTH: tf.constant([4, 7]),\n InternalFtrType.TOKENIZED_IDS: tf.constant([[1, 0, 0, 2, 3, 3, 3],\n [1, 4, 4, 4, 4, 0, 2]])}\n\n for k, v in outputs.items():\n self.assertAllEqual(v, expected_outputs[k])\n\n def testCreateVocabLayer(self):\n for vocab_hub_url in ['', self.vocab_hub_url]:\n self._testCreateVocabLayer(vocab_hub_url)\n\n def _testCreateVocabLayer(self, vocab_hub_url):\n layer = vocab_layer.create_vocab_layer(self.vocab_layer_param, vocab_hub_url)\n outputs = layer(self.inputs)\n tf.saved_model.save(layer, self.vocab_layer_dir)\n\n loaded_layer = vocab_layer.create_vocab_layer(None, self.vocab_layer_dir)\n loaded_layer_outputs = loaded_layer(self.inputs)\n\n for k, v in outputs.items():\n self.assertAllEqual(v, loaded_layer_outputs[k])\n shutil.rmtree(self.vocab_layer_dir)\n\n\nif __name__ == '__main__':\n tf.test.main()\n" ]
[ [ "tensorflow.constant", "tensorflow.data.TFRecordDataset", "tensorflow.io.parse_single_example", "tensorflow.cast", "tensorflow.io.FixedLenFeature" ], [ "tensorflow.saved_model.save", "tensorflow.constant", "tensorflow.test.main", "tensorflow.shape" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
wensun/baselines
[ "81b7b988918de2c1c2f5fa9f38b7716608efc125" ]
[ "baselines/ddpg/main.py" ]
[ "import argparse\nimport time\nimport os\nimport logging\nfrom baselines import logger, bench\nfrom baselines.common.misc_util import (\n set_global_seeds,\n boolean_flag,\n)\n#import baselines.ddpg.training as training\nimport training as training\nfrom baselines.ddpg.models import Actor, Critic\nfrom baselines.ddpg.memory import Memory\nfrom baselines.ddpg.noise import *\n\nimport gym\nimport tensorflow as tf\nfrom mpi4py import MPI\n\ndef run(env_id, seed, noise_type, layer_norm, evaluation, **kwargs):\n # Configure things.\n rank = MPI.COMM_WORLD.Get_rank()\n if rank != 0:\n logger.set_level(logger.DISABLED)\n\n # Create envs.\n env = gym.make(env_id)\n env = bench.Monitor(env, logger.get_dir() and os.path.join(logger.get_dir(), str(rank)))\n\n if evaluation and rank==0:\n eval_env = gym.make(env_id)\n eval_env = bench.Monitor(eval_env, os.path.join(logger.get_dir(), 'gym_eval'))\n #env = bench.Monitor(env, None)\n else:\n eval_env = None\n\n # Parse noise_type\n action_noise = None\n param_noise = None\n nb_actions = env.action_space.shape[-1]\n for current_noise_type in noise_type.split(','):\n current_noise_type = current_noise_type.strip()\n if current_noise_type == 'none':\n pass\n elif 'adaptive-param' in current_noise_type:\n _, stddev = current_noise_type.split('_')\n param_noise = AdaptiveParamNoiseSpec(initial_stddev=float(stddev), desired_action_stddev=float(stddev))\n elif 'normal' in current_noise_type:\n _, stddev = current_noise_type.split('_')\n action_noise = NormalActionNoise(mu=np.zeros(nb_actions), sigma=float(stddev) * np.ones(nb_actions))\n elif 'ou' in current_noise_type:\n _, stddev = current_noise_type.split('_')\n action_noise = OrnsteinUhlenbeckActionNoise(mu=np.zeros(nb_actions), sigma=float(stddev) * np.ones(nb_actions))\n else:\n raise RuntimeError('unknown noise type \"{}\"'.format(current_noise_type))\n\n # Configure components.\n memory = Memory(limit=int(1e6), action_shape=env.action_space.shape, observation_shape=env.observation_space.shape)\n critic = Critic(layer_norm=layer_norm)\n actor = Actor(nb_actions, layer_norm=layer_norm)\n\n # Seed everything to make things reproducible.\n seed = seed + 1000000 * rank\n logger.info('rank {}: seed={}, logdir={}'.format(rank, seed, logger.get_dir()))\n tf.reset_default_graph()\n set_global_seeds(seed)\n env.seed(seed)\n if eval_env is not None:\n eval_env.seed(seed)\n\n # Disable logging for rank != 0 to avoid noise.\n if rank == 0:\n start_time = time.time()\n training.train(env=env, eval_env=eval_env, param_noise=param_noise,\n action_noise=action_noise, actor=actor, critic=critic, memory=memory, **kwargs)\n env.close()\n if eval_env is not None:\n eval_env.close()\n if rank == 0:\n logger.info('total runtime: {}s'.format(time.time() - start_time))\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('--env-id', type=str, default='HalfCheetah-v2')\n boolean_flag(parser, 'render-eval', default=False)\n boolean_flag(parser, 'layer-norm', default=True)\n boolean_flag(parser, 'render', default=False)\n boolean_flag(parser, 'normalize-returns', default=False)\n boolean_flag(parser, 'normalize-observations', default=True)\n parser.add_argument('--seed', help='RNG seed', type=int, default=0)\n parser.add_argument('--critic-l2-reg', type=float, default=1e-2)\n parser.add_argument('--batch-size', type=int, default=64) # per MPI worker\n parser.add_argument('--actor-lr', type=float, default=1e-4)\n parser.add_argument('--critic-lr', type=float, default=1e-3)\n boolean_flag(parser, 'popart', default=False)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--reward-scale', type=float, default=1.)\n parser.add_argument('--clip-norm', type=float, default=None)\n parser.add_argument('--nb-epochs', type=int, default=500) # with default settings, perform 1M steps total, was 500\n parser.add_argument('--nb-epoch-cycles', type=int, default=20)\n parser.add_argument('--nb-train-steps', type=int, default=50) # per epoch cycle and MPI worker\n parser.add_argument('--nb-eval-steps', type=int, default=1000) # per epoch cycle and MPI worker\n parser.add_argument('--nb-rollout-steps', type=int, default=100) # per epoch cycle and MPI worker\n parser.add_argument('--noise-type', type=str, default='adaptive-param_0.2') # choices are adaptive-param_xx, ou_xx, normal_xx, none\n parser.add_argument('--num-timesteps', type=int, default=None)\n parser.add_argument('--alg', type=str, default='DDPG') # DDPG or DDPGRM\n #boolean_flag(parser, 'evaluation', default=False)\n \n boolean_flag(parser, 'evaluation', default=True) #turn evaluation on \n args = parser.parse_args()\n # we don't directly specify timesteps for this script, so make sure that if we do specify them\n # they agree with the other parameters. default: 1M total steps\n \n\n eval_steps_per_epoch = args.nb_epoch_cycles*args.nb_eval_steps #defualt: 1000*20 = 10K (~ 20 episodes)\n print(args)\n if args.num_timesteps is not None:\n assert(args.num_timesteps == args.nb_epochs * args.nb_epoch_cycles * args.nb_rollout_steps)\n dict_args = vars(args)\n del dict_args['num_timesteps']\n return dict_args\n\n\nif __name__ == '__main__':\n args = parse_args()\n if MPI.COMM_WORLD.Get_rank() == 0:\n logger.configure()\n # Run actual script.\n run(**args)\n" ]
[ [ "tensorflow.reset_default_graph" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
Ziaeemehr/brian2
[ "0d28f61881a033f877fb333b5e93c56e5c479b4b" ]
[ "brian2/tests/test_codegen.py" ]
[ "\nfrom collections import namedtuple\nimport os\n\nimport numpy as np\nimport pytest\n\nfrom brian2 import prefs, clear_cache, _cache_dirs_and_extensions\nfrom brian2.codegen.cpp_prefs import compiler_supports_c99\nfrom brian2.codegen.optimisation import optimise_statements\nfrom brian2.codegen.translation import (analyse_identifiers,\n get_identifiers_recursively,\n parse_statement,\n make_statements,\n )\nfrom brian2.codegen.statements import Statement\nfrom brian2.codegen.codeobject import CodeObject\nfrom brian2.parsing.sympytools import str_to_sympy, sympy_to_str\nfrom brian2.core.variables import Subexpression, Variable, Constant, ArrayVariable\nfrom brian2.core.functions import Function, DEFAULT_FUNCTIONS, DEFAULT_CONSTANTS\nfrom brian2.devices.device import auto_target, device\nfrom brian2.units.fundamentalunits import Unit\nfrom brian2.units import second, ms\n\nFakeGroup = namedtuple('FakeGroup', ['variables'])\n\[email protected]_independent\ndef test_auto_target():\n # very basic test that the \"auto\" codegen target is useable\n assert issubclass(auto_target(), CodeObject)\n\n\[email protected]_independent\ndef test_analyse_identifiers():\n '''\n Test that the analyse_identifiers function works on a simple clear example.\n '''\n code = '''\n a = b+c\n d = e+f\n '''\n known = {'b': Variable(name='b'),\n 'c': Variable(name='c'),\n 'd': Variable(name='d'),\n 'g': Variable(name='g')}\n \n defined, used_known, dependent = analyse_identifiers(code, known)\n assert 'a' in defined # There might be an additional constant added by the\n # loop-invariant optimisation\n assert used_known == {'b', 'c', 'd'}\n assert dependent == {'e', 'f'}\n\n\[email protected]_independent\ndef test_get_identifiers_recursively():\n '''\n Test finding identifiers including subexpressions.\n '''\n variables = {'sub1': Subexpression(name='sub1',\n dtype=np.float32, expr='sub2 * z',\n owner=FakeGroup(variables={}),\n device=None),\n 'sub2': Subexpression(name='sub2',\n dtype=np.float32, expr='5 + y',\n owner=FakeGroup(variables={}),\n device=None),\n 'x': Variable(name='x')}\n identifiers = get_identifiers_recursively(['_x = sub1 + x'],\n variables)\n assert identifiers == {'x', '_x', 'y', 'z', 'sub1', 'sub2'}\n\n\[email protected]_independent\ndef test_write_to_subexpression():\n variables = {\n 'a': Subexpression(name='a', dtype=np.float32,\n owner=FakeGroup(variables={}), device=None,\n expr='2*z'),\n 'z': Variable(name='z')\n }\n\n # Writing to a subexpression is not allowed\n code = 'a = z'\n with pytest.raises(SyntaxError):\n make_statements(code, variables, np.float32)\n\n\[email protected]_independent\ndef test_repeated_subexpressions():\n variables = {\n 'a': Subexpression(name='a', dtype=np.float32,\n owner=FakeGroup(variables={}), device=None,\n expr='2*z'),\n 'x': Variable(name='x'),\n 'y': Variable(name='y'),\n 'z': Variable(name='z')\n }\n # subexpression a (referring to z) is used twice, but can be reused the\n # second time (no change to z)\n code = '''\n x = a\n y = a\n '''\n scalar_stmts, vector_stmts = make_statements(code, variables, np.float32)\n assert len(scalar_stmts) == 0\n assert [stmt.var for stmt in vector_stmts] == ['a', 'x', 'y']\n assert vector_stmts[0].constant\n\n code = '''\n x = a\n z *= 2\n '''\n scalar_stmts, vector_stmts = make_statements(code, variables, np.float32)\n assert len(scalar_stmts) == 0\n assert [stmt.var for stmt in vector_stmts] == ['a', 'x', 'z']\n # Note that we currently do not mark the subexpression as constant in this\n # case, because its use after the \"z *=2\" line would actually redefine it.\n # Our algorithm is currently not smart enough to detect that it is actually\n # not used afterwards\n\n # a refers to z, therefore we have to redefine a after z changed, and a\n # cannot be constant\n code = '''\n x = a\n z *= 2\n y = a\n '''\n scalar_stmts, vector_stmts = make_statements(code, variables, np.float32)\n assert len(scalar_stmts) == 0\n assert [stmt.var for stmt in vector_stmts] == ['a', 'x', 'z', 'a', 'y']\n assert not any(stmt.constant for stmt in vector_stmts)\n\n\[email protected]_independent\ndef test_nested_subexpressions():\n '''\n This test checks that code translation works with nested subexpressions.\n '''\n code = '''\n x = a + b + c\n c = 1\n x = a + b + c\n d = 1\n x = a + b + c\n '''\n variables = {\n 'a': Subexpression(name='a', dtype=np.float32, owner=FakeGroup(variables={}), device=None,\n expr='b*b+d'),\n 'b': Subexpression(name='b', dtype=np.float32, owner=FakeGroup(variables={}), device=None,\n expr='c*c*c'),\n 'c': Variable(name='c'),\n 'd': Variable(name='d'),\n }\n scalar_stmts, vector_stmts = make_statements(code, variables, np.float32)\n assert len(scalar_stmts) == 0\n evalorder = ''.join(stmt.var for stmt in vector_stmts)\n # This is the order that variables ought to be evaluated in (note that\n # previously this test did not expect the last \"b\" evaluation, because its\n # value did not change (c was not changed). We have since removed this\n # subexpression caching, because it did not seem to apply in practical\n # use cases)\n assert evalorder == 'baxcbaxdbax'\n\[email protected]_independent\ndef test_apply_loop_invariant_optimisation():\n variables = {'v': Variable('v', scalar=False),\n 'w': Variable('w', scalar=False),\n 'dt': Constant('dt', dimensions=second.dim, value=0.1*ms),\n 'tau': Constant('tau', dimensions=second.dim, value=10*ms),\n 'exp': DEFAULT_FUNCTIONS['exp']}\n statements = [Statement('v', '=', 'dt*w*exp(-dt/tau)/tau + v*exp(-dt/tau)', '', np.float32),\n Statement('w', '=', 'w*exp(-dt/tau)', '', np.float32)]\n scalar, vector = optimise_statements([], statements, variables)\n # The optimisation should pull out at least exp(-dt / tau)\n assert len(scalar) >= 1\n assert np.issubdtype(scalar[0].dtype, np.floating)\n assert scalar[0].var == '_lio_1'\n assert len(vector) == 2\n assert all('_lio_' in stmt.expr for stmt in vector)\n\[email protected]_independent\ndef test_apply_loop_invariant_optimisation_integer():\n variables = {'v': Variable('v', scalar=False),\n 'N': Constant('N', 10),\n 'b': Variable('b', scalar=True, dtype=int),\n 'c': Variable('c', scalar=True, dtype=int),\n 'd': Variable('d', scalar=True, dtype=int),\n 'y': Variable('y', scalar=True, dtype=float),\n 'z': Variable('z', scalar=True, dtype=float),\n 'w': Variable('w', scalar=True, dtype=float),\n }\n statements = [Statement('v', '=', 'v % (2*3*N)', '', np.float32),\n # integer version doesn't get rewritten but float version does\n Statement('a', ':=', 'b//(c//d)', '', int),\n Statement('x', ':=', 'y/(z/w)', '', float),\n ]\n scalar, vector = optimise_statements([], statements, variables)\n assert len(scalar) == 3\n assert np.issubdtype(scalar[0].dtype, np.signedinteger)\n assert scalar[0].var == '_lio_1'\n expr = scalar[0].expr.replace(' ', '')\n assert expr=='6*N' or expr=='N*6'\n assert np.issubdtype(scalar[1].dtype, np.signedinteger)\n assert scalar[1].var == '_lio_2'\n expr = scalar[1].expr.replace(' ', '')\n assert expr=='b//(c//d)'\n assert np.issubdtype(scalar[2].dtype, np.floating)\n assert scalar[2].var == '_lio_3'\n expr = scalar[2].expr.replace(' ', '')\n assert expr=='(y*w)/z' or expr=='(w*y)/z'\n\[email protected]_independent\ndef test_apply_loop_invariant_optimisation_boolean():\n variables = {'v1': Variable('v1', scalar=False),\n 'v2': Variable('v2', scalar=False),\n 'N': Constant('N', 10),\n 'b': Variable('b', scalar=True, dtype=bool),\n 'c': Variable('c', scalar=True, dtype=bool),\n 'int': DEFAULT_FUNCTIONS['int'],\n 'foo': Function(lambda x: None,\n arg_units=[Unit(1)], return_unit=Unit(1),\n arg_types=['boolean'], return_type='float',\n stateless=False)\n }\n # The calls for \"foo\" cannot be pulled out, since foo is marked as stateful\n statements = [Statement('v1', '=', '1.0*int(b and c)', '', np.float32),\n Statement('v1', '=', '1.0*foo(b and c)', '', np.float32),\n Statement('v2', '=', 'int(not b and True)', '', np.float32),\n Statement('v2', '=', 'foo(not b and True)', '', np.float32)\n ]\n scalar, vector = optimise_statements([], statements, variables)\n assert len(scalar) == 4\n assert scalar[0].expr == '1.0 * int(b and c)'\n assert scalar[1].expr == 'b and c'\n assert scalar[2].expr == 'int((not b) and True)'\n assert scalar[3].expr == '(not b) and True'\n assert len(vector) == 4\n assert vector[0].expr == '_lio_1'\n assert vector[1].expr == 'foo(_lio_2)'\n assert vector[2].expr == '_lio_3'\n assert vector[3].expr == 'foo(_lio_4)'\n\[email protected]_independent\ndef test_apply_loop_invariant_optimisation_no_optimisation():\n variables = {'v1': Variable('v1', scalar=False),\n 'v2': Variable('v2', scalar=False),\n 'N': Constant('N', 10),\n 's1': Variable('s1', scalar=True, dtype=float),\n 's2': Variable('s2', scalar=True, dtype=float),\n 'rand': DEFAULT_FUNCTIONS['rand']\n }\n statements = [\n # This hould not be simplified to 0!\n Statement('v1', '=', 'rand() - rand()', '', np.float),\n Statement('v1', '=', '3*rand() - 3*rand()', '', np.float),\n Statement('v1', '=', '3*rand() - ((1+2)*rand())', '', np.float),\n # This should not pull out rand()*N\n Statement('v1', '=', 's1*rand()*N', '', np.float),\n Statement('v1', '=', 's2*rand()*N', '', np.float),\n # This is not important mathematically, but it would change the numbers\n # that are generated\n Statement('v1', '=', '0*rand()*N', '', np.float),\n Statement('v1', '=', '0/rand()*N', '', np.float)\n ]\n scalar, vector = optimise_statements([], statements, variables)\n for vs in vector[:3]:\n assert vs.expr.count('rand()') == 2, 'Expression should still contain two rand() calls, but got ' + str(vs)\n for vs in vector[3:]:\n assert vs.expr.count('rand()') == 1, 'Expression should still contain a rand() call, but got ' + str(vs)\n\[email protected]_independent\ndef test_apply_loop_invariant_optimisation_simplification():\n variables = {'v1': Variable('v1', scalar=False),\n 'v2': Variable('v2', scalar=False),\n 'i1': Variable('i1', scalar=False, dtype=int),\n 'N': Constant('N', 10)\n }\n statements = [\n # Should be simplified to 0.0\n Statement('v1', '=', 'v1 - v1', '', np.float),\n Statement('v1', '=', 'N*v1 - N*v1', '', np.float),\n Statement('v1', '=', 'v1*N * 0', '', np.float),\n Statement('v1', '=', 'v1 * 0', '', np.float),\n Statement('v1', '=', 'v1 * 0.0', '', np.float),\n Statement('v1', '=', '0.0 / (v1*N)', '', np.float),\n # Should be simplified to 0\n Statement('i1', '=', 'i1*N * 0', '', np.int),\n Statement('i1', '=', '0 * i1', '', np.int),\n Statement('i1', '=', '0 * i1*N', '', np.int),\n Statement('i1', '=', 'i1 * 0', '', np.int),\n # Should be simplified to v1*N\n Statement('v2', '=', '0 + v1*N', '', np.float),\n Statement('v2', '=', 'v1*N + 0.0', '', np.float),\n Statement('v2', '=', 'v1*N - 0', '', np.float),\n Statement('v2', '=', 'v1*N - 0.0', '', np.float),\n Statement('v2', '=', '1 * v1*N', '', np.float),\n Statement('v2', '=', '1.0 * v1*N', '', np.float),\n Statement('v2', '=', 'v1*N / 1.0', '', np.float),\n Statement('v2', '=', 'v1*N / 1', '', np.float),\n # Should be simplified to i1\n Statement('i1', '=', 'i1*1', '', int),\n Statement('i1', '=', 'i1//1', '', int),\n Statement('i1', '=', 'i1+0', '', int),\n Statement('i1', '=', '0+i1', '', int),\n Statement('i1', '=', 'i1-0', '', int),\n # Should *not* be simplified (because it would change the type,\n # important for integer division, for example)\n Statement('v1', '=', 'i1*1.0', '', float),\n Statement('v1', '=', '1.0*i1', '', float),\n Statement('v1', '=', 'i1/1.0', '', float),\n Statement('v1', '=', 'i1/1', '', float),\n Statement('v1', '=', 'i1+0.0', '', float),\n Statement('v1', '=', '0.0+i1', '', float),\n Statement('v1', '=', 'i1-0.0', '', float),\n ## Should *not* be simplified, flooring division by 1 changes the value\n Statement('v1', '=', 'v2//1.0', '', float),\n Statement('i1', '=', 'i1//1.0', '', float) # changes type\n ]\n scalar, vector = optimise_statements([], statements, variables)\n assert len(scalar) == 0\n for s in vector[:6]:\n assert s.expr == '0.0'\n for s in vector[6:10]:\n assert s.expr == '0', s.expr # integer\n for s in vector[10:18]:\n expr = s.expr.replace(' ', '')\n assert expr == 'v1*N' or expr == 'N*v1'\n for s in vector[18:23]:\n expr = s.expr.replace(' ', '')\n assert expr == 'i1'\n for s in vector[23:27]:\n expr = s.expr.replace(' ', '')\n assert expr == '1.0*i1' or expr == 'i1*1.0' or expr == 'i1/1.0'\n for s in vector[27:30]:\n expr = s.expr.replace(' ', '')\n assert expr == '0.0+i1' or expr == 'i1+0.0'\n for s in vector[30:31]:\n expr = s.expr.replace(' ', '')\n assert expr == 'v2//1.0' or expr == 'v2//1'\n for s in vector[31:]:\n expr = s.expr.replace(' ', '')\n assert expr == 'i1//1.0'\n\n\[email protected]_independent\ndef test_apply_loop_invariant_optimisation_constant_evaluation():\n variables = {'v1': Variable('v1', scalar=False),\n 'v2': Variable('v2', scalar=False),\n 'i1': Variable('i1', scalar=False, dtype=int),\n 'N': Constant('N', 10),\n 's1': Variable('s1', scalar=True, dtype=float),\n 's2': Variable('s2', scalar=True, dtype=float),\n 'exp': DEFAULT_FUNCTIONS['exp']\n }\n statements = [\n Statement('v1', '=', 'v1 * (1 + 2 + 3)', '', np.float),\n Statement('v1', '=', 'exp(N)*v1', '', np.float),\n Statement('v1', '=', 'exp(0)*v1', '', np.float),\n ]\n scalar, vector = optimise_statements([], statements, variables)\n # exp(N) should be pulled out of the vector statements, the rest should be\n # evaluated in place\n assert len(scalar) == 1\n assert scalar[0].expr == 'exp(N)'\n assert len(vector) == 3\n expr = vector[0].expr.replace(' ', '')\n assert expr == '_lio_1*v1' or 'v1*_lio_1'\n expr = vector[1].expr.replace(' ', '')\n assert expr == '6.0*v1' or 'v1*6.0'\n assert vector[2].expr == 'v1'\n\n\[email protected]_independent\ndef test_automatic_augmented_assignments():\n # We test that statements that could be rewritten as augmented assignments\n # are correctly rewritten (using sympy to test for symbolic equality)\n variables = {\n 'x': ArrayVariable('x', owner=None, size=10,\n device=device),\n 'y': ArrayVariable('y', owner=None, size=10,\n device=device),\n 'z': ArrayVariable('y', owner=None, size=10,\n device=device),\n 'b': ArrayVariable('b', owner=None, size=10,\n dtype=np.bool, device=device),\n 'clip': DEFAULT_FUNCTIONS['clip'],\n 'inf': DEFAULT_CONSTANTS['inf']\n }\n statements = [\n # examples that should be rewritten\n # Note that using our approach, we will never get -= or /= but always\n # the equivalent += or *= statements\n ('x = x + 1.0', 'x += 1.0'),\n ('x = 2.0 * x', 'x *= 2.0'),\n ('x = x - 3.0', 'x += -3.0'),\n ('x = x/2.0', 'x *= 0.5'),\n ('x = y + (x + 1.0)', 'x += y + 1.0'),\n ('x = x + x', 'x *= 2.0'),\n ('x = x + y + z', 'x += y + z'),\n ('x = x + y + z', 'x += y + z'),\n # examples that should not be rewritten\n ('x = 1.0/x', 'x = 1.0/x'),\n ('x = 1.0', 'x = 1.0'),\n ('x = 2.0*(x + 1.0)', 'x = 2.0*(x + 1.0)'),\n ('x = clip(x + y, 0.0, inf)', 'x = clip(x + y, 0.0, inf)'),\n ('b = b or False', 'b = b or False')\n ]\n for orig, rewritten in statements:\n scalar, vector = make_statements(orig, variables, np.float32)\n try: # we augment the assertion error with the original statement\n assert len(scalar) == 0, 'Did not expect any scalar statements but got ' + str(scalar)\n assert len(vector) == 1, 'Did expect a single statement but got ' + str(vector)\n statement = vector[0]\n expected_var, expected_op, expected_expr, _ = parse_statement(rewritten)\n assert expected_var == statement.var, 'expected write to variable %s, not to %s' % (expected_var, statement.var)\n assert expected_op == statement.op, 'expected operation %s, not %s' % (expected_op, statement.op)\n # Compare the two expressions using sympy to allow for different order etc.\n sympy_expected = str_to_sympy(expected_expr)\n sympy_actual = str_to_sympy(statement.expr)\n assert sympy_expected == sympy_actual, ('RHS expressions \"%s\" and \"%s\" are not identical' % (sympy_to_str(sympy_expected),\n sympy_to_str(sympy_actual)))\n except AssertionError as ex:\n raise AssertionError('Transformation for statement \"%s\" gave an unexpected result: %s' % (orig, str(ex)))\n\n\ndef test_clear_cache():\n target = prefs.codegen.target\n if target == 'numpy':\n assert 'numpy' not in _cache_dirs_and_extensions\n with pytest.raises(ValueError):\n clear_cache('numpy')\n else:\n assert target in _cache_dirs_and_extensions\n cache_dir, _ = _cache_dirs_and_extensions[target]\n # Create a file that should not be there\n fname = os.path.join(cache_dir, 'some_file.py')\n open(fname, 'w').close()\n # clear_cache should refuse to clear the directory\n with pytest.raises(IOError):\n clear_cache(target)\n\n os.remove(fname)\n\n\ndef test_compiler_c99():\n # On a user's computer, we do not know whether the compiler actually\n # has C99 support, so we just check whether the test does not raise an\n # error\n c99_support = compiler_supports_c99()\n # On our Azure test server we know that the compilers support C99\n if os.environ.get('AGENT_OS', ''):\n assert c99_support\n\n\nif __name__ == '__main__':\n test_auto_target()\n test_analyse_identifiers()\n test_get_identifiers_recursively()\n test_write_to_subexpression()\n test_repeated_subexpressions()\n test_nested_subexpressions()\n test_apply_loop_invariant_optimisation()\n test_apply_loop_invariant_optimisation_integer()\n test_apply_loop_invariant_optimisation_boolean()\n test_apply_loop_invariant_optimisation_no_optimisation()\n test_apply_loop_invariant_optimisation_simplification()\n test_apply_loop_invariant_optimisation_constant_evaluation()\n test_automatic_augmented_assignments()\n test_clear_cache()\n\n" ]
[ [ "numpy.issubdtype" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Kronemeyer/project-athena
[ "0e79cba1c4d30146326ce7bd311f69f2ee845e80" ]
[ "src/attacks/attack.py" ]
[ "\"\"\"\nImplement white-box attacks on top of IBM ART.\n@author: Ying Meng (y(dot)meng201011(at)gmail(dot)com)\n\"\"\"\n\nimport numpy as np\nimport torch\n\n# from art.attacks.evasion.fast_gradient import FastGradientMethod\n# from art.attacks.evasion.projected_gradient_descent import ProjectedGradientDescent\nfrom art.attacks.evasion.carlini import CarliniL2Method, CarliniLInfMethod\nfrom art.attacks.evasion.deepfool import DeepFool\nfrom art.attacks.evasion.saliency_map import SaliencyMapMethod\nfrom art.attacks.evasion.iterative_method import BasicIterativeMethod\nfrom art.attacks.evasion.spatial_transformation import SpatialTransformation\nfrom art.attacks.evasion.hop_skip_jump import HopSkipJump\nfrom art.attacks.evasion.zoo import ZooAttack\n\nfrom attacks.fast_gradient import FastGradientMethod\nfrom attacks.pgd import ProjectedGradientDescent\nfrom attacks.utils import WHITEBOX_ATTACK as ATTACK\n\n\ndef generate(model, data_loader, attack_args, device=None):\n \"\"\"\n Generate adversarial examples.\n :param model: an instances of art.classifiers.classifier. The targeted model.\n :param data_loader: a tuple of benign samples and corresponding true labels.\n :param attack_args: dictionary. adversarial configurations.\n :param device: string. cuda (for gpu) or cpu.\n :return:\n \"\"\"\n attack = attack_args.get('attack').lower()\n eot = attack_args.get('eot')\n\n if eot and attack not in [ATTACK.FGSM.value, ATTACK.PGD.value]:\n raise NotImplementedError(\"`EOT` is not supported for {} attack yet.\".format(attack))\n\n print(\">>> Generating {}(EOT:{}) examples.\".format(attack_args.get('description'),\n \"ON\" if eot else \"OFF\"))\n\n if device is None:\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n images, labels = data_loader\n\n if attack == ATTACK.FGSM.value:\n return _fgsm(model, images, labels, attack_args)\n elif attack == ATTACK.CW.value:\n return _cw(model, images, labels, attack_args)\n elif attack == ATTACK.PGD.value:\n return _pgd(model, images, labels, attack_args)\n elif attack == ATTACK.BIM.value:\n return _bim(model, images, labels, attack_args)\n elif attack == ATTACK.JSMA.value:\n return _jsma(model, images, labels, attack_args)\n elif attack == ATTACK.DF.value:\n return _df(model, images, labels, attack_args)\n elif attack == ATTACK.MIM.value:\n return _mim(model, images, labels, attack_args)\n elif attack == ATTACK.OP.value:\n return _op(model, images, labels, attack_args)\n elif attack == ATTACK.HOP_SKIP_JUMP.value:\n raise _hop_skip_jump(model, images, labels, attack_args)\n elif attack == ATTACK.SPATIAL_TRANS.value:\n return _spatial(model, images, labels, attack_args)\n elif attack == ATTACK.ZOO.value:\n return _zoo(model, images, labels, attack_args)\n else:\n raise ValueError('{} is not supported.'.format(attack))\n\n\ndef _fgsm(model, data, labels, attack_args):\n \"\"\"\n Fast Gradient Sign Method\n Explaining and Harnessing Adversarial Examples\n by Ian J. Goodfellow, Jonathon Shlens, Christian Szegedy\n ``https://arxiv.org/abs/1412.6572``\n :param model:\n :param data:\n :param labels:\n :param attack_args:\n :param distribution: dictionary. the configurations of distribution (for EOT)\n :return:\n \"\"\"\n eps = attack_args.get('eps', 0.3)\n\n targeted = attack_args.get('targeted', False)\n num_random_init = attack_args.get('num_random_init', 0)\n minimal = attack_args.get('minimal', False)\n\n if attack_args.get(\"eot\"):\n distribution = attack_args.get('distribution', None)\n else:\n distribution = None\n\n attacker = FastGradientMethod(model, eps=eps, eps_step=eps, targeted=targeted,\n num_random_init=num_random_init, minimal=minimal,\n distribution=distribution)\n\n return attacker.generate(data, labels)\n\n\ndef _cw(model, data, labels, attack_args):\n \"\"\"\n Carlini & Wanger\n Towards Evaluating the Robustness of Neural Networks\n by Nicholas Carlini, David Wagner\n ``https://arxiv.org/abs/1608.04644``\n :param model:\n :param data:\n :param labels:\n :param attack_args:\n :return:\n \"\"\"\n norm = attack_args.get('norm').lower()\n\n lr = attack_args.get('lr')\n max_iter = attack_args.get('max_iter', 10)\n\n # use default values for the following arguments\n confidence = attack_args.get('confidence', 0.0)\n targeted = attack_args.get('targeted', False)\n init_const = attack_args.get('init_const', 0.01)\n max_halving = attack_args.get('max_halving', 5)\n max_doubling = attack_args.get('max_doubling', 5)\n\n if norm == 'l2':\n print('>>> Generating CW_l2 examples.')\n binary_search_steps = attack_args.get('binary_search_steps', 10)\n\n attacker = CarliniL2Method(classifier=model, confidence=confidence, targeted=targeted, learning_rate=lr,\n binary_search_steps=binary_search_steps, max_iter=max_iter,\n initial_const=init_const, max_halving=max_halving,\n max_doubling=max_doubling)\n\n elif norm == 'linf':\n print('>>> Generating CW_linf examples.')\n eps = attack_args.get('eps', 0.3)\n attacker = CarliniLInfMethod(classifier=model, confidence=confidence, targeted=targeted, learning_rate=lr,\n max_iter=max_iter, max_halving=max_halving, max_doubling=max_doubling, eps=eps)\n else:\n raise ValueError('Support `l2` and `linf` norms. But found {}'.format(norm))\n\n return attacker.generate(data, labels)\n\n\ndef _pgd(model, data, labels, attack_args):\n \"\"\"\n Projected Gradient Descent\n Towards deep learning models resistant to adversarial attacks\n by Aleksander Madry, Aleksandar Makelov, Ludwig Schmidt, Dimitris Tsipras, and Adrian Vladu.\n ``https://arxiv.org/abs/1706.06083``\n :param model:\n :param data:\n :param labels:\n :param attack_args:\n :return:\n \"\"\"\n eps = attack_args.get('eps', 0.3)\n eps_step = attack_args.get('eps_step', eps/10.)\n max_iter = attack_args.get('max_iter', 10)\n\n norm = _get_norm_value(attack_args.get('norm', 'linf'))\n targeted = attack_args.get('targeted', False)\n num_random_init = attack_args.get('num_random_init', 0)\n random_eps = attack_args.get('random_eps', False)\n\n if attack_args.get(\"eot\"):\n distribution = attack_args.get('distribution', None)\n else:\n distribution = None\n\n attacker = ProjectedGradientDescent(classifier=model, norm=norm, eps=eps, eps_step=eps_step,\n max_iter=max_iter, targeted=targeted,\n num_random_init=num_random_init, random_eps=random_eps,\n distribution=distribution)\n return attacker.generate(data, labels)\n\n\ndef _bim(model, data, labels, attack_args):\n \"\"\"\n Basic Iteractive Method\n ADVERSARIAL EXAMPLES IN THE PHYSICAL WORLD\n Alexey Kurakin, Ian J. Goodfellow, Samy Bengio\n ``https://arxiv.org/pdf/1607.02533.pdf``\n :param model:\n :param data:\n :param labels:\n :param attack_args:\n :return:\n \"\"\"\n eps = attack_args.get('eps', 0.3)\n eps_step = attack_args.get('eps_step', eps/10.)\n max_iter = attack_args.get('max_iter', 100)\n\n targeted = attack_args.get('targeted', False)\n attacker = BasicIterativeMethod(classifier=model, eps=eps, eps_step=eps_step,\n max_iter=max_iter, targeted=targeted)\n return attacker.generate(data, labels)\n\n\ndef _jsma(model, data, labels, attack_args):\n theta = attack_args.get('theta', 0.15)\n gamma = attack_args.get('gamma', 0.5)\n\n batch_size = attack_args.get('batch_size', 1)\n\n attacker = SaliencyMapMethod(classifier=model, theta=theta, gamma=gamma, batch_size=batch_size)\n return attacker.generate(data, labels)\n\n\ndef _df(model, data, labels, attack_args):\n max_iter = attack_args.get('max_iter', 100)\n eps = attack_args.get('eps', 0.01)\n nb_grads = attack_args.get('nb_grads', 10)\n\n attacker = DeepFool(classifier=model, max_iter=max_iter, epsilon=eps, nb_grads=nb_grads)\n return attacker.generate(data, labels)\n\n\ndef _mim(model, data, labels, attack_args):\n raise NotImplementedError\n\n\ndef _op(model, data, labels, attack_args):\n raise NotImplementedError\n\n\ndef _spatial(model, data, labels, attack_args):\n max_translation = attack_args.get('max_translation', 0.2)\n num_translations = attack_args.get('num_translations', 1)\n max_rotation = attack_args.get('max_rotation', 10)\n num_rotations = attack_args.get('num_rotations', 1)\n\n attacker = SpatialTransformation(classifier=model,\n max_translation=max_translation, num_translations=num_translations,\n max_rotation=max_rotation, num_rotations=num_rotations)\n return attacker.generate(data, labels)\n\n\ndef _hop_skip_jump(model, data, labels, attack_args):\n norm = _get_norm_value(attack_args.get('norm', 'l2'))\n max_iter = attack_args.get('max_iter', 50)\n max_eval = attack_args.get('max_eval', 10000)\n init_eval = attack_args.get('init_eval', 100)\n init_size = attack_args.get('init_size', 100)\n\n targeted = attack_args.get('targeted', False)\n attacker = HopSkipJump(classifier=model, targeted=targeted, norm=norm,\n max_iter=max_iter, max_eval=max_eval,\n init_eval=init_eval, init_size=init_size)\n\n return attacker.generate(data, labels)\n\n\ndef _zoo(model, data, labels, attack_args):\n lr = attack_args.get('learning_rate', 0.01)\n max_iter = attack_args.get('max_iter', 10)\n binary_search_steps = attack_args.get('binary_search_steps', 1)\n\n confidence = attack_args.get('confidence', 0.0)\n targeted = attack_args.get('targeted', False)\n init_const = attack_args.get('init_const', 1e-3)\n abort_early = attack_args.get('abort_early', True)\n use_resize = attack_args.get('use_resize', True)\n use_importance = attack_args.get('use_importance', True)\n nb_parallel = attack_args.get('nb_parallel', 128)\n variable_h = attack_args.get('variable_h', 1e-4)\n\n attacker = ZooAttack(classifier=model, confidence=confidence, targeted=targeted,\n learning_rate=lr, max_iter=max_iter, binary_search_steps=binary_search_steps,\n initial_const=init_const, abort_early=abort_early, use_resize=use_resize,\n use_importance=use_importance, nb_parallel=nb_parallel, variable_h=variable_h)\n\n return attacker.generate(data, labels)\n\n\ndef _get_norm_value(norm):\n \"\"\"\n Convert a string norm to a numeric value.\n :param norm:\n :return:\n \"\"\"\n norm = norm.lower()\n if norm == 'linf':\n value = np.inf\n elif norm == 'l2':\n value = 2\n else:\n raise ValueError('Support `l2` and `linf` norms. But found {}.'.format(norm))\n\n return value\n" ]
[ [ "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
visr/neuralhydrology
[ "77f6c9214945c8e857e3b9545afe8470da751cab", "77f6c9214945c8e857e3b9545afe8470da751cab" ]
[ "neuralhydrology/datasetzoo/camelsus.py", "neuralhydrology/modelzoo/ealstm.py" ]
[ "from pathlib import Path\nfrom typing import Dict, List, Tuple, Union\n\nimport numpy as np\nimport pandas as pd\nimport xarray\n\nfrom neuralhydrology.datasetzoo.basedataset import BaseDataset\nfrom neuralhydrology.utils.config import Config\n\n\nclass CamelsUS(BaseDataset):\n \"\"\"Data set class for the CAMELS US data set by [#]_ and [#]_.\n \n Parameters\n ----------\n cfg : Config\n The run configuration.\n is_train : bool \n Defines if the dataset is used for training or evaluating. If True (training), means/stds for each feature\n are computed and stored to the run directory. If one-hot encoding is used, the mapping for the one-hot encoding \n is created and also stored to disk. If False, a `scaler` input is expected and similarly the `id_to_int` input\n if one-hot encoding is used. \n period : {'train', 'validation', 'test'}\n Defines the period for which the data will be loaded\n basin : str, optional\n If passed, the data for only this basin will be loaded. Otherwise the basin(s) are read from the appropriate\n basin file, corresponding to the `period`.\n additional_features : List[Dict[str, pd.DataFrame]], optional\n List of dictionaries, mapping from a basin id to a pandas DataFrame. This DataFrame will be added to the data\n loaded from the dataset and all columns are available as 'dynamic_inputs', 'static_inputs' and \n 'target_variables'\n id_to_int : Dict[str, int], optional\n If the config argument 'use_basin_id_encoding' is True in the config and period is either 'validation' or \n 'test', this input is required. It is a dictionary, mapping from basin id to an integer (the one-hot encoding).\n scaler : Dict[str, Union[pd.Series, xarray.DataArray]], optional\n If period is either 'validation' or 'test', this input is required. It contains the means and standard \n deviations for each feature and is stored to the run directory during training (train_data/train_data_scaler.p)\n \n References\n ----------\n .. [#] A. J. Newman, M. P. Clark, K. Sampson, A. Wood, L. E. Hay, A. Bock, R. J. Viger, D. Blodgett, \n L. Brekke, J. R. Arnold, T. Hopson, and Q. Duan: Development of a large-sample watershed-scale \n hydrometeorological dataset for the contiguous USA: dataset characteristics and assessment of regional \n variability in hydrologic model performance. Hydrol. Earth Syst. Sci., 19, 209-223, \n doi:10.5194/hess-19-209-2015, 2015\n .. [#] Addor, N., Newman, A. J., Mizukami, N. and Clark, M. P.: The CAMELS data set: catchment attributes and \n meteorology for large-sample studies, Hydrol. Earth Syst. Sci., 21, 5293-5313, doi:10.5194/hess-21-5293-2017,\n 2017.\n \"\"\"\n\n def __init__(self,\n cfg: Config,\n is_train: bool,\n period: str,\n basin: str = None,\n additional_features: List[Dict[str, pd.DataFrame]] = [],\n id_to_int: Dict[str, int] = {},\n scaler: Dict[str, Union[pd.Series, xarray.DataArray]] = {}):\n super(CamelsUS, self).__init__(cfg=cfg,\n is_train=is_train,\n period=period,\n basin=basin,\n additional_features=additional_features,\n id_to_int=id_to_int,\n scaler=scaler)\n\n def _load_basin_data(self, basin: str) -> pd.DataFrame:\n \"\"\"Load input and output data from text files.\"\"\"\n # get forcings\n dfs = []\n for forcing in self.cfg.forcings:\n df, area = load_camels_us_forcings(self.cfg.data_dir, basin, forcing)\n\n # rename columns\n if len(self.cfg.forcings) > 1:\n df = df.rename(columns={col: f\"{col}_{forcing}\" for col in df.columns})\n dfs.append(df)\n df = pd.concat(dfs, axis=1)\n\n # add discharge\n df['QObs(mm/d)'] = load_camels_us_discharge(self.cfg.data_dir, basin, area)\n\n # replace invalid discharge values by NaNs\n qobs_cols = [col for col in df.columns if \"qobs\" in col.lower()]\n for col in qobs_cols:\n df.loc[df[col] < 0, col] = np.nan\n\n return df\n\n def _load_attributes(self) -> pd.DataFrame:\n if self.cfg.camels_attributes:\n\n df = load_camels_us_attributes(self.cfg.data_dir, basins=self.basins)\n\n # remove all attributes not defined in the config\n drop_cols = [c for c in df.columns if c not in self.cfg.camels_attributes]\n df = df.drop(drop_cols, axis=1)\n\n return df\n\n\ndef load_camels_us_attributes(data_dir: Path, basins: List[str] = []) -> pd.DataFrame:\n \"\"\"Load CAMELS US attributes from the dataset provided by [#]_\n\n Parameters\n ----------\n data_dir : Path\n Path to the CAMELS US directory. This folder must contain a 'camels_attributes_v2.0' folder (the original \n data set) containing the corresponding txt files for each attribute group.\n basins : List[str], optional\n If passed, return only attributes for the basins specified in this list. Otherwise, the attributes of all basins\n are returned.\n\n Returns\n -------\n pandas.DataFrame\n Basin-indexed DataFrame, containing the attributes as columns.\n\n References\n ----------\n .. [#] Addor, N., Newman, A. J., Mizukami, N. and Clark, M. P.: The CAMELS data set: catchment attributes and \n meteorology for large-sample studies, Hydrol. Earth Syst. Sci., 21, 5293-5313, doi:10.5194/hess-21-5293-2017,\n 2017.\n \"\"\"\n attributes_path = Path(data_dir) / 'camels_attributes_v2.0'\n\n if not attributes_path.exists():\n raise RuntimeError(f\"Attribute folder not found at {attributes_path}\")\n\n txt_files = attributes_path.glob('camels_*.txt')\n\n # Read-in attributes into one big dataframe\n dfs = []\n for txt_file in txt_files:\n df_temp = pd.read_csv(txt_file, sep=';', header=0, dtype={'gauge_id': str})\n df_temp = df_temp.set_index('gauge_id')\n\n dfs.append(df_temp)\n\n df = pd.concat(dfs, axis=1)\n # convert huc column to double digit strings\n df['huc'] = df['huc_02'].apply(lambda x: str(x).zfill(2))\n df = df.drop('huc_02', axis=1)\n\n if basins:\n # drop rows of basins not contained in the passed list\n drop_basins = [b for b in df.index if b not in basins]\n df = df.drop(drop_basins, axis=0)\n\n return df\n\n\ndef load_camels_us_forcings(data_dir: Path, basin: str, forcings: str) -> Tuple[pd.DataFrame, int]:\n \"\"\"Load the forcing data for a basin of the CAMELS US data set.\n\n Parameters\n ----------\n data_dir : Path\n Path to the CAMELS US directory. This folder must contain a 'basin_mean_forcing' folder containing one \n subdirectory for each forcing. The forcing directories have to contain 18 subdirectories (for the 18 HUCS) as in\n the original CAMELS data set. In each HUC folder are the forcing files (.txt), starting with the 8-digit basin \n id.\n basin : str\n 8-digit USGS identifier of the basin.\n forcings : str\n Can be e.g. 'daymet' or 'nldas', etc. Must match the folder names in the 'basin_mean_forcing' directory. \n\n Returns\n -------\n pd.DataFrame\n Time-indexed DataFrame, containing the forcing data.\n int\n Catchment area (m2), specified in the header of the forcing file.\n \"\"\"\n forcing_path = data_dir / 'basin_mean_forcing' / forcings\n if not forcing_path.is_dir():\n raise OSError(f\"{forcing_path} does not exist\")\n\n files = list(forcing_path.glob('**/*_forcing_leap.txt'))\n file_path = [f for f in files if f.name[:8] == basin]\n if file_path:\n file_path = file_path[0]\n else:\n raise FileNotFoundError(f'No file for Basin {basin} at {file_path}')\n\n df = pd.read_csv(file_path, sep='\\s+', header=3)\n df[\"date\"] = pd.to_datetime(df.Year.map(str) + \"/\" + df.Mnth.map(str) + \"/\" + df.Day.map(str), format=\"%Y/%m/%d\")\n df = df.set_index(\"date\")\n\n # load area from header\n with open(file_path, 'r') as fp:\n content = fp.readlines()\n area = int(content[2])\n\n return df, area\n\n\ndef load_camels_us_discharge(data_dir: Path, basin: str, area: int) -> pd.Series:\n \"\"\"Load the discharge data for a basin of the CAMELS US data set.\n\n Parameters\n ----------\n data_dir : Path\n Path to the CAMELS US directory. This folder must contain a 'usgs_streamflow' folder with 18\n subdirectories (for the 18 HUCS) as in the original CAMELS data set. In each HUC folder are the discharge files \n (.txt), starting with the 8-digit basin id.\n basin : str\n 8-digit USGS identifier of the basin.\n area : int\n Catchment area (m2), used to normalize the discharge.\n\n Returns\n -------\n pd.Series\n Time-index pandas.Series of the discharge values (mm/day)\n \"\"\"\n\n discharge_path = data_dir / 'usgs_streamflow'\n files = list(discharge_path.glob('**/*_streamflow_qc.txt'))\n file_path = [f for f in files if f.name[:8] == basin]\n if file_path:\n file_path = file_path[0]\n else:\n raise FileNotFoundError(f'No file for Basin {basin} at {file_path}')\n\n col_names = ['basin', 'Year', 'Mnth', 'Day', 'QObs', 'flag']\n df = pd.read_csv(file_path, sep='\\s+', header=None, names=col_names)\n df[\"date\"] = pd.to_datetime(df.Year.map(str) + \"/\" + df.Mnth.map(str) + \"/\" + df.Day.map(str), format=\"%Y/%m/%d\")\n df = df.set_index(\"date\")\n\n # normalize discharge from cubic feed per second to mm per day\n df.QObs = 28316846.592 * df.QObs * 86400 / (area * 10**6)\n\n return df.QObs\n", "from typing import Dict, Tuple\n\nimport torch\nimport torch.nn as nn\n\nfrom neuralhydrology.modelzoo.basemodel import BaseModel\nfrom neuralhydrology.modelzoo.fc import FC\nfrom neuralhydrology.modelzoo.head import get_head\nfrom neuralhydrology.utils.config import Config\n\n\nclass EALSTM(BaseModel):\n \"\"\"Entity-Aware LSTM (EA-LSTM) model class.\n\n This model has been proposed by Kratzert et al. [#]_ as a variant of the standard LSTM. The main difference is that\n the input gate of the EA-LSTM is modulated using only the static inputs, while the dynamic (time series) inputs are\n used in all other parts of the model (i.e. forget gate, cell update gate and output gate).\n To control the initial forget gate bias, use the config argument `initial_forget_bias`. Often it is useful to set \n this value to a positive value at the start of the model training, to keep the forget gate closed and to facilitate\n the gradient flow. \n The `EALSTM` class does only support single timescale predictions. Use `MTSLSTM` to train an LSTM-based model and \n get predictions on multiple temporal resolutions at the same time.\n\n Parameters\n ----------\n cfg : Config\n The run configuration.\n \n References\n ----------\n .. [#] Kratzert, F., Klotz, D., Shalev, G., Klambauer, G., Hochreiter, S., and Nearing, G.: Towards learning \n universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets, \n Hydrol. Earth Syst. Sci., 23, 5089–5110, https://doi.org/10.5194/hess-23-5089-2019, 2019.\n \"\"\"\n # specify submodules of the model that can later be used for finetuning. Names must match class attributes\n module_parts = ['input_gate', 'dynamic_gates', 'head']\n\n def __init__(self, cfg: Config):\n super(EALSTM, self).__init__(cfg=cfg)\n self._hidden_size = cfg.hidden_size\n\n input_size_stat = len(cfg.static_inputs + cfg.camels_attributes + cfg.hydroatlas_attributes)\n if cfg.use_basin_id_encoding:\n input_size_stat += cfg.number_of_basins\n\n # If hidden units for a embedding network are specified, create FC, otherwise single linear layer\n if cfg.embedding_hiddens:\n self.input_gate = FC(cfg=cfg)\n else:\n self.input_gate = nn.Linear(input_size_stat, cfg.hidden_size)\n\n # create tensors of learnable parameters\n self.dynamic_gates = _DynamicGates(cfg=cfg)\n self.dropout = nn.Dropout(p=cfg.output_dropout)\n\n self.head = get_head(cfg=cfg, n_in=cfg.hidden_size, n_out=self.output_size)\n\n def _cell(self, x: torch.Tensor, i: torch.Tensor,\n states: Tuple[torch.Tensor, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Single time step logic of EA-LSTM cell\"\"\"\n h_0, c_0 = states\n\n # calculate gates\n gates = self.dynamic_gates(h_0, x)\n f, o, g = gates.chunk(3, 1)\n\n c_1 = torch.sigmoid(f) * c_0 + i * torch.tanh(g)\n h_1 = torch.sigmoid(o) * torch.tanh(c_1)\n\n return h_1, c_1\n\n def forward(self, data: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:\n \"\"\"Perform a forward pass on the EA-LSTM model.\n\n Parameters\n ----------\n data : Dict[str, torch.Tensor]\n Dictionary, containing input features as key-value pairs.\n\n Returns\n -------\n Dict[str, torch.Tensor]\n Model outputs and intermediate states as a dictionary. \n - `y_hat`: model predictions of shape [batch size, sequence length, number of target variables].\n - `h_n`: hidden state at the last time step of the sequence of shape \n [batch size, sequence length, number of target variables].\n - `c_n`: cell state at the last time step of the sequence of shape \n [batch size, sequence length, number of target variables].\n \"\"\"\n # transpose to [seq_length, batch_size, n_features]\n x_d = data['x_d'].transpose(0, 1)\n\n if 'x_s' in data and 'x_one_hot' in data:\n x_s = torch.cat([data['x_s'], data['x_one_hot']], dim=-1)\n elif 'x_s' in data:\n x_s = data['x_s']\n elif 'x_one_hot' in data:\n x_s = data['x_one_hot']\n else:\n raise ValueError('Need x_s or x_one_hot in forward pass.')\n\n # TODO: move hidden and cell state initialization to init and only reset states in forward pass to zero.\n h_t = x_d.data.new(x_d.shape[1], self._hidden_size).zero_()\n c_t = x_d.data.new(x_d.shape[1], self._hidden_size).zero_()\n\n # empty lists to temporally store all intermediate hidden/cell states\n h_n, c_n = [], []\n\n # calculate input gate only once because inputs are static\n i = torch.sigmoid(self.input_gate(x_s))\n\n # perform forward steps over input sequence\n for x_dt in x_d:\n\n h_t, c_t = self._cell(x_dt, i, (h_t, c_t))\n\n # store intermediate hidden/cell state in list\n h_n.append(h_t)\n c_n.append(c_t)\n\n h_n = torch.stack(h_n, 0).transpose(0, 1)\n c_n = torch.stack(c_n, 0).transpose(0, 1)\n\n pred = {'h_n': h_n, 'c_n': c_n}\n pred.update(self.head(self.dropout(h_n)))\n\n return pred\n\n\nclass _DynamicGates(nn.Module):\n \"\"\"Internal class to wrap the dynamic gate parameters into a dedicated PyTorch Module\"\"\"\n\n def __init__(self, cfg: Config):\n super(_DynamicGates, self).__init__()\n self.cfg = cfg\n self.weight_ih = nn.Parameter(torch.FloatTensor(len(cfg.dynamic_inputs), 3 * cfg.hidden_size))\n self.weight_hh = nn.Parameter(torch.FloatTensor(cfg.hidden_size, 3 * cfg.hidden_size))\n self.bias = nn.Parameter(torch.FloatTensor(3 * cfg.hidden_size))\n\n # initialize parameters\n self._reset_parameters()\n\n def _reset_parameters(self):\n \"\"\"Special initialization of certain model weights.\"\"\"\n nn.init.orthogonal_(self.weight_ih.data)\n\n weight_hh_data = torch.eye(self.cfg.hidden_size)\n weight_hh_data = weight_hh_data.repeat(1, 3)\n self.weight_hh.data = weight_hh_data\n\n nn.init.constant_(self.bias.data, val=0)\n\n if self.cfg.initial_forget_bias is not None:\n self.bias.data[:self.cfg.hidden_size] = self.cfg.initial_forget_bias\n\n def forward(self, h: torch.Tensor, x_d: torch.Tensor):\n gates = h @ self.weight_hh + x_d @ self.weight_ih + self.bias\n return gates\n" ]
[ [ "pandas.concat", "pandas.read_csv" ], [ "torch.nn.Dropout", "torch.sigmoid", "torch.cat", "torch.nn.init.constant_", "torch.eye", "torch.tanh", "torch.nn.Linear", "torch.FloatTensor", "torch.nn.init.orthogonal_", "torch.stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
biomac-lab/covid19_forecast
[ "6613064f8a6d8023ecbdaddbc2e7525b6ad0796f" ]
[ "functions/plot_utils.py" ]
[ "from matplotlib.dates import date2num, num2date\nfrom matplotlib.colors import ListedColormap\nfrom matplotlib import dates as mdates\nfrom matplotlib.patches import Patch\nfrom matplotlib import pyplot as plt\nfrom matplotlib import ticker\n\nimport os\n\ndef plot_fit(df_fit, df_data, y_label='Deaths', y_lim_up = 200, color='blue', col_data='smoothed_death', col_up='high_95', col_down='low_95', col_point='median', ax=None, sharey=True, forecast=True, path_to_save=None):\n \"\"\" df_fit with columns:\n 'mean', 'median', 'std', 'low_95', 'high_95', 'low_80', 'high_80', 'low_50', 'high_50', 'type'\n type in ['estimate', 'forecast']\n\n df_data with columns:\n 'confirmed', 'death', 'smoothed_confirmed', 'smoothed_death', 'type'\n type in ['fitted', 'preliminary']\n \"\"\"\n\n df_estimate = df_fit.copy(); df_estimate = df_estimate[ df_estimate.type=='estimate' ]\n df_forecast = df_fit.copy(); df_forecast = df_forecast[ df_forecast.type=='forecast' ]\n\n df_data_fitted = df_data.copy(); df_data_fitted = df_data_fitted[df_data_fitted.type=='fitted']\n df_data_preliminary = df_data.copy(); df_data_preliminary = df_data_preliminary[df_data_preliminary.type=='preliminary']\n\n fig, axes = plt.subplots(1, 2, figsize=(20, 7), sharey=sharey)\n axes[0].fill_between(df_estimate.index.values, df_estimate[col_down], df_estimate[col_up], color='gray', alpha=0.4, label='95 CI - Nowcast')\n axes[0].plot(df_estimate.index.values, df_estimate[col_point], color='black', alpha=0.4, label='Median - Nowcast')\n\n axes[0].scatter(df_data_fitted.index.values, df_data_fitted[col_data], facecolor='black', alpha=0.6, edgecolor='black', s=30)\n (y1_l, y2_l) = axes[0].get_ylim()\n\n axes[0].fill_between(df_forecast.index.values, df_forecast[col_down], df_forecast[col_up], color=color, alpha=0.6, label='95% CI')\n axes[0].fill_between(df_forecast.index.values, df_forecast['low_80'], df_forecast['high_80'], color=color, alpha=0.4, label='80% CI')\n axes[0].fill_between(df_forecast.index.values, df_forecast['low_50'], df_forecast['high_50'], color=color, alpha=0.4, label='50% CI')\n\n axes[0].plot(df_forecast.index.values, df_forecast[col_point], color=color, alpha=0.4, label='Forecast - Median')\n axes[0].scatter(df_forecast.index.values, df_forecast[col_point], edgecolor='k', facecolor='white', s=10)\n axes[0].tick_params(axis='both', labelsize=15)\n\n axes[1].fill_between(df_estimate.iloc[-10:].index.values, df_estimate.iloc[-10:][col_up], df_estimate.iloc[-10:][col_down], color='gray', alpha=0.4)\n axes[1].plot(df_estimate.iloc[-10:].index.values, df_estimate.iloc[-10:][col_point], color='black', alpha=0.4)\n axes[1].fill_between(df_forecast.index.values, df_forecast[col_down], df_forecast[col_up], color=color, alpha=0.2, label='90% CI')\n axes[1].fill_between(df_forecast.index.values, df_forecast['low_80'], df_forecast['high_80'], color=color, alpha=0.4, label='80% CI')\n axes[1].fill_between(df_forecast.index.values, df_forecast['low_50'], df_forecast['high_50'], color=color, alpha=0.6, label='50% CI')\n\n axes[1].plot(df_forecast.index.values, df_forecast[col_point], color='black', alpha=0.4)\n axes[1].scatter(df_estimate.iloc[-10:].index.values, df_data_fitted.iloc[-10:][col_data], facecolor='black', alpha=0.6, edgecolor='black', s=50)\n axes[1].scatter(df_data_preliminary.index.values, df_data_preliminary[col_data], edgecolor='k', facecolor='red', s=50, label='Preliminary data')\n\n\n for ax in axes:\n ax.xaxis.set_major_locator(mdates.MonthLocator())\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))\n ax.xaxis.set_minor_locator(mdates.DayLocator())\n ax.xaxis.set_major_locator(mdates.WeekdayLocator())\n ax.xaxis.set_major_locator(mdates.MonthLocator())\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['left'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.grid(which='major', axis='y', c='k', alpha=.1, zorder=-2)\n ax.yaxis.set_major_formatter(ticker.StrMethodFormatter(\"{x:.0f}\"))\n ax.set_ylabel(y_label, size=15)\n ax.set_ylim( (y1_l, y_lim_up) )\n ax.legend(loc='upper left')\n\n axes[1].xaxis.set_major_locator(mdates.MonthLocator())\n axes[1].xaxis.set_major_formatter(mdates.DateFormatter('%d-%b'))\n axes[1].xaxis.set_minor_locator(mdates.DayLocator())\n axes[1].xaxis.set_minor_formatter(mdates.DateFormatter('%d'))\n\n axes[1].xaxis.set_major_locator(mdates.WeekdayLocator())\n axes[1].xaxis.set_major_locator(mdates.MonthLocator())\n axes[1].tick_params(which='both', axis='both', labelrotation=90, labelsize=15)\n\n axes[1].grid(which='both', axis='x', c='k', alpha=.1, zorder=-2)\n axes[0].grid(which='major', axis='x', c='k', alpha=.1, zorder=-2)\n plt.tight_layout()\n\n if path_to_save:\n fig.savefig(path_to_save, dpi=300, bbox_inches='tight', transparent=False)\n plt.close()" ]
[ [ "matplotlib.dates.DateFormatter", "matplotlib.pyplot.tight_layout", "matplotlib.dates.WeekdayLocator", "matplotlib.ticker.StrMethodFormatter", "matplotlib.pyplot.subplots", "matplotlib.pyplot.close", "matplotlib.dates.DayLocator", "matplotlib.dates.MonthLocator" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rekhabiswal/sage
[ "e8633b09919542a65e7e990c8369fee30c7edefd" ]
[ "src/sage/plot/arrow.py" ]
[ "\"\"\"\nArrows\n\"\"\"\n#*****************************************************************************\n# Copyright (C) 2006 Alex Clemesha <[email protected]>,\n# William Stein <[email protected]>,\n# 2008 Mike Hansen <[email protected]>,\n# 2009 Emily Kirkman\n#\n# Distributed under the terms of the GNU General Public License (GPL)\n#\n# This code is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# The full text of the GPL is available at:\n#\n# http://www.gnu.org/licenses/\n#*****************************************************************************\nfrom sage.plot.primitive import GraphicPrimitive\nfrom sage.misc.decorators import options, rename_keyword\nfrom sage.plot.colors import to_mpl_color\n\n\nclass CurveArrow(GraphicPrimitive):\n def __init__(self, path, options):\n \"\"\"\n Returns an arrow graphics primitive along the provided path (bezier curve).\n\n EXAMPLES::\n\n sage: from sage.plot.arrow import CurveArrow\n sage: b = CurveArrow(path=[[(0,0),(.5,.5),(1,0)],[(.5,1),(0,0)]],\n ....: options={})\n sage: b\n CurveArrow from (0, 0) to (0, 0)\n \"\"\"\n import numpy as np\n self.path = path\n codes = [1] + (len(self.path[0])-1)*[len(self.path[0])]\n vertices = self.path[0]\n for curve in self.path[1:]:\n vertices += curve\n codes += (len(curve))*[len(curve)+1]\n self.codes = codes\n self.vertices = np.array(vertices, np.float)\n GraphicPrimitive.__init__(self, options)\n\n def get_minmax_data(self):\n \"\"\"\n Returns a dictionary with the bounding box data.\n\n EXAMPLES::\n\n sage: from sage.plot.arrow import CurveArrow\n sage: b = CurveArrow(path=[[(0,0),(.5,.5),(1,0)],[(.5,1),(0,0)]],\n ....: options={})\n sage: d = b.get_minmax_data()\n sage: d['xmin']\n 0.0\n sage: d['xmax']\n 1.0\n \"\"\"\n return {'xmin': self.vertices[:,0].min(),\n 'xmax': self.vertices[:,0].max(),\n 'ymin': self.vertices[:,1].min(),\n 'ymax': self.vertices[:,1].max()}\n\n def _allowed_options(self):\n \"\"\"\n Return the dictionary of allowed options for the curve arrow graphics\n primitive.\n\n EXAMPLES::\n\n sage: from sage.plot.arrow import CurveArrow\n sage: list(sorted(CurveArrow(path=[[(0,0),(2,3)]],options={})._allowed_options().items()))\n [('arrowsize', 'The size of the arrowhead'),\n ('arrowstyle', 'todo'),\n ('head', '2-d only: Which end of the path to draw the head (one of 0 (start), 1 (end) or 2 (both)'),\n ('hue', 'The color given as a hue.'),\n ('legend_color', 'The color of the legend text.'),\n ('legend_label', 'The label for this item in the legend.'),\n ('linestyle', \"2d only: The style of the line, which is one of\n 'dashed', 'dotted', 'solid', 'dashdot', or '--', ':', '-', '-.',\n respectively.\"),\n ('rgbcolor', 'The color as an RGB tuple.'),\n ('thickness', 'The thickness of the arrow.'),\n ('width', 'The width of the shaft of the arrow, in points.'),\n ('zorder', '2-d only: The layer level in which to draw')]\n \"\"\"\n return {'width': 'The width of the shaft of the arrow, in points.',\n 'rgbcolor': 'The color as an RGB tuple.',\n 'hue': 'The color given as a hue.',\n 'legend_label': 'The label for this item in the legend.',\n 'legend_color': 'The color of the legend text.',\n 'arrowstyle': 'todo',\n 'arrowsize': 'The size of the arrowhead',\n 'thickness': 'The thickness of the arrow.',\n 'zorder': '2-d only: The layer level in which to draw',\n 'head': '2-d only: Which end of the path to draw the head (one of 0 (start), 1 (end) or 2 (both)',\n 'linestyle': \"2d only: The style of the line, which is one of \"\n \"'dashed', 'dotted', 'solid', 'dashdot', or '--', ':', '-', '-.', \"\n \"respectively.\"}\n\n def _repr_(self):\n \"\"\"\n Text representation of an arrow graphics primitive.\n\n EXAMPLES::\n\n sage: from sage.plot.arrow import CurveArrow\n sage: CurveArrow(path=[[(0,0),(1,4),(2,3)]],options={})._repr_()\n 'CurveArrow from (0, 0) to (2, 3)'\n \"\"\"\n return \"CurveArrow from %s to %s\" % (self.path[0][0], self.path[-1][-1])\n\n def _render_on_subplot(self, subplot):\n \"\"\"\n Render this arrow in a subplot. This is the key function that\n defines how this arrow graphics primitive is rendered in\n matplotlib's library.\n\n EXAMPLES::\n\n This function implicitly ends up rendering this arrow on a matplotlib\n subplot:\n sage: arrow(path=[[(0,1), (2,-1), (4,5)]])\n Graphics object consisting of 1 graphics primitive\n \"\"\"\n from sage.plot.misc import get_matplotlib_linestyle\n\n options = self.options()\n width = float(options['width'])\n head = options.pop('head')\n if head == 0: style = '<|-'\n elif head == 1: style = '-|>'\n elif head == 2: style = '<|-|>'\n else: raise KeyError('head parameter must be one of 0 (start), 1 (end) or 2 (both).')\n arrowsize = float(options.get('arrowsize', 5))\n head_width = arrowsize\n head_length = arrowsize * 2.0\n color = to_mpl_color(options['rgbcolor'])\n from matplotlib.patches import FancyArrowPatch\n from matplotlib.path import Path\n bpath = Path(self.vertices, self.codes)\n p = FancyArrowPatch(path=bpath,\n lw=width, arrowstyle='%s,head_width=%s,head_length=%s' % (style, head_width, head_length),\n fc=color, ec=color, \n linestyle=get_matplotlib_linestyle(options['linestyle'], return_type='long'))\n p.set_zorder(options['zorder'])\n p.set_label(options['legend_label'])\n subplot.add_patch(p)\n return p\n\n\nclass Arrow(GraphicPrimitive):\n \"\"\"\n Primitive class that initializes the (line) arrow graphics type\n\n EXAMPLES:\n\n We create an arrow graphics object, then take the 0th entry\n in it to get the actual Arrow graphics primitive::\n\n sage: P = arrow((0,1), (2,3))[0]\n sage: type(P)\n <class 'sage.plot.arrow.Arrow'>\n sage: P\n Arrow from (0.0,1.0) to (2.0,3.0)\n \"\"\"\n def __init__(self, xtail, ytail, xhead, yhead, options):\n \"\"\"\n Create an arrow graphics primitive.\n\n EXAMPLES::\n\n sage: from sage.plot.arrow import Arrow\n sage: Arrow(0,0,2,3,{})\n Arrow from (0.0,0.0) to (2.0,3.0)\n \"\"\"\n self.xtail = float(xtail)\n self.xhead = float(xhead)\n self.ytail = float(ytail)\n self.yhead = float(yhead)\n GraphicPrimitive.__init__(self, options)\n\n def get_minmax_data(self):\n \"\"\"\n Returns a bounding box for this arrow.\n\n EXAMPLES::\n\n sage: d = arrow((1,1), (5,5)).get_minmax_data()\n sage: d['xmin']\n 1.0\n sage: d['xmax']\n 5.0\n \"\"\"\n return {'xmin': min(self.xtail, self.xhead),\n 'xmax': max(self.xtail, self.xhead),\n 'ymin': min(self.ytail, self.yhead),\n 'ymax': max(self.ytail, self.yhead)}\n\n def _allowed_options(self):\n \"\"\"\n Return the dictionary of allowed options for the line arrow graphics\n primitive.\n\n EXAMPLES::\n\n sage: from sage.plot.arrow import Arrow\n sage: list(sorted(Arrow(0,0,2,3,{})._allowed_options().items()))\n [('arrowshorten', 'The length in points to shorten the arrow.'),\n ('arrowsize', 'The size of the arrowhead'),\n ('head',\n '2-d only: Which end of the path to draw the head (one of 0 (start), 1 (end) or 2 (both)'),\n ('hue', 'The color given as a hue.'),\n ('legend_color', 'The color of the legend text.'),\n ('legend_label', 'The label for this item in the legend.'),\n ('linestyle',\n \"2d only: The style of the line, which is one of 'dashed',\n 'dotted', 'solid', 'dashdot', or '--', ':', '-', '-.',\n respectively.\"),\n ('rgbcolor', 'The color as an RGB tuple.'),\n ('thickness', 'The thickness of the arrow.'),\n ('width', 'The width of the shaft of the arrow, in points.'),\n ('zorder', '2-d only: The layer level in which to draw')]\n \"\"\"\n return {'width': 'The width of the shaft of the arrow, in points.',\n 'rgbcolor': 'The color as an RGB tuple.',\n 'hue': 'The color given as a hue.',\n 'arrowshorten': 'The length in points to shorten the arrow.',\n 'arrowsize': 'The size of the arrowhead',\n 'thickness': 'The thickness of the arrow.',\n 'legend_label': 'The label for this item in the legend.',\n 'legend_color': 'The color of the legend text.',\n 'zorder': '2-d only: The layer level in which to draw',\n 'head': '2-d only: Which end of the path to draw the head (one of 0 (start), 1 (end) or 2 (both)',\n 'linestyle': \"2d only: The style of the line, which is one of \"\n \"'dashed', 'dotted', 'solid', 'dashdot', or '--', ':', '-', '-.', \"\n \"respectively.\"}\n\n def _plot3d_options(self, options=None):\n \"\"\"\n Translate 2D plot options into 3D plot options.\n\n EXAMPLES::\n\n sage: P = arrow((0,1), (2,3), width=5)\n sage: p=P[0]; p\n Arrow from (0.0,1.0) to (2.0,3.0)\n sage: q=p.plot3d()\n sage: q.thickness\n 5\n \"\"\"\n if options is None:\n options = self.options()\n options = dict(self.options())\n options_3d = {}\n if 'width' in options:\n options_3d['thickness'] = options['width']\n del options['width']\n # ignore zorder and head in 3d plotting\n if 'zorder' in options:\n del options['zorder']\n if 'head' in options:\n del options['head']\n if 'linestyle' in options:\n del options['linestyle']\n options_3d.update(GraphicPrimitive._plot3d_options(self, options))\n return options_3d\n\n def plot3d(self, ztail=0, zhead=0, **kwds):\n \"\"\"\n Takes 2D plot and places it in 3D.\n\n EXAMPLES::\n\n sage: A = arrow((0,0),(1,1))[0].plot3d()\n sage: A.jmol_repr(A.testing_render_params())[0]\n 'draw line_1 diameter 2 arrow {0.0 0.0 0.0} {1.0 1.0 0.0} '\n\n Note that we had to index the arrow to get the Arrow graphics\n primitive. We can also change the height via the :meth:`Graphics.plot3d`\n method, but only as a whole::\n\n sage: A = arrow((0,0),(1,1)).plot3d(3)\n sage: A.jmol_repr(A.testing_render_params())[0][0]\n 'draw line_1 diameter 2 arrow {0.0 0.0 3.0} {1.0 1.0 3.0} '\n\n Optional arguments place both the head and tail outside the\n `xy`-plane, but at different heights. This must be done on\n the graphics primitive obtained by indexing::\n\n sage: A=arrow((0,0),(1,1))[0].plot3d(3,4)\n sage: A.jmol_repr(A.testing_render_params())[0]\n 'draw line_1 diameter 2 arrow {0.0 0.0 3.0} {1.0 1.0 4.0} '\n \"\"\"\n from sage.plot.plot3d.shapes2 import line3d\n options = self._plot3d_options()\n options.update(kwds)\n return line3d([(self.xtail, self.ytail, ztail), (self.xhead, self.yhead, zhead)], arrow_head=True, **options)\n\n def _repr_(self):\n \"\"\"\n Text representation of an arrow graphics primitive.\n\n EXAMPLES::\n\n sage: from sage.plot.arrow import Arrow\n sage: Arrow(0,0,2,3,{})._repr_()\n 'Arrow from (0.0,0.0) to (2.0,3.0)'\n \"\"\"\n return \"Arrow from (%s,%s) to (%s,%s)\" % (self.xtail, self.ytail, self.xhead, self.yhead)\n\n def _render_on_subplot(self, subplot):\n r\"\"\"\n Render this arrow in a subplot. This is the key function that\n defines how this arrow graphics primitive is rendered in\n matplotlib's library.\n\n EXAMPLES:\n\n This function implicitly ends up rendering this arrow on\n a matplotlib subplot::\n\n sage: arrow((0,1), (2,-1))\n Graphics object consisting of 1 graphics primitive\n\n TESTS:\n\n The length of the ends (shrinkA and shrinkB) should not depend\n on the width of the arrow, because Matplotlib already takes\n this into account. See :trac:`12836`::\n\n sage: fig = Graphics().matplotlib()\n sage: sp = fig.add_subplot(1,1,1, label='axis1')\n sage: a = arrow((0,0), (1,1))\n sage: b = arrow((0,0), (1,1), width=20)\n sage: p1 = a[0]._render_on_subplot(sp)\n sage: p2 = b[0]._render_on_subplot(sp)\n sage: p1.shrinkA == p2.shrinkA\n True\n sage: p1.shrinkB == p2.shrinkB\n True\n\n Dashed arrows should have solid arrowheads,\n :trac:`12852`. This test saves the plot of a dashed arrow to\n an EPS file. Within the EPS file, ``stroke`` will be called\n twice: once to draw the line, and again to draw the\n arrowhead. We check that both calls do not occur while the\n dashed line style is enabled::\n\n sage: a = arrow((0,0), (1,1), linestyle='dashed')\n sage: filename = tmp_filename(ext='.eps')\n sage: a.save(filename=filename)\n sage: with open(filename, 'r') as f:\n ....: contents = f.read().replace('\\n', ' ')\n sage: two_stroke_pattern = r'setdash.*stroke.*stroke.*setdash.*setdash'\n sage: import re\n sage: two_stroke_re = re.compile(two_stroke_pattern)\n sage: two_stroke_re.search(contents) is None\n True\n \"\"\"\n from sage.plot.misc import get_matplotlib_linestyle\n\n options = self.options()\n head = options.pop('head')\n if head == 0: style = '<|-'\n elif head == 1: style = '-|>'\n elif head == 2: style = '<|-|>'\n else: raise KeyError('head parameter must be one of 0 (start), 1 (end) or 2 (both).')\n width = float(options['width'])\n arrowshorten_end = float(options.get('arrowshorten', 0)) / 2.0\n arrowsize = float(options.get('arrowsize', 5))\n head_width = arrowsize\n head_length = arrowsize * 2.0\n color = to_mpl_color(options['rgbcolor'])\n from matplotlib.patches import FancyArrowPatch\n p = FancyArrowPatch((self.xtail, self.ytail), (self.xhead, self.yhead),\n lw=width,\n arrowstyle='%s,head_width=%s,head_length=%s' % (style, head_width, head_length),\n shrinkA=arrowshorten_end, shrinkB=arrowshorten_end,\n fc=color, ec=color,\n linestyle=get_matplotlib_linestyle(options['linestyle'], return_type='long'))\n p.set_zorder(options['zorder'])\n p.set_label(options['legend_label'])\n\n if options['linestyle'] != 'solid':\n # The next few lines work around a design issue in matplotlib.\n # Currently, the specified linestyle is used to draw both the path\n # and the arrowhead. If linestyle is 'dashed', this looks really\n # odd. This code is from Jae-Joon Lee in response to a post to the\n # matplotlib mailing list.\n # See http://sourceforge.net/mailarchive/forum.php?thread_name=CAG%3DuJ%2Bnw2dE05P9TOXTz_zp-mGP3cY801vMH7yt6vgP9_WzU8w%40mail.gmail.com&forum_name=matplotlib-users\n\n import matplotlib.patheffects as pe\n\n class CheckNthSubPath(object):\n def __init__(self, patch, n):\n \"\"\"\n creates an callable object that returns True if the\n provided path is the n-th path from the patch.\n \"\"\"\n self._patch = patch\n self._n = n\n\n def get_paths(self, renderer):\n self._patch.set_dpi_cor(renderer.points_to_pixels(1.))\n paths, fillables = self._patch.get_path_in_displaycoord()\n return paths\n\n def __call__(self, renderer, gc, tpath, affine, rgbFace):\n path = self.get_paths(renderer)[self._n]\n vert1, code1 = path.vertices, path.codes\n import numpy as np\n\n return np.array_equal(vert1, tpath.vertices) and np.array_equal(code1, tpath.codes)\n\n class ConditionalStroke(pe.RendererBase):\n\n def __init__(self, condition_func, pe_list):\n \"\"\"\n path effect that is only applied when the condition_func\n returns True.\n \"\"\"\n super(ConditionalStroke, self).__init__()\n self._pe_list = pe_list\n self._condition_func = condition_func\n\n def draw_path(self, renderer, gc, tpath, affine, rgbFace):\n\n if self._condition_func(renderer, gc, tpath, affine, rgbFace):\n for pe1 in self._pe_list:\n pe1.draw_path(renderer, gc, tpath, affine, rgbFace)\n\n pe1 = ConditionalStroke(CheckNthSubPath(p, 0), [pe.Stroke()])\n pe2 = ConditionalStroke(CheckNthSubPath(p, 1), [pe.Stroke(dashes={'dash_offset': 0, 'dash_list': None})])\n p.set_path_effects([pe1, pe2])\n\n subplot.add_patch(p)\n return p\n\n\ndef arrow(tailpoint=None, headpoint=None, **kwds):\n \"\"\"\n Returns either a 2-dimensional or 3-dimensional arrow depending\n on value of points.\n\n For information regarding additional arguments, see either arrow2d?\n or arrow3d?.\n\n EXAMPLES::\n\n sage: arrow((0,0), (1,1))\n Graphics object consisting of 1 graphics primitive\n\n .. PLOT::\n\n sphinx_plot(arrow((0,0), (1,1)))\n\n ::\n\n sage: arrow((0,0,1), (1,1,1))\n Graphics3d Object\n\n .. PLOT::\n\n sphinx_plot(arrow((0,0,1), (1,1,1)))\n\n \"\"\"\n try:\n return arrow2d(tailpoint, headpoint, **kwds)\n except ValueError:\n from sage.plot.plot3d.shapes import arrow3d\n return arrow3d(tailpoint, headpoint, **kwds)\n\n\n@rename_keyword(color='rgbcolor')\n@options(width=2, rgbcolor=(0,0,1), zorder=2, head=1, linestyle='solid', legend_label=None)\ndef arrow2d(tailpoint=None, headpoint=None, path=None, **options):\n \"\"\"\n If ``tailpoint`` and ``headpoint`` are provided, returns an arrow from\n (xtail, ytail) to (xhead, yhead). If ``tailpoint`` or ``headpoint`` is None and\n ``path`` is not None, returns an arrow along the path. (See further info on\n paths in :class:`bezier_path`).\n\n INPUT:\n\n - ``tailpoint`` - the starting point of the arrow\n\n - ``headpoint`` - where the arrow is pointing to\n\n - ``path`` - the list of points and control points (see bezier_path for\n detail) that the arrow will follow from source to destination\n\n - ``head`` - 0, 1 or 2, whether to draw the head at the start (0), end (1)\n or both (2) of the path (using 0 will swap headpoint and tailpoint).\n This is ignored in 3D plotting.\n\n - ``linestyle`` - (default: ``'solid'``) The style of the line, which is\n one of ``'dashed'``, ``'dotted'``, ``'solid'``, ``'dashdot'``,\n or ``'--'``, ``':'``, ``'-'``, ``'-.'``, respectively.\n\n - ``width`` - (default: 2) the width of the arrow shaft, in points\n\n - ``color`` - (default: (0,0,1)) the color of the arrow (as an RGB tuple or\n a string)\n\n - ``hue`` - the color of the arrow (as a number)\n\n - ``arrowsize`` - the size of the arrowhead\n\n - ``arrowshorten`` - the length in points to shorten the arrow (ignored if\n using path parameter)\n\n - ``legend_label`` - the label for this item in the legend\n\n - ``legend_color`` - the color for the legend label\n\n - ``zorder`` - the layer level to draw the arrow-- note that this is\n ignored in 3D plotting.\n\n EXAMPLES:\n\n A straight, blue arrow::\n\n sage: arrow2d((1,1), (3,3))\n Graphics object consisting of 1 graphics primitive\n\n .. PLOT::\n\n sphinx_plot(arrow2d((1,1), (3,3)))\n\n Make a red arrow::\n\n sage: arrow2d((-1,-1), (2,3), color=(1,0,0))\n Graphics object consisting of 1 graphics primitive\n\n .. PLOT::\n\n sphinx_plot(arrow2d((-1,-1), (2,3), color=(1,0,0)))\n\n ::\n\n sage: arrow2d((-1,-1), (2,3), color='red')\n Graphics object consisting of 1 graphics primitive\n\n .. PLOT::\n\n sphinx_plot(arrow2d((-1,-1), (2,3), color='red'))\n\n You can change the width of an arrow::\n\n sage: arrow2d((1,1), (3,3), width=5, arrowsize=15)\n Graphics object consisting of 1 graphics primitive\n\n .. PLOT::\n\n P = arrow2d((1,1), (3,3), width=5, arrowsize=15)\n sphinx_plot(P)\n\n Use a dashed line instead of a solid one for the arrow::\n\n sage: arrow2d((1,1), (3,3), linestyle='dashed')\n Graphics object consisting of 1 graphics primitive\n sage: arrow2d((1,1), (3,3), linestyle='--')\n Graphics object consisting of 1 graphics primitive\n\n .. PLOT::\n\n P = arrow2d((1,1), (3,3), linestyle='--')\n sphinx_plot(P)\n\n A pretty circle of arrows::\n\n sage: sum([arrow2d((0,0), (cos(x),sin(x)), hue=x/(2*pi)) for x in [0..2*pi,step=0.1]])\n Graphics object consisting of 63 graphics primitives\n\n .. PLOT::\n\n P = sum([arrow2d((0,0), (cos(x*0.1),sin(x*0.1)), hue=x/(20*pi)) for x in range(floor(20*pi)+1)])\n sphinx_plot(P)\n\n If we want to draw the arrow between objects, for example, the\n boundaries of two lines, we can use the ``arrowshorten`` option\n to make the arrow shorter by a certain number of points::\n\n sage: L1 = line([(0,0), (1,0)], thickness=10)\n sage: L2 = line([(0,1), (1,1)], thickness=10)\n sage: A = arrow2d((0.5,0), (0.5,1), arrowshorten=10, rgbcolor=(1,0,0))\n sage: L1 + L2 + A\n Graphics object consisting of 3 graphics primitives\n\n .. PLOT::\n\n L1 = line([(0,0), (1,0)],thickness=10)\n L2 = line([(0,1), (1,1)], thickness=10)\n A = arrow2d((0.5,0), (0.5,1), arrowshorten=10, rgbcolor=(1,0,0))\n sphinx_plot(L1 + L2 + A)\n\n If BOTH ``headpoint`` and ``tailpoint`` are None, then an empty plot is\n returned::\n\n sage: arrow2d(headpoint=None, tailpoint=None)\n Graphics object consisting of 0 graphics primitives\n\n We can also draw an arrow with a legend::\n\n sage: arrow((0,0), (0,2), legend_label='up', legend_color='purple')\n Graphics object consisting of 1 graphics primitive\n\n .. PLOT::\n\n P = arrow((0,0), (0,2), legend_label='up', legend_color='purple')\n sphinx_plot(P)\n\n Extra options will get passed on to :meth:`Graphics.show()`, as long as they are valid::\n\n sage: arrow2d((-2,2), (7,1), frame=True)\n Graphics object consisting of 1 graphics primitive\n\n .. PLOT::\n\n sphinx_plot(arrow2d((-2,2), (7,1), frame=True))\n\n ::\n\n sage: arrow2d((-2,2), (7,1)).show(frame=True)\n \"\"\"\n from sage.plot.all import Graphics\n g = Graphics()\n g._set_extra_kwds(Graphics._extract_kwds_for_show(options))\n\n if headpoint is not None and tailpoint is not None:\n xtail, ytail = tailpoint\n xhead, yhead = headpoint\n g.add_primitive(Arrow(xtail, ytail, xhead, yhead, options=options))\n elif path is not None:\n g.add_primitive(CurveArrow(path, options=options))\n elif tailpoint is None and headpoint is None:\n return g\n else:\n raise TypeError('Arrow requires either both headpoint and tailpoint or a path parameter.')\n if options['legend_label']:\n g.legend(True)\n g._legend_colors = [options['legend_color']]\n return g\n" ]
[ [ "matplotlib.path.Path", "numpy.array", "numpy.array_equal", "matplotlib.patheffects.Stroke" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Nirmal1313/Regression-Methods
[ "b1f885dc798ca4aae47661e0a27fe0e21e4ee4e0" ]
[ "Linear_Ridge_Regression .py" ]
[ "\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd # for working with data in Python\nimport numpy as np\nimport matplotlib.pyplot as plt # for visualization\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn import linear_model\n\n# use Pandas to read in csv files. The pd.read_csv() method creates a DataFrame from a csv file\ntrain = pd.read_csv('train.csv')\ntest = pd.read_csv('test.csv')\n\nprint(\"1 \\n\")\n\n# check out the size of the data\nprint(\"Train data shape:\", train.shape)\nprint(\"Test data shape:\", test.shape)\n\n\n\nprint(\"2 \\n\")\n\n# look at a few rows using the DataFrame.head() method\n# train.head()\nprint(train.head())\n\n\n# In[3]:\n\n\nplt.style.use(style='ggplot')\nplt.rcParams['figure.figsize'] = (10, 6)\n\n\n#######################################################\n# 2. Explore the data and engineer Features ###\n#######################################################\n\nprint(\"3 \\n\")\n\n\n# In[4]:\n\n\n# to get more information like count, mean, std, min, max etc\n# train.SalePrice.describe()\nprint (train.SalePrice.describe())\n\nprint(\"4 \\n\")\n\n# to plot a histogram of SalePrice\nprint (\"Skew is:\", train.SalePrice.skew())\nplt.hist(train.SalePrice, color='blue')\nplt.show()\n\nprint(\"5 \\n\")\n\n\n# In[5]:\n\n\n# use np.log() to transform train.SalePric and calculate the skewness a second time, as well as re-plot the data\ntarget = np.log(train.SalePrice)\nprint (\"\\n Skew is:\", target.skew())\nplt.hist(target, color='blue')\nplt.show()\n\n\n# In[6]:\n\n\n# return a subset of columns matching the specified data types\nnumeric_features = train.select_dtypes(include=[np.number])\n# numeric_features.dtypes\nprint(numeric_features.dtypes)\n\n\n# In[7]:\n\n\ncorr = numeric_features.corr()\n\n# The first five features are the most positively correlated with SalePrice, while the next five are the most negatively correlated.\nprint (corr['SalePrice'].sort_values(ascending=False)[:5], '\\n')\nprint (corr['SalePrice'].sort_values(ascending=False)[-5:])\n\n\n# In[8]:\n\n\nprint(train.OverallQual.unique())\n\"\"\"\nprint(\"9 \\n\")\n\"\"\"\n#investigate the relationship between OverallQual and SalePrice.\n#We set index='OverallQual' and values='SalePrice'. We chose to look at the median here.\nquality_pivot = train.pivot_table(index='OverallQual', values='SalePrice', aggfunc=np.median)\nprint(quality_pivot)\n\n\n# In[11]:\n\n\n#visualize this pivot table more easily, we can create a bar plot\n#Notice that the median sales price strictly increases as Overall Quality increases.\nquality_pivot.plot(kind='bar', color='blue')\nplt.xlabel('Overall Quality')\nplt.ylabel('Median Sale Price')\nplt.xticks(rotation=0)\nplt.show()\n\n\n# In[12]:\n\n\nprint(\"11 \\n\")\n\"\"\"\n#to generate some scatter plots and visualize the relationship between the Ground Living Area(GrLivArea) and SalePrice\nplt.scatter(x=train['GrLivArea'], y=target)\nplt.ylabel('Sale Price')\nplt.xlabel('Above grade (ground) living area square feet')\nplt.show()\n\"\"\"\nprint(\"12 \\n\")\n\n# do the same for GarageArea.\nplt.scatter(x=train['GarageArea'], y=target)\nplt.ylabel('Sale Price')\nplt.xlabel('Garage Area')\nplt.show()\n\n\n# In[13]:\n\n\n# create a new dataframe with some outliers removed\ntrain = train[train['GarageArea'] < 1200]\n\n# display the previous graph again without outliers\nplt.scatter(x=train['GarageArea'], y=np.log(train.SalePrice))\nplt.xlim(-200,1600) # This forces the same scale as before\nplt.ylabel('Sale Price')\nplt.xlabel('Garage Area')\nplt.show()\n\n\n# In[14]:\n\n\n# create a DataFrame to view the top null columns and return the counts of the null values in each column\nnulls = pd.DataFrame(train.isnull().sum().sort_values(ascending=False)[:25])\nnulls.columns = ['Null Count']\nnulls.index.name = 'Feature'\n#nulls\nprint(nulls)\n\n\n# In[15]:\n\n\nprint(\"15 \\n\")\n\"\"\"\n#to return a list of the unique values\nprint (\"Unique values are:\", train.MiscFeature.unique())\n\"\"\"\n\n######################################################\n# Wrangling the non-numeric Features ##\n######################################################\n\nprint(\"16 \\n\")\n\n# consider the non-numeric features and display details of columns\ncategoricals = train.select_dtypes(exclude=[np.number])\n#categoricals.describe()\nprint(categoricals.describe())\n\n\n# In[16]:\n\n\n#####################################################\n# Transforming and engineering features ##\n######################################################\n\nprint(\"17 \\n\")\n\n# When transforming features, it's important to remember that any transformations that you've applied to the training data before\n# fitting the model must be applied to the test data.\n\n#Eg:\nprint (\"Original: \\n\")\nprint (train.Street.value_counts(), \"\\n\")\n\n\n# In[17]:\n\n\nprint(\"18 \\n\")\n\n# our model needs numerical data, so we will use one-hot encoding to transform the data into a Boolean column.\n# create a new column called enc_street. The pd.get_dummies() method will handle this for us\ntrain['enc_street'] = pd.get_dummies(train.Street, drop_first=True)\ntest['enc_street'] = pd.get_dummies(test.Street, drop_first=True)\n\nprint ('Encoded: \\n')\nprint (train.enc_street.value_counts()) # Pave and Grvl values converted into 1 and 0\n\nprint(\"19 \\n\")\n\n# look at SaleCondition by constructing and plotting a pivot table, as we did above for OverallQual\ncondition_pivot = train.pivot_table(index='SaleCondition', values='SalePrice', aggfunc=np.median)\ncondition_pivot.plot(kind='bar', color='blue')\nplt.xlabel('Sale Condition')\nplt.ylabel('Median Sale Price')\nplt.xticks(rotation=0)\nplt.show()\n\n\n# In[18]:\n\n\n# encode this SaleCondition as a new feature by using a similar method that we used for Street above\ndef encode(x): return 1 if x == 'Partial' else 0\ntrain['enc_condition'] = train.SaleCondition.apply(encode)\ntest['enc_condition'] = test.SaleCondition.apply(encode)\n\nprint(\"20 \\n\")\n\n# explore this newly modified feature as a plot.\ncondition_pivot = train.pivot_table(index='enc_condition', values='SalePrice', aggfunc=np.median)\ncondition_pivot.plot(kind='bar', color='blue')\nplt.xlabel('Encoded Sale Condition')\nplt.ylabel('Median Sale Price')\nplt.xticks(rotation=0)\nplt.show()\n\n\n# In[19]:\n\n\n######################################################################################################\n# Dealing with missing values #\n# We'll fill the missing values with an average value and then assign the results to data #\n# This is a method of interpolation #\n######################################################################################################\ndata = train.select_dtypes(include=[np.number]).interpolate().dropna()\n\nprint(\"21 \\n\")\n# Check if the all of the columns have 0 null values.\n# sum(data.isnull().sum() != 0)\nprint(sum(data.isnull().sum() != 0))\n\nprint(\"22 \\n\")\n\n\n# In[20]:\n\n\n######################################################\n# 3. Build a linear model ##\n######################################################\n\n# separate the features and the target variable for modeling.\n# We will assign the features to X and the target variable(Sales Price)to y.\n\ny = np.log(train.SalePrice)\nX = data.drop(['SalePrice', 'Id'], axis=1)\n# exclude ID from features since Id is just an index with no relationship to SalePrice.\n\n#======= partition the data ===================================================================================================#\n# Partitioning the data in this way allows us to evaluate how our model might perform on data that it has never seen before.\n# If we train the model on all of the test data, it will be difficult to tell if overfitting has taken place.\n#==============================================================================================================================#\n# also state how many percentage from train data set, we want to take as test data set\n# In this example, about 33% of the data is devoted to the hold-out set.\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=.33)\n\n\n# In[21]:\n\n\n#========= Begin modelling =========================#\n# Linear Regression Model #\n#===================================================#\n\n# ---- first create a Linear Regression model.\n# First, we instantiate the model.\nlr = linear_model.LinearRegression()\n\n# ---- fit the model / Model fitting\n# lr.fit() method will fit the linear regression on the features and target variable that we pass.\nmodel = lr.fit(X_train, y_train)\n\nprint(\"23 \\n\")\n\n\n# In[22]:\n\n\n\n# ---- Evaluate the performance and visualize results\n# r-squared value is a measure of how close the data are to the fitted regression line\n# a higher r-squared value means a better fit(very close to value 1)\nprint(\"R^2 is: \\n\", model.score(X_test, y_test))\n\n# use the model we have built to make predictions on the test data set.\npredictions = model.predict(X_test)\n\nprint(\"24 \\n\")\n\n\n# In[23]:\n\n\nprint('RMSE is: \\n', mean_squared_error(y_test, predictions))\n\nprint(\"25 \\n\")\n# view this relationship between predictions and actual_values graphically with a scatter plot.\nactual_values = y_test\nplt.scatter(predictions, actual_values, alpha=.75,\n color='b') # alpha helps to show overlapping data\nplt.xlabel('Predicted Price')\nplt.ylabel('Actual Price')\nplt.title('Linear Regression Model')\nplt.show()\n\n\n# In[24]:\n\n\n#====== improve the model ================================================================#\n# try using Ridge Regularization to decrease the influence of less important features #\n#=========================================================================================#\n\nprint(\"26 \\n\")\n# experiment by looping through a few different values of alpha, and see how this changes our results.\n\nfor i in range (-2, 3):\n alpha = 10**i\n rm = linear_model.Ridge(alpha=alpha)\n ridge_model = rm.fit(X_train, y_train)\n preds_ridge = ridge_model.predict(X_test)\n\n plt.scatter(preds_ridge, actual_values, alpha=.75, color='b')\n plt.xlabel('Predicted Price')\n plt.ylabel('Actual Price')\n plt.title('Ridge Regularization with alpha = {}'.format(alpha))\n overlay = 'R^2 is: {}\\nRMSE is: {}'.format(\n ridge_model.score(X_test, y_test),\n mean_squared_error(y_test, preds_ridge))\n plt.annotate(s=overlay,xy=(12.1,10.6),size='x-large')\n plt.show()\n\n# if you examined the plots you can see these models perform almost identically to the first model.\n# In our case, adjusting the alpha did not substantially improve our model.\n\nprint(\"27 \\n\")\nprint(\"R^2 is: \\n\", model.score(X_test, y_test))\n\n\n# In[25]:\n\n\n######################################################\n# 4. Make a submission ##\n######################################################\n\n# create a csv that contains the predicted SalePrice for each observation in the test.csv dataset.\nsubmission = pd.DataFrame()\n# The first column must the contain the ID from the test data.\nsubmission['Id'] = test.Id\n\n# select the features from the test data for the model as we did above.\nfeats = test.select_dtypes(\n include=[np.number]).drop(['Id'], axis=1).interpolate()\n\n# generate predictions\npredictions = model.predict(feats)\n\n# transform the predictions to the correct form\n# apply np.exp() to our predictions becasuse we have taken the logarithm(np.log()) previously.\nfinal_predictions = np.exp(predictions)\n\nprint(\"28 \\n\")\n\n# check the difference\nprint(\"Original predictions are: \\n\", predictions[:10], \"\\n\")\nprint(\"Final predictions are: \\n\", final_predictions[:10])\n\nprint(\"29 \\n\")\n# assign these predictions and check\nsubmission['SalePrice'] = final_predictions\n# submission.head()\nprint(submission.head())\n\n# export to a .csv file as Kaggle expects.\n# pass index=False because Pandas otherwise would create a new index for us.\nsubmission.to_csv('submission1.csv', index=False)\n\n\nprint(\"\\n Finish\")\n\n" ]
[ [ "pandas.DataFrame", "sklearn.metrics.mean_squared_error", "numpy.exp", "pandas.read_csv", "matplotlib.pyplot.style.use", "numpy.log", "matplotlib.pyplot.title", "matplotlib.pyplot.annotate", "sklearn.model_selection.train_test_split", "sklearn.linear_model.Ridge", "matplotlib.pyplot.show", "matplotlib.pyplot.hist", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.scatter", "matplotlib.pyplot.xlim", "sklearn.linear_model.LinearRegression", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks", "pandas.get_dummies" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
Nintorac/survae_experiments
[ "d68cc25e2604aab08b53617c1f3ffe4716f166c4" ]
[ "survae/transforms/bijections/conv1x1.py" ]
[ "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom survae.transforms.bijections import Bijection\n\n\nclass Conv1x1(Bijection):\n \"\"\"\n Invertible 1x1 Convolution [1].\n The weight matrix is initialized as a random rotation matrix\n as described in Section 3.2 of [1].\n\n Args:\n num_channels (int): Number of channels in the input and output.\n orthogonal_init: bool, if True initialize weights to be a random orthogonal matrix (default=True).\n\n References:\n [1] Glow: Generative Flow with Invertible 1×1 Convolutions,\n Kingma & Dhariwal, 2018, https://arxiv.org/abs/1807.03039\n \"\"\"\n def __init__(self, num_channels, orthogonal_init=True):\n super(Conv1x1, self).__init__()\n self.num_channels = num_channels\n self.weight = nn.Parameter(torch.Tensor(num_channels, num_channels))\n self.reset_parameters(orthogonal_init)\n\n def reset_parameters(self, orthogonal_init):\n self.orthogonal_init = orthogonal_init\n\n if self.orthogonal_init:\n nn.init.orthogonal_(self.weight)\n else:\n bound = 1.0 / np.sqrt(self.num_channels)\n nn.init.uniform_(self.weight, -bound, bound)\n\n def _conv(self, weight, v):\n return F.conv2d(v, weight.unsqueeze(-1).unsqueeze(-1))\n\n def _logdet(self, x_shape):\n b, c, h, w = x_shape\n _, ldj_per_pixel = torch.slogdet(self.weight)\n ldj = ldj_per_pixel * h * w\n return ldj.expand([b])\n\n def forward(self, x):\n z = self._conv(self.weight, x)\n ldj = self._logdet(x.shape)\n return z, ldj\n\n def inverse(self, z):\n weight_inv = torch.inverse(self.weight)\n x = self._conv(weight_inv, z)\n return x\n\n\nclass Conv1x11d(Bijection):\n \"\"\"\n Invertible 1x1 Convolution [1].\n The weight matrix is initialized as a random rotation matrix\n as described in Section 3.2 of [1].\n\n Args:\n num_channels (int): Number of channels in the input and output.\n orthogonal_init: bool, if True initialize weights to be a random orthogonal matrix (default=True).\n\n References:\n [1] Glow: Generative Flow with Invertible 1×1 Convolutions,\n Kingma & Dhariwal, 2018, https://arxiv.org/abs/1807.03039\n \"\"\"\n def __init__(self, num_channels, orthogonal_init=True):\n super(Conv1x11d, self).__init__()\n self.num_channels = num_channels\n self.weight = nn.Parameter(torch.Tensor(num_channels, num_channels))\n self.reset_parameters(orthogonal_init)\n\n def reset_parameters(self, orthogonal_init):\n self.orthogonal_init = orthogonal_init\n\n if self.orthogonal_init:\n nn.init.orthogonal_(self.weight)\n else:\n bound = 1.0 / np.sqrt(self.num_channels)\n nn.init.uniform_(self.weight, -bound, bound)\n\n def _conv(self, weight, v):\n return F.conv1d(v, weight.unsqueeze(-1))\n\n def _logdet(self, x_shape):\n b, c, l = x_shape\n _, ldj_per_pixel = torch.slogdet(self.weight)\n ldj = ldj_per_pixel * l\n return ldj.expand([b])\n\n def forward(self, x):\n z = self._conv(self.weight, x)\n ldj = self._logdet(x.shape)\n return z, ldj\n\n def inverse(self, z):\n weight_inv = torch.inverse(self.weight)\n x = self._conv(weight_inv, z)\n return x\n" ]
[ [ "torch.nn.init.uniform_", "numpy.sqrt", "torch.Tensor", "torch.slogdet", "torch.inverse", "torch.nn.init.orthogonal_" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
WarrenWeckesser/numtypes
[ "4e46ac4a338ab46eec11cbacf9165827841ea4ff" ]
[ "numtypes/tests/test_nint32.py" ]
[ "\nimport pytest\nimport math\nimport numpy as np\nfrom numpy.testing import assert_equal\nfrom numtypes import nint32\n\n\ndef test_basic():\n x = nint32(3)\n assert x == 3\n assert int(x) == 3\n\n\[email protected]('typ', [np.int8, np.uint8, np.int16, np.uint16,\n np.int32, np.uint32, np.int64, np.uint64])\ndef test_init_np_types(typ):\n x = nint32(typ(123))\n assert x == 123\n\n\ndef test_init_str_type():\n x = nint32(\"123\")\n assert x == 123\n\n\ndef test_comparison():\n x = nint32(100)\n y = nint32(-500)\n assert x > 0\n assert x < 200\n assert x < 123.4\n assert x <= 200\n assert 200 >= x\n assert x == 100\n assert x > y\n assert x >= y\n assert y < x\n assert y <= x\n assert x != y\n\n\ndef test_true_division():\n x = nint32(20)\n y = nint32(10)\n z = x / y\n assert isinstance(z, float)\n assert z == 2.0\n\n\[email protected]('nanstr', ['nan', '\\t+NAN ', '-nAn'])\ndef test_nan_str(nanstr):\n z = nint32(nanstr)\n assert math.isnan(float(z))\n assert math.isnan(z + 1.5)\n\n\ndef test_nan():\n z = nint32(math.nan)\n assert math.isnan(float(z))\n assert z != z\n\n\ndef test_bool():\n assert bool(nint32(123))\n assert bool(nint32('nan'))\n assert not bool(nint32(0))\n\n\ndef test_other():\n z = 1.0 + 2.0j\n a = nint32(2)\n w = z / a\n assert w == z/2\n\n\[email protected]('value', [2**31, -2**31, 2**65])\ndef test_init_arg_too_big(value):\n with pytest.raises(OverflowError, match='int too big to convert'):\n nint32(value)\n\n\[email protected]('arg', [2.5, None, 'abc'])\ndef test_init_bad_arg(arg):\n with pytest.raises(TypeError, match='argument must be'):\n nint32(arg)\n\n\[email protected]('extreme_func, expected',\n [(np.maximum, [20, 10, 18]),\n (np.minimum, [10, -2, 10])])\ndef test_extreme_func(extreme_func, expected):\n a = np.array([10, -2, 18], dtype=np.int32).astype(nint32)\n b = np.array([20, 10, 10], dtype=np.int32).astype(nint32)\n m = extreme_func(a, b)\n assert m.dtype == nint32\n assert_equal(m, expected)\n\n\[email protected]('methodname, expected', [('min', -2), ('max', 18)])\ndef test_extreme_method(methodname, expected):\n a = np.array([10, -2, 18], dtype=nint32)\n m = getattr(a, methodname)()\n assert m.dtype == nint32\n assert m == expected\n\n\[email protected]('methodname', ['min', 'max'])\ndef test_extreme_method_with_nan(methodname):\n a = np.array([10, np.nan, -2, 18], dtype=nint32)\n m = getattr(a, methodname)()\n assert m.dtype == nint32\n assert np.isnan(m)\n" ]
[ [ "numpy.isnan", "numpy.testing.assert_equal", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
PApostol/pandas
[ "578e918777f6f512f85a917dc34910df87f63e90" ]
[ "pandas/tests/util/test_show_versions.py" ]
[ "import json\nimport os\nimport re\n\nimport pytest\n\nfrom pandas.compat import (\n IS64,\n is_ci_environment,\n)\nfrom pandas.util._print_versions import (\n _get_dependency_info,\n _get_sys_info,\n)\n\nimport pandas as pd\n\n\[email protected](\n # openpyxl\n \"ignore:defusedxml.lxml is no longer supported:DeprecationWarning\"\n)\[email protected](\n # html5lib\n \"ignore:Using or importing the ABCs from:DeprecationWarning\"\n)\[email protected](\n # fastparquet\n \"ignore:pandas.core.index is deprecated:FutureWarning\"\n)\[email protected](\n # pandas_datareader\n \"ignore:pandas.util.testing is deprecated:FutureWarning\"\n)\[email protected](\n # https://github.com/pandas-dev/pandas/issues/35252\n \"ignore:Distutils:UserWarning\"\n)\[email protected](\"ignore:Setuptools is replacing distutils:UserWarning\")\ndef test_show_versions(tmpdir):\n # GH39701\n as_json = os.path.join(tmpdir, \"test_output.json\")\n\n pd.show_versions(as_json=as_json)\n\n with open(as_json) as fd:\n # check if file output is valid JSON, will raise an exception if not\n result = json.load(fd)\n\n # Basic check that each version element is found in output\n expected = {\n \"system\": _get_sys_info(),\n \"dependencies\": _get_dependency_info(),\n }\n\n assert result == expected\n\n\ndef test_show_versions_console_json(capsys):\n # GH39701\n pd.show_versions(as_json=True)\n stdout = capsys.readouterr().out\n\n # check valid json is printed to the console if as_json is True\n result = json.loads(stdout)\n\n # Basic check that each version element is found in output\n expected = {\n \"system\": _get_sys_info(),\n \"dependencies\": _get_dependency_info(),\n }\n\n assert result == expected\n\n\[email protected](\n is_ci_environment() and not IS64, reason=\"Failing on 32 bit Python CI job\"\n)\ndef test_show_versions_console(capsys):\n # gh-32041\n # gh-32041\n pd.show_versions(as_json=False)\n result = capsys.readouterr().out\n\n # check header\n assert \"INSTALLED VERSIONS\" in result\n\n # check full commit hash\n assert re.search(r\"commit\\s*:\\s[0-9a-f]{40}\\n\", result)\n\n # check required dependency\n # 2020-12-09 npdev has \"dirty\" in the tag\n # 2022-05-25 npdev released with RC wo/ \"dirty\".\n # Just ensure we match [0-9]+\\..* since npdev version is variable\n assert re.search(r\"numpy\\s*:\\s[0-9]+\\..*\\n\", result)\n\n # check optional dependency\n assert re.search(r\"pyarrow\\s*:\\s([0-9\\.]+|None)\\n\", result)\n\n\ndef test_json_output_match(capsys, tmpdir):\n # GH39701\n pd.show_versions(as_json=True)\n result_console = capsys.readouterr().out\n\n out_path = os.path.join(tmpdir, \"test_json.json\")\n pd.show_versions(as_json=out_path)\n with open(out_path) as out_fd:\n result_file = out_fd.read()\n\n assert result_console == result_file\n" ]
[ [ "pandas.compat.is_ci_environment", "pandas.util._print_versions._get_dependency_info", "pandas.util._print_versions._get_sys_info", "pandas.show_versions" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
riokt/video-paragraph
[ "2da3298819e73809af495457db2cf1dfffad712f", "2da3298819e73809af495457db2cf1dfffad712f" ]
[ "metrics/evaluation.py", "modules/transformer.py" ]
[ "from cap_eval.bleu.bleu import Bleu\nfrom cap_eval.cider.cider import Cider\nfrom cap_eval.meteor.meteor import Meteor\n\nimport json\nimport numpy as np\n\n# initialize the caption evaluators\nmeteor_scorer = Meteor()\ncider_scorer = Cider()\nbleu_scorer = Bleu(4)\n\n\ndef bleu_eval(refs, cands):\n print (\"calculating bleu_4 score...\")\n bleu, _ = bleu_scorer.compute_score(refs, cands)\n return bleu\n\n\ndef cider_eval(refs, cands):\n print (\"calculating cider score...\")\n cider, _ = cider_scorer.compute_score(refs, cands)\n return cider\n\n\ndef meteor_eval(refs, cands):\n print (\"calculating meteor score...\")\n meteor, _ = meteor_scorer.compute_score(refs, cands)\n return meteor\n\n\ndef getNgrams(words_pred, unigrams, bigrams, trigrams, fourgrams):\n # N=1\n for w in words_pred:\n if w not in unigrams:\n unigrams[w] = 0\n unigrams[w] += 1\n # N=2\n for i, w in enumerate(words_pred):\n if i<len(words_pred)-1:\n w_next = words_pred[i+1]\n bigram = '%s_%s' % (w, w_next)\n if bigram not in bigrams:\n bigrams[bigram] = 0\n bigrams[bigram] += 1\n # N=3\n for i, w in enumerate(words_pred):\n if i<len(words_pred)-2:\n w_next = words_pred[i + 1]\n w_next_ = words_pred[i + 2]\n tri = '%s_%s_%s' % (w, w_next, w_next_)\n if tri not in trigrams:\n trigrams[tri] = 0\n trigrams[tri] += 1\n # N=4\n for i, w in enumerate(words_pred):\n if i<len(words_pred)-3:\n w_next = words_pred[i + 1]\n w_next_ = words_pred[i + 2]\n w_next__ = words_pred[i + 3]\n four = '%s_%s_%s_%s' % (w, w_next, w_next_, w_next__)\n if four not in fourgrams:\n fourgrams[four] = 0\n fourgrams[four] += 1\n return unigrams, bigrams, trigrams, fourgrams\n\n\ndef diversity(data_pred):\n div1, div2, re4 = [], [], []\n try:\n for i in range(len(data_pred)):\n unigrams, bigrams, trigrams, fourgrams = {}, {}, {}, {}\n if data_pred[i][-1] == '.':\n para = data_pred[i].split('.')[:-1]\n else:\n para = data_pred[i].split('.')\n for j, pred_sentence in enumerate(para):\n if pred_sentence[-1] == '.':\n pred_sentence = pred_sentence[:-1]\n while len(pred_sentence) > 0 and pred_sentence[-1] == ' ':\n pred_sentence = pred_sentence[:-1]\n while len(pred_sentence) > 0 and pred_sentence[0] == ' ':\n pred_sentence = pred_sentence[1:]\n pred_sentence = pred_sentence.replace(',', ' ')\n while ' ' in pred_sentence:\n pred_sentence = pred_sentence.replace(' ', ' ')\n\n words_pred = pred_sentence.split(' ')\n unigrams, bigrams, trigrams, fourgrams = getNgrams(words_pred, unigrams, bigrams, trigrams, fourgrams)\n\n sum_unigrams = sum([unigrams[un] for un in unigrams])\n vid_div1 = float(len(unigrams)) / (float(sum_unigrams) + 1e-28)\n vid_div2 = float(len(bigrams)) / (float(sum_unigrams) + 1e-28)\n vid_re4 = float(sum([max(fourgrams[f]-1,0) for f in fourgrams])) / (float(sum([fourgrams[f] for f in fourgrams])) + 1e-28)\n\n div1.append(vid_div1)\n div2.append(vid_div2)\n re4.append(vid_re4)\n except Exception as e:\n print(e)\n pass\n return np.mean(div1), np.mean(div2), np.mean(re4)\n\n\ndef compute(preds, names, refs):\n refcaps = {}\n candcaps = {}\n for i in range(len(preds)):\n candcaps[i] = [preds[i]]\n refcaps[i] = refs[names[i]]\n bleu = bleu_eval(refcaps, candcaps)\n cider = cider_eval(refcaps, candcaps)\n meteor = meteor_eval(refcaps, candcaps)\n div1, div2, re4 = diversity(preds)\n scores = {'bleu_4':bleu[3], 'bleu_3':bleu[2], 'bleu_2':bleu[1], 'bleu_1':bleu[0],\n 'cider':cider, 'meteor':meteor,\n 'div1':div1, 'div2':div2, 're4':re4}\n return scores\n\n if guess in word:\n print(\"\\nYes!\", guess, \"is in the word!\")\n\n # Create a new variable (so_far) to contain the guess\n new = \"\"\n i = 0\n for i in range(len(word)):\n if guess == word[i]:\n new += guess\n else:\n new += so_far[i]\n so_far = new\n", "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport framework.configbase\nimport math\nimport time\nimport numpy as np\nfrom modules.transformer_encoder import Encoder\nfrom modules.transformer_decoder import Decoder\n\ndecay1 = [(i+1)*20**(-1) for i in range(20)]\ndecay2 = [1-(i+1)*50**(-1) for i in range(50)]\n\n\nclass TransformerConfig(framework.configbase.ModuleConfig):\n def __init__(self):\n super(TransformerConfig, self).__init__()\n self.vocab = 0\n self.max_words_in_sent = 150\n self.ft_dim = 4096\n self.d_model = 512\n self.enc_n_layers = 3\n self.dec_n_layers = 3\n self.heads = 8\n self.dropout = 0.1\n self.keyframes = False\n self.rl = False\n self.document_freq = None\n\n \nclass Transformer(nn.Module):\n def __init__(self, config):\n super(Transformer, self).__init__()\n self.config = config\n self.encoder = Encoder(self.config.ft_dim, self.config.d_model, self.config.enc_n_layers, self.config.heads, self.config.dropout, self.config.keyframes, act=True)\n self.decoder = Decoder(self.config.vocab, self.config.d_model, self.config.dec_n_layers, self.config.heads, self.config.dropout, act=True)\n self.dropout = nn.Dropout(self.config.dropout)\n self.logit = nn.Linear(self.config.d_model, self.config.vocab)\n self.logit.weight = self.decoder.embed.embed.weight\n self.remove_gate = nn.Linear(self.config.d_model, 1)\n self.add_gate = nn.Linear(self.config.d_model, 1)\n self.q_linear = nn.Linear(self.config.d_model, self.config.d_model, bias=False)\n self.next_attn = nn.Linear(2*self.config.d_model, 1)\n self.init_weights()\n\n def init_weights(self,):\n for p in self.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)\n\n def forward(self, src, trg, src_mask, trg_mask):\n e_outputs, org_key, select = self.encoder(src, src_mask)\n add_state = torch.tensor(decay2[:e_outputs.size(1)]+[0]*max(0,e_outputs.size(1)-50)).cuda().unsqueeze(0).unsqueeze(-1)\n memory_bank = e_outputs * add_state\n d_output, attn_weights = [], []\n \n for i in range(1, trg.size(1)+1):\n word, attn, _ = self.decoder(trg[:,i-1].unsqueeze(1), memory_bank, src_mask, trg_mask[:,i-1,i-1].unsqueeze(1), step=i-1)\n d_output.append(word[:,-1])\n attn_weights.append(attn[:,:,-1].mean(dim=1))\n memory_bank, add_state = self.update_memory(memory_bank, add_state, e_outputs, attn_weights[-20:], d_output[-20:])\n output = self.logit(torch.cat([_.unsqueeze(1) for _ in d_output], 1))\n return output, org_key, select\n\n def update_memory(self, memory_bank, add_state, e_outputs, attn, query_s):\n remove_prob = torch.sigmoid(self.remove_gate(query_s[-1])).unsqueeze(-1)\n add_prob = torch.sigmoid(self.add_gate(query_s[-1])).unsqueeze(-1)\n temp = torch.softmax(torch.tensor(decay1[20-len(attn):]).cuda(), dim=-1)\n attn = sum([attn[i]*temp[i] for i in range(len(attn))]).unsqueeze(-1)\n # remove for diversity\n query_s = sum([query_s[i]*temp[i] for i in range(len(query_s))])\n sim = torch.sigmoid(torch.matmul(memory_bank, self.q_linear(query_s).unsqueeze(-1)))\n memory_bank = memory_bank * (1 - remove_prob * attn * sim)\n # add for coherence\n last_ctx = (e_outputs * attn).sum(dim=1, keepdim=True)\n next_attn = torch.sigmoid(self.next_attn(torch.cat([e_outputs,last_ctx.expand_as(e_outputs)], dim=-1)))\n memory_bank = memory_bank + e_outputs * (1-add_state) * (add_prob*next_attn)\n add_state = add_state + (1-add_state) * (add_prob*next_attn)\n return memory_bank, add_state\n\n def sample(self, src, src_mask, decoding='greedy'):\n init_tok = 2\n eos_tok = 3\n if self.config.keyframes:\n e_outputs, src_mask = self.encoder.get_keyframes(src, src_mask)\n else:\n e_outputs, _, _ = self.encoder(src, src_mask)\n add_state = torch.tensor(decay2[:e_outputs.size(1)]+[0]*max(0,e_outputs.size(1)-50)).cuda().unsqueeze(0).unsqueeze(-1)\n memory_bank = e_outputs * add_state\n outputs = torch.ones(src.size(0), 1).fill_(init_tok).long().cuda()\n seqLogprobs = torch.zeros(src.size(0), 60).cuda()\n attn_weights, d_output = [], []\n for i in range(1, 60):\n trg_mask = self.nopeak_mask(i)\n word, attn, _ = self.decoder(outputs[:,-1].unsqueeze(1), memory_bank, src_mask, trg_mask[:,-1,-1].unsqueeze(1), step=i-1)\n attn_weights.append(attn[:,:,-1].mean(dim=1))\n d_output.append(word[:,-1])\n out = self.logit(word)\n logprobs = F.log_softmax(out[:,-1], dim=-1)\n if decoding == 'greedy':\n _, next_word = torch.max(logprobs, dim=1)\n next_word = next_word.unsqueeze(-1)\n else:\n probs = torch.exp(logprobs.data).cpu()\n next_word = torch.multinomial(probs, 1).cuda()\n seqLogprobs[:,i] = logprobs.gather(1, next_word).view(-1)\n outputs = torch.cat([outputs, next_word], dim=1)\n memory_bank, add_state = self.update_memory(memory_bank, add_state, e_outputs, attn_weights[-20:], d_output[-20:])\n attn_weights = torch.cat([_.unsqueeze(1) for _ in attn_weights], dim=1)\n return outputs, seqLogprobs, attn_weights\n\n def nopeak_mask(self, size):\n np_mask = np.triu(np.ones((1, size, size)), k=1).astype('uint8')\n np_mask = Variable(torch.from_numpy(np_mask) == 0).cuda()\n return np_mask\n\n" ]
[ [ "numpy.mean" ], [ "torch.nn.Dropout", "torch.max", "torch.nn.functional.log_softmax", "torch.cat", "torch.from_numpy", "torch.multinomial", "numpy.ones", "torch.exp", "torch.nn.Linear", "torch.nn.init.xavier_uniform_" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Noahs-ARK/PaLM
[ "fe943bb0516d80b09f2b56de60dac9c54dc196e6" ]
[ "eval.py" ]
[ "import math\nimport numpy as np\nimport torch\nimport data\nfrom torch.autograd import Variable\nfrom utils import batchify, get_batch, repackage_hidden\nimport argparser\nargs = argparser.args()\nfrom utils import Input\n\n# Set the random seed manually for reproducibility.\nnp.random.seed(args.seed)\ntorch.manual_seed(args.seed)\nif torch.cuda.is_available():\n if not args.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n else:\n torch.cuda.manual_seed(args.seed)\n\ndef model_load(fn):\n global model, criterion, optimizer\n with open(fn, 'rb') as f:\n model, criterion, optimizer = torch.load(f)\n\nimport os\nimport hashlib\n\nfn = 'corpus'\nif os.path.exists(fn):\n print('Loading cached dataset...')\n corpus = torch.load(fn)\nelse:\n print('Producing dataset...')\n corpus = data.Corpus(args.data)\n torch.save(corpus, fn)\neval_batch_size = 10\ntest_batch_size = 1\ntrain_data, train_rps = batchify(corpus.train, corpus.train_rps, args.batch_size, args)\nval_data, val_rps = batchify(corpus.valid, corpus.valid_rps, eval_batch_size, args)\ntest_data, test_rps = batchify(corpus.test, corpus.test_rps, test_batch_size, args)\nprint('Args:', args)\n\ndef evaluate(data_source, rps, batch_size=10):\n # Turn on evaluation mode which disables dropout.\n \n criterion = torch.nn.CrossEntropyLoss()\n ntokens = len(corpus.dictionary)\n model.eval()\n if args.model == 'QRNN': model.reset()\n total_loss = 0\n hidden = model.init_hidden(batch_size)\n with torch.no_grad():\n for i in range(0, data_source.shape[1] - 1, args.bptt):\n data, rp, targets = get_batch(\n data_source, rps, i, batch_size=batch_size, args=args, evaluation=True)\n input = Input(x=data, rp=rp)\n output, hidden = model(input, hidden)\n # total_loss += data.size(1) * criterion(model.decoder.weight, model.decoder.bias, output, targets).data\n output = torch.nn.functional.linear(output, model.decoder.weight, bias=model.decoder.bias)\n output = torch.nn.functional.log_softmax(output, dim=-1)\n output_flat = output.view(-1, ntokens)\n total_loss += data.size(1) * criterion(output_flat, targets).data\n hidden = repackage_hidden(hidden)\n return total_loss.item() / data_source.shape[1]\nmodel_load(args.save)\n\ntest_loss = evaluate(val_data, val_rps, 10)\nprint('=' * 89)\nprint('| End of training | test loss {:5.2f} | test ppl {:8.2f} | test bpc {:8.3f}'.format(\n val_loss, math.exp(test_loss), val_loss / math.log(2)))\nprint('=' * 89)\ndsa\n\ntest_loss = evaluate(test_data, test_rps, 1)\nprint('=' * 89)\nprint('| End of training | test loss {:5.2f} | test ppl {:8.2f} | test bpc {:8.3f}'.format(\n test_loss, math.exp(test_loss), test_loss / math.log(2)))\nprint('=' * 89)\n" ]
[ [ "torch.nn.CrossEntropyLoss", "numpy.random.seed", "torch.load", "torch.cuda.manual_seed", "torch.manual_seed", "torch.nn.functional.log_softmax", "torch.no_grad", "torch.cuda.is_available", "torch.nn.functional.linear", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
javiergodoy/pandas-profiling
[ "0bed133520b9982263ed8cbc1af6b8f5a511bf0d", "0bed133520b9982263ed8cbc1af6b8f5a511bf0d", "0bed133520b9982263ed8cbc1af6b8f5a511bf0d" ]
[ "tests/unit/test_url.py", "tests/issues/test_issue51.py", "examples/website_inaccessibility/website_inaccessibility.py" ]
[ "import pandas as pd\nimport numpy as np\n\nimport pandas_profiling\n\n\ndef test_urls(get_data_file):\n file_name = get_data_file(\n \"whitelist_urls.csv\",\n \"https://raw.githubusercontent.com/openeventdata/scraper/master/whitelist_urls.csv\",\n )\n\n df = pd.read_csv(\n file_name, header=None, names=[\"source\", \"url\", \"reach\", \"language\"]\n )\n\n # Add ~10% missing values\n df = df.mask(np.random.random(df.shape) < 0.1)\n\n profile = df.profile_report(\n title=\"DataFrame with URL column\", samples={\"head\": 0, \"tail\": 0}\n )\n\n assert \"<small>URL</small>\" in profile.to_html(), \"URL not detected\"\n assert \"<th>URL</th>\" in profile.to_html(), \"URL not detected\"\n", "\"\"\"\nTest for issue 51:\nhttps://github.com/pandas-profiling/pandas-profiling/issues/51\n\"\"\"\nfrom pathlib import Path\n\nimport pandas as pd\nimport pandas_profiling\nimport requests\n\nimport numpy as np\n\n\ndef test_issue51(get_data_file):\n # Categorical has empty ('') value\n file_name = get_data_file(\n \"buggy1.pkl\",\n \"https://raw.githubusercontent.com/adamrossnelson/HelloWorld/master/sparefiles/buggy1.pkl\",\n )\n\n df = pd.read_pickle(str(file_name))\n\n report = df.profile_report(title=\"Pandas Profiling Report\")\n assert (\n \"<title>Pandas Profiling Report</title>\" in report.to_html()\n ), \"Profile report should be generated.\"\n\n\ndef test_issue51_similar():\n df = pd.DataFrame(\n {\n \"test\": [\"\", \"hoi\", None],\n \"blest\": [None, \"\", \"geert\"],\n \"bert\": [\"snor\", \"\", None],\n }\n )\n\n report = df.profile_report(title=\"Pandas Profiling Report\")\n\n assert (\n \"<title>Pandas Profiling Report</title>\" in report.to_html()\n ), \"Profile report should be generated.\"\n\n\n# def test_issue51_mixed():\n# df = pd.DataFrame(\n# {\n# \"test\": [\"\", \"hoi\", None, \"friet\"],\n# \"blest\": [None, \"\", \"geert\", \"pizza\"],\n# \"bert\": [\"snor\", \"\", np.nan, \"\"],\n# \"fruit\": [\"\", \"ok\", np.nan, \"\"],\n# }\n# )\n# report = df.profile_report(title=\"Pandas Profiling Report\")\n# assert (\n# \"data-toggle=tab>Recoded</a>\" in report.to_html()\n# ), \"Recoded should be present\"\n\n\ndef test_issue51_empty():\n df = pd.DataFrame(\n {\"test\": [\"\", \"\", \"\"], \"blest\": [\"\", \"\", \"\"], \"bert\": [\"\", \"\", \"\"]}\n )\n\n report = df.profile_report(title=\"Pandas Profiling Report\")\n\n assert (\n \"<title>Pandas Profiling Report</title>\" in report.to_html()\n ), \"Profile report should be generated.\"\n", "from pathlib import Path\n\nimport pandas as pd\nfrom pandas_profiling import ProfileReport\nfrom pandas_profiling.utils.cache import cache_file\n\nif __name__ == \"__main__\":\n file_name = cache_file(\n \"websites.csv\",\n \"https://raw.githubusercontent.com/berkmancenter/url-lists/master/lists/et.csv\",\n )\n\n df = pd.read_csv(file_name, parse_dates=[\"date_added\"])\n profile = ProfileReport(\n df,\n title=\"Website Inaccessibility Test Lists\",\n correlations={\"cramers\": {\"calculate\": False}},\n )\n profile.to_file(output_file=Path(\"./website_inaccessibility_report.html\"))\n" ]
[ [ "pandas.read_csv", "numpy.random.random" ], [ "pandas.DataFrame" ], [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
Lguiller/machinelearning-az
[ "7c062302944b91131783fe663e1cff21e5956ca2" ]
[ "datasets/Part 2 - Regression/Section 6 - Polynomial Regression/polinomial_regression.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 5 12:45:44 2019\n\n@author: juangabriel\n\"\"\"\n\n# Regresión polinómica\n\n# Cómo importar las librerías\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importar el data set\ndataset = pd.read_csv('Position_Salaries.csv')\nX = dataset.iloc[:, 1:2].values\ny = dataset.iloc[:, 2].values\n\n\n# Dividir el data set en conjunto de entrenamiento y conjunto de testing\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\"\"\"\n\n# Escalado de variables\n\"\"\"from sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\"\"\"\n\n# Ajustar la regresión lineal con el dataset\nfrom sklearn.linear_model import LinearRegression\nlin_reg = LinearRegression()\nlin_reg.fit(X, y)\n\n# Ajustar la regresión polinómica con el dataset\nfrom sklearn.preprocessing import PolynomialFeatures\npoly_reg = PolynomialFeatures(degree = 4)\nX_poly = poly_reg.fit_transform(X)\nlin_reg_2 = LinearRegression()\nlin_reg_2.fit(X_poly, y)\n\n# Visualización de los resultados del Modelo Lineal\nplt.scatter(X, y, color = \"red\")\nplt.plot(X, lin_reg.predict(X), color = \"blue\")\nplt.title(\"Modelo de Regresión Lineal\")\nplt.xlabel(\"Posición del empleado\")\nplt.ylabel(\"Sueldo (en $)\")\nplt.show()\n\n# Visualización de los resultados del Modelo Polinómico\nX_grid = np.arange(min(X), max(X), 0.1)\nX_grid = X_grid.reshape(len(X_grid), 1)\nplt.scatter(X, y, color = \"red\")\nplt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)), color = \"blue\")\nplt.title(\"Modelo de Regresión Polinómica\")\nplt.xlabel(\"Posición del empleado\")\nplt.ylabel(\"Sueldo (en $)\")\nplt.show()\n\n# Predicción de nuestros modelos\nlin_reg.predict(6.5)\nlin_reg_2.predict(poly_reg.fit_transform(6.5))\n\n\n\n\n\n\n" ]
[ [ "pandas.read_csv", "matplotlib.pyplot.scatter", "matplotlib.pyplot.title", "sklearn.preprocessing.PolynomialFeatures", "sklearn.linear_model.LinearRegression", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
sighingnow/mars
[ "c7897fbd144d230fff5edabc1494fb3ff44aa0d2", "c7897fbd144d230fff5edabc1494fb3ff44aa0d2", "c7897fbd144d230fff5edabc1494fb3ff44aa0d2", "c7897fbd144d230fff5edabc1494fb3ff44aa0d2", "c7897fbd144d230fff5edabc1494fb3ff44aa0d2", "c7897fbd144d230fff5edabc1494fb3ff44aa0d2", "c7897fbd144d230fff5edabc1494fb3ff44aa0d2" ]
[ "mars/tensor/reduction/nanargmin.py", "mars/worker/tests/test_calc.py", "mars/worker/storage/tests/test_procmem_io.py", "mars/tensor/random/vonmises.py", "mars/tensor/indexing/unravel_index.py", "mars/tensor/tests/test_core_execute.py", "mars/worker/tests/test_transfer.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright 1999-2018 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\n\nfrom ... import opcodes as OperandDef\nfrom ...serialize import Int64Field, TupleField\nfrom .core import TensorReduction, TensorArgReductionMixin, TensorArgMapMixin, TensorArgCombineMixin\n\n\nclass TensorNanArgminMap(TensorReduction, TensorArgMapMixin):\n _op_type_ = OperandDef.NANARGMIN_CHUNK\n\n _offset = Int64Field('offset')\n _total_shape = TupleField('total_shape')\n\n _func_name = 'nanargmin'\n _agg_func_name = 'nanmin'\n\n def __init__(self, axis=None, dtype=np.dtype(int), combine_size=None,\n offset=None, total_shape=None,**kw):\n super(TensorNanArgminMap, self).__init__(_axis=axis, _dtype=dtype, _combine_size=combine_size,\n _offset=offset, _total_shape=total_shape, **kw)\n\n @property\n def offset(self):\n return getattr(self, '_offset', None)\n\n @property\n def total_shape(self):\n return getattr(self, '_total_shape', None)\n\n\nclass TensorNanArgminCombine(TensorReduction, TensorArgCombineMixin):\n _op_type_ = OperandDef.NANARGMIN_COMBINE\n _func_name = 'nanargmin'\n\n def __init__(self, axis=None, dtype=np.dtype(int), combine_size=None, **kw):\n super(TensorNanArgminCombine, self).__init__(_axis=axis, _dtype=dtype,\n _combine_size=combine_size, **kw)\n\n\nclass TensorNanArgmin(TensorReduction, TensorArgReductionMixin):\n _op_type_ = OperandDef.NANARGMIN\n _func_name = 'nanargmin'\n\n def __init__(self, axis=None, dtype=np.dtype(int), combine_size=None, **kw):\n super(TensorNanArgmin, self).__init__(_axis=axis, _dtype=dtype, _combine_size=combine_size, **kw)\n\n @staticmethod\n def _get_op_types():\n return TensorNanArgminMap, TensorNanArgmin, TensorNanArgminCombine\n\n\ndef nanargmin(a, axis=None, out=None, combine_size=None):\n \"\"\"\n Return the indices of the minimum values in the specified axis ignoring\n NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results\n cannot be trusted if a slice contains only NaNs and Infs.\n\n Parameters\n ----------\n a : array_like\n Input data.\n axis : int, optional\n Axis along which to operate. By default flattened input is used.\n combine_size: int, optional\n The number of chunks to combine.\n\n Returns\n -------\n index_array : Tensor\n A tensor of indices or a single index value.\n\n See Also\n --------\n argmin, nanargmax\n\n Examples\n --------\n >>> import mars.tensor as mt\n\n >>> a = mt.array([[mt.nan, 4], [2, 3]])\n >>> mt.argmin(a).execute()\n 0\n >>> mt.nanargmin(a).execute()\n 2\n >>> mt.nanargmin(a, axis=0).execute()\n array([1, 1])\n >>> mt.nanargmin(a, axis=1).execute()\n array([1, 0])\n\n \"\"\"\n op = TensorNanArgmin(axis=axis, dtype=np.dtype(int), combine_size=combine_size)\n return op(a, out=out)\n", "# Copyright 1999-2018 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport contextlib\nimport uuid\nimport weakref\n\nimport numpy as np\n\nfrom mars.errors import StorageFull\nfrom mars.graph import DAG\nfrom mars.utils import get_next_port, serialize_graph\nfrom mars.scheduler import ChunkMetaActor\nfrom mars.scheduler.utils import SchedulerClusterInfoActor\nfrom mars.tests.core import patch_method\nfrom mars.worker import WorkerDaemonActor, DispatchActor, StorageManagerActor, \\\n CpuCalcActor, IORunnerActor, PlasmaKeyMapActor, SharedHolderActor, \\\n InProcHolderActor, QuotaActor, MemQuotaActor, StatusActor\nfrom mars.worker.storage import DataStorageDevice\nfrom mars.worker.storage.sharedstore import PlasmaSharedStore\nfrom mars.worker.tests.base import WorkerCase\nfrom mars.worker.utils import build_quota_key, WorkerClusterInfoActor\n\n\nclass Test(WorkerCase):\n @contextlib.contextmanager\n def _start_calc_pool(self):\n mock_addr = '127.0.0.1:%d' % get_next_port()\n with self.create_pool(n_process=1, backend='gevent', address=mock_addr) as pool:\n pool.create_actor(SchedulerClusterInfoActor, [mock_addr],\n uid=SchedulerClusterInfoActor.default_uid())\n pool.create_actor(WorkerClusterInfoActor, [mock_addr],\n uid=WorkerClusterInfoActor.default_uid())\n\n pool.create_actor(ChunkMetaActor, uid=ChunkMetaActor.default_uid())\n pool.create_actor(StatusActor, mock_addr, uid=StatusActor.default_uid())\n\n pool.create_actor(PlasmaKeyMapActor, uid=PlasmaKeyMapActor.default_uid())\n pool.create_actor(WorkerDaemonActor, uid=WorkerDaemonActor.default_uid())\n pool.create_actor(DispatchActor, uid=DispatchActor.default_uid())\n pool.create_actor(StorageManagerActor, uid=StorageManagerActor.default_uid())\n pool.create_actor(IORunnerActor)\n pool.create_actor(QuotaActor, 1024 ** 2, uid=MemQuotaActor.default_uid())\n shared_holder_ref = pool.create_actor(\n SharedHolderActor, uid=SharedHolderActor.default_uid())\n pool.create_actor(InProcHolderActor)\n pool.create_actor(CpuCalcActor, uid=CpuCalcActor.default_uid())\n\n with self.run_actor_test(pool) as test_actor:\n try:\n yield pool, test_actor\n finally:\n shared_holder_ref.destroy()\n\n @staticmethod\n def _build_test_graph(data_list):\n from mars.tensor.fetch import TensorFetch\n from mars.tensor.arithmetic import TensorTreeAdd\n\n inputs = []\n for idx, d in enumerate(data_list):\n chunk_key = 'chunk-%d' % idx\n fetch_chunk = TensorFetch(to_fetch_key=chunk_key, dtype=d.dtype) \\\n .new_chunk([], shape=d.shape, _key=chunk_key)\n inputs.append(fetch_chunk)\n add_chunk = TensorTreeAdd(data_list[0].dtype).new_chunk(inputs, shape=data_list[0].shape)\n\n exec_graph = DAG()\n exec_graph.add_node(add_chunk)\n for input_chunk in inputs:\n exec_graph.add_node(input_chunk)\n exec_graph.add_edge(input_chunk, add_chunk)\n return exec_graph, inputs, add_chunk\n\n def testCpuCalcSingleFetches(self):\n with self._start_calc_pool() as (_pool, test_actor):\n quota_ref = test_actor.promise_ref(MemQuotaActor.default_uid())\n calc_ref = test_actor.promise_ref(CpuCalcActor.default_uid())\n\n session_id = str(uuid.uuid4())\n data_list = [np.random.random((10, 10)) for _ in range(3)]\n exec_graph, fetch_chunks, add_chunk = self._build_test_graph(data_list)\n\n storage_client = test_actor.storage_client\n\n for fetch_chunk, d in zip(fetch_chunks, data_list):\n self.waitp(\n storage_client.put_object(\n session_id, fetch_chunk.key, d, [DataStorageDevice.SHARED_MEMORY]),\n )\n self.assertEqual(list(storage_client.get_data_locations(session_id, fetch_chunks[0].key)),\n [(0, DataStorageDevice.SHARED_MEMORY)])\n\n quota_batch = {\n build_quota_key(session_id, add_chunk.key, add_chunk.op.key): data_list[0].nbytes,\n }\n\n for idx in [1, 2]:\n quota_batch[build_quota_key(session_id, fetch_chunks[idx].key, add_chunk.op.key)] \\\n = data_list[idx].nbytes\n\n self.waitp(\n storage_client.copy_to(session_id, fetch_chunks[idx].key, [DataStorageDevice.DISK])\n .then(lambda *_: storage_client.delete(\n session_id, fetch_chunks[idx].key, [DataStorageDevice.SHARED_MEMORY]))\n )\n self.assertEqual(\n list(storage_client.get_data_locations(session_id, fetch_chunks[idx].key)),\n [(0, DataStorageDevice.DISK)])\n\n self.waitp(\n quota_ref.request_batch_quota(quota_batch, _promise=True),\n )\n\n o_create = PlasmaSharedStore.create\n\n def _mock_plasma_create(store, session_id, data_key, size):\n if data_key == fetch_chunks[2].key:\n raise StorageFull\n return o_create(store, session_id, data_key, size)\n\n ref_store = []\n\n def _extract_value_ref(*_):\n inproc_handler = storage_client.get_storage_handler(DataStorageDevice.PROC_MEMORY)\n obj = inproc_handler.get_object(session_id, add_chunk.key)\n ref_store.append(weakref.ref(obj))\n del obj\n\n with patch_method(PlasmaSharedStore.create, _mock_plasma_create):\n self.waitp(\n calc_ref.calc(session_id, add_chunk.op.key, serialize_graph(exec_graph),\n [add_chunk.key], _promise=True)\n .then(_extract_value_ref)\n .then(lambda *_: calc_ref.store_results(session_id, [add_chunk.key], _promise=True))\n )\n\n self.assertIsNone(ref_store[-1]())\n\n quota_dump = quota_ref.dump_data()\n self.assertEqual(len(quota_dump.allocations), 0)\n self.assertEqual(len(quota_dump.requests), 0)\n self.assertEqual(len(quota_dump.proc_sizes), 0)\n self.assertEqual(len(quota_dump.hold_sizes), 0)\n\n self.assertEqual(sorted(storage_client.get_data_locations(session_id, fetch_chunks[0].key)),\n [(0, DataStorageDevice.SHARED_MEMORY)])\n self.assertEqual(sorted(storage_client.get_data_locations(session_id, fetch_chunks[1].key)),\n [(0, DataStorageDevice.SHARED_MEMORY), (0, DataStorageDevice.DISK)])\n self.assertEqual(sorted(storage_client.get_data_locations(session_id, fetch_chunks[2].key)),\n [(0, DataStorageDevice.DISK)])\n self.assertEqual(sorted(storage_client.get_data_locations(session_id, add_chunk.key)),\n [(0, DataStorageDevice.SHARED_MEMORY)])\n\n def testCpuCalcErrorInRunning(self):\n with self._start_calc_pool() as (_pool, test_actor):\n calc_ref = test_actor.promise_ref(CpuCalcActor.default_uid())\n\n session_id = str(uuid.uuid4())\n data_list = [np.random.random((10, 10)) for _ in range(2)]\n exec_graph, fetch_chunks, add_chunk = self._build_test_graph(data_list)\n\n storage_client = test_actor.storage_client\n\n for fetch_chunk, d in zip(fetch_chunks, data_list):\n self.waitp(\n storage_client.put_object(\n session_id, fetch_chunk.key, d, [DataStorageDevice.SHARED_MEMORY]),\n )\n\n def _mock_calc_results_error(*_, **__):\n raise ValueError\n\n with patch_method(CpuCalcActor._calc_results, _mock_calc_results_error), \\\n self.assertRaises(ValueError):\n self.waitp(\n calc_ref.calc(session_id, add_chunk.op.key, serialize_graph(exec_graph),\n [add_chunk.key], _promise=True)\n .then(lambda *_: calc_ref.store_results(session_id, [add_chunk.key], _promise=True))\n )\n", "# Copyright 1999-2019 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport uuid\nimport weakref\n\nimport numpy as np\nfrom numpy.testing import assert_allclose\n\nfrom mars.serialize import dataserializer\nfrom mars.utils import get_next_port\nfrom mars.worker import WorkerDaemonActor, QuotaActor, MemQuotaActor\nfrom mars.worker.tests.base import WorkerCase\nfrom mars.worker.storage import *\n\n\nclass Test(WorkerCase):\n def testProcMemPutAndGet(self):\n test_addr = '127.0.0.1:%d' % get_next_port()\n with self.create_pool(n_process=1, address=test_addr) as pool, \\\n self.run_actor_test(pool) as test_actor:\n pool.create_actor(WorkerDaemonActor, uid=WorkerDaemonActor.default_uid())\n storage_manager_ref = pool.create_actor(\n StorageManagerActor, uid=StorageManagerActor.default_uid())\n pool.create_actor(QuotaActor, 1024 ** 2, uid=MemQuotaActor.default_uid())\n pool.create_actor(InProcHolderActor)\n\n data1 = np.random.random((10, 10))\n data2 = np.random.random((10, 10))\n ser_data2 = dataserializer.serialize(data2)\n bytes_data2 = ser_data2.to_buffer()\n\n session_id = str(uuid.uuid4())\n data_key1 = str(uuid.uuid4())\n data_key2 = str(uuid.uuid4())\n\n storage_client = test_actor.storage_client\n handler = storage_client.get_storage_handler(DataStorageDevice.PROC_MEMORY)\n\n handler.put_object(session_id, data_key1, data1)\n self.assertEqual(sorted(storage_manager_ref.get_data_locations(session_id, data_key1)),\n [(0, DataStorageDevice.PROC_MEMORY)])\n assert_allclose(data1, handler.get_object(session_id, data_key1))\n\n handler.delete(session_id, data_key1)\n self.assertIsNone(storage_manager_ref.get_data_locations(session_id, data_key1))\n with self.assertRaises(KeyError):\n handler.get_object(session_id, data_key1)\n\n handler.put_object(session_id, data_key2, ser_data2, serialized=True)\n assert_allclose(data2, handler.get_object(session_id, data_key2))\n handler.delete(session_id, data_key2)\n\n handler.put_object(session_id, data_key2, bytes_data2, serialized=True)\n assert_allclose(data2, handler.get_object(session_id, data_key2))\n handler.delete(session_id, data_key2)\n\n def testProcMemLoad(self):\n test_addr = '127.0.0.1:%d' % get_next_port()\n with self.create_pool(n_process=1, address=test_addr) as pool, \\\n self.run_actor_test(pool) as test_actor:\n pool.create_actor(WorkerDaemonActor, uid=WorkerDaemonActor.default_uid())\n storage_manager_ref = pool.create_actor(\n StorageManagerActor, uid=StorageManagerActor.default_uid())\n\n pool.create_actor(QuotaActor, 1024 ** 2, uid=MemQuotaActor.default_uid())\n pool.create_actor(InProcHolderActor)\n\n pool.create_actor(PlasmaKeyMapActor, uid=PlasmaKeyMapActor.default_uid())\n pool.create_actor(SharedHolderActor, uid=SharedHolderActor.default_uid())\n\n data1 = np.random.random((10, 10))\n data2 = np.random.random((10, 10))\n ser_data1 = dataserializer.serialize(data1)\n\n session_id = str(uuid.uuid4())\n data_key1 = str(uuid.uuid4())\n data_key2 = str(uuid.uuid4())\n\n storage_client = test_actor.storage_client\n handler = storage_client.get_storage_handler(DataStorageDevice.PROC_MEMORY)\n\n # load from bytes io\n disk_handler = storage_client.get_storage_handler(DataStorageDevice.DISK)\n with disk_handler.create_bytes_writer(\n session_id, data_key1, ser_data1.total_bytes) as writer:\n ser_data1.write_to(writer)\n\n handler.load_from_bytes_io(session_id, data_key1, disk_handler) \\\n .then(lambda *_: test_actor.set_result(None),\n lambda *exc: test_actor.set_result(exc, accept=False))\n self.get_result(5)\n self.assertEqual(sorted(storage_manager_ref.get_data_locations(session_id, data_key1)),\n [(0, DataStorageDevice.PROC_MEMORY), (0, DataStorageDevice.DISK)])\n\n disk_handler.delete(session_id, data_key1)\n\n data_load = handler.get_object(session_id, data_key1)\n ref_data = weakref.ref(data_load)\n del data_load\n handler.delete(session_id, data_key1)\n self.assertIsNone(ref_data())\n\n # load from object io\n shared_handler = storage_client.get_storage_handler(DataStorageDevice.SHARED_MEMORY)\n shared_handler.put_object(session_id, data_key2, data2)\n\n handler.load_from_object_io(session_id, data_key2, shared_handler) \\\n .then(lambda *_: test_actor.set_result(None),\n lambda *exc: test_actor.set_result(exc, accept=False))\n self.get_result(5)\n self.assertEqual(sorted(storage_manager_ref.get_data_locations(session_id, data_key2)),\n [(0, DataStorageDevice.PROC_MEMORY), (0, DataStorageDevice.SHARED_MEMORY)])\n\n shared_handler.delete(session_id, data_key2)\n\n data_load = handler.get_object(session_id, data_key2)\n ref_data = weakref.ref(data_load)\n del data_load\n handler.delete(session_id, data_key2)\n self.assertIsNone(ref_data())\n\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright 1999-2018 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\n\nfrom ... import opcodes as OperandDef\nfrom ...serialize import AnyField\nfrom .core import TensorRandomOperandMixin, handle_array, TensorDistribution\n\n\nclass TensorVonmises(TensorDistribution, TensorRandomOperandMixin):\n __slots__ = '_mu', '_kappa', '_size'\n _input_fields_ = ['_mu', '_kappa']\n _op_type_ = OperandDef.RAND_VONMISES\n\n _mu = AnyField('mu')\n _kappa = AnyField('kappa')\n _func_name = 'vonmises'\n\n def __init__(self, size=None, state=None, dtype=None, gpu=None, **kw):\n dtype = np.dtype(dtype) if dtype is not None else dtype\n super(TensorVonmises, self).__init__(_size=size, _state=state, _dtype=dtype,\n _gpu=gpu, **kw)\n\n @property\n def mu(self):\n return self._mu\n\n @property\n def kappa(self):\n return self._kappa\n\n def __call__(self, mu, kappa, chunk_size=None):\n return self.new_tensor([mu, kappa], None, raw_chunk_size=chunk_size)\n\n\ndef vonmises(random_state, mu, kappa, size=None, chunk_size=None, gpu=None, dtype=None):\n r\"\"\"\n Draw samples from a von Mises distribution.\n\n Samples are drawn from a von Mises distribution with specified mode\n (mu) and dispersion (kappa), on the interval [-pi, pi].\n\n The von Mises distribution (also known as the circular normal\n distribution) is a continuous probability distribution on the unit\n circle. It may be thought of as the circular analogue of the normal\n distribution.\n\n Parameters\n ----------\n mu : float or array_like of floats\n Mode (\"center\") of the distribution.\n kappa : float or array_like of floats\n Dispersion of the distribution, has to be >=0.\n size : int or tuple of ints, optional\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn. If size is ``None`` (default),\n a single value is returned if ``mu`` and ``kappa`` are both scalars.\n Otherwise, ``np.broadcast(mu, kappa).size`` samples are drawn.\n chunk_size : int or tuple of int or tuple of ints, optional\n Desired chunk size on each dimension\n gpu : bool, optional\n Allocate the tensor on GPU if True, False as default\n dtype : data-type, optional\n Data-type of the returned tensor.\n\n Returns\n -------\n out : Tensor or scalar\n Drawn samples from the parameterized von Mises distribution.\n\n See Also\n --------\n scipy.stats.vonmises : probability density function, distribution, or\n cumulative density function, etc.\n\n Notes\n -----\n The probability density for the von Mises distribution is\n\n .. math:: p(x) = \\frac{e^{\\kappa cos(x-\\mu)}}{2\\pi I_0(\\kappa)},\n\n where :math:`\\mu` is the mode and :math:`\\kappa` the dispersion,\n and :math:`I_0(\\kappa)` is the modified Bessel function of order 0.\n\n The von Mises is named for Richard Edler von Mises, who was born in\n Austria-Hungary, in what is now the Ukraine. He fled to the United\n States in 1939 and became a professor at Harvard. He worked in\n probability theory, aerodynamics, fluid mechanics, and philosophy of\n science.\n\n References\n ----------\n .. [1] Abramowitz, M. and Stegun, I. A. (Eds.). \"Handbook of\n Mathematical Functions with Formulas, Graphs, and Mathematical\n Tables, 9th printing,\" New York: Dover, 1972.\n .. [2] von Mises, R., \"Mathematical Theory of Probability\n and Statistics\", New York: Academic Press, 1964.\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> import mars.tensor as mt\n\n >>> mu, kappa = 0.0, 4.0 # mean and dispersion\n >>> s = mt.random.vonmises(mu, kappa, 1000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> from scipy.special import i0\n >>> plt.hist(s.execute(), 50, normed=True)\n >>> x = mt.linspace(-mt.pi, mt.pi, num=51)\n >>> y = mt.exp(kappa*mt.cos(x-mu))/(2*mt.pi*i0(kappa))\n >>> plt.plot(x.execute(), y.execute(), linewidth=2, color='r')\n >>> plt.show()\n \"\"\"\n if dtype is None:\n dtype = np.random.RandomState().vonmises(\n handle_array(mu), handle_array(kappa), size=(0,)).dtype\n\n size = random_state._handle_size(size)\n op = TensorVonmises(size=size, state=random_state.to_numpy(), gpu=gpu, dtype=dtype)\n return op(mu, kappa, chunk_size=chunk_size)\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright 1999-2018 Alibaba Group Holding Ltd.\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\nfrom collections import Iterable\n\nimport numpy as np\n\nfrom ... import opcodes as OperandDef\nfrom ...serialize import ValueType, KeyField, TupleField, StringField\nfrom ...core import ExecutableTuple\nfrom ...compat import izip\nfrom ..operands import TensorHasInput, TensorOperandMixin\nfrom ..datasource import tensor as astensor\nfrom ..array_utils import as_same_device, device\nfrom ..core import TensorOrder\n\n\nclass TensorUnravelIndex(TensorHasInput, TensorOperandMixin):\n _op_type_ = OperandDef.UNRAVEL_INDEX\n\n _input = KeyField('input')\n _dims = TupleField('dims', ValueType.int32)\n _order = StringField('order')\n\n def __init__(self, dims=None, dtype=None, order=None, **kw):\n super(TensorUnravelIndex, self).__init__(_dims=dims, _dtype=dtype,\n _order=order, **kw)\n if self._order is None:\n self._order = 'C'\n\n @property\n def dims(self):\n return self._dims\n\n @property\n def order(self):\n return self._order\n\n @property\n def output_limit(self):\n return float('inf')\n\n def _set_inputs(self, inputs):\n super(TensorUnravelIndex, self)._set_inputs(inputs)\n self._input = self._inputs[0]\n\n def __call__(self, indices):\n order = TensorOrder.C_ORDER if self._order == 'C' else TensorOrder.F_ORDER\n kws = [{'pos': i, 'order': order} for i in range(len(self._dims))]\n return ExecutableTuple(self.new_tensors([indices], indices.shape, kws=kws, output_limit=len(kws)))\n\n @classmethod\n def tile(cls, op):\n indices = op.inputs[0]\n dims = op.dims\n order = op.outputs[0].order\n\n out_chunks = [list() for _ in range(len(dims))]\n for in_chunk in indices.chunks:\n chunk_op = op.copy().reset_key()\n chunk_kws = [{'pos': i, 'index': in_chunk.index, 'order': order}\n for i in range(len(dims))]\n chunks = chunk_op.new_chunks([in_chunk], shape=in_chunk.shape, kws=chunk_kws,\n output_limit=len(dims))\n for out_chunk, c in zip(out_chunks, chunks):\n out_chunk.append(c)\n\n new_op = op.copy()\n kws = [{'chunks': out_chunk, 'nsplits': indices.nsplits, 'shape': o.shape}\n for out_chunk, o in zip(out_chunks, op.outputs)]\n return new_op.new_tensors(op.inputs, kws=kws, output_limit=len(dims), order=order)\n\n @classmethod\n def execute(cls, ctx, op):\n inputs, device_id, xp = as_same_device(\n [ctx[c.key] for c in op.inputs], device=op.device, ret_extra=True)\n indices = inputs[0]\n\n with device(device_id):\n outputs = xp.unravel_index(indices, op.dims, order=op.order)\n for o, output in izip(op.outputs, outputs):\n ctx[o.key] = output\n\n\ndef unravel_index(indices, dims, order='C'):\n \"\"\"\n Converts a flat index or tensor of flat indices into a tuple\n of coordinate tensors.\n\n Parameters\n ----------\n indices : array_like\n An integer tensor whose elements are indices into the flattened\n version of a tensor of dimensions ``dims``.\n dims : tuple of ints\n The shape of the tensor to use for unraveling ``indices``.\n order : {'C', 'F'}, optional\n Determines whether the indices should be viewed as indexing in\n row-major (C-style) or column-major (Fortran-style) order.\n\n Returns\n -------\n unraveled_coords : tuple of Tensor\n Each tensor in the tuple has the same shape as the ``indices``\n tensor.\n\n See Also\n --------\n ravel_multi_index\n\n Examples\n --------\n >>> import mars.tensor as mt\n >>> from mars.session import new_session\n\n >>> sess = new_session().as_default()\n\n >>> sess.run(mt.unravel_index([22, 41, 37], (7,6)))\n (array([3, 6, 6]), array([4, 5, 1]))\n\n >>> sess.run(mt.unravel_index(1621, (6,7,8,9)))\n (3, 1, 4, 1)\n \"\"\"\n indices = astensor(indices)\n if isinstance(dims, Iterable):\n dims = tuple(dims)\n else:\n dims = (dims,)\n\n if order not in 'CF':\n raise TypeError(\"only 'C' or 'F' order is permitted\")\n\n op = TensorUnravelIndex(dims=dims, dtype=np.dtype(np.intp), order=order)\n return op(indices)\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright 1999-2018 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\n\nimport numpy as np\n\nfrom mars.executor import Executor\nfrom mars.tensor import ones, add, swapaxes, moveaxis, atleast_1d, atleast_2d, \\\n atleast_3d, squeeze, tensor\nfrom mars.session import LocalSession, Session\n\n\nclass Test(unittest.TestCase):\n def setUp(self):\n self.executor = Executor('numpy')\n local_session = LocalSession()\n local_session._executor = self.executor\n self.session = Session()\n self.session._sess = local_session\n\n def testDecref(self):\n a = ones((10, 20), chunk_size=5)\n b = a + 1\n\n b.execute(session=self.session)\n\n self.assertEqual(len(self.executor.chunk_result), 1)\n\n del b\n # decref called\n self.assertEqual(len(self.executor.chunk_result), 0)\n\n def testArrayFunction(self):\n a = ones((10, 20), chunk_size=5)\n\n # test sum\n self.assertEqual(np.sum(a).execute(), 200)\n\n # test qr\n q, r = np.linalg.qr(a)\n self.assertTrue(np.allclose(np.dot(q, r), a).execute())\n\n def testViewDataOnSlice(self):\n data = np.random.rand(10, 20)\n a = tensor(data, chunk_size=6)\n b = a[:5, 5:10]\n b[:3, :3] = 3\n\n npa = data.copy()\n npb = npa[:5, 5:10]\n npb[:3, :3] = 3\n\n np.testing.assert_array_equal(b.execute(), npb)\n np.testing.assert_array_equal(a.execute(), npa)\n\n def testSetItemOnView(self):\n a = ones((5, 8), dtype=int)\n b = a[:3]\n b[0, 0] = 2\n c = b.ravel() # create view\n c[1] = 4\n\n npa = np.ones((5, 8), dtype=int)\n npb = npa[:3]\n npb[0, 0] = 2\n npc = npb.ravel() # create view\n npc[1] = 4\n\n np.testing.assert_array_equal(a.execute(), npa)\n np.testing.assert_array_equal(b.execute(), npb)\n np.testing.assert_array_equal(c.execute(), npc)\n\n def testViewDataOnTranspose(self):\n data = np.random.rand(10, 20)\n a = tensor(data, chunk_size=6)\n b = a.T\n add(b, 1, out=b)\n\n np.testing.assert_array_equal(b.execute(), data.T + 1)\n np.testing.assert_array_equal(a.execute(), data + 1)\n\n def testViewDataOnSwapaxes(self):\n data = np.random.rand(10, 20)\n a = tensor(data, chunk_size=6)\n b = swapaxes(a, 1, 0)\n a[1] = 10\n\n npa = data.copy()\n npb = np.swapaxes(npa, 1, 0)\n npa[1] = 10\n\n np.testing.assert_array_equal(b.execute(), npb)\n np.testing.assert_array_equal(a.execute(), npa)\n\n def testViewDataOnMoveaxis(self):\n data = np.random.rand(10, 20)\n a = tensor(data, chunk_size=6)\n b = moveaxis(a, 1, 0)\n a[0][1] = 10\n\n npa = data.copy()\n npb = np.moveaxis(npa, 1, 0)\n npa[0][1] = 10\n\n np.testing.assert_array_equal(b.execute(), npb)\n np.testing.assert_array_equal(a.execute(), npa)\n\n def testViewDataOnAtleast1d(self):\n a = atleast_1d(1)\n b = a[:]\n b[0] = 10\n\n np.testing.assert_array_equal(b.execute(), np.array([10]))\n np.testing.assert_array_equal(a.execute(), np.array([10]))\n\n def testViewDataOnAtleast2d(self):\n data = np.random.rand(10)\n a = atleast_2d(tensor(data, chunk_size=5))\n b = add(a[:, :5], 1, out=a[:, 5:])\n\n npa = np.atleast_2d(data.copy())\n npb = np.add(npa[:, :5], 1, out=npa[:, 5:])\n\n np.testing.assert_array_equal(b.execute(), npb)\n np.testing.assert_array_equal(a.execute(), npa)\n\n def testViewDataOnAtleast3d(self):\n data = np.random.rand(10, 20)\n a = atleast_3d(tensor(data, chunk_size=5))\n b = a[:, :5, :10][0]\n c = add(b[:4], b[1:], out=a[0, 16:])\n\n npa = np.atleast_3d(data.copy())\n npb = npa[:, :5, :10][0]\n npc = np.add(npb[:4], npb[1:], out=npa[0, 16:])\n\n np.testing.assert_array_equal(c.execute(), npc)\n np.testing.assert_array_equal(b.execute(), npb)\n np.testing.assert_array_equal(a.execute(), npa)\n\n def testViewDataOnSqueeze(self):\n data = np.random.rand(1, 4, 1)\n a = tensor(data, chunk_size=2)\n b = squeeze(a, axis=0)\n b[:3] = 10\n\n npa = data.copy()\n npb = np.squeeze(npa, axis=0)\n npb[:3] = 10\n\n np.testing.assert_array_equal(b.execute(), npb)\n np.testing.assert_array_equal(a.execute(), npa)\n\n def testViewDataOnReshape(self):\n data = np.random.random((3, 4, 5))\n a = tensor(data.copy(), chunk_size=2)\n b = a.reshape((5, 4, 3))\n b[:3] = 10\n\n npa = data.copy()\n npb = npa.reshape((5, 4, 3))\n npb[:3] = 10\n\n np.testing.assert_array_equal(b.execute(), npb)\n np.testing.assert_array_equal(a.execute(), npa)\n\n data = np.random.random((4, 5))\n a2 = tensor(data.copy(), chunk_size=2)\n b2 = a2.reshape((5, 4), order='F')\n b2[:3] = 10\n\n npa = data.copy()\n npb = npa.reshape((5, 4), order='F')\n npb[:3] = 10\n\n b2_result = b2.execute()\n np.testing.assert_array_equal(b2_result, npb)\n np.testing.assert_array_equal(a2.execute(), npa)\n\n def testViewDataOnRavel(self):\n # ravel creates a view\n data = np.random.rand(3, 4, 5)\n a = tensor(data, chunk_size=2)\n b = a.ravel()\n b[:10] = 10\n\n npa = data.copy()\n npb = npa.ravel()\n npb[:10] = 10\n\n np.testing.assert_array_equal(b.execute(), npb)\n np.testing.assert_array_equal(a.execute(), npa)\n\n # flatten creates a copy\n data = np.random.rand(3, 4, 5)\n a = tensor(data, chunk_size=2)\n b = a.flatten()\n b[:10] = 10\n\n npa = data.copy()\n npb = npa.flatten()\n npb[:10] = 10\n\n np.testing.assert_array_equal(b.execute(), npb)\n np.testing.assert_array_equal(a.execute(), npa)\n\n def testCopyAndView(self):\n data = np.random.rand(10, 20)\n a = tensor(data, chunk_size=6)\n b = a.view()\n b[:5] = 10\n\n npa = data.copy()\n npb = npa.view()\n npb[:5] = 10\n\n np.testing.assert_array_equal(b.execute(), npb)\n np.testing.assert_array_equal(a.execute(), npa)\n\n data = np.random.rand(10, 20)\n a = tensor(data.copy(), chunk_size=6)\n b = a.copy()\n b[:5] = 10\n\n npa = data.copy()\n npb = npa.copy()\n npb[:5] = 10\n\n np.testing.assert_array_equal(b.execute(), npb)\n np.testing.assert_array_equal(a.execute(), npa)\n\n a = tensor(data.copy(), chunk_size=6)\n b = a[:5, :4]\n c = b.copy()\n c[0, 0] = 10\n\n npa = data.copy()\n npb = npa[:5, :4]\n npc = npb.copy()\n npc[0, 0] =10\n\n np.testing.assert_array_equal(c.execute(), npc)\n np.testing.assert_array_equal(a.execute(), npa)\n\n def testFlat(self):\n data = np.random.rand(10, 20)\n a = tensor(data, chunk_size=4)\n fl = a.flat\n fl[1: 10] = 10\n b = fl[10: 20]\n b[0: 4] = 20\n\n npa = data.copy()\n npfl = npa.flat\n npfl[1: 10] = 10\n npb = npfl[10: 20]\n npb[0: 4] = 20\n\n np.testing.assert_array_equal(b.execute(), npb)\n np.testing.assert_array_equal(a.execute(), npa)\n", "# Copyright 1999-2018 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport contextlib\nimport multiprocessing\nimport os\nimport signal\nimport tempfile\nimport time\nimport uuid\nimport zlib\nfrom collections import defaultdict\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nfrom pyarrow import plasma\n\nfrom mars import promise\nfrom mars.actors import create_actor_pool\nfrom mars.compat import Empty, BrokenPipeError, TimeoutError\nfrom mars.config import options\nfrom mars.errors import ChecksumMismatch, DependencyMissing, StorageFull,\\\n SpillNotConfigured, ExecutionInterrupted, WorkerDead\nfrom mars.scheduler import ChunkMetaActor\nfrom mars.scheduler.utils import SchedulerClusterInfoActor\nfrom mars.serialize import dataserializer\nfrom mars.tests.core import patch_method\nfrom mars.utils import get_next_port\nfrom mars.worker import SenderActor, ReceiverActor, DispatchActor, QuotaActor, \\\n MemQuotaActor, StorageManagerActor, IORunnerActor, StatusActor, \\\n SharedHolderActor, InProcHolderActor\nfrom mars.worker.storage import DataStorageDevice\nfrom mars.worker.storage.sharedstore import PlasmaSharedStore, PlasmaKeyMapActor\nfrom mars.worker.tests.base import WorkerCase, StorageClientActor\nfrom mars.worker.transfer import ReceiveStatus, ReceiverDataMeta\nfrom mars.worker.utils import WorkerActor, WorkerClusterInfoActor\n\n\nclass MockReceiverActor(WorkerActor):\n \"\"\"\n Actor handling receiving data from a SenderActor\n \"\"\"\n def __init__(self):\n super(MockReceiverActor, self).__init__()\n self._dispatch_ref = None\n\n self._data_metas = dict()\n self._data_writers = dict()\n self._callbacks = defaultdict(list)\n\n def post_create(self):\n super(MockReceiverActor, self).post_create()\n self._dispatch_ref = self.ctx.actor_ref(DispatchActor.default_uid())\n self._dispatch_ref.register_free_slot(self.uid, 'receiver')\n\n def set_status(self, session_id, chunk_key, status):\n query_key = (session_id, chunk_key)\n try:\n self._data_metas[query_key].status = status\n except KeyError:\n self._data_metas[query_key] = ReceiverDataMeta(status=status)\n\n def get_result_data(self, session_id, chunk_key):\n buf = self._data_writers[(session_id, chunk_key)].getvalue()\n return dataserializer.loads(buf)\n\n def check_status(self, session_id, chunk_key):\n try:\n return self._data_metas[(session_id, chunk_key)].status\n except KeyError:\n return ReceiveStatus.NOT_STARTED\n\n def register_finish_callback(self, session_id, chunk_key, callback):\n query_key = (session_id, chunk_key)\n try:\n meta = self._data_metas[query_key]\n if meta.status in (ReceiveStatus.RECEIVED, ReceiveStatus.ERROR):\n self.tell_promise(callback, *meta.callback_args, **meta.callback_kwargs)\n else:\n raise KeyError\n except KeyError:\n self._callbacks[query_key].append(callback)\n\n def create_data_writer(self, session_id, chunk_key, data_size, sender_ref,\n ensure_cached=True, timeout=0, callback=None):\n from mars.compat import BytesIO\n query_key = (session_id, chunk_key)\n if query_key in self._data_metas and \\\n self._data_metas[query_key].status in (ReceiveStatus.RECEIVED, ReceiveStatus.RECEIVING):\n self.tell_promise(callback, self.address, self._data_metas[query_key].status)\n return\n self._data_metas[query_key] = ReceiverDataMeta(chunk_size=data_size, status=ReceiveStatus.RECEIVING)\n self._data_writers[query_key] = BytesIO()\n self.tell_promise(callback, self.address, None)\n\n def receive_data_part(self, session_id, chunk_key, data_part, checksum, is_last=False):\n query_key = (session_id, chunk_key)\n meta = self._data_metas[query_key] # type: ReceiverDataMeta\n if data_part:\n new_checksum = zlib.crc32(data_part, meta.checksum)\n if new_checksum != checksum:\n raise ChecksumMismatch\n meta.checksum = checksum\n self._data_writers[query_key].write(data_part)\n if is_last:\n meta.status = ReceiveStatus.RECEIVED\n for cb in self._callbacks[query_key]:\n self.tell_promise(cb)\n\n\n def cancel_receive(self, session_id, chunk_key):\n pass\n\n\[email protected]\ndef start_transfer_test_pool(**kwargs):\n address = kwargs.pop('address')\n plasma_size = kwargs.pop('plasma_size')\n with create_actor_pool(n_process=1, backend='gevent', address=address, **kwargs) as pool:\n pool.create_actor(SchedulerClusterInfoActor, [address],\n uid=SchedulerClusterInfoActor.default_uid())\n pool.create_actor(WorkerClusterInfoActor, [address],\n uid=WorkerClusterInfoActor.default_uid())\n\n pool.create_actor(PlasmaKeyMapActor, uid=PlasmaKeyMapActor.default_uid())\n pool.create_actor(StorageManagerActor, uid=StorageManagerActor.default_uid())\n pool.create_actor(ChunkMetaActor, uid=ChunkMetaActor.default_uid())\n pool.create_actor(DispatchActor, uid=DispatchActor.default_uid())\n pool.create_actor(QuotaActor, 1024 * 1024 * 20, uid=MemQuotaActor.default_uid())\n shared_holder_ref = pool.create_actor(SharedHolderActor,\n plasma_size, uid=SharedHolderActor.default_uid())\n pool.create_actor(StatusActor, address, uid=StatusActor.default_uid())\n pool.create_actor(IORunnerActor)\n pool.create_actor(StorageClientActor, uid=StorageClientActor.default_uid())\n pool.create_actor(InProcHolderActor)\n\n yield pool\n\n shared_holder_ref.destroy()\n\n\ndef run_transfer_worker(pool_address, session_id, chunk_keys, spill_dir, msg_queue):\n options.worker.spill_directory = spill_dir\n plasma_size = 1024 * 1024 * 10\n\n # don't use multiple with-statement as we need the options be forked\n with plasma.start_plasma_store(plasma_size) as store_args:\n options.worker.plasma_socket = plasma_socket = store_args[0]\n\n with start_transfer_test_pool(address=pool_address, plasma_size=plasma_size) as pool:\n storage_client_ref = pool.create_actor(StorageClientActor)\n\n for _ in range(2):\n pool.create_actor(SenderActor, uid='%s' % str(uuid.uuid4()))\n pool.create_actor(ReceiverActor, uid='%s' % str(uuid.uuid4()))\n\n for idx in range(0, len(chunk_keys) - 7):\n data = np.ones((640 * 1024,), dtype=np.int16) * idx\n storage_client_ref.put_object(session_id, chunk_keys[idx], data, [DataStorageDevice.PROC_MEMORY])\n for idx in range(len(chunk_keys) - 7, len(chunk_keys)):\n data = np.ones((640 * 1024,), dtype=np.int16) * idx\n storage_client_ref.put_object(session_id, chunk_keys[idx], data, [DataStorageDevice.SHARED_MEMORY])\n\n while not all(storage_client_ref.get_data_locations(session_id, k) for k in chunk_keys):\n pool.sleep(0.1)\n\n for idx in range(0, len(chunk_keys) - 7):\n storage_client_ref.copy_to(session_id, chunk_keys[idx], [DataStorageDevice.DISK])\n\n while not all((0, DataStorageDevice.DISK) in storage_client_ref.get_data_locations(session_id, k)\n for k in chunk_keys[:-7]):\n pool.sleep(0.1)\n\n msg_queue.put(plasma_socket)\n t = time.time()\n while True:\n try:\n msg_queue.get_nowait()\n except Empty:\n if time.time() > t + 60:\n raise SystemError('Transfer finish timed out.')\n pool.sleep(0.1)\n\n\nclass Test(WorkerCase):\n def setUp(self):\n super(Test, self).setUp()\n self._old_block_size = options.worker.transfer_block_size\n options.worker.transfer_block_size = 4 * 1024\n\n def tearDown(self):\n super(Test, self).tearDown()\n options.worker.transfer_block_size = self._old_block_size\n self.rm_spill_dirs(options.worker.spill_directory)\n\n def testSender(self):\n send_pool_addr = 'localhost:%d' % get_next_port()\n recv_pool_addr = 'localhost:%d' % get_next_port()\n recv_pool_addr2 = 'localhost:%d' % get_next_port()\n\n options.worker.spill_directory = tempfile.mkdtemp(prefix='mars_test_sender_')\n session_id = str(uuid.uuid4())\n\n mock_data = np.array([1, 2, 3, 4])\n chunk_key1 = str(uuid.uuid4())\n chunk_key2 = str(uuid.uuid4())\n\n @contextlib.contextmanager\n def start_send_recv_pool():\n with start_transfer_test_pool(\n address=send_pool_addr, plasma_size=self.plasma_storage_size) as sp:\n sp.create_actor(SenderActor, uid=SenderActor.default_uid())\n with start_transfer_test_pool(\n address=recv_pool_addr, plasma_size=self.plasma_storage_size) as rp:\n rp.create_actor(MockReceiverActor, uid=ReceiverActor.default_uid())\n yield sp, rp\n\n with start_send_recv_pool() as (send_pool, recv_pool):\n sender_ref = send_pool.actor_ref(SenderActor.default_uid())\n receiver_ref = recv_pool.actor_ref(ReceiverActor.default_uid())\n\n with self.run_actor_test(send_pool) as test_actor:\n storage_client = test_actor.storage_client\n\n # send when data missing\n sender_ref_p = test_actor.promise_ref(sender_ref)\n sender_ref_p.send_data(session_id, str(uuid.uuid4()), recv_pool_addr, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s)) \\\n .catch(lambda *exc: test_actor.set_result(exc, accept=False))\n with self.assertRaises(DependencyMissing):\n self.get_result(5)\n\n # send data in spill\n serialized = dataserializer.serialize(mock_data)\n self.waitp(\n storage_client.create_writer(session_id, chunk_key1, serialized.total_bytes,\n [DataStorageDevice.DISK])\n .then(lambda writer: promise.finished().then(lambda *_: writer.write(serialized))\n .then(lambda *_: writer.close()))\n )\n\n sender_ref_p.send_data(session_id, chunk_key1, recv_pool_addr, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s)) \\\n .catch(lambda *exc: test_actor.set_result(exc, accept=False))\n self.get_result(5)\n assert_array_equal(mock_data, receiver_ref.get_result_data(session_id, chunk_key1))\n storage_client.delete(session_id, chunk_key1)\n\n # send data in plasma store\n self.waitp(\n storage_client.put_object(session_id, chunk_key1, mock_data, [DataStorageDevice.SHARED_MEMORY])\n )\n\n sender_ref_p.send_data(session_id, chunk_key1, recv_pool_addr, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s)) \\\n .catch(lambda *exc: test_actor.set_result(exc, accept=False))\n self.get_result(5)\n assert_array_equal(mock_data, receiver_ref.get_result_data(session_id, chunk_key1))\n\n # send data to multiple targets\n with start_transfer_test_pool(\n address=recv_pool_addr2, plasma_size=self.plasma_storage_size) as rp2:\n recv_ref2 = rp2.create_actor(MockReceiverActor, uid=ReceiverActor.default_uid())\n\n self.waitp(\n sender_ref_p.send_data(session_id, chunk_key1,\n [recv_pool_addr, recv_pool_addr2], _promise=True)\n )\n # send data to already transferred / transferring\n sender_ref_p.send_data(session_id, chunk_key1,\n [recv_pool_addr, recv_pool_addr2], _promise=True) \\\n .then(lambda *s: test_actor.set_result(s)) \\\n .catch(lambda *exc: test_actor.set_result(exc, accept=False))\n self.get_result(5)\n assert_array_equal(mock_data, recv_ref2.get_result_data(session_id, chunk_key1))\n\n # send data to non-exist endpoint which causes error\n self.waitp(\n storage_client.put_object(session_id, chunk_key2, mock_data, [DataStorageDevice.SHARED_MEMORY])\n )\n\n sender_ref_p.send_data(session_id, chunk_key2, recv_pool_addr2, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s)) \\\n .catch(lambda *exc: test_actor.set_result(exc, accept=False))\n with self.assertRaises(BrokenPipeError):\n self.get_result(5)\n\n def mocked_receive_data_part(*_, **__):\n raise ChecksumMismatch\n\n with patch_method(MockReceiverActor.receive_data_part, new=mocked_receive_data_part):\n sender_ref_p.send_data(session_id, chunk_key2, recv_pool_addr, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s)) \\\n .catch(lambda *exc: test_actor.set_result(exc, accept=False))\n with self.assertRaises(ChecksumMismatch):\n self.get_result(5)\n\n def testReceiver(self):\n pool_addr = 'localhost:%d' % get_next_port()\n options.worker.spill_directory = tempfile.mkdtemp(prefix='mars_test_receiver_')\n session_id = str(uuid.uuid4())\n\n mock_data = np.array([1, 2, 3, 4])\n serialized_arrow_data = dataserializer.serialize(mock_data)\n data_size = serialized_arrow_data.total_bytes\n serialized_mock_data = serialized_arrow_data.to_buffer()\n serialized_crc32 = zlib.crc32(serialized_arrow_data.to_buffer())\n\n chunk_key1 = str(uuid.uuid4())\n chunk_key2 = str(uuid.uuid4())\n chunk_key3 = str(uuid.uuid4())\n chunk_key4 = str(uuid.uuid4())\n chunk_key5 = str(uuid.uuid4())\n chunk_key6 = str(uuid.uuid4())\n chunk_key7 = str(uuid.uuid4())\n\n with start_transfer_test_pool(address=pool_addr, plasma_size=self.plasma_storage_size) as pool:\n receiver_ref = pool.create_actor(ReceiverActor, uid=str(uuid.uuid4()))\n\n with self.run_actor_test(pool) as test_actor:\n storage_client = test_actor.storage_client\n\n # check_status on receiving and received\n self.assertEqual(receiver_ref.check_status(session_id, chunk_key1),\n ReceiveStatus.NOT_STARTED)\n\n self.waitp(\n storage_client.create_writer(session_id, chunk_key1, serialized_arrow_data.total_bytes,\n [DataStorageDevice.DISK])\n .then(lambda writer: promise.finished().then(lambda *_: writer.write(serialized_arrow_data))\n .then(lambda *_: writer.close()))\n )\n self.assertEqual(receiver_ref.check_status(session_id, chunk_key1),\n ReceiveStatus.RECEIVED)\n storage_client.delete(session_id, chunk_key1)\n\n self.waitp(\n storage_client.put_object(session_id, chunk_key1, mock_data, [DataStorageDevice.SHARED_MEMORY])\n )\n\n self.assertEqual(receiver_ref.check_status(session_id, chunk_key1),\n ReceiveStatus.RECEIVED)\n\n receiver_ref_p = test_actor.promise_ref(receiver_ref)\n\n # cancel on an un-run / missing result will result in nothing\n receiver_ref_p.cancel_receive(session_id, chunk_key2)\n\n # start creating writer\n receiver_ref_p.create_data_writer(session_id, chunk_key1, data_size, test_actor, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s))\n self.assertTupleEqual(self.get_result(5), (receiver_ref.address, ReceiveStatus.RECEIVED))\n\n result = receiver_ref_p.create_data_writer(session_id, chunk_key1, data_size, test_actor,\n use_promise=False)\n self.assertTupleEqual(result, (receiver_ref.address, ReceiveStatus.RECEIVED))\n\n receiver_ref_p.create_data_writer(session_id, chunk_key2, data_size, test_actor, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s))\n self.assertTupleEqual(self.get_result(5), (receiver_ref.address, None))\n\n result = receiver_ref_p.create_data_writer(session_id, chunk_key2, data_size, test_actor,\n use_promise=False)\n self.assertTupleEqual(result, (receiver_ref.address, ReceiveStatus.RECEIVING))\n\n receiver_ref_p.create_data_writer(session_id, chunk_key2, data_size, test_actor, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s))\n self.assertTupleEqual(self.get_result(5), (receiver_ref.address, ReceiveStatus.RECEIVING))\n\n receiver_ref_p.cancel_receive(session_id, chunk_key2)\n self.assertEqual(receiver_ref.check_status(session_id, chunk_key2),\n ReceiveStatus.NOT_STARTED)\n\n # test checksum error on receive_data_part\n receiver_ref_p.create_data_writer(session_id, chunk_key2, data_size, test_actor, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s))\n self.get_result(5)\n\n receiver_ref_p.register_finish_callback(session_id, chunk_key2, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s)) \\\n .catch(lambda *exc: test_actor.set_result(exc, accept=False))\n\n receiver_ref_p.receive_data_part(session_id, chunk_key2, serialized_mock_data, 0)\n\n with self.assertRaises(ChecksumMismatch):\n self.get_result(5)\n\n receiver_ref_p.cancel_receive(session_id, chunk_key2)\n\n # test intermediate cancellation\n receiver_ref_p.create_data_writer(session_id, chunk_key2, data_size, test_actor, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s))\n self.assertTupleEqual(self.get_result(5), (receiver_ref.address, None))\n\n receiver_ref_p.register_finish_callback(session_id, chunk_key2, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s)) \\\n .catch(lambda *exc: test_actor.set_result(exc, accept=False))\n\n receiver_ref_p.receive_data_part(session_id, chunk_key2, serialized_mock_data[:64],\n zlib.crc32(serialized_mock_data[:64]))\n receiver_ref_p.cancel_receive(session_id, chunk_key2)\n receiver_ref_p.receive_data_part(session_id, chunk_key2, serialized_mock_data[64:],\n serialized_crc32)\n with self.assertRaises(ExecutionInterrupted):\n self.get_result(5)\n\n # test transfer in memory\n receiver_ref_p.register_finish_callback(session_id, chunk_key3, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s)) \\\n .catch(lambda *exc: test_actor.set_result(exc, accept=False))\n\n receiver_ref_p.create_data_writer(session_id, chunk_key3, data_size, test_actor, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s))\n self.assertTupleEqual(self.get_result(5), (receiver_ref.address, None))\n\n receiver_ref_p.receive_data_part(session_id, chunk_key3, serialized_mock_data[:64],\n zlib.crc32(serialized_mock_data[:64]))\n receiver_ref_p.receive_data_part(\n session_id, chunk_key3, serialized_mock_data[64:], serialized_crc32, is_last=True)\n\n self.assertTupleEqual((), self.get_result(5))\n\n receiver_ref_p.create_data_writer(session_id, chunk_key3, data_size, test_actor, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s))\n self.assertTupleEqual(self.get_result(5), (receiver_ref.address, ReceiveStatus.RECEIVED))\n\n # test transfer in spill file\n def mocked_store_create(*_):\n raise StorageFull\n\n with patch_method(PlasmaSharedStore.create, new=mocked_store_create):\n with self.assertRaises(StorageFull):\n receiver_ref_p.create_data_writer(session_id, chunk_key4, data_size, test_actor,\n ensure_cached=True, use_promise=False)\n # test receive aborted\n receiver_ref_p.create_data_writer(\n session_id, chunk_key4, data_size, test_actor, ensure_cached=False, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s))\n self.assertTupleEqual(self.get_result(5), (receiver_ref.address, None))\n\n receiver_ref_p.register_finish_callback(session_id, chunk_key4, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s)) \\\n .catch(lambda *exc: test_actor.set_result(exc, accept=False))\n\n receiver_ref_p.receive_data_part(session_id, chunk_key4, serialized_mock_data[:64],\n zlib.crc32(serialized_mock_data[:64]))\n receiver_ref_p.cancel_receive(session_id, chunk_key4)\n with self.assertRaises(ExecutionInterrupted):\n self.get_result(5)\n\n # test receive into spill\n receiver_ref_p.create_data_writer(\n session_id, chunk_key4, data_size, test_actor, ensure_cached=False, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s))\n self.assertTupleEqual(self.get_result(5), (receiver_ref.address, None))\n\n receiver_ref_p.register_finish_callback(session_id, chunk_key4, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s)) \\\n .catch(lambda *exc: test_actor.set_result(exc, accept=False))\n\n receiver_ref_p.receive_data_part(\n session_id, chunk_key4, serialized_mock_data, serialized_crc32, is_last=True)\n self.assertTupleEqual((), self.get_result(5))\n\n # test intermediate error\n def mocked_store_create(*_):\n raise SpillNotConfigured\n\n with patch_method(PlasmaSharedStore.create, new=mocked_store_create):\n receiver_ref_p.create_data_writer(\n session_id, chunk_key5, data_size, test_actor, ensure_cached=False, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s),\n lambda *s: test_actor.set_result(s, accept=False))\n\n with self.assertRaises(SpillNotConfigured):\n self.get_result(5)\n\n # test receive timeout\n receiver_ref_p.register_finish_callback(session_id, chunk_key6, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s)) \\\n .catch(lambda *exc: test_actor.set_result(exc, accept=False))\n\n receiver_ref_p.create_data_writer(session_id, chunk_key6, data_size, test_actor,\n timeout=2, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s))\n self.assertTupleEqual(self.get_result(5), (receiver_ref.address, None))\n receiver_ref_p.receive_data_part(session_id, chunk_key6, serialized_mock_data[:64],\n zlib.crc32(serialized_mock_data[:64]))\n\n with self.assertRaises(TimeoutError):\n self.get_result(5)\n\n # test sender halt\n receiver_ref_p.register_finish_callback(session_id, chunk_key7, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s)) \\\n .catch(lambda *exc: test_actor.set_result(exc, accept=False))\n\n mock_ref = pool.actor_ref(test_actor.uid, address='MOCK_ADDR')\n receiver_ref_p.create_data_writer(\n session_id, chunk_key7, data_size, mock_ref, _promise=True) \\\n .then(lambda *s: test_actor.set_result(s))\n self.assertTupleEqual(self.get_result(5), (receiver_ref.address, None))\n receiver_ref_p.receive_data_part(session_id, chunk_key7, serialized_mock_data[:64],\n zlib.crc32(serialized_mock_data[:64]))\n receiver_ref_p.notify_dead_senders(['MOCK_ADDR'])\n\n with self.assertRaises(WorkerDead):\n self.get_result(5)\n\n def testSimpleTransfer(self):\n session_id = str(uuid.uuid4())\n\n local_pool_addr = 'localhost:%d' % get_next_port()\n remote_pool_addr = 'localhost:%d' % get_next_port()\n remote_chunk_keys = [str(uuid.uuid4()) for _ in range(9)]\n msg_queue = multiprocessing.Queue()\n\n remote_spill_dir = tempfile.mkdtemp(prefix='mars_test_simple_transfer_')\n\n proc = multiprocessing.Process(\n target=run_transfer_worker,\n args=(remote_pool_addr, session_id, remote_chunk_keys, remote_spill_dir, msg_queue)\n )\n proc.start()\n try:\n remote_plasma_socket = msg_queue.get(timeout=30)\n except Empty:\n if proc.is_alive():\n proc.terminate()\n raise\n\n with start_transfer_test_pool(address=local_pool_addr, plasma_size=self.plasma_storage_size) as pool:\n sender_refs, receiver_refs = [], []\n for _ in range(2):\n sender_refs.append(pool.create_actor(SenderActor, uid=str(uuid.uuid4())))\n receiver_refs.append(pool.create_actor(ReceiverActor, uid=str(uuid.uuid4())))\n\n try:\n for data_id in (-1, 0):\n chunk_key = remote_chunk_keys[data_id]\n\n with self.run_actor_test(pool) as test_actor:\n remote_dispatch_ref = test_actor.promise_ref(\n DispatchActor.default_uid(), address=remote_pool_addr)\n\n def _call_send_data(sender_uid):\n sender_ref = test_actor.promise_ref(sender_uid, address=remote_pool_addr)\n return sender_ref.send_data(session_id, chunk_key, local_pool_addr, _promise=True)\n\n def _test_data_exist(*_):\n local_client_ref = test_actor.promise_ref(StorageClientActor.default_uid())\n remote_client_ref = test_actor.promise_ref(StorageClientActor.default_uid(),\n address=remote_pool_addr)\n\n targets = [DataStorageDevice.PROC_MEMORY]\n return local_client_ref.get_object(session_id, chunk_key, targets, _promise=True) \\\n .then(lambda local_data: remote_client_ref.get_object(\n session_id, chunk_key, targets, _promise=True)\n .then(lambda remote_data: assert_array_equal(local_data, remote_data))) \\\n\n remote_dispatch_ref.get_free_slot('sender', _promise=True) \\\n .then(_call_send_data) \\\n .then(_test_data_exist) \\\n .then(\n lambda *_: test_actor.set_result(chunk_key),\n lambda *exc: test_actor.set_result(exc, False),\n )\n self.assertEqual(self.get_result(60), chunk_key)\n\n msg_queue.put(1)\n finally:\n [pool.destroy_actor(ref) for ref in sender_refs + receiver_refs]\n\n os.unlink(remote_plasma_socket)\n os.kill(proc.pid, signal.SIGINT)\n\n t = time.time()\n while proc.is_alive() and time.time() < t + 2:\n time.sleep(1)\n if proc.is_alive():\n proc.terminate()\n\n self.rm_spill_dirs(remote_spill_dir)\n" ]
[ [ "numpy.dtype" ], [ "numpy.random.random" ], [ "numpy.random.random" ], [ "numpy.random.RandomState", "numpy.dtype" ], [ "numpy.dtype" ], [ "numpy.dot", "numpy.swapaxes", "numpy.random.random", "numpy.squeeze", "numpy.ones", "numpy.testing.assert_array_equal", "numpy.random.rand", "numpy.moveaxis", "numpy.linalg.qr", "numpy.add", "numpy.array", "numpy.sum" ], [ "numpy.testing.assert_array_equal", "numpy.array", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
nabobalis/glue
[ "1c718378b5527e64d85cc6a6f9a0330652e5cf4b" ]
[ "glue/viewers/image/composite_array.py" ]
[ "# This artist can be used to deal with the sampling of the data as well as any\n# RGB blending.\n\nimport numpy as np\n\nfrom matplotlib.colors import ColorConverter, Colormap\nfrom astropy.visualization import (LinearStretch, SqrtStretch, AsinhStretch,\n LogStretch, ManualInterval, ContrastBiasStretch)\n\n\n__all__ = ['CompositeArray']\n\nCOLOR_CONVERTER = ColorConverter()\n\nSTRETCHES = {\n 'linear': LinearStretch,\n 'sqrt': SqrtStretch,\n 'arcsinh': AsinhStretch,\n 'log': LogStretch\n}\n\n\nclass CompositeArray(object):\n\n def __init__(self, **kwargs):\n\n # We keep a dictionary of layers. The key should be the UUID of the\n # layer artist, and the values should be dictionaries that contain\n # 'zorder', 'visible', 'array', 'color', and 'alpha'.\n self.layers = {}\n\n self._first = True\n\n def allocate(self, uuid):\n self.layers[uuid] = {'zorder': 0,\n 'visible': True,\n 'array': None,\n 'shape': None,\n 'color': '0.5',\n 'alpha': 1,\n 'clim': (0, 1),\n 'contrast': 1,\n 'bias': 0.5,\n 'stretch': 'linear'}\n\n def deallocate(self, uuid):\n self.layers.pop(uuid)\n\n def set(self, uuid, **kwargs):\n for key, value in kwargs.items():\n if key not in self.layers[uuid]:\n raise KeyError(\"Unknown key: {0}\".format(key))\n else:\n self.layers[uuid][key] = value\n\n @property\n def shape(self):\n for layer in self.layers.values():\n if callable(layer['shape']):\n shape = layer['shape']()\n elif layer['shape'] is not None:\n shape = layer['shape']\n elif callable(layer['array']):\n array = layer['array']()\n if array is None:\n return None\n else:\n shape = array.shape\n else:\n shape = layer['array'].shape\n if shape is not None:\n return shape\n return None\n\n def __getitem__(self, item):\n return self()[item]\n\n def __call__(self, bounds=None):\n\n img = None\n visible_layers = 0\n\n for uuid in sorted(self.layers, key=lambda x: self.layers[x]['zorder']):\n\n layer = self.layers[uuid]\n\n if not layer['visible']:\n continue\n\n interval = ManualInterval(*layer['clim'])\n contrast_bias = ContrastBiasStretch(layer['contrast'], layer['bias'])\n\n if callable(layer['array']):\n array = layer['array'](bounds=bounds)\n else:\n array = layer['array']\n\n if array is None:\n continue\n\n if np.isscalar(array):\n scalar = True\n array = np.atleast_2d(array)\n else:\n scalar = False\n\n data = STRETCHES[layer['stretch']]()(contrast_bias(interval(array)))\n data[np.isnan(data)] = 0\n\n if isinstance(layer['color'], Colormap):\n\n if img is None:\n img = np.ones(data.shape + (4,))\n\n # Compute colormapped image\n plane = layer['color'](data)\n\n alpha_plane = layer['alpha'] * plane[:, :, 3]\n\n # Use traditional alpha compositing\n plane[:, :, 0] = plane[:, :, 0] * alpha_plane\n plane[:, :, 1] = plane[:, :, 1] * alpha_plane\n plane[:, :, 2] = plane[:, :, 2] * alpha_plane\n\n img[:, :, 0] *= (1 - alpha_plane)\n img[:, :, 1] *= (1 - alpha_plane)\n img[:, :, 2] *= (1 - alpha_plane)\n img[:, :, 3] = 1\n\n else:\n\n if img is None:\n img = np.zeros(data.shape + (4,))\n\n # Get color and pre-multiply by alpha values\n color = COLOR_CONVERTER.to_rgba_array(layer['color'])[0]\n color *= layer['alpha']\n\n # We should treat NaN values as zero (post-stretch), which means\n # that those pixels don't contribute towards the final image.\n reset = np.isnan(data)\n if np.any(reset):\n data[reset] = 0.\n\n plane = data[:, :, np.newaxis] * color\n plane[:, :, 3] = 1\n\n visible_layers += 1\n\n if scalar:\n plane = plane[0, 0]\n\n img += plane\n\n if img is None:\n return None\n else:\n img = np.clip(img, 0, 1)\n\n return img\n\n @property\n def dtype(self):\n return np.dtype(float)\n\n @property\n def ndim(self):\n return 2\n\n @property\n def size(self):\n return np.product(self.shape)\n\n def __contains__(self, item):\n return item in self.layers\n" ]
[ [ "numpy.product", "numpy.clip", "numpy.isnan", "numpy.dtype", "numpy.ones", "numpy.atleast_2d", "matplotlib.colors.ColorConverter", "numpy.isscalar", "numpy.any", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
SalAlba/matplotlib
[ "f73ff4e77074152fb9abc400d66f56111e656687" ]
[ "tutorial/basic/ex3.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\n\n\nfrom sal_timer import timer\n\n\n\ndef plot_1():\n # ...\n data = {\n 'a': np.arange(50),\n 'c': np.random.randint(0, 50, 50),\n 'd': np.random.randn(50)\n }\n data['b'] = data['a'] + 10 * np.random.randn(50)\n data['d'] = np.abs(data['d']) * 100\n\n # ...\n # x : x\n # y : y\n # c : color\n # s : size\n plt.scatter(x='a', y='b', c='c', s='d', data=data)\n\n # ...\n plt.xlabel('entry a')\n plt.ylabel('entry b')\n plt.show()\n\n\n\n@timer\ndef main():\n plot_1()\n\n\n\nif __name__ == '__main__':\n print('========================================== START ==========================================')\n #...\n main()\n print('========================================== END ============================================')" ]
[ [ "numpy.abs", "matplotlib.pyplot.scatter", "numpy.arange", "numpy.random.randint", "numpy.random.randn", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
eherr/vis_utils
[ "b757b01f42e6da02ad62130c3b0e61e9eaa3886f", "b757b01f42e6da02ad62130c3b0e61e9eaa3886f", "b757b01f42e6da02ad62130c3b0e61e9eaa3886f" ]
[ "vis_utils/graphics/geometry/splines.py", "vis_utils/animation/point_cloud_animation_controller.py", "vis_utils/graphics/light/directional_light.py" ]
[ "#!/usr/bin/env python\n#\n# Copyright 2019 DFKI GmbH.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the\n# following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n# USE OR OTHER DEALINGS IN THE SOFTWARE.\n# -*- coding: utf-8 -*-\n\n\nimport numpy as np\nimport scipy.interpolate as si\nimport math\nfrom .utils import closestLowerValueBinarySearch\n \nB_SPLINE_DEGREE=3\n\n\nclass BSplineWrapper(object):\n def __init__(self, points, degree=B_SPLINE_DEGREE, domain=None):\n self.points = np.array(points)\n if isinstance(points[0], (int, float, complex)):\n self.dimensions = 1\n else:\n self.dimensions = len(points[0])\n self.degree = degree\n if domain is not None:\n self.domain = domain\n else:\n self.domain = (0.0, 1.0)\n \n self.initiated = True\n self.spline_def = []\n points_t = np.array(points).T\n t_func = np.linspace(self.domain[0], self.domain[1], len(points)).tolist()\n for d in range(len(points_t)):\n #print d, self.dimensions\n self.spline_def.append(si.splrep(t_func, points_t[d], w=None, k=3))\n\n def _initiate_control_points(self):\n return\n\n def clear(self):\n return\n\n def queryPoint(self, u):\n \"\"\"\n\n \"\"\"\n point = []\n for d in range(self.dimensions):\n point.append(si.splev(u, self.spline_def[d]))\n return np.array(point)\n\n def get_last_control_point(self):\n return self.points[-1]\n\nclass BSpline(object):\n \"\"\"\n http://demonstrations.wolfram.com/GeneratingABSplineCurveByTheCoxDeBoorAlgorithm/\n http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/B-spline/bspline-basis.html\n \"\"\"\n def __init__(self, points, degree=3, domain=None):\n self.points = np.array(points)\n if isinstance(points[0], (int, float, complex)):\n self.dimensions = 1\n else:\n self.dimensions = len(points[0])\n self.degree = degree\n if domain is not None:\n self.domain = domain\n else:\n self.domain = (0.0, 1.0)\n self.knots = None\n self.initiated = False\n self._create_knots()\n\n def _initiate_control_points(self):\n return\n\n def clear(self):\n return\n\n def get_last_control_point(self):\n return self.points[-1]\n\n def _create_knots(self):\n \"\"\"\n http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/B-spline/bspline-curve.html\n #To change the shape of a B-spline curve, one can modify one or more of \n #these control parameters: \n #the positions of control points, the positions of knots, and the degree of the curve.\n # given n+1 control points and m+1 knots the following property must be true\n #m = n + p + 1. // p+1 = m-n\n # for a campled curve the last knot must be of multiplicity p+1\n \n If you have n+1 control points (n=9) and p = 3. \n Then, m must be 13 so that the knot vector has 14 knots\n The remaining 14 - (4 + 4) = 6 knots can be anywhere in the domain. \n U = { 0, 0, 0, 0, 0.14, 0.28, 0.42, 0.57, 0.71, 0.85, 1, 1, 1, 1 }. \n how do find the knot points C(ui).\n \"\"\"\n outer_knots = self.degree+1\n print(\"multiplicity\", outer_knots)\n n = len(self.points) - 1 \n print(\"control points\", len(self.points))\n print(\"n\", n)\n p = self.degree\n m = n + p + 1\n n_knots = m + 1\n inner_knots = n_knots-(outer_knots*2 - 2)\n print(\"knots\", n_knots)\n print(\"free knots\", inner_knots)\n print(\"domain\", self.domain)\n #print np.linspace(0.0, 1.0, 4)\n knots = np.linspace(self.domain[0], self.domain[1], inner_knots).tolist()\n #print self.knots\n self.knots = knots[:1] * (outer_knots-1) + knots +\\\n knots[-1:] * (outer_knots-1)\n print(self.knots)\n print(len(self.knots))\n self.initiated = True\n\n def queryPoint(self, u):\n \"\"\"\n\n \"\"\"\n return self.evaluate(u, algorithm=\"deboor\")\n\n def evaluate(self, u, algorithm=\"standard\"):\n #print \"evaluate\", u\n if self.domain[0] < u < self.domain[1]:\n if algorithm == \"standard\":\n value = 0.0#np.zeros(self.dim)\n n = len(self.points)\n w_list = []\n for i in range(n):\n #i+=self.degree\n #print \"iteration\",i, self.basis(u, i, self.degree)\n #i = self.get_begin_of_knot_range(u)\n w = self.basis(u, i, self.degree)\n w_list.append(w)\n #print temp\n value += w * self.points[i]\n #print sum(w_list)\n return value\n elif algorithm == \"deboor\":\n i = self.get_begin_of_knot_range(u)\n #print u\n return self.deboor(self.degree, self.degree, u, i)\n elif u >= self.domain[1]:\n return self.points[-1]\n elif u <= self.domain[0]:\n return self.points[0]\n\n def basis(self, u, i, p):\n \"\"\"http://devosaurus.blogspot.de/2013/10/exploring-b-splines-in-python.html\n \"\"\"\n if p == 0:\n if self.knots[i] <= u < self.knots[i+1]:\n return 1.0\n else:\n return 0.0\n elif p >= 1:\n #print i+p\n #print \"knot interval\", i, i+p, self.knots[i+p]\n out = 0.0\n w_nom = (u-self.knots[i])\n w_denom = (self.knots[i+p]-self.knots[i])\n if w_denom > 0.0:\n w = w_nom / w_denom\n out += w * self.basis(u, i, p-1)\n \n w_inv_nom = (self.knots[i+p+1] - u)\n w_inv_denom = (self.knots[i+p+1] - self.knots[i+1])\n if w_inv_denom > 0.0:\n w_inv = w_inv_nom / w_inv_denom\n out += w_inv * self.basis(u, i+1, p-1)\n return out\n \n def get_begin_of_knot_range(self, u):\n begin_of_range = 0 \n for i, u_i in enumerate(self.knots):\n if u_i < u:\n begin_of_range = i\n else:\n break\n #print \"begin\", begin_of_range\n return begin_of_range\n \n def deboor(self, k, p, u, i):\n \"\"\"\n https://chi3x10.wordpress.com/2009/10/18/de-boor-algorithm-in-c/\n \"\"\"\n if k == 0:\n return self.points[i]\n elif k >= 1:\n\n denom = (self.knots[i+p+1-k] - self.knots[i])\n if denom >0:\n alpha = (u-self.knots[i])/denom\n return (1-alpha) * self.deboor(k-1, p, u, i-1) \\\n + (alpha * self.deboor(k-1, p, u, i))\n else:\n return np.zeros(self.dimensions)\n\n\nclass CatmullRomSpline():\n '''\n spline that goes through control points with arc length mapping used by motion planning\n implemented using the following resources and examples:\n #http://www.cs.cmu.edu/~462/projects/assn2/assn2/catmullRom.pdf\n #http://algorithmist.net/docs/catmullrom.pdf\n #http://www.mvps.org/directx/articles/catmull/\n #http://hawkesy.blogspot.de/2010/05/catmull-rom-spline-curve-implementation.html\n #http://pages.cpsc.ucalgary.ca/~jungle/587/pdf/5-interpolation.pdf\n '''\n def __init__(self,controlPoints, dimensions, granularity=100):\n self.granularity = granularity\n #http://algorithmist.net/docs/catmullrom.pdf\n #base matrix to calculate one component of a point on the spline based on the influence of control points\n self.catmullRomBaseMatrix = np.array([[-1.0, 3.0, -3.0, 1.0],\n [2.0, -5.0, 4.0, -1.0],\n [-1.0, 0.0, 1.0, 0.0],\n [0.0, 2.0, 0.0, 0.0]])\n self.dimensions = dimensions\n self.fullArcLength = 0\n self.initiated = False\n self.controlPoints = []\n self.numberOfSegments = 0\n if len (controlPoints) >0:\n self.initiateControlPoints(controlPoints)\n self.initiated = True\n\n\n def initiateControlPoints(self,controlPoints):\n '''\n @param controlPoints array of class accessible by controlPoints[index][dimension]\n '''\n self.numberOfSegments = len(controlPoints)-1\n self.controlPoints = [controlPoints[0]]+controlPoints+[controlPoints[-1],controlPoints[-1]]#as a workaround add multiple points at the end instead of one\n print(\"length of control point list \",len(self.controlPoints))\n print(\"number of segments \",self.numberOfSegments)\n print(\"number of dimensions\",self.dimensions)\n\n\n self.updateArcLengthMappingTable()\n\n return\n\n def addPoint(self,point):\n\n #add point replace auxiliary control points\n if self.initiated:\n del self.controlPoints[-2:]\n self.numberOfSegments = len(self.controlPoints)-1#\"-2 + 1\n self.controlPoints += [point,point,point]\n print(self.controlPoints)\n\n #update arc length mapping\n self.updateArcLengthMappingTable()\n else:\n self.initiateControlPoints([point,])\n self.initiated = True\n\n\n def clear(self):\n self.controlPoints = []\n self.initiated = False\n self.fullArcLength = 0\n self.numberOfSegments = 0\n self.arcLengthMap = []\n\n def transformByMatrix(self,matrix):\n '''\n matrix nxn transformation matrix where n is the number of dimensions of the catmull rom spline\n '''\n if self.dimensions < matrix.shape[0]:\n for i in range(len(self.controlPoints)):\n self.controlPoints[i] = np.dot(matrix, self.controlPoints[i])\n else:\n print(\"failed\",matrix.shape)\n return\n\n def updateArcLengthMappingTable(self):\n '''\n creates a table that maps from parameter space of query point to relative arc length based on the given granularity in the constructor of the catmull rom spline\n http://pages.cpsc.ucalgary.ca/~jungle/587/pdf/5-interpolation.pdf\n '''\n self.fullArcLength = 0\n granularity = self.granularity\n u = np.arange(granularity+1) / float(granularity)\n lastPoint = None\n numberOfEvalulations = 0\n self.arcLengthMap = []\n for i in u:\n point = self.queryPoint(i)\n if lastPoint is not None:\n delta = []\n d = 0\n while d < self.dimensions:\n delta.append(math.sqrt((point[d]-lastPoint[d])**2))\n d += 1\n self.fullArcLength += np.sum(delta)#(point-lastPoint).length()\n #print self.fullArcLength\n self.arcLengthMap.append([i,self.fullArcLength])\n numberOfEvalulations+=1\n lastPoint= point\n\n # self.fullArcLength = arcLength\n #normalize values\n if self.fullArcLength > 0 :\n for i in range(numberOfEvalulations):\n self.arcLengthMap[i][1] /= self.fullArcLength\n\n\n def getFullArcLength(self, granularity = 100):\n #granularity = self.granularity\n u = np.arange(granularity+1) / float(granularity)\n arcLength = 0.0\n lastPoint = None\n for i in u:\n print(\"sample\",i)\n point = self.queryPoint(i)\n if lastPoint != None:\n arcLength += np.linalg.norm(point-lastPoint)#(point-lastPoint).length()\n lastPoint= point\n print(point)\n return arcLength\n\n def getDistanceToPath(self,absoluteArcLength, position):\n '''\n evaluates a point with absoluteArcLength on self to get a point on the path\n then the distance between the given position and the point on the path is returned\n '''\n pointOnPath = self.getPointAtAbsoluteArcLength(absoluteArcLength)\n return np.linalg.norm(position-pointOnPath)\n\n def getLastControlPoint(self):\n if len(self.controlPoints)> 0:\n return self.controlPoints[-1]\n else:\n return [0,0,0]\n\n def getArcLengthForParameter(self,t):\n stepSize = 1/self.granularity\n tableIndex = int(t/stepSize)\n return self.arcLengthMap[tableIndex][1]*self.fullArcLength\n\n\n\n def getPointAtAbsoluteArcLength(self,absoluteArcLength):\n point = np.zeros((1,self.dimensions))#source of bug\n if absoluteArcLength <= self.fullArcLength:\n # parameterize curve by arc length\n relativeArcLength = absoluteArcLength/self.fullArcLength\n point = self.queryPointByRelativeArcLength(relativeArcLength)\n else:\n return None\n# else:\n# raise ValueError('%f exceeded arc length %f' % (absoluteArcLength,self.fullArcLength))\n return point\n\n def findClosestValuesInArcLengthMap(self,relativeArcLength):\n '''\n - given a relative arc length between 0 and 1 it uses closestLowerValueBinarySearch from the Generic Algorithms module to search the self.arcLengthMap for the values bounding the searched value\n - returns floor parameter, ceiling parameter, floor arc length, ceiling arc length and a bool if the exact value was found\n '''\n foundExactValue = True\n result = closestLowerValueBinarySearch(self.arcLengthMap,0,len(self.arcLengthMap)-1,relativeArcLength, getter = lambda A,i: A[i][1])#returns the index and a flag value, requires a getter for the array\n\n index = result[0]\n\n if result[1] == 0:#found exact value\n floorP, ceilP = self.arcLengthMap[index][0],self.arcLengthMap[index][0]\n floorL, ceilL = self.arcLengthMap[index][1],self.arcLengthMap[index][1]\n foundExactValue = True\n elif result[1] ==1:#found lower value\n floorP = self.arcLengthMap[index][0]\n floorL = self.arcLengthMap[index][1]\n if index <len(self.arcLengthMap):#check array bounds\n ceilP = self.arcLengthMap[index+1][0]\n ceilL = self.arcLengthMap[index+1][1]\n foundExactValue = False\n else:\n foundExactValue = True\n ceilP= floorP\n ceilL = floorL\n elif result[1] ==2:#value smaller than smallest element in the array\n ceilP = self.arcLengthMap[index][0]\n floorL = self.arcLengthMap[index][1]\n floorP = ceilP\n ceilL = floorL\n foundExactValue = True\n elif result[1] ==3:#value larger than largest element in the array\n ceilP = self.arcLengthMap[index][0]\n ceilL = self.arcLengthMap[index][1]\n floorP = ceilP\n floorL = ceilL\n foundExactValue = True\n #print relativeArcLength,floorL,ceilL,foundExactValue\n return floorP,ceilP,floorL,ceilL,foundExactValue\n\n #see slide 30 of http://pages.cpsc.ucalgary.ca/~jungle/587/pdf/5-interpolation.pdf\n #note it does a binary search so it is rather expensive to be called at every frame\n def queryPointByRelativeArcLength(self,relativeArcLength):\n\n floorP,ceilP,floorL,ceilL,foundExactValue = self.findClosestValuesInArcLengthMap(relativeArcLength)\n if not foundExactValue:\n alpha = (relativeArcLength-floorL)/(ceilL-floorL)#can be reused a-\n #t = floorL+alpha*(ceilL-floorL)\n t = floorP+alpha*(ceilP-floorP)\n else:\n t = floorP\n #t = relativeArcLength#todo add correct mapping\n\n return self.queryPoint(t)\n\n def mapToSegment(self,t):\n\n i = min(math.floor( self.numberOfSegments *t),self.numberOfSegments)#the part of t before i\n localT =(self.numberOfSegments*t) -math.floor( self.numberOfSegments *t)#the rest, e.g. N = 10 and t = 0.62 => i = 6 and the rest is 0.02\n #i = min(i,self.numberOfSegments)\n return i+1,localT#increment i by 1 to ignore the first auxiliary control point\n\n\n def getControlPointVectors(self,i):\n i = int(i)\n #if i<=self.numberOfSegments-2:\n d = 0\n vectors = []\n\n while d < self.dimensions:\n v = [float(self.controlPoints[i-1][d]),float(self.controlPoints[i][d]),float(self.controlPoints[i+1][d]),float(self.controlPoints[i+2][d])]\n vectors.append(np.array(v))\n d+=1\n\n return vectors\n\n#\n def queryPoint(self, t):\n i,localT = self.mapToSegment(t)\n weightVector = np.array([localT**3,localT**2,localT,1])\n controlPointVectors = self.getControlPointVectors(i)\n point =[]\n d =0\n while d < self.dimensions:\n point.append(self.queryValue(weightVector, controlPointVectors[d]))\n d += 1\n return np.array(point)\n\n def queryValue(self, weightVector, controllPointVector):\n v = np.dot(self.catmullRomBaseMatrix, controllPointVector)\n v = np.dot(weightVector, v)\n return 0.5 * v\n", "#!/usr/bin/env python\n#\n# Copyright 2019 DFKI GmbH.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the\n# following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n# USE OR OTHER DEALINGS IN THE SOFTWARE.\nimport numpy as np\nfrom PySignal import Signal\nfrom ..graphics.renderer.lines import DebugLineRenderer\nfrom .animation_controller import AnimationController\nfrom ..graphics.renderer import SphereRenderer\nfrom ..scene.components import ComponentBase\nfrom ..graphics.utils import get_translation_matrix\nfrom ..io import load_json_file\n\nDEFAULT_COLOR = [0, 0, 1]\n\nclass PointCloudAnimationController(ComponentBase, AnimationController):\n updated_animation_frame = Signal()\n reached_end_of_animation = Signal()\n\n def __init__(self, scene_object, color=DEFAULT_COLOR, visualize=True):\n ComponentBase.__init__(self, scene_object)\n AnimationController.__init__(self)\n self.animated_joints = []\n self.visualize = visualize\n self.skeleton = None\n if visualize:\n self._sphere = SphereRenderer(10, 10, 1, color=color)\n a = [0, 0, 0]\n b = [1, 0, 0]\n self._line = DebugLineRenderer(a, b, color)\n self.draw_bone = False\n self._semantic_annotation = None\n self.frameTime = 1.0/30\n self.motion_data = []\n self.skeleton_model = None\n self.target_skeleton = None\n\n def toggle_animation_loop(self):\n self.loopAnimation = not self.loopAnimation\n\n def isLoadedCorrectly(self):\n return len(self.motion_data) > 0\n\n def set_data(self, data):\n self.motion_data = []\n for idx, frame in enumerate(data[\"motion_data\"]):\n pc_frame = []\n for p in frame:\n pc_frame.append(list(map(float, p)))\n self.motion_data.append(pc_frame)\n self.motion_data = np.array(self.motion_data)\n\n if 'skeleton' in list(data.keys()):\n self.skeleton = data[\"skeleton\"]\n else:\n self.skeleton = None\n\n if 'has_skeleton' in list(data.keys()) and 'skeleton' in list(data.keys()):\n self.draw_bone = False#data['has_skeleton']\n\n def update(self, dt):\n dt *= self.animationSpeed\n if self.isLoadedCorrectly():\n if self.playAnimation:\n self.animationTime += dt\n self.currentFrameNumber = int(self.animationTime / self.getFrameTime())\n\n # update gui\n if self.currentFrameNumber > self.getNumberOfFrames():\n self.resetAnimationTime()\n else:\n self.updated_animation_frame.emit(self.currentFrameNumber)\n\n def draw(self, modelMatrix, viewMatrix, projectionMatrix, lightSources):\n if self._sphere is None:\n return\n\n if self.currentFrameNumber < 0 or self.currentFrameNumber >= self.getNumberOfFrames():\n return\n\n for position in self.motion_data[self.currentFrameNumber]:\n m = get_translation_matrix(position[:3])\n m = np.dot(m, modelMatrix)\n self._sphere.draw(m, viewMatrix, projectionMatrix, lightSources)\n\n if self.draw_bone:\n for joint, value in list(self.skeleton.items()):\n if value['parent'] is not None:\n joint_idx = value['index']\n joint_parent_idx = self.skeleton[value['parent']]['index']\n start_point = self.motion_data[self.currentFrameNumber][joint_parent_idx]\n end_point = self.motion_data[self.currentFrameNumber][joint_idx]\n self._line.set_line(start_point, end_point)\n self._line.draw(modelMatrix, viewMatrix, projectionMatrix)\n\n def getNumberOfFrames(self):\n return len(self.motion_data)\n\n def getFrameTime(self):\n return self.frameTime\n\n def updateTransformation(self, frame_number=None):\n if frame_number is not None:\n self.currentFrameNumber = frame_number\n self.animationTime = self.getFrameTime() * self.currentFrameNumber\n\n def setCurrentFrameNumber(self, frame_number=None):\n if frame_number is not None:\n self.currentFrameNumber = frame_number\n self.animationTime = self.getFrameTime() * self.currentFrameNumber\n\n def apply_scale(self, scale):\n self.motion_data[:, :, :3] *= scale\n\n def apply_transform(self, m):\n for i, frame in enumerate(self.motion_data):\n for j, p in enumerate(frame):\n p = self.motion_data[i, j, :3]\n self.motion_data[i, j, :3] = np.dot(m, p)\n\n def setColor(self, color):\n self._sphere.technique.material.diffuse_color = color\n self._sphere.technique.material.ambient_color = color * 0.1\n\n def getColor(self):\n return self._sphere.technique.material.diffuse_color\n\n def replace_skeleton_model(self, filename):\n data = load_json_file(filename)\n self.set_skeleton_model(data)\n\n def set_skeleton_model(self, model):\n self.skeleton_model = model\n #self.skeleton = SkeletonBuilder().load_from_json_data(data)\n #self.skeleton.joints = self._joints\n\n def get_semantic_annotation(self):\n return dict()\n\n def get_current_frame(self):\n if self.currentFrameNumber < 0 or self.currentFrameNumber >= self.getNumberOfFrames():\n return None\n return self.motion_data[self.currentFrameNumber]\n\n def get_skeleton(self):\n return self.skeleton\n\n def get_frame_time(self):\n return self.getFrameTime()\n\n def get_label_color_map(self):\n return dict()\n\n def set_frame_time(self, frame_time):\n self.frameTime = frame_time\n\n", "#!/usr/bin/env python\n#\n# Copyright 2019 DFKI GmbH.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the\n# following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n# USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\" http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-16-shadow-mapping/#rendering-the-shadow-map\n https://learnopengl.com/code_viewer_gh.php?code=src/5.advanced_lighting/3.1.2.shadow_mapping_base/shadow_mapping_base.cpp\nthin matrix shadow tutorial\nsrc: https://www.youtube.com/watch?v=o6zDfDkOFIc\nhttps://www.dropbox.com/sh/g9vnfiubdglojuh/AACpq1KDpdmB8ZInYxhsKj2Ma/shadows\n\n\"\"\"\nfrom OpenGL.GL import *\nimport numpy as np\nfrom ..shadow_map_buffer import ShadowMapBuffer\nfrom ..shadow_box import ShadowBox, get_lookat_matrix, get_orthographic_matrix\n\n\nBIAS_MATRIX = np.array([[0.5, 0.0, 0.0, 0.0],\n [0.0, 0.5, 0.0, 0.0],\n [0.0, 0.0, 0.5, 0.0],\n [0.5, 0.5, 0.5, 1.0]\n ])# transform homogenous to texture coordinates\n\nclass DirectionalLight(object):\n def __init__(self, position, target, up_vector, intensities, w=4096, h=4096, scene_scale=1, shadow_box_length=500):\n #w*=4\n #h*=4\n self.up_vector = up_vector\n self.target = target\n self._dir = (target-position)\n self._dir /= np.linalg.norm(self._dir)\n self._pos = position\n self.shadow_box = ShadowBox(self, shadow_box_length)\n self.shadow_buffer = ShadowMapBuffer(w, h)\n scale = 100*scene_scale#10000.0\n near = -1.0# 1.0\n far = 1000*scene_scale\n self.proj_mat = get_orthographic_matrix(-scale, scale, -scale, scale, near, far)\n self.view_mat = get_lookat_matrix(self._pos, target-self._pos, up_vector)\n self.intensities = intensities\n self.position = -np.array([self._dir[0], self._dir[1], self._dir[2], 0])\n self.scale = scale\n self.near = near\n self.far = far\n\n def update(self, camera):\n \"\"\" update the position of the view matrix and based on the center of the shadow box\n \"\"\"\n self.view_mat,self.proj_mat = self.shadow_box.update(camera, self._dir) # update center and dims from camera frustrum\n\n def pre_render(self):\n self.shadow_buffer.prepare_buffer()\n\n def post_render(self):\n self.shadow_buffer.unbind()\n\n def get_depth_texture(self):\n return self.shadow_buffer.depth_texture\n\n\n\n\n" ]
[ [ "numpy.dot", "scipy.interpolate.splrep", "numpy.linspace", "numpy.arange", "numpy.linalg.norm", "scipy.interpolate.splev", "numpy.array", "numpy.zeros", "numpy.sum" ], [ "numpy.dot", "numpy.array" ], [ "numpy.array", "numpy.linalg.norm" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "1.3", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
truthiswill/federated
[ "d25eeac036dfc2a485120a195fd904223cfc823a", "d25eeac036dfc2a485120a195fd904223cfc823a" ]
[ "tensorflow_federated/python/aggregators/quantile_estimation_test.py", "tensorflow_federated/examples/stateful_clients/stateful_fedavg_tff.py" ]
[ "# Copyright 2020, The TensorFlow Federated 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\nimport collections\n\nfrom absl.testing import parameterized\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_privacy as tfp\n\nfrom tensorflow_federated.python.aggregators import quantile_estimation\nfrom tensorflow_federated.python.core.api import test_case\nfrom tensorflow_federated.python.core.backends.test import execution_contexts\nfrom tensorflow_federated.python.core.impl.types import computation_types\nfrom tensorflow_federated.python.core.impl.types import placements\nfrom tensorflow_federated.python.core.impl.types import type_conversions\nfrom tensorflow_federated.python.core.templates import estimation_process\nfrom tensorflow_federated.python.core.test import static_assert\n\nQEProcess = quantile_estimation.PrivateQuantileEstimationProcess\n\n\nclass PrivateQEComputationTest(test_case.TestCase, parameterized.TestCase):\n\n @parameterized.named_parameters(('private', True), ('non_private', False))\n def test_process_type_signature(self, private):\n if private:\n quantile_estimator_query = tfp.QuantileEstimatorQuery(\n initial_estimate=1.0,\n target_quantile=0.5,\n learning_rate=1.0,\n below_estimate_stddev=0.5,\n expected_num_records=100,\n geometric_update=True)\n else:\n quantile_estimator_query = tfp.NoPrivacyQuantileEstimatorQuery(\n initial_estimate=1.0,\n target_quantile=0.5,\n learning_rate=1.0,\n geometric_update=True)\n\n process = QEProcess(quantile_estimator_query)\n\n query_state = quantile_estimator_query.initial_global_state()\n sum_process_state = ()\n\n server_state_type = computation_types.FederatedType(\n type_conversions.type_from_tensors((query_state, sum_process_state)),\n placements.SERVER)\n\n self.assertEqual(\n computation_types.FunctionType(\n parameter=None, result=server_state_type),\n process.initialize.type_signature)\n\n estimate_type = computation_types.FederatedType(tf.float32,\n placements.SERVER)\n\n self.assertEqual(\n computation_types.FunctionType(\n parameter=server_state_type, result=estimate_type),\n process.report.type_signature)\n\n client_value_type = computation_types.FederatedType(tf.float32,\n placements.CLIENTS)\n self.assertTrue(\n process.next.type_signature.is_equivalent_to(\n computation_types.FunctionType(\n parameter=collections.OrderedDict(\n state=server_state_type, value=client_value_type),\n result=server_state_type)))\n\n def test_bad_query(self):\n non_quantile_estimator_query = tfp.GaussianSumQuery(\n l2_norm_clip=1.0, stddev=1.0)\n\n with self.assertRaises(TypeError):\n QEProcess(non_quantile_estimator_query)\n\n def test_bad_aggregation_factory(self):\n quantile_estimator_query = tfp.NoPrivacyQuantileEstimatorQuery(\n initial_estimate=1.0,\n target_quantile=0.5,\n learning_rate=1.0,\n geometric_update=True)\n\n with self.assertRaises(TypeError):\n QEProcess(\n quantile_estimator_query=quantile_estimator_query,\n record_aggregation_factory=\"I'm not a record_aggregation_factory.\")\n\n\nclass PrivateQEExecutionTest(test_case.TestCase, parameterized.TestCase):\n\n @parameterized.named_parameters(('arithmetic', False), ('geometric', True))\n def test_adaptation(self, geometric_update):\n initial_estimate = 3.14159\n target_quantile = 0.61803\n learning_rate = 2.71828\n\n quantile_estimator_query = tfp.NoPrivacyQuantileEstimatorQuery(\n initial_estimate=initial_estimate,\n target_quantile=target_quantile,\n learning_rate=learning_rate,\n geometric_update=geometric_update)\n\n process = QEProcess(quantile_estimator_query)\n\n state = process.initialize()\n self.assertAllClose(process.report(state), initial_estimate)\n\n # Run on two records greater than estimate.\n state = process.next(state, [initial_estimate + 1, initial_estimate + 2])\n\n if geometric_update:\n expected_estimate = (\n initial_estimate * np.exp(learning_rate * target_quantile))\n else:\n expected_estimate = initial_estimate + learning_rate * target_quantile\n\n self.assertAllClose(process.report(state), expected_estimate)\n\n def test_no_noise_cls(self):\n process = QEProcess.no_noise(\n initial_estimate=1.0, target_quantile=0.5, learning_rate=1.0)\n self.assertIsInstance(process, QEProcess)\n state = process.initialize()\n self.assertEqual(process.report(state), 1.0)\n\n def test_no_noise_affine_cls(self):\n process = QEProcess.no_noise(\n initial_estimate=1.0,\n target_quantile=0.5,\n learning_rate=1.0,\n multiplier=2.0,\n increment=1.0)\n self.assertIsInstance(process, estimation_process.EstimationProcess)\n state = process.initialize()\n self.assertEqual(process.report(state), 3.0)\n\n def test_no_noise_secure_true_false_equal_results(self):\n simple_process = QEProcess.no_noise(\n initial_estimate=1.0,\n target_quantile=0.5,\n learning_rate=1.0,\n secure_estimation=False)\n secure_process = QEProcess.no_noise(\n initial_estimate=1.0,\n target_quantile=0.5,\n learning_rate=1.0,\n secure_estimation=True)\n\n data = [0.5, 1.5, 2.5] # 2 bigger than the initial estimate 1.0, 1 smaller.\n\n simple_state = simple_process.initialize()\n secure_state = secure_process.initialize()\n for _ in range(3):\n simple_state = simple_process.next(simple_state, data)\n secure_state = secure_process.next(secure_state, data)\n self.assertAllClose(\n simple_process.report(simple_state),\n secure_process.report(secure_state))\n\n def test_secure_estimation_true_only_contains_secure_aggregation(self):\n secure_process = QEProcess.no_noise(\n initial_estimate=1.0,\n target_quantile=0.5,\n learning_rate=1.0,\n secure_estimation=True)\n try:\n static_assert.assert_not_contains_unsecure_aggregation(\n secure_process.next)\n except: # pylint: disable=bare-except\n self.fail('Computation contains non-secure aggregation.')\n\n\nif __name__ == '__main__':\n execution_contexts.set_test_execution_context()\n test_case.main()\n", "# Copyright 2020, The TensorFlow Federated 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\"\"\"An implementation of the Federated Averaging algorithm.\n\nThis is intended to be a minimal stand-alone implementation of Federated\nAveraging, suitable for branching as a starting point for algorithm\nmodifications; see `tff.learning.build_federated_averaging_process` for a\nmore full-featured implementation.\n\nBased on the paper:\n\nCommunication-Efficient Learning of Deep Networks from Decentralized Data\n H. Brendan McMahan, Eider Moore, Daniel Ramage,\n Seth Hampson, Blaise Aguera y Arcas. AISTATS 2017.\n https://arxiv.org/abs/1602.05629\n\"\"\"\n\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\nfrom tensorflow_federated.examples.stateful_clients.stateful_fedavg_tf import build_server_broadcast_message\nfrom tensorflow_federated.examples.stateful_clients.stateful_fedavg_tf import client_update\nfrom tensorflow_federated.examples.stateful_clients.stateful_fedavg_tf import get_model_weights\nfrom tensorflow_federated.examples.stateful_clients.stateful_fedavg_tf import server_update\nfrom tensorflow_federated.examples.stateful_clients.stateful_fedavg_tf import ServerState\n\n\ndef _initialize_optimizer_vars(model, optimizer):\n \"\"\"Creates optimizer variables to assign the optimizer's state.\"\"\"\n # Create zero gradients to force an update that doesn't modify.\n # Force eagerly constructing the optimizer variables. Normally Keras lazily\n # creates the variables on first usage of the optimizer. Optimizers such as\n # Adam, Adagrad, or using momentum need to create a new set of variables shape\n # like the model weights.\n model_weights = get_model_weights(model)\n zero_gradient = [tf.zeros_like(t) for t in model_weights.trainable]\n optimizer.apply_gradients(zip(zero_gradient, model_weights.trainable))\n assert optimizer.variables()\n\n\ndef build_federated_averaging_process(\n model_fn,\n client_state_fn,\n server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0),\n client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.1)):\n \"\"\"Builds the TFF computations for optimization using federated averaging.\n\n Args:\n model_fn: A no-arg function that returns a `tff.learning.TrainableModel`.\n client_state_fn: A no-arg function that returns a\n `stateful_fedavg_tf.ClientState`.\n server_optimizer_fn: A no-arg function that returns a\n `tf.keras.optimizers.Optimizer` for server update.\n client_optimizer_fn: A no-arg function that returns a\n `tf.keras.optimizers.Optimizer` for client update.\n\n Returns:\n A `tff.templates.IterativeProcess`.\n \"\"\"\n\n whimsy_model = model_fn()\n\n @tff.tf_computation\n def server_init_tf():\n model = model_fn()\n server_optimizer = server_optimizer_fn()\n _initialize_optimizer_vars(model, server_optimizer)\n return ServerState(\n model_weights=get_model_weights(model),\n optimizer_state=server_optimizer.variables(),\n round_num=0,\n total_iters_count=0)\n\n server_state_type = server_init_tf.type_signature.result\n\n model_weights_type = server_state_type.model_weights\n\n client_state_type = tff.framework.type_from_tensors(client_state_fn())\n\n @tff.tf_computation(server_state_type, model_weights_type.trainable,\n client_state_type.iters_count) # pytype: disable=attribute-error # gen-stub-imports\n def server_update_fn(server_state, model_delta, total_iters_count):\n model = model_fn()\n server_optimizer = server_optimizer_fn()\n _initialize_optimizer_vars(model, server_optimizer)\n return server_update(model, server_optimizer, server_state, model_delta,\n total_iters_count)\n\n @tff.tf_computation(server_state_type)\n def server_message_fn(server_state):\n return build_server_broadcast_message(server_state)\n\n server_message_type = server_message_fn.type_signature.result\n tf_dataset_type = tff.SequenceType(whimsy_model.input_spec)\n\n @tff.tf_computation(tf_dataset_type, client_state_type, server_message_type)\n def client_update_fn(tf_dataset, client_state, server_message):\n model = model_fn()\n client_optimizer = client_optimizer_fn()\n return client_update(model, tf_dataset, client_state, server_message,\n client_optimizer)\n\n federated_server_state_type = tff.type_at_server(server_state_type)\n federated_dataset_type = tff.type_at_clients(tf_dataset_type)\n\n federated_client_state_type = tff.type_at_clients(client_state_type)\n\n @tff.federated_computation(federated_server_state_type,\n federated_dataset_type,\n federated_client_state_type)\n def run_one_round(server_state, federated_dataset, client_states):\n \"\"\"Orchestration logic for one round of computation.\n\n Args:\n server_state: A `stateful_fedavg_tf.ServerState`.\n federated_dataset: A federated `tf.data.Dataset` with placement\n `tff.CLIENTS`.\n client_states: A federated `stateful_fedavg_tf.ClientState`.\n\n Returns:\n A tuple of updated `ServerState` and `tf.Tensor` of average loss.\n \"\"\"\n server_message = tff.federated_map(server_message_fn, server_state)\n server_message_at_client = tff.federated_broadcast(server_message)\n\n client_outputs = tff.federated_map(\n client_update_fn,\n (federated_dataset, client_states, server_message_at_client))\n\n weight_denom = client_outputs.client_weight\n round_model_delta = tff.federated_mean(\n client_outputs.weights_delta, weight=weight_denom)\n total_iters_count = tff.federated_sum(\n client_outputs.client_state.iters_count)\n server_state = tff.federated_map(\n server_update_fn, (server_state, round_model_delta, total_iters_count))\n round_loss_metric = tff.federated_mean(\n client_outputs.model_output, weight=weight_denom)\n\n return server_state, round_loss_metric, client_outputs.client_state\n\n @tff.federated_computation\n def server_init_tff():\n \"\"\"Orchestration logic for server model initialization.\"\"\"\n return tff.federated_value(server_init_tf(), tff.SERVER)\n\n return tff.templates.IterativeProcess(\n initialize_fn=server_init_tff, next_fn=run_one_round)\n" ]
[ [ "numpy.exp" ], [ "tensorflow.zeros_like", "tensorflow.keras.optimizers.SGD" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
s3a-spatialaudio/VISR
[ "55f6289bc5058d4898106f3520e1a60644ffb3ab", "55f6289bc5058d4898106f3520e1a60644ffb3ab", "55f6289bc5058d4898106f3520e1a60644ffb3ab" ]
[ "src/python/scripts/rsao/reverbObjectBinauralisation_flexible.py", "src/python/packages/visr_bst/renderers/hoa_binaural_renderer.py", "src/python/packages/visr_bst/hoa_components/hoa_object_encoder.py" ]
[ " # -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 14 15:59:11 2017\n\n@author: af5u13\n\"\"\"\n\n# Usage for debugging from raw Python console\n#exec(open(\"/Users/af5u13/dev/visr/src/python/scripts/rsao/reverbObjectBinauralisation.py\").read())\n\nimport visr\nimport signalflows\nimport panning\nimport pml\nimport rbbl\nimport rcl\nimport rrl\n#import objectmodel as om\n\nimport h5py\nimport numpy as np;\nimport matplotlib.pyplot as plt\nimport os\n\nclass ReverbToBinaural( visr.CompositeComponent ):\n def __init__( self, context, name, parent,\n loudspeakerConfig,\n numberOfInputs,\n rendererOutputs,\n interpolationPeriod,\n diffusionFilters,\n trackingConfiguration,\n brirRouting,\n brirFilters,\n scenePort = 4242,\n reverbConfiguration=''):\n super(ReverbToBinaural,self).__init__( context, name, parent )\n self.coreRenderer = signalflows.BaselineRenderer( ctxt, 'renderer', self,\n loudspeakerConfig=loudspeakerConfig,\n numberOfInputs=numberOfInputs,\n numberOfOutputs=rendererOutputs,\n interpolationPeriod=interpolationPeriod,\n diffusionFilters=diffusionFilters,\n reverbConfig=reverbConfiguration,\n sceneReceiverPort=scenePort,\n trackingConfiguration=trackingConfiguration\n )\n numFilters = brirFilters.numberOfRows\n firLength = brirFilters.numberOfColumns\n numRoutings = brirRouting.size\n self.convolver = rcl.FirFilterMatrix( ctxt, 'convolver', self,\n numberOfInputs=rendererOutputs,\n numberOfOutputs=2,\n maxFilters=numFilters,\n filterLength=firLength,\n maxRoutings=numRoutings,\n filters=brirFilters,\n routings=brirRouting,\n controlInputs=rcl.FirFilterMatrix.ControlPortConfig.NoInputs\n )\n self.audioIn = visr.AudioInputFloat( \"audioIn\", self, numberOfInputs )\n self.audioOut = visr.AudioOutputFloat( \"audioOut\", self, 2 )\n self.audioConnection( self.audioIn, self.coreRenderer.audioPort(\"input\"))\n self.audioConnection( self.coreRenderer.audioPort(\"output\"),\n self.convolver.audioPort(\"in\"))\n self.audioConnection( self.convolver.audioPort(\"out\"), self.audioOut )\n if len(trackingConfiguration) > 0:\n self.posIn = visr.ParameterInput( \"posIn\", self,\n pml.ListenerPosition.staticType,\n pml.DoubleBufferingProtocol.staticType,\n pml.EmptyParameterConfig() )\n self.parameterConnection( self.posIn, self.coreRenderer.parameterPort(\"trackingPositionInput\") )\n\n# Get VISR base directory from rsao subdirectory.\nvisrBaseDirectory = os.path.normpath(os.path.join( os.getcwd(), '../../../..' )).replace('\\\\','/')\n\nblockSize = 1024\nsamplingFrequency = 48000\nparameterUpdatePeriod = 1024\n\nnumBlocks = 8\nsignalLength = blockSize * numBlocks\nt = 1.0/samplingFrequency * np.arange(0,signalLength)\n\nnumObjects = 1;\n\nctxt = visr.SignalFlowContext( blockSize, samplingFrequency)\n\nlspConfigFile = os.path.join( visrBaseDirectory, 'config/bbc/bs2051-4+5+0.xml').replace('\\\\','/')\n# lspConfigFile = os.path.join( visrBaseDirectory, 'config/isvr/audiolab_39speakers_1subwoofer.xml' )\n\nlc = panning.LoudspeakerArray( lspConfigFile )\n\nnumOutputChannels = np.max( lc.channelIndices() + lc.subwooferChannelIndices() ) +1\nnumLoudspeakers = lc.numberOfRegularLoudspeakers\n\ndiffFilterFile = os.path.join( visrBaseDirectory, 'config/filters/random_phase_allpass_64ch_512taps.wav')\ndiffFiltersRaw = np.array(pml.MatrixParameterFloat.fromAudioFile( diffFilterFile ),\n dtype = np.float32 )\ndiffFilters = pml.MatrixParameterFloat( diffFiltersRaw[ np.array(lc.channelIndices() )-1,: ] )\n\nreverbConfigStr = '{ \"numReverbObjects\": %i, \"discreteReflectionsPerObject\": 20, \"lateReverbFilterLength\": 2.0, \"lateReverbDecorrelationFilters\": \"%s/config/filters/random_phase_allpass_64ch_1024taps.wav\" }' % (numObjects, visrBaseDirectory )\n\n## Load the BBC BRIR dataset\nbrirFile = os.path.join( os.getcwd(), 'BBC_BRIR.mat' )\nbrirMat = h5py.File( brirFile )\nbrirFull = np.array( brirMat['h_sweetspot'], dtype=np.float32 ).copy('C')\n# Scalefactor to compensate for the very low amplitudes of the BBC BRIRs\nbrirScaleFactor = 500;\nbrirFlat = brirScaleFactor * np.concatenate( (brirFull[:,0,:], brirFull[:,1,:] ) )\nbrirFilterParam = pml.MatrixParameterFloat( brirFlat, 16 )\nnumBrirSpeakers = brirFull.shape[0]\n# Define the routing for the binaural convolver such that it matches the organisation of the\n# flat BRIR matrix.\nfilterRouting = rbbl.FilterRoutingList()\nfor idx in range(0, numBrirSpeakers ):\n filterRouting.addRouting( idx, 0, idx, 1.0 )\n filterRouting.addRouting( idx, 1, idx+numBrirSpeakers, 1.0 )\n\n\nrenderer = ReverbToBinaural( ctxt, 'top', None,\n loudspeakerConfig=lc,\n numberOfInputs=numObjects,\n rendererOutputs=numOutputChannels,\n interpolationPeriod=parameterUpdatePeriod,\n diffusionFilters=diffFilters,\n trackingConfiguration='',\n brirFilters = brirFilterParam,\n brirRouting = filterRouting,\n reverbConfiguration=reverbConfigStr,\n scenePort = 4242\n )\n\nprint( 'Created renderer.' )\n\nflow = rrl.AudioSignalFlow( renderer )\n\n## Non-realtime code\n#inputSignal = np.zeros( (numObjects, signalLength ), dtype=np.float32 )\n## inputSignal[0,:] = 0.75*np.sin( 2.0*np.pi*440 * t )\n#inputSignal[ 0, 100 ] = 1\n#\n#outputSignal = np.zeros( (2, signalLength ), dtype=np.float32 )\n#\n#for blockIdx in range(0,numBlocks):\n## if blockIdx % (parameterUpdatePeriod/blockSize) == 0:\n## ov = paramInput.data()\n## ov.clear()\n## ov.set( ro.objectId, ro )\n## paramInput.swapBuffers()\n#\n# inputBlock = inputSignal[:, blockIdx*blockSize:(blockIdx+1)*blockSize]\n# outputBlock = flow.process( inputBlock )\n# outputSignal[:, blockIdx*blockSize:(blockIdx+1)*blockSize] = outputBlock\n#\n#\n#plt.figure(1)\n#plt.plot( t, outputSignal[0,:], 'bo-', t, outputSignal[1,:], 'rx-' )\n#plt.show( block = False )\n", "# -*- coding: utf-8 -*-\n\n# Copyright (C) 2017-2018 Andreas Franck and Giacomo Costantini\n# Copyright (C) 2017-2018 University of Southampton\n\n# VISR Binaural Synthesis Toolkit (BST)\n# Authors: Andreas Franck and Giacomo Costantini\n# Project page: http://cvssp.org/data/s3a/public/BinauralSynthesisToolkit/\n\n\n# The Binaural Synthesis Toolkit is provided under the ISC (Internet Systems Consortium) license\n# https://www.isc.org/downloads/software-support-policy/isc-license/ :\n\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\n# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n\n# We kindly ask to acknowledge the use of this software in publications or software.\n# Paper citation:\n# Andreas Franck, Giacomo Costantini, Chris Pike, and Filippo Maria Fazi,\n# “An Open Realtime Binaural Synthesis Toolkit for Audio Research,” in Proc. Audio Eng.\n# Soc. 144th Conv., Milano, Italy, 2018, Engineering Brief.\n# http://www.aes.org/e-lib/browse.cfm?elib=19525\n\n# The Binaural Synthesis Toolkit is based on the VISR framework. Information about the VISR,\n# including download, setup and usage instructions, can be found on the VISR project page\n# http://cvssp.org/data/s3a/public/VISR .\n\nimport numpy as np\n\n# Core VISR packages\nimport visr\nimport rbbl\nimport pml\nimport rcl\n\nfrom visr_bst.hoa_components import HoaRotationMatrixCalculator\nfrom visr_bst.util import readSofaFile\n\nclass HoaBinauralRenderer( visr.CompositeComponent ):\n \"\"\"\n Component to render binaural audio from plane wave and point source objects using an Higher Order Ambisonics (HOA)\n algorithm.\n \"\"\"\n def __init__( self,\n context, name, parent,\n hoaOrder = None,\n sofaFile = None,\n decodingFilters = None,\n interpolationSteps = None,\n headOrientation = None,\n headTracking = True,\n fftImplementation = 'default'\n ):\n \"\"\"\n Constructor.\n\n Parameters\n ----------\n context : visr.SignalFlowContext\n Standard visr.Component construction argument, holds the block size and the sampling frequency\n name : string\n Name of the component, Standard visr.Component construction argument\n parent : visr.CompositeComponent\n Containing component if there is one, None if this is a top-level component of the signal flow.\n hoaOrder: int or None\n The maximum HOA order that can be reproduced. If None, the HOA order is deduced\n from the first dimension of the HOA filters (possibly contained in a SOFA file).\n sofaFile: string or NoneType\n A file in SOFA format containing the decoding filters. This expects the filters in the\n field 'Data.IR', dimensions (hoaOrder+1)**2 x 2 x irLength. If None, then the filters\n must be provided in 'decodingFilters' parameter.\n decodingFilters : numpy.ndarray or NoneType\n Alternative way to provide the HOA decoding filters.\n interpolationSteps: int, optional\n Number of samples to transition to new object positions after an update.\n headOrientation : array-like\n Head orientation in spherical coordinates (2- or 3-element vector or list). Either a static orientation (when no tracking is used),\n or the initial view direction\n headTracking: bool\n Whether dynamic head tracking is active.\n fftImplementation: string, optional\n The FFT library to be used in the filtering. THe default uses VISR's\n default implementation for the present platform.\n \"\"\"\n if (decodingFilters is None) == (sofaFile is None ):\n raise ValueError( \"HoaObjectToBinauralRenderer: Either 'decodingFilters' or 'sofaFile' must be provided.\" )\n if sofaFile is None:\n filters = decodingFilters\n else:\n # pos and delays are not used here.\n [pos, filters, delays] = readSofaFile( sofaFile )\n\n if hoaOrder is None:\n numHoaCoeffs = filters.shape[0]\n orderP1 = int(np.floor(np.sqrt(numHoaCoeffs)))\n if orderP1**2 != numHoaCoeffs:\n raise ValueError( \"If hoaOrder is not given, the number of HOA filters must be a square number\" )\n hoaOrder = orderP1 - 1\n else:\n numHoaCoeffs = (hoaOrder+1)**2\n\n if filters.ndim != 3 or filters.shape[1] != 2 or filters.shape[0] < numHoaCoeffs:\n raise ValueError( \"HoaObjectToBinauralRenderer: the filter data must be a 3D matrix where the second dimension is 2 and the first dimension is equal or larger than (hoaOrder+1)^2.\" )\n\n # Set default value for fading between interpolation\n if interpolationSteps is None:\n interpolationSteps = context.period\n\n super( HoaBinauralRenderer, self ).__init__( context, name, parent )\n self.hoaSignalInput = visr.AudioInputFloat( \"audioIn\", self, numHoaCoeffs )\n self.binauralOutput = visr.AudioOutputFloat( \"audioOut\", self, 2 )\n\n filterMtx = np.concatenate( (filters[0:numHoaCoeffs,0,:], filters[0:numHoaCoeffs,1,:]) )\n routings = rbbl.FilterRoutingList()\n for idx in range(0,numHoaCoeffs):\n routings.addRouting( idx, 0, idx, 1.0 )\n routings.addRouting( idx, 1, idx+numHoaCoeffs, 1.0 )\n\n self.binauralFilterBank = rcl.FirFilterMatrix( context, 'binauralFilterBank', self,\n numberOfInputs = numHoaCoeffs,\n numberOfOutputs = 2,\n filterLength = filters.shape[-1],\n maxFilters = 2*numHoaCoeffs,\n maxRoutings = 2*numHoaCoeffs,\n filters = filterMtx,\n routings = routings,\n controlInputs=rcl.FirFilterMatrix.ControlPortConfig.NoInputs,\n fftImplementation = fftImplementation )\n\n if headTracking or (headOrientation is not None):\n\n numMatrixCoeffs = ((hoaOrder+1)*(2*hoaOrder+1)*(2*hoaOrder+3))//3\n\n\n self.rotationCalculator = HoaRotationMatrixCalculator( context, \"RotationCalculator\", self,\n hoaOrder,\n dynamicOrientation = headTracking,\n initialOrientation = headOrientation\n )\n\n rotationMatrixRoutings = rbbl.SparseGainRoutingList()\n for oIdx in range(hoaOrder+1):\n entryStart = (oIdx*(2*oIdx-1)*(2*oIdx+1)) // 3\n diagStart = oIdx**2\n for rowIdx in range( 2*oIdx+1 ):\n row = diagStart + rowIdx\n colsPerRow = 2*oIdx+1\n for colIdx in range( 2*oIdx+1 ):\n col = diagStart + colIdx\n entryIdx = entryStart + rowIdx * colsPerRow + colIdx\n rotationMatrixRoutings.addRouting( entryIdx, row, col, 0.0 )\n\n self.rotationMatrix = rcl.SparseGainMatrix( context, \"rotationMatrix\", self,\n numberOfInputs = numHoaCoeffs,\n numberOfOutputs = numHoaCoeffs,\n interpolationSteps = interpolationSteps,\n maxRoutingPoints = numMatrixCoeffs,\n initialRoutings = rotationMatrixRoutings,\n controlInputs = rcl.SparseGainMatrix.ControlPortConfig.Gain )\n self.audioConnection( self.hoaSignalInput, self.rotationMatrix.audioPort(\"in\") )\n self.audioConnection( self.rotationMatrix.audioPort(\"out\"), self.binauralFilterBank.audioPort(\"in\") )\n self.parameterConnection( self.rotationCalculator.parameterPort(\"coefficients\"),\n self.rotationMatrix.parameterPort( \"gainInput\" ) )\n\n if headTracking:\n self.trackingInput = visr.ParameterInput( \"tracking\", self, pml.ListenerPosition.staticType,\n pml.DoubleBufferingProtocol.staticType,\n pml.EmptyParameterConfig() )\n self.parameterConnection( self.trackingInput,\n self.rotationCalculator.parameterPort(\"orientation\") )\n else:\n self.audioConnection( self.hoaSignalInput, self.binauralFilterbank.audioPort(\"in\") )\n\n self.audioConnection( self.binauralFilterBank.audioPort(\"out\"), self.binauralOutput )\n", "# -*- coding: utf-8 -*-\n\n# Copyright (C) 2017-2018 Andreas Franck and Giacomo Costantini\n# Copyright (C) 2017-2018 University of Southampton\n\n# VISR Binaural Synthesis Toolkit (BST)\n# Authors: Andreas Franck and Giacomo Costantini\n# Project page: http://cvssp.org/data/s3a/public/BinauralSynthesisToolkit/\n\n\n# The Binaural Synthesis Toolkit is provided under the ISC (Internet Systems Consortium) license\n# https://www.isc.org/downloads/software-support-policy/isc-license/ :\n\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\n# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n\n# We kindly ask to acknowledge the use of this software in publications or software.\n# Paper citation:\n# Andreas Franck, Giacomo Costantini, Chris Pike, and Filippo Maria Fazi,\n# “An Open Realtime Binaural Synthesis Toolkit for Audio Research,” in Proc. Audio Eng.\n# Soc. 144th Conv., Milano, Italy, 2018, Engineering Brief.\n# http://www.aes.org/e-lib/browse.cfm?elib=19525\n\n# The Binaural Synthesis Toolkit is based on the VISR framework. Information about the VISR,\n# including download, setup and usage instructions, can be found on the VISR project page\n# http://cvssp.org/data/s3a/public/VISR .\n\n# VISR core packages\nimport visr\nimport pml\nimport objectmodel as om\nimport rbbl\n\n# Helper functions contained in the\nfrom visr_bst.util import cart2sph\nfrom visr_bst.util import allSphHarmRealACN\n\n# Standard Python packages\nimport numpy as np\nimport warnings\n\nclass HoaObjectEncoder( visr.AtomicComponent ):\n \"\"\"\n Component to calculate encoding coefficients for point source and plane wave audio objects contained in\n an object vector.\n \"\"\"\n def __init__( self,\n context, name, parent, # Standard visr component constructor arguments\n numberOfObjects, # The number of point source objects rendered.\n hoaOrder, # The Ambisonics order for encoding the objects\n channelAllocation = False # Whether to allocate object channels dynamically (not used at the moment)\n ):\n \"\"\"\n Constructor.\n\n Parameters\n ----------\n numberOfObjects: int\n The maximum number of audio objects to be rendered.\n hoaOrder: int\n The Ambisonics order for encoding the objects.\n channelAllocation: bool, optional\n Whether to send dynamic channel allocation data. Not used at the moment.\n Default value means that the object channels are allocated statically and correspond to the\n obbject's channel id.\n \"\"\"\n # Call base class (AtomicComponent) constructor\n super( HoaObjectEncoder, self ).__init__( context, name, parent )\n self.numberOfObjects = numberOfObjects\n self.hoaOrder = hoaOrder\n self.numHoaCoeffs = (self.hoaOrder+1)**2\n\n # %% Define parameter ports\n self.objectInput = visr.ParameterInput( \"objectVector\", self, pml.ObjectVector.staticType,\n pml.DoubleBufferingProtocol.staticType,\n pml.EmptyParameterConfig() )\n self.objectInputProtocol = self.objectInput.protocolInput()\n\n matrixConfig = pml.MatrixParameterConfig( self.numHoaCoeffs, self.numberOfObjects )\n self.coefficientOutput = visr.ParameterOutput( \"coefficientOutput\", self,\n pml.MatrixParameterFloat.staticType,\n pml.SharedDataProtocol.staticType,\n matrixConfig )\n self.coefficientOutputProtocol = self.coefficientOutput.protocolOutput()\n\n if channelAllocation:\n self.channelAllocator = rbbl.ObjectChannelAllocator( self.numberOfObjects )\n self.usedChannels = set() # Initialised with an empty set.\n self.routingOutput = visr.ParameterOutput( \"routingOutput\", self,\n pml.SignalRoutingParameter.staticType,\n pml.DoubleBufferingProtocol.staticType,\n pml.EmptyParameterConfig() )\n self.routingOutputProtocol = self.routingOutput.protocolOutput()\n else:\n self.routingOutputProtocol = None\n self.channelAllocator = None\n\n def process( self ):\n if self.objectInputProtocol.changed():\n ov = self.objectInputProtocol.data();\n\n coeffOut = np.array( self.coefficientOutputProtocol.data(), copy=False )\n if coeffOut.shape != ( self.numHoaCoeffs, self.numberOfObjects ):\n raise ValueError( 'The dimensions of the output coefficient matrix does not match the expected shape.' )\n coeffOut[...] = 0.0\n\n objIndicesRaw = [x.objectId for x in ov\n if isinstance( x, (om.PointSource, om.PlaneWave) ) ]\n if self.channelAllocator is not None:\n self.channelAllocator.setObjects( objIndicesRaw )\n objIndices = self.channelAllocator.getObjectChannels()\n numObjects = len(objIndices)\n\n for chIdx in range(0, numObjects):\n objIdx = objIndices[chIdx]\n src = ov[objIdx]\n if isinstance( src, om.PlaneWave ):\n sph = [src.azimuth, src.elevation, src.referenceDistance ]\n else:\n sph = cart2sph( src.x, src.y, src.z )\n pwCoeffs = allSphHarmRealACN( self.hoaOrder, np.pi/2-sph[1], sph[0], dtype = coeffOut.dtype )\n coeffOut[ :, chIdx] = pwCoeffs * src.level # encode the object level in the coefficients\n else:\n levels = np.zeros( self.numberOfObjects, dtype=coeffOut.dtype )\n pos = np.zeros( (self.numberOfObjects,3), dtype=coeffOut.dtype )\n pos[:,0] = 1.0 # Set unused sources to a valid direction.\n for src in ov:\n chIdx = src.channels[0]\n if chIdx > self.numberOfObjects:\n warnings.warn('The number of dynamically instantiated sound objects is more than the maximum number specified')\n continue\n levels[chIdx] = src.level\n pos[chIdx,:] = src.position\n sphPos = cart2sph( pos[:,0], pos[:,1], pos[:,2] )\n shCoeffs = allSphHarmRealACN( self.hoaOrder, np.pi/2-sphPos[1,:], sphPos[0,:], dtype = coeffOut.dtype )\n res = shCoeffs * levels[np.newaxis,:]\n coeffOut[...] = res\n# Old, serialized code:\n# for index,src in enumerate(ov):\n# if index < self.numberOfObjects :\n# chIdx = src.channels[0]\n# sph = cart2sph( src.x, src.y, src.z )\n# pwCoeffs = allSphHarmRealACN( self.hoaOrder, np.pi/2-sph[1], sph[0], dtype = coeffOut.dtype )\n# coeffOut[ :, chIdx ] = pwCoeffs * src.level # encode the object level in the coefficients\n# else:\n# warnings.warn('The number of dynamically instantiated sound objects is more than the maximum number specified')\n# break" ]
[ [ "numpy.concatenate", "numpy.arange", "numpy.array" ], [ "numpy.concatenate", "numpy.sqrt" ], [ "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Woooosz/dgl
[ "729ff2ef385f302af562c8305b1006d067d2067f", "729ff2ef385f302af562c8305b1006d067d2067f" ]
[ "examples/pytorch/gcmc/model.py", "python/dgl/nn/pytorch/conv/tagconv.py" ]
[ "\"\"\"NN modules\"\"\"\nimport torch as th\nimport torch.nn as nn\nfrom torch.nn import init\nimport dgl.function as fn\nimport dgl.nn.pytorch as dglnn\n\nfrom utils import get_activation\n\nclass GCMCGraphConv(nn.Module):\n \"\"\"Graph convolution module used in the GCMC model.\n\n Parameters\n ----------\n in_feats : int\n Input feature size.\n out_feats : int\n Output feature size.\n weight : bool, optional\n If True, apply a linear layer. Otherwise, aggregating the messages\n without a weight matrix or with an shared weight provided by caller.\n device: str, optional\n Which device to put data in. Useful in mix_cpu_gpu training and\n multi-gpu training\n \"\"\"\n def __init__(self,\n in_feats,\n out_feats,\n weight=True,\n device=None,\n dropout_rate=0.0):\n super(GCMCGraphConv, self).__init__()\n self._in_feats = in_feats\n self._out_feats = out_feats\n self.device = device\n self.dropout = nn.Dropout(dropout_rate)\n\n if weight:\n self.weight = nn.Parameter(th.Tensor(in_feats, out_feats))\n else:\n self.register_parameter('weight', None)\n self.reset_parameters()\n\n def reset_parameters(self):\n \"\"\"Reinitialize learnable parameters.\"\"\"\n if self.weight is not None:\n init.xavier_uniform_(self.weight)\n\n def forward(self, graph, feat, weight=None):\n \"\"\"Compute graph convolution.\n\n Normalizer constant :math:`c_{ij}` is stored as two node data \"ci\"\n and \"cj\".\n\n Parameters\n ----------\n graph : DGLGraph\n The graph.\n feat : torch.Tensor\n The input feature\n weight : torch.Tensor, optional\n Optional external weight tensor.\n dropout : torch.nn.Dropout, optional\n Optional external dropout layer.\n\n Returns\n -------\n torch.Tensor\n The output feature\n \"\"\"\n with graph.local_scope():\n if isinstance(feat, tuple):\n feat, _ = feat # dst feature not used\n cj = graph.srcdata['cj']\n ci = graph.dstdata['ci']\n if self.device is not None:\n cj = cj.to(self.device)\n ci = ci.to(self.device)\n if weight is not None:\n if self.weight is not None:\n raise DGLError('External weight is provided while at the same time the'\n ' module has defined its own weight parameter. Please'\n ' create the module with flag weight=False.')\n else:\n weight = self.weight\n\n if weight is not None:\n feat = dot_or_identity(feat, weight, self.device)\n\n feat = feat * self.dropout(cj)\n graph.srcdata['h'] = feat\n graph.update_all(fn.copy_src(src='h', out='m'),\n fn.sum(msg='m', out='h'))\n rst = graph.dstdata['h']\n rst = rst * ci\n\n return rst\n\nclass GCMCLayer(nn.Module):\n r\"\"\"GCMC layer\n\n .. math::\n z_j^{(l+1)} = \\sigma_{agg}\\left[\\mathrm{agg}\\left(\n \\sum_{j\\in\\mathcal{N}_1}\\frac{1}{c_{ij}}W_1h_j, \\ldots,\n \\sum_{j\\in\\mathcal{N}_R}\\frac{1}{c_{ij}}W_Rh_j\n \\right)\\right]\n\n After that, apply an extra output projection:\n\n .. math::\n h_j^{(l+1)} = \\sigma_{out}W_oz_j^{(l+1)}\n\n The equation is applied to both user nodes and movie nodes and the parameters\n are not shared unless ``share_user_item_param`` is true.\n\n Parameters\n ----------\n rating_vals : list of int or float\n Possible rating values.\n user_in_units : int\n Size of user input feature\n movie_in_units : int\n Size of movie input feature\n msg_units : int\n Size of message :math:`W_rh_j`\n out_units : int\n Size of of final output user and movie features\n dropout_rate : float, optional\n Dropout rate (Default: 0.0)\n agg : str, optional\n Function to aggregate messages of different ratings.\n Could be any of the supported cross type reducers:\n \"sum\", \"max\", \"min\", \"mean\", \"stack\".\n (Default: \"stack\")\n agg_act : callable, str, optional\n Activation function :math:`sigma_{agg}`. (Default: None)\n out_act : callable, str, optional\n Activation function :math:`sigma_{agg}`. (Default: None)\n share_user_item_param : bool, optional\n If true, user node and movie node share the same set of parameters.\n Require ``user_in_units`` and ``move_in_units`` to be the same.\n (Default: False)\n device: str, optional\n Which device to put data in. Useful in mix_cpu_gpu training and\n multi-gpu training\n \"\"\"\n def __init__(self,\n rating_vals,\n user_in_units,\n movie_in_units,\n msg_units,\n out_units,\n dropout_rate=0.0,\n agg='stack', # or 'sum'\n agg_act=None,\n out_act=None,\n share_user_item_param=False,\n device=None):\n super(GCMCLayer, self).__init__()\n self.rating_vals = rating_vals\n self.agg = agg\n self.share_user_item_param = share_user_item_param\n self.ufc = nn.Linear(msg_units, out_units)\n if share_user_item_param:\n self.ifc = self.ufc\n else:\n self.ifc = nn.Linear(msg_units, out_units)\n if agg == 'stack':\n # divide the original msg unit size by number of ratings to keep\n # the dimensionality\n assert msg_units % len(rating_vals) == 0\n msg_units = msg_units // len(rating_vals)\n self.dropout = nn.Dropout(dropout_rate)\n self.W_r = nn.ParameterDict()\n subConv = {}\n for rating in rating_vals:\n # PyTorch parameter name can't contain \".\"\n rating = str(rating).replace('.', '_')\n rev_rating = 'rev-%s' % rating\n if share_user_item_param and user_in_units == movie_in_units:\n self.W_r[rating] = nn.Parameter(th.randn(user_in_units, msg_units))\n self.W_r['rev-%s' % rating] = self.W_r[rating]\n subConv[rating] = GCMCGraphConv(user_in_units,\n msg_units,\n weight=False,\n device=device,\n dropout_rate=dropout_rate)\n subConv[rev_rating] = GCMCGraphConv(user_in_units,\n msg_units,\n weight=False,\n device=device,\n dropout_rate=dropout_rate)\n else:\n self.W_r = None\n subConv[rating] = GCMCGraphConv(user_in_units,\n msg_units,\n weight=True,\n device=device,\n dropout_rate=dropout_rate)\n subConv[rev_rating] = GCMCGraphConv(movie_in_units,\n msg_units,\n weight=True,\n device=device,\n dropout_rate=dropout_rate)\n self.conv = dglnn.HeteroGraphConv(subConv, aggregate=agg)\n self.agg_act = get_activation(agg_act)\n self.out_act = get_activation(out_act)\n self.device = device\n self.reset_parameters()\n\n def partial_to(self, device):\n \"\"\"Put parameters into device except W_r\n\n Parameters\n ----------\n device : torch device\n Which device the parameters are put in.\n \"\"\"\n assert device == self.device\n if device is not None:\n self.ufc.cuda(device)\n if self.share_user_item_param is False:\n self.ifc.cuda(device)\n self.dropout.cuda(device)\n\n def reset_parameters(self):\n for p in self.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)\n\n def forward(self, graph, ufeat=None, ifeat=None):\n \"\"\"Forward function\n\n Parameters\n ----------\n graph : DGLHeteroGraph\n User-movie rating graph. It should contain two node types: \"user\"\n and \"movie\" and many edge types each for one rating value.\n ufeat : torch.Tensor, optional\n User features. If None, using an identity matrix.\n ifeat : torch.Tensor, optional\n Movie features. If None, using an identity matrix.\n\n Returns\n -------\n new_ufeat : torch.Tensor\n New user features\n new_ifeat : torch.Tensor\n New movie features\n \"\"\"\n in_feats = {'user' : ufeat, 'movie' : ifeat}\n mod_args = {}\n for i, rating in enumerate(self.rating_vals):\n rating = str(rating).replace('.', '_')\n rev_rating = 'rev-%s' % rating\n mod_args[rating] = (self.W_r[rating] if self.W_r is not None else None,)\n mod_args[rev_rating] = (self.W_r[rev_rating] if self.W_r is not None else None,)\n out_feats = self.conv(graph, in_feats, mod_args=mod_args)\n ufeat = out_feats['user']\n ifeat = out_feats['movie']\n ufeat = ufeat.view(ufeat.shape[0], -1)\n ifeat = ifeat.view(ifeat.shape[0], -1)\n\n # fc and non-linear\n ufeat = self.agg_act(ufeat)\n ifeat = self.agg_act(ifeat)\n ufeat = self.dropout(ufeat)\n ifeat = self.dropout(ifeat)\n ufeat = self.ufc(ufeat)\n ifeat = self.ifc(ifeat)\n return self.out_act(ufeat), self.out_act(ifeat)\n\nclass BiDecoder(nn.Module):\n r\"\"\"Bi-linear decoder.\n\n Given a bipartite graph G, for each edge (i, j) ~ G, compute the likelihood\n of it being class r by:\n\n .. math::\n p(M_{ij}=r) = \\text{softmax}(u_i^TQ_rv_j)\n\n The trainable parameter :math:`Q_r` is further decomposed to a linear\n combination of basis weight matrices :math:`P_s`:\n\n .. math::\n Q_r = \\sum_{s=1}^{b} a_{rs}P_s\n\n Parameters\n ----------\n in_units : int\n Size of input user and movie features\n num_classes : int\n Number of classes.\n num_basis : int, optional\n Number of basis. (Default: 2)\n dropout_rate : float, optional\n Dropout raite (Default: 0.0)\n \"\"\"\n def __init__(self,\n in_units,\n num_classes,\n num_basis=2,\n dropout_rate=0.0):\n super(BiDecoder, self).__init__()\n self._num_basis = num_basis\n self.dropout = nn.Dropout(dropout_rate)\n self.Ps = nn.ParameterList()\n for i in range(num_basis):\n self.Ps.append(nn.Parameter(th.randn(in_units, in_units)))\n self.combine_basis = nn.Linear(self._num_basis, num_classes, bias=False)\n self.reset_parameters()\n\n def reset_parameters(self):\n for p in self.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)\n\n def forward(self, graph, ufeat, ifeat):\n \"\"\"Forward function.\n\n Parameters\n ----------\n graph : DGLHeteroGraph\n \"Flattened\" user-movie graph with only one edge type.\n ufeat : th.Tensor\n User embeddings. Shape: (|V_u|, D)\n ifeat : th.Tensor\n Movie embeddings. Shape: (|V_m|, D)\n\n Returns\n -------\n th.Tensor\n Predicting scores for each user-movie edge.\n \"\"\"\n with graph.local_scope():\n ufeat = self.dropout(ufeat)\n ifeat = self.dropout(ifeat)\n graph.nodes['movie'].data['h'] = ifeat\n basis_out = []\n for i in range(self._num_basis):\n graph.nodes['user'].data['h'] = ufeat @ self.Ps[i]\n graph.apply_edges(fn.u_dot_v('h', 'h', 'sr'))\n basis_out.append(graph.edata['sr'])\n out = th.cat(basis_out, dim=1)\n out = self.combine_basis(out)\n return out\n\nclass DenseBiDecoder(BiDecoder):\n r\"\"\"Dense bi-linear decoder.\n\n Dense implementation of the bi-linear decoder used in GCMC. Suitable when\n the graph can be efficiently represented by a pair of arrays (one for source\n nodes; one for destination nodes).\n\n Parameters\n ----------\n in_units : int\n Size of input user and movie features\n num_classes : int\n Number of classes.\n num_basis : int, optional\n Number of basis. (Default: 2)\n dropout_rate : float, optional\n Dropout raite (Default: 0.0)\n \"\"\"\n def __init__(self,\n in_units,\n num_classes,\n num_basis=2,\n dropout_rate=0.0):\n super(DenseBiDecoder, self).__init__(in_units,\n num_classes,\n num_basis,\n dropout_rate)\n\n def forward(self, ufeat, ifeat):\n \"\"\"Forward function.\n\n Compute logits for each pair ``(ufeat[i], ifeat[i])``.\n\n Parameters\n ----------\n ufeat : th.Tensor\n User embeddings. Shape: (B, D)\n ifeat : th.Tensor\n Movie embeddings. Shape: (B, D)\n\n Returns\n -------\n th.Tensor\n Predicting scores for each user-movie edge. Shape: (B, num_classes)\n \"\"\"\n ufeat = self.dropout(ufeat)\n ifeat = self.dropout(ifeat)\n basis_out = []\n for i in range(self._num_basis):\n ufeat_i = ufeat @ self.Ps[i]\n out = th.einsum('ab,ab->a', ufeat_i, ifeat)\n basis_out.append(out.unsqueeze(1))\n out = th.cat(basis_out, dim=1)\n out = self.combine_basis(out)\n return out\n\ndef dot_or_identity(A, B, device=None):\n # if A is None, treat as identity matrix\n if A is None:\n return B\n elif len(A.shape) == 1:\n if device is None:\n return B[A]\n else:\n return B[A].to(device)\n else:\n return A @ B\n", "\"\"\"Torch Module for Topology Adaptive Graph Convolutional layer\"\"\"\n# pylint: disable= no-member, arguments-differ, invalid-name\nimport torch as th\nfrom torch import nn\n\nfrom .... import function as fn\n\n\nclass TAGConv(nn.Module):\n r\"\"\"Topology Adaptive Graph Convolutional layer from paper `Topology\n Adaptive Graph Convolutional Networks <https://arxiv.org/pdf/1710.10370.pdf>`__.\n\n .. math::\n \\mathbf{X}^{\\prime} = \\sum_{k=0}^K \\mathbf{D}^{-1/2} \\mathbf{A}\n \\mathbf{D}^{-1/2}\\mathbf{X} \\mathbf{\\Theta}_{k},\n\n where :math:`\\mathbf{A}` denotes the adjacency matrix and\n :math:`D_{ii} = \\sum_{j=0} A_{ij}` its diagonal degree matrix.\n\n Parameters\n ----------\n in_feats : int\n Input feature size.\n out_feats : int\n Output feature size.\n k: int, optional\n Number of hops :math: `k`. (default: 2)\n bias: bool, optional\n If True, adds a learnable bias to the output. Default: ``True``.\n activation: callable activation function/layer or None, optional\n If not None, applies an activation function to the updated node features.\n Default: ``None``.\n\n Attributes\n ----------\n lin : torch.Module\n The learnable linear module.\n \"\"\"\n def __init__(self,\n in_feats,\n out_feats,\n k=2,\n bias=True,\n activation=None):\n super(TAGConv, self).__init__()\n self._in_feats = in_feats\n self._out_feats = out_feats\n self._k = k\n self._activation = activation\n self.lin = nn.Linear(in_feats * (self._k + 1), out_feats, bias=bias)\n\n self.reset_parameters()\n\n def reset_parameters(self):\n \"\"\"Reinitialize learnable parameters.\"\"\"\n gain = nn.init.calculate_gain('relu')\n nn.init.xavier_normal_(self.lin.weight, gain=gain)\n\n def forward(self, graph, feat):\n r\"\"\"Compute topology adaptive graph convolution.\n\n Parameters\n ----------\n graph : DGLGraph\n The graph.\n feat : torch.Tensor\n The input feature of shape :math:`(N, D_{in})` where :math:`D_{in}`\n is size of input feature, :math:`N` is the number of nodes.\n\n Returns\n -------\n torch.Tensor\n The output feature of shape :math:`(N, D_{out})` where :math:`D_{out}`\n is size of output feature.\n \"\"\"\n with graph.local_scope():\n assert graph.is_homogeneous(), 'Graph is not homogeneous'\n\n norm = th.pow(graph.in_degrees().float().clamp(min=1), -0.5)\n shp = norm.shape + (1,) * (feat.dim() - 1)\n norm = th.reshape(norm, shp).to(feat.device)\n\n #D-1/2 A D -1/2 X\n fstack = [feat]\n for _ in range(self._k):\n\n rst = fstack[-1] * norm\n graph.ndata['h'] = rst\n\n graph.update_all(fn.copy_src(src='h', out='m'),\n fn.sum(msg='m', out='h'))\n rst = graph.ndata['h']\n rst = rst * norm\n fstack.append(rst)\n\n rst = self.lin(th.cat(fstack, dim=-1))\n\n if self._activation is not None:\n rst = self._activation(rst)\n\n return rst\n" ]
[ [ "torch.nn.Dropout", "torch.Tensor", "torch.cat", "torch.nn.ParameterDict", "torch.einsum", "torch.randn", "torch.nn.Linear", "torch.nn.ParameterList", "torch.nn.init.xavier_uniform_" ], [ "torch.nn.init.calculate_gain", "torch.cat", "torch.reshape", "torch.nn.init.xavier_normal_", "torch.nn.Linear" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
xyt556/rsnet
[ "5f20f5308f89695e9f26ee4724d5591201d0c52d" ]
[ "rsnet/dataset/raster.py" ]
[ "import os\n\nimport rasterio\nimport numpy as np\n\nfrom ..utils import pair, bytescale\nfrom .base import BaseRasterData\n\n\nclass RasterSampleDataset(BaseRasterData):\n \"\"\"Dataset wrapper for remote sensing data.\n\n Args:\n fname:\n win_size:\n step_size:\n pad_size:\n band_index:\n \"\"\"\n def __init__(self,\n fname,\n win_size=512,\n step_size=512,\n pad_size=0,\n band_index=None,\n to_type=None,\n data_format='channel_last',\n transform=None):\n super().__init__(fname=fname)\n\n assert data_format in (\n 'channel_first',\n 'channel_last'), \"data format must be 'channel_first' or \"\n f\"'channel_last', but got type {data_format}\"\n self.data_format = data_format\n\n self.win_size = pair(win_size)\n self.step_size = pair(step_size)\n self.pad_size = pair(pad_size)\n\n total_band_index = [i + 1 for i in range(self.count)]\n if band_index is None:\n self.band_index = total_band_index\n else:\n assert set(band_index).issubset(set(total_band_index))\n self.band_index = band_index\n\n self.to_type = to_type\n self.window_ids = self.get_windows_info()\n self.transform = transform\n\n self.start = 0\n self.end = len(self)\n\n def get_windows_info(self):\n left, top = 0, 0\n width, height = self.width, self.height\n left_top_xy = [] # left-top corner coordinates (xmin, ymin)\n while left < width:\n if left + self.win_size[0] >= width:\n left = max(width - self.win_size[0], 0)\n top = 0\n while top < height:\n if top + self.win_size[1] >= height:\n top = max(height - self.win_size[1], 0)\n # right = min(left + self.win_size[0], width - 1)\n # bottom = min(top + self.win_size[1], height - 1)\n # save\n left_top_xy.append((left, top))\n if top + self.win_size[1] >= height:\n break\n else:\n top += self.step_size[1]\n\n if left + self.win_size[0] >= width:\n break\n else:\n left += self.step_size[0]\n\n return left_top_xy\n\n def sample(self, x, y):\n \"\"\"Get the values of dataset at certain positions.\n \"\"\"\n xmin, ymin = x, y\n xsize, ysize = self.win_size\n xpad, ypad = self.pad_size\n\n xmin -= xpad\n ymin -= ypad\n left, top = 0, 0\n if xmin < 0:\n xmin = 0\n xsize += xpad\n left = xpad\n elif xmin + xsize + 2 * xpad > self.width:\n xsize += xpad\n else:\n xsize += 2 * xpad\n\n if ymin < 0:\n ymin = 0\n ysize += ypad\n top = ypad\n elif ymin + ysize + 2 * ypad > self.height:\n ysize += ypad\n else:\n ysize += 2 * ypad\n\n # col_off, row_off, width, height\n window = rasterio.windows.Window(xmin, ymin, xsize, ysize)\n\n # with rasterio.open(self.image_file) as src:\n # bands = [src.read(k, window=tile_window) for k in self.band_index]\n # tile_image = np.stack(bands, axis=-1)\n bands = [self._band.read(k, window=window) for k in self.band_index]\n if self.to_type and np.dtype(self.to_type) != np.dtype(self.dtype):\n bmin, bmax = self.minmax\n msks = [\n self._band.read_masks(k, window=window)\n for k in self.band_index\n ]\n bands = [\n bytescale(b, msk, bmin[i], bmax[i], dtype=self.to_type)\n for i, (b, msk) in enumerate(zip(bands, msks))\n ]\n\n tile_image = np.stack(bands, axis=-1)\n img = np.zeros(\n (self.win_size[0] + 2 * xpad, self.win_size[0] + 2 * ypad,\n len(self.band_index)),\n dtype=tile_image.dtype)\n img[top:top + ysize, left:left + xsize] = tile_image\n\n if self.data_format == 'channel_first':\n img = img.transpose(2, 0, 1)\n\n return img\n\n def __getitem__(self, idx):\n x, y = self.window_ids[idx]\n img = self.sample(x, y)\n if self.transform is not None:\n img = self.transform(img)\n\n return img, x, y\n\n def __len__(self):\n return len(self.window_ids)\n\n @property\n def step(self):\n return self.step_size\n\n @property\n def pad(self):\n return self.pad_size\n" ]
[ [ "numpy.dtype", "numpy.stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
KainRasleafar/sedfitter
[ "4f0e9e46f7903a853166835bb74857cc15eef219", "4f0e9e46f7903a853166835bb74857cc15eef219", "4f0e9e46f7903a853166835bb74857cc15eef219" ]
[ "sedfitter/sed/sed.py", "sedfitter/fitting_routines.py", "sedfitter/filter/filter.py" ]
[ "from __future__ import print_function, division\n\nimport os\n\nimport numpy as np\nfrom astropy import log\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom scipy.interpolate import interp1d\nfrom astropy import units as u\n\nfrom ..utils.validator import validate_array\n\nfrom .helpers import parse_unit_safe, assert_allclose_quantity, convert_flux\n\n__all__ = ['SED']\n\n\nclass SED(object):\n\n def __init__(self):\n\n # Metadata\n self.name = None\n self.distance = None\n\n # Spectral info\n self.wav = None\n self.nu = None\n\n # Apertures\n self.apertures = None\n\n # Fluxes\n self.flux = None\n self.error = None\n\n def __eq__(self, other):\n\n try:\n\n assert self.name == other.name\n\n assert_allclose_quantity(self.distance, other.distance)\n\n assert_allclose_quantity(self.wav, other.wav)\n assert_allclose_quantity(self.nu, other.nu)\n\n assert_allclose_quantity(self.apertures, other.apertures)\n\n assert_allclose_quantity(self.flux, other.flux)\n assert_allclose_quantity(self.error, other.error)\n\n except AssertionError:\n raise\n return False\n else:\n return True\n\n def copy(self):\n from copy import deepcopy\n return deepcopy(self)\n\n def scale_to_distance(self, distance):\n \"\"\"\n Returns the SED scaled to distance `distance`\n\n Parameters\n ----------\n distance : float\n The distance in cm\n\n Returns\n -------\n sed : SED\n The SED, scaled to the new distance\n \"\"\"\n sed = self.copy()\n sed.distance = distance * u.cm\n sed.flux = sed.flux * (self.distance.to(u.cm) / sed.distance) ** 2\n sed.error = sed.error * (self.distance.to(u.cm) / sed.distance) ** 2\n return sed\n\n def scale_to_av(self, av, law):\n sed = self.copy()\n sed.flux = sed.flux * 10. ** (av * law(sed.wav))\n sed.error = sed.error * 10. ** (av * law(sed.wav))\n return sed\n\n @property\n def wav(self):\n \"\"\"\n The wavelengths at which the SED is defined\n \"\"\"\n if self._wav is None and self._nu is not None:\n return self._nu.to(u.micron, equivalencies=u.spectral())\n else:\n return self._wav\n\n @wav.setter\n def wav(self, value):\n if value is None:\n self._wav = None\n else:\n self._wav = validate_array('wav', value, domain='positive', ndim=1,\n shape=None if self.nu is None else (len(self.nu),),\n physical_type='length')\n\n @property\n def nu(self):\n \"\"\"\n The frequencies at which the SED is defined\n \"\"\"\n if self._nu is None and self._wav is not None:\n return self._wav.to(u.Hz, equivalencies=u.spectral())\n else:\n return self._nu\n\n @nu.setter\n def nu(self, value):\n if value is None:\n self._nu = None\n else:\n self._nu = validate_array('nu', value, domain='positive', ndim=1,\n shape=None if self.wav is None else (len(self.wav),),\n physical_type='frequency')\n\n @property\n def apertures(self):\n \"\"\"\n The apertures at which the SED is defined\n \"\"\"\n return self._apertures\n\n @apertures.setter\n def apertures(self, value):\n if value is None:\n self._apertures = None\n else:\n self._apertures = validate_array('apertures', value, domain='positive',\n ndim=1, physical_type='length')\n\n @property\n def flux(self):\n \"\"\"\n The SED fluxes\n \"\"\"\n return self._flux\n\n @flux.setter\n def flux(self, value):\n if value is None:\n self._flux = value\n else:\n self._flux = validate_array('flux', value, ndim=2,\n shape=(self.n_ap, self.n_wav),\n physical_type=('power', 'flux', 'spectral flux density'))\n\n @property\n def error(self):\n \"\"\"\n The convolved flux errors\n \"\"\"\n return self._error\n\n @error.setter\n def error(self, value):\n if value is None:\n self._error = value\n else:\n self._error = validate_array('error', value, ndim=2,\n shape=(self.n_ap, self.n_wav),\n physical_type=('power', 'flux', 'spectral flux density'))\n\n @property\n def n_ap(self):\n if self.apertures is None:\n return 1\n else:\n return len(self.apertures)\n\n @property\n def n_wav(self):\n if self.wav is None:\n return None\n else:\n return len(self.wav)\n\n @classmethod\n def read(cls, filename, unit_wav=u.micron, unit_freq=u.Hz,\n unit_flux=u.erg / u.cm ** 2 / u.s, order='nu'):\n \"\"\"\n Read an SED from a FITS file.\n\n Parameters\n ----------\n filename: str\n The name of the file to read the SED from.\n unit_wav: `~astropy.units.Unit`, optional\n The units to convert the wavelengths to.\n unit_freq: `~astropy.units.Unit`, optional\n The units to convert the frequency to.\n unit_flux: `~astropy.units.Unit`, optional\n The units to convert the flux to.\n order: str, optional\n Whether to sort the SED by increasing wavelength (`wav`) or\n frequency ('nu').\n \"\"\"\n\n # Instantiate SED class\n sed = cls()\n\n # Assume that the filename may be missing the .gz extension\n if not os.path.exists(filename) and os.path.exists(filename + '.gz'):\n filename += \".gz\"\n\n # Open FILE file\n hdulist = fits.open(filename, memmap=False)\n\n # Extract model name\n sed.name = hdulist[0].header['MODEL']\n\n # Check if distance is specified in header, otherwise assume 1kpc\n if 'DISTANCE' in hdulist[0].header:\n sed.distance = hdulist[0].header['DISTANCE'] * u.cm\n else:\n log.debug(\"No distance found in SED file, assuming 1kpc\")\n sed.distance = 1. * u.kpc\n\n # Extract SED values\n wav = hdulist[1].data.field('WAVELENGTH') * parse_unit_safe(hdulist[1].columns[0].unit)\n nu = hdulist[1].data.field('FREQUENCY') * parse_unit_safe(hdulist[1].columns[1].unit)\n ap = hdulist[2].data.field('APERTURE') * parse_unit_safe(hdulist[2].columns[0].unit)\n flux = hdulist[3].data.field('TOTAL_FLUX') * parse_unit_safe(hdulist[3].columns[0].unit)\n error = hdulist[3].data.field('TOTAL_FLUX_ERR') * parse_unit_safe(hdulist[3].columns[1].unit)\n\n # Set SED attributes\n sed.apertures = ap\n\n # Convert wavelength and frequencies to requested units\n sed.wav = wav.to(unit_wav)\n sed.nu = nu.to(unit_freq)\n\n # Set fluxes\n sed.flux = convert_flux(nu, flux, unit_flux, distance=sed.distance)\n sed.error = convert_flux(nu, error, unit_flux, distance=sed.distance)\n\n # Sort SED\n\n if order not in ('nu', 'wav'):\n raise ValueError('order should be nu or wav')\n\n if (order == 'nu' and sed.nu[0] > sed.nu[-1]) or \\\n (order == 'wav' and sed.wav[0] > sed.wav[-1]):\n sed.wav = sed.wav[::-1]\n sed.nu = sed.nu[::-1]\n sed.flux = sed.flux[..., ::-1]\n sed.error = sed.error[..., ::-1]\n\n return sed\n\n def write(self, filename, overwrite=False):\n \"\"\"\n Write an SED to a FITS file.\n\n Parameters\n ----------\n filename: str\n The name of the file to write the SED to.\n \"\"\"\n\n # Create first HDU with meta-data\n hdu0 = fits.PrimaryHDU()\n\n if self.name is None:\n raise ValueError(\"Model name is not set\")\n else:\n hdu0.header['MODEL'] = self.name\n\n if self.distance is None:\n raise ValueError(\"Model distance is not set\")\n else:\n hdu0.header['DISTANCE'] = self.distance.to(u.cm).value\n\n hdu0.header['NAP'] = self.n_ap\n hdu0.header['NWAV'] = self.n_wav\n\n # Create wavelength table\n twav = Table()\n if self.wav is None:\n raise ValueError(\"Wavelengths are not set\")\n else:\n twav['WAVELENGTH'] = self.wav\n if self.nu is None:\n raise ValueError(\"Frequencies are not set\")\n else:\n twav['FREQUENCY'] = self.nu\n twav.sort('FREQUENCY')\n\n # TODO: here sorting needs to be applied to fluxes too?\n\n hdu1 = fits.BinTableHDU(np.array(twav))\n hdu1.columns[0].unit = self.wav.unit.to_string(format='fits')\n hdu1.columns[1].unit = self.nu.unit.to_string(format='fits')\n hdu1.header['EXTNAME'] = \"WAVELENGTHS\"\n\n # Create aperture table\n tap = Table()\n if self.apertures is None:\n tap['APERTURE'] = [1.e-30]\n else:\n tap['APERTURE'] = self.apertures\n hdu2 = fits.BinTableHDU(np.array(tap))\n if self.apertures is None:\n hdu2.columns[0].unit = 'cm'\n else:\n hdu2.columns[0].unit = self.apertures.unit.to_string(format='fits')\n hdu2.header['EXTNAME'] = \"APERTURES\"\n\n # Create flux table\n tflux = Table()\n tflux['TOTAL_FLUX'] = self.flux\n if self.flux is None:\n raise ValueError(\"Fluxes are not set\")\n else:\n tflux['TOTAL_FLUX'] = self.flux\n if self.error is None:\n raise ValueError(\"Errors are not set\")\n else:\n tflux['TOTAL_FLUX_ERR'] = self.error\n hdu3 = fits.BinTableHDU(np.array(tflux))\n hdu3.columns[0].unit = self.flux.unit.to_string(format='fits')\n hdu3.columns[1].unit = self.error.unit.to_string(format='fits')\n hdu3.header['EXTNAME'] = \"SEDS\"\n\n hdus = [hdu0, hdu1, hdu2, hdu3]\n\n # Create overall FITS file\n hdulist = fits.HDUList(hdus)\n hdulist.writeto(filename, clobber=overwrite)\n\n def interpolate(self, apertures):\n \"\"\"\n Interpolate the SED to different apertures\n \"\"\"\n\n # If there is only one aperture, we can't interpolate, we can only repeat\n if self.n_ap == 1:\n return np.repeat(self.flux[0, :], len(apertures)).reshape(self.n_wav, len(apertures))\n\n # Create interpolating function\n flux_interp = interp1d(self.apertures, self.flux.swapaxes(0, 1))\n\n # If any apertures are larger than the defined max, reset to max\n apertures[apertures > self.apertures.max()] = self.apertures.max()\n\n # If any apertures are smaller than the defined min, raise Exception\n if np.any(apertures < self.apertures.min()):\n raise Exception(\"Aperture(s) requested too small\")\n\n return flux_interp(apertures)\n\n def interpolate_variable(self, wavelengths, apertures):\n \"\"\"\n Interpolate the SED to a variable aperture as a function of\n wavelength. This method should be called with an interpolating\n function for aperture as a function of wavelength, in log10 space.\n \"\"\"\n\n if self.n_ap == 1:\n return self.flux[0, :]\n\n sed_apertures = self.apertures.to(u.au).value\n sed_wav = self.wav.to(u.micron).value\n\n # If any apertures are larger than the defined max, reset to max\n apertures[apertures > sed_apertures.max()] = sed_apertures.max() * 0.999\n\n # If any apertures are smaller than the defined min, raise Exception\n if np.any(apertures < sed_apertures.min()):\n raise Exception(\"Aperture(s) requested too small\")\n\n # Find wavelength order\n order = np.argsort(wavelengths)\n\n # Interpolate apertures vs wavelength\n log10_ap_interp = interp1d(np.log10(wavelengths[order]), np.log10(apertures[order]), bounds_error=False, fill_value=np.nan)\n\n # Create interpolating function\n flux_interp = interp1d(sed_apertures, self.flux.swapaxes(0, 1))\n\n # Interpolate the apertures\n apertures = 10. ** log10_ap_interp(np.log10(sed_wav))\n\n # Extrapolate on either side\n apertures[np.log10(sed_wav) < log10_ap_interp.x[0]] = 10. ** log10_ap_interp.y[0]\n apertures[np.log10(sed_wav) > log10_ap_interp.x[-1]] = 10. ** log10_ap_interp.y[-1]\n\n # Interpolate and return only diagonal elements\n return flux_interp(apertures).diagonal()\n", "from __future__ import print_function, division\n\nimport numpy as np\n\n\ndef linear_regression(data, weights, pattern1, pattern2):\n\n c1 = np.sum(data * pattern1 * weights, axis=1)\n c2 = np.sum(data * pattern2 * weights, axis=1)\n m11 = np.sum(pattern1 * pattern1 * weights)\n m12 = np.sum(pattern1 * pattern2 * weights)\n m22 = np.sum(pattern2 * pattern2 * weights)\n\n inv_det = 1. / (m11 * m22 - m12 * m12)\n\n p1 = (m22 * c1 - m12 * c2) * inv_det\n p2 = (m11 * c2 - m12 * c1) * inv_det\n\n return p1, p2\n\n\ndef optimal_scaling(data, weights, pattern1):\n return np.sum(data * pattern1 * weights, axis=data.ndim - 1) / \\\n np.sum(pattern1 * pattern1 * weights)\n\n\ndef chi_squared(valid, data, error, weight, model):\n \"\"\"\n valid has dimension (n_wav, )\n data has dimension (n_wav, n_models)\n error has dimension(n_wav)\n weight has dimension(n_wav)\n model has dimension (n_wav, n_models)\n \"\"\"\n\n # Calculate the 'default' chi^2 and handle special cases after\n chi2_array = (data - model) ** 2 * weight\n\n # Force chi^2 to zero for valid == 0\n if chi2_array.ndim == 2:\n chi2_array[:, valid == 0] = 0.\n elif chi2_array.ndim == 3:\n chi2_array[:, :, valid == 0] = 0.\n else:\n raise Exception(\"Chi^2 array has unexpected number of dimensions: %i\" % chi2_array.ndim)\n\n # Reset lower limits where model < data\n if chi2_array.ndim == 2:\n for j in np.where(valid == 2)[0]:\n reset = model[:, j] < data[:, j]\n chi2_array[:, j][reset] = -2. * np.log(1. - error[j])\n else:\n for j in np.where(valid == 2)[0]:\n reset = model[:, :, j] < data[:, :, j]\n chi2_array[:, :, j][reset] = -2. * np.log(1. - error[j])\n\n # Reset upper limits where model > data\n if chi2_array.ndim == 2:\n for j in np.where(valid == 3)[0]:\n reset = model[:, j] > data[:, j]\n chi2_array[:, j][reset] = -2. * np.log(1. - error[j])\n else:\n for j in np.where(valid == 3)[0]:\n reset = model[:, :, j] > data[:, :, j]\n chi2_array[:, :, j][reset] = -2. * np.log(1. - error[j])\n\n # Check that there are no infinities\n chi2_array[np.isinf(chi2_array)] = 1.e30\n\n return np.sum(chi2_array, axis=chi2_array.ndim - 1)\n", "from __future__ import print_function, division\n\nimport os\n\nimport numpy as np\nfrom astropy import units as u\n\nfrom ..utils.integrate import integrate_subset, integrate\nfrom ..utils.validator import validate_array, validate_scalar\n\nc = 299792458.\n\n\nclass Filter(object):\n \"\"\"\n A filter used to convolve SED models.\n\n Parameters\n ----------\n name : str\n The name of the filter (typically short and with no spaces, such as\n ``2K`` or 2MASS K-band or ``I1`` for IRAC 3.6 microns).\n central_wavelength : :class:`~astropy.units.quantity.Quantity`\n The central wavelength (in units of length)\n nu : :class:`~astropy.units.quantity.Quantity`\n The frequencies at which the filter is defined.\n response : `numpy.ndarray`\n The relative response at the different frequencies. Note that this\n should already take into account the assumptions about whether this is\n the response per photon or energy, and any other assumptions about\n converting the SED to a monochromatic flux. See the documentation for\n more details.\n \"\"\"\n def __init__(self, name=None, central_wavelength=None, nu=None, response=None):\n self.name = name\n self.central_wavelength = central_wavelength\n self.nu = nu\n self.response = response\n\n @classmethod\n def read(cls, filename):\n \"\"\"\n Read a filter from a file.\n\n This method assumes that the file contains a column with wavelengths\n (in micron) and the other column contains the response. It also\n assumes that the first line contains a header with the central\n wavelength (in microns), using the following syntax::\n\n # wav = 1.25\n\n Parameters\n ----------\n filename: str\n The name of the file containing the filter\n \"\"\"\n\n self = cls()\n\n # Read in central wavelength\n self.central_wavelength = float(open(filename, 'r').readline().split('=')[1]) * u.micron\n\n # Read in spectral response curve\n self.wav = np.loadtxt(filename, usecols=[0], dtype=float) * u.micron\n self.response = np.loadtxt(filename, usecols=[1], dtype=float)\n\n # Compute frequency\n self.nu = self.wav.to(u.Hz, equivalencies=u.spectral())\n\n # Set name\n if self.name is None:\n self.name = os.path.basename(filename).split('.')[0]\n\n return self\n\n def normalize(self):\n \"\"\"\n Normalize so the integral over nu is 1\n \"\"\"\n if self.nu is None:\n raise ValueError(\"nu has not been set\")\n if self.response is None:\n raise ValueError(\"response has not been set\")\n self.response = self.response / np.abs(integrate(self.nu.to(u.Hz).value, self.response))\n\n def rebin(self, nu_new):\n \"\"\"\n Re-bin the filter onto a new frequency grid\n\n Parameters\n ----------\n nu_new: np.ndarray\n The new frequency grid\n\n Returns\n -------\n filter: Filter\n The binned filter\n \"\"\"\n\n # Define new filter\n f = Filter()\n f.name = self.name\n f.central_wavelength = self.central_wavelength\n f.nu = nu_new\n\n self_nu_hz = self.nu.to(u.Hz).value\n nu_new_hz = f.nu.to(u.Hz).value\n\n # Compute re-binned transmission\n\n f.response = np.zeros(nu_new.shape)\n\n for i in range(len(f.response)):\n\n if i == 0:\n nu1 = nu_new_hz[0]\n else:\n nu1 = 0.5 * (nu_new_hz[i - 1] + nu_new_hz[i])\n\n if i == len(nu_new_hz) - 1:\n nu2 = nu_new_hz[-1]\n else:\n nu2 = 0.5 * (nu_new_hz[i] + nu_new_hz[i + 1])\n\n nu1 = min(max(nu1, self_nu_hz[0]), self_nu_hz[-1])\n nu2 = min(max(nu2, self_nu_hz[0]), self_nu_hz[-1])\n\n if nu2 != nu1:\n f.response[i] = integrate_subset(self_nu_hz, self.response, nu1, nu2)\n\n return f\n\n @property\n def central_wavelength(self):\n \"\"\"\n The central or characteristic wavelength of the filter\n \"\"\"\n return self._wavelength\n\n @central_wavelength.setter\n def central_wavelength(self, value):\n if value is None:\n self._wavelength = None\n else:\n self._wavelength = validate_scalar('central_wavelength', value,\n domain='strictly-positive',\n physical_type='length')\n\n @property\n def nu(self):\n \"\"\"\n The frequencies at which the filter is defined\n \"\"\"\n return self._nu\n\n @nu.setter\n def nu(self, value):\n if value is None:\n self._nu = None\n else:\n self._nu = validate_array('nu', value, domain='strictly-positive', ndim=1,\n physical_type='frequency')\n\n @property\n def response(self):\n \"\"\"\n The filter response\n \"\"\"\n return self._r\n\n @response.setter\n def response(self, value):\n if value is None:\n self._r = None\n else:\n self._r = validate_array('r', value, domain='positive', ndim=1,\n shape=None if self.nu is None else (len(self.nu),))\n" ]
[ [ "numpy.argsort", "numpy.log10", "numpy.array" ], [ "numpy.isinf", "numpy.log", "numpy.where", "numpy.sum" ], [ "numpy.zeros", "numpy.loadtxt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Rick0514/VPR_SMCN
[ "7a00dc8e4de0c21438474c05a4a7be18d05367fa" ]
[ "main/MCN.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport main.utils as utils\nimport time\n\n# ---------------------------- 说明 ----------------------------------\n# MCN的python复现\n# ---------------------------- 说明 ----------------------------------\n\n\nclass MCNParams:\n \"\"\"\n a struct define the input params MCN class use\n \"\"\"\n def __init__(self, probAddCon, nCellPerCol, nConPerCol,\n minColActivity, nColPerPattern, kActiveCol):\n self.probAddCon = probAddCon\n self.nCellPerCol = nCellPerCol\n self.nConPerCol = nConPerCol\n self.minColActivity = minColActivity\n self.nColPerPattern = nColPerPattern\n self.kActiveCol = kActiveCol\n\n\nclass MCN:\n\n def __init__(self, params):\n\n # MCNParams class define the params\n self.params = params\n\n self.nCols = 0\n self.winnerCells = []\n self.prevWinnerCells = []\n\n self.FF = np.empty((self.params.nConPerCol, self.nCols), dtype=np.int)\n self.P = np.empty((self.params.nCellPerCol, self.nCols), dtype=np.bool)\n self.prevP = np.empty_like(self.P, dtype=np.bool)\n\n self.burstedCol = np.empty((self.nCols, ), dtype=np.bool)\n self.predicitionConnections = []\n\n def prepareNewIteration(self):\n\n # winnerCells and P need to reset each time\n self.prevWinnerCells = self.winnerCells\n self.prevP = self.P\n\n self.winnerCells = []\n if self.nCols > 0:\n self.P = np.zeros_like(self.P)\n self.burstedCol = np.zeros_like(self.burstedCol)\n\n\n def resetPredP(self):\n self.prevP = np.empty((self.params.nCellPerCol, self.nCols), dtype=np.bool)\n\n def createNewColumn(self, inputSDR, nNewColumn):\n\n nonZeroIdx = np.where(inputSDR > 0)[0]\n\n start_id = self.nCols\n for i in range(nNewColumn):\n self.nCols += 1\n\n sampleIdx = np.random.randint(0, len(nonZeroIdx), self.params.nConPerCol)\n tmp = nonZeroIdx[sampleIdx].reshape((-1, 1))\n self.FF = np.concatenate((self.FF, tmp), axis=1)\n\n newPcol = np.zeros((self.params.nCellPerCol, 1), dtype=np.bool)\n self.P = np.concatenate((self.P, newPcol), axis=1)\n self.prevP = np.concatenate((self.prevP, newPcol), axis=1)\n self.burstedCol = np.concatenate((self.burstedCol, np.array([0], dtype=bool)))\n for k in range(nNewColumn * self.params.nCellPerCol):\n self.predicitionConnections.append([])\n\n return np.arange(start_id, self.nCols)\n\n\n def compute(self, inputSDR, supressLearningFlag):\n \"\"\"\n compute sequence descriptor\n :param inputSDR:\n :param supressLearningFlag: in case of inference, not learning\n :return:\n \"\"\"\n\n self.prepareNewIteration()\n\n # compare SDR with minicolumn\n simScore = np.sum(inputSDR[self.FF], axis=0) / self.params.nConPerCol\n sort_idx = np.argsort(simScore)\n topk_sort_idx = sort_idx[-self.params.kActiveCol:]\n topk_sort_score = simScore[topk_sort_idx]\n if not supressLearningFlag:\n # if all activities below threshold, then create a new\n # activity and make it active\n # otherwise select the top k most active ones\n if len(simScore):\n activeCols = topk_sort_idx[topk_sort_score > self.params.minColActivity]\n # activeCols = np.array(self.getActiveCols(simScore, supressLearningFlag), dtype=np.int)\n else:\n activeCols = np.empty((0, ), dtype=np.int)\n\n activeCols = np.concatenate((activeCols, self.createNewColumn(inputSDR, max(0, self.params.nColPerPattern - len(activeCols)))))\n\n else:\n # in non-learning mode, take the k most active columns\n # activeCols = np.array(self.getActiveCols(simScore, supressLearningFlag), dtype=np.int)\n activeCols = topk_sort_idx\n # if len(activeCols) == 0:\n # sort_idx = np.argsort(simScore)\n # activeCols = sort_idx[-self.params.nColPerPattern:]\n\n for eachActiveCol in activeCols:\n predictedIdx = np.where(self.prevP[:, eachActiveCol] > 0)[0]\n\n if len(predictedIdx):\n for each_predictedIdx in predictedIdx:\n self.activatePredictions(eachActiveCol, each_predictedIdx)\n self.winnerCells.append(eachActiveCol * self.params.nCellPerCol + each_predictedIdx)\n else:\n winnerCell = self.burst(eachActiveCol, supressLearningFlag)\n for each in winnerCell:\n self.winnerCells.append(eachActiveCol * self.params.nCellPerCol + each)\n\n if not supressLearningFlag:\n self.learnPreditions()\n # predict newly learned preditions, i think it's useless\n for colIdx in range(self.nCols):\n if self.burstedCol[colIdx]:\n for i in range(self.params.nCellPerCol):\n self.activatePredictions(colIdx, i)\n\n return self.winnerCells\n\n def activatePredictions(self, colIdx, cellIdx):\n predIdx = self.predicitionConnections[colIdx * self.params.nCellPerCol + cellIdx]\n for each in predIdx:\n c = each // self.params.nCellPerCol\n r = each % self.params.nCellPerCol\n self.P[r, c] = True\n\n def burst(self, colIdx, supressLearningFlag):\n\n self.burstedCol[colIdx] = True\n for i in range(self.params.nCellPerCol):\n self.activatePredictions(colIdx, i)\n\n # winnerCell is the cells with fewest connections with other cells\n st = colIdx * self.params.nCellPerCol\n nCon = []\n for i in range(self.params.nCellPerCol):\n nCon.append(len(self.predicitionConnections[st + i]))\n\n if not supressLearningFlag:\n # inhibit winning cells from the last iteration\n for i in self.prevWinnerCells:\n col = i // self.params.nCellPerCol\n if col == colIdx:\n nCon[i % self.params.nCellPerCol] += self.params.nCellPerCol\n\n # find the fewest ones\n candidateIdx = [0]\n minV = nCon[0]\n for i in range(1, len(nCon)):\n if nCon[i] < minV:\n candidateIdx = [i]\n minV = nCon[i]\n elif nCon[i] == minV:\n candidateIdx.append(i)\n\n nCan = len(candidateIdx)\n\n if nCan == 1:\n return [candidateIdx[0]]\n else:\n chosenIdx = np.random.randint(0, nCan, 1)\n return [candidateIdx[chosenIdx[0]]]\n\n else:\n # in case of inference, return all used winner cells\n winnerIdx = np.where(np.array(nCon) > 0)[0]\n if len(winnerIdx):\n return winnerIdx\n\n return [np.random.randint(0, self.params.nCellPerCol, 1)[0]]\n\n\n def learnPreditions(self):\n\n for prevIdx in self.prevWinnerCells:\n prevIdxCol = prevIdx // self.params.nCellPerCol\n for curIdx in self.winnerCells:\n curIdxCol = curIdx // self.params.nCellPerCol\n if prevIdxCol == curIdxCol:\n continue\n\n existingPredConFlag = self.checkExistingPredCon(prevIdxCol, curIdx)\n if not existingPredConFlag or np.random.rand() <= self.params.probAddCon:\n if curIdx not in self.predicitionConnections[prevIdx]:\n self.predicitionConnections[prevIdx].append(curIdx)\n\n\n def checkExistingPredCon(self, prevColIdx, curCellIdx):\n st = prevColIdx * self.params.nCellPerCol\n for i in range(self.params.nCellPerCol):\n if curCellIdx in self.predicitionConnections[st + i]:\n return True\n\n return False\n\n\n def visualizeCon(self, displayCol=10):\n\n plt.figure()\n dis = 5\n dCol = displayCol\n plt.title('Prediction Connections')\n plt.xlim(0, dCol * dis)\n plt.ylim(0, self.params.nCellPerCol * dis)\n\n for k, con in enumerate(self.predicitionConnections):\n x = k // self.params.nCellPerCol * dis\n if x >= dCol * dis:\n break\n y = k % self.params.nCellPerCol\n y = (self.params.nCellPerCol - 1 - y) * dis\n plt.plot(x, y, 'o', color='blue')\n if len(con):\n for each in con:\n cx = each // self.params.nCellPerCol * dis\n cy = each % self.params.nCellPerCol\n cy = (self.params.nCellPerCol - 1 - cy) * dis\n plt.plot([x, cx], [y, cy], '-', color='red')\n\n\n\ndef getSim(w1, w2):\n \"\"\"\n\n :param w1: winner cell which should be a list\n :param w2:\n :return: simularity score\n \"\"\"\n w1 = set(w1)\n w2 = set(w2)\n return len(w1 & w2) / len(w1 | w2)\n\n\ndef runMCN(params, dbFeat, qFeat, gt):\n\n # st = time.time()\n _, old_dims = dbFeat.shape\n new_dims = 8192\n P = np.random.rand(old_dims, new_dims // 2)\n P /= np.linalg.norm(P, axis=1, keepdims=True)\n\n D1_slsbh = utils.getLSBH(dbFeat, P, 0.25)\n D2_slsbh = utils.getLSBH(qFeat, P, 0.25)\n\n mcn = MCN(params)\n train_winnerCells = []\n for i in range(D1_slsbh.shape[0]):\n train_winnerCells.append(mcn.compute(D1_slsbh[i, :], False))\n\n valid_winnerCells = []\n mcn.resetPredP()\n for i in range(D2_slsbh.shape[0]):\n valid_winnerCells.append(mcn.compute(D2_slsbh[i, :], True))\n\n # print('Done! cost : %.3f' % (time.time() - st))\n # get similarity matrix\n S_mcn = np.zeros((dbFeat.shape[0], qFeat.shape[0]))\n for k1, each_v in enumerate(valid_winnerCells):\n for k2, each_t in enumerate(train_winnerCells):\n S_mcn[k2, k1] = getSim(each_v, each_t)\n # time_cost = time.time() - st\n # P, R = utils.drawPR(S_mcn, gt)\n # ap = utils.calAvgPred(P, R)\n del train_winnerCells, valid_winnerCells, mcn\n\n return S_mcn\n\ndef runMCN_SDR(params, dbFeat, qFeat, gt):\n\n mcn = MCN(params)\n train_winnerCells = []\n for i in range(dbFeat.shape[0]):\n train_winnerCells.append(mcn.compute(dbFeat[i, :], False))\n\n valid_winnerCells = []\n mcn.resetPredP()\n for i in range(qFeat.shape[0]):\n valid_winnerCells.append(mcn.compute(qFeat[i, :], True))\n\n # print('Done! cost : %.3f' % (time.time() - st))\n # get similarity matrix\n S_mcn = np.zeros((dbFeat.shape[0], qFeat.shape[0]))\n for k1, each_v in enumerate(valid_winnerCells):\n for k2, each_t in enumerate(train_winnerCells):\n S_mcn[k2, k1] = getSim(each_v, each_t)\n # time_cost = time.time() - st\n # P, R = utils.drawPR(S_mcn, gt)\n # ap = utils.calAvgPred(P, R)\n del train_winnerCells, valid_winnerCells, mcn\n\n return S_mcn\n" ]
[ [ "numpy.sum", "matplotlib.pyplot.title", "numpy.empty_like", "numpy.arange", "matplotlib.pyplot.ylim", "numpy.linalg.norm", "numpy.concatenate", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlim", "numpy.zeros_like", "numpy.random.rand", "numpy.random.randint", "numpy.argsort", "numpy.array", "numpy.zeros", "numpy.where", "numpy.empty", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
FynnBe/pytorch-3dunet
[ "34918e82c3afeff02360b03964de973eac3a4f75" ]
[ "pytorch3dunet/augment/transforms.py" ]
[ "import importlib\n\nimport numpy as np\nimport torch\nfrom scipy.ndimage import rotate, map_coordinates, gaussian_filter\nfrom scipy.ndimage.filters import convolve\nfrom skimage.filters import gaussian\nfrom skimage.segmentation import find_boundaries\nfrom torchvision.transforms import Compose\n\n# WARN: use fixed random state for reproducibility; if you want to randomize on each run seed with `time.time()` e.g.\nGLOBAL_RANDOM_STATE = np.random.RandomState(47)\n\n\nclass RandomFlip:\n \"\"\"\n Randomly flips the image across the given axes. Image can be either 3D (DxHxW) or 4D (CxDxHxW).\n\n When creating make sure that the provided RandomStates are consistent between raw and labeled datasets,\n otherwise the models won't converge.\n \"\"\"\n\n def __init__(self, random_state, axis_prob=0.5, **kwargs):\n assert random_state is not None, 'RandomState cannot be None'\n self.random_state = random_state\n self.axes = (0, 1, 2)\n self.axis_prob = axis_prob\n\n def __call__(self, m):\n assert m.ndim in [3, 4], 'Supports only 3D (DxHxW) or 4D (CxDxHxW) images'\n\n for axis in self.axes:\n if self.random_state.uniform() > self.axis_prob:\n if m.ndim == 3:\n m = np.flip(m, axis)\n else:\n channels = [np.flip(m[c], axis) for c in range(m.shape[0])]\n m = np.stack(channels, axis=0)\n\n return m\n\n\nclass RandomRotate90:\n \"\"\"\n Rotate an array by 90 degrees around a randomly chosen plane. Image can be either 3D (DxHxW) or 4D (CxDxHxW).\n\n When creating make sure that the provided RandomStates are consistent between raw and labeled datasets,\n otherwise the models won't converge.\n\n IMPORTANT: assumes DHW axis order (that's why rotation is performed across (1,2) axis)\n \"\"\"\n\n def __init__(self, random_state, **kwargs):\n self.random_state = random_state\n # always rotate around z-axis\n self.axis = (1, 2)\n\n def __call__(self, m):\n assert m.ndim in [3, 4], 'Supports only 3D (DxHxW) or 4D (CxDxHxW) images'\n\n # pick number of rotations at random\n k = self.random_state.randint(0, 4)\n # rotate k times around a given plane\n if m.ndim == 3:\n m = np.rot90(m, k, self.axis)\n else:\n channels = [np.rot90(m[c], k, self.axis) for c in range(m.shape[0])]\n m = np.stack(channels, axis=0)\n\n return m\n\n\nclass RandomRotate:\n \"\"\"\n Rotate an array by a random degrees from taken from (-angle_spectrum, angle_spectrum) interval.\n Rotation axis is picked at random from the list of provided axes.\n \"\"\"\n\n def __init__(self, random_state, angle_spectrum=30, axes=None, mode='reflect', order=0, **kwargs):\n if axes is None:\n axes = [(1, 0), (2, 1), (2, 0)]\n else:\n assert isinstance(axes, list) and len(axes) > 0\n\n self.random_state = random_state\n self.angle_spectrum = angle_spectrum\n self.axes = axes\n self.mode = mode\n self.order = order\n\n def __call__(self, m):\n axis = self.axes[self.random_state.randint(len(self.axes))]\n angle = self.random_state.randint(-self.angle_spectrum, self.angle_spectrum)\n\n if m.ndim == 3:\n m = rotate(m, angle, axes=axis, reshape=False, order=self.order, mode=self.mode, cval=-1)\n else:\n channels = [rotate(m[c], angle, axes=axis, reshape=False, order=self.order, mode=self.mode, cval=-1) for c\n in range(m.shape[0])]\n m = np.stack(channels, axis=0)\n\n return m\n\n\nclass RandomContrast:\n \"\"\"\n Adjust contrast by scaling each voxel to `mean + alpha * (v - mean)`.\n \"\"\"\n\n def __init__(self, random_state, alpha=(0.5, 1.5), mean=0.0, execution_probability=0.1, **kwargs):\n self.random_state = random_state\n assert len(alpha) == 2\n self.alpha = alpha\n self.mean = mean\n self.execution_probability = execution_probability\n\n def __call__(self, m):\n if self.random_state.uniform() < self.execution_probability:\n alpha = self.random_state.uniform(self.alpha[0], self.alpha[1])\n result = self.mean + alpha * (m - self.mean)\n return np.clip(result, -1, 1)\n\n return m\n\n\n# it's relatively slow, i.e. ~1s per patch of size 64x200x200, so use multiple workers in the DataLoader\n# remember to use spline_order=0 when transforming the labels\nclass ElasticDeformation:\n \"\"\"\n Apply elasitc deformations of 3D patches on a per-voxel mesh. Assumes ZYX axis order (or CZYX if the data is 4D).\n Based on: https://github.com/fcalvet/image_tools/blob/master/image_augmentation.py#L62\n \"\"\"\n\n def __init__(self, random_state, spline_order, alpha=2000, sigma=50, execution_probability=0.1, apply_3d=True,\n **kwargs):\n \"\"\"\n :param spline_order: the order of spline interpolation (use 0 for labeled images)\n :param alpha: scaling factor for deformations\n :param sigma: smoothing factor for Gaussian filter\n :param execution_probability: probability of executing this transform\n :param apply_3d: if True apply deformations in each axis\n \"\"\"\n self.random_state = random_state\n self.spline_order = spline_order\n self.alpha = alpha\n self.sigma = sigma\n self.execution_probability = execution_probability\n self.apply_3d = apply_3d\n\n def __call__(self, m):\n if self.random_state.uniform() < self.execution_probability:\n assert m.ndim in [3, 4]\n\n if m.ndim == 3:\n volume_shape = m.shape\n else:\n volume_shape = m[0].shape\n\n if self.apply_3d:\n dz = gaussian_filter(self.random_state.randn(*volume_shape), self.sigma, mode=\"reflect\") * self.alpha\n else:\n dz = np.zeros_like(m)\n\n dy, dx = [\n gaussian_filter(\n self.random_state.randn(*volume_shape),\n self.sigma, mode=\"reflect\"\n ) * self.alpha for _ in range(2)\n ]\n\n z_dim, y_dim, x_dim = volume_shape\n z, y, x = np.meshgrid(np.arange(z_dim), np.arange(y_dim), np.arange(x_dim), indexing='ij')\n indices = z + dz, y + dy, x + dx\n\n if m.ndim == 3:\n return map_coordinates(m, indices, order=self.spline_order, mode='reflect')\n else:\n channels = [map_coordinates(c, indices, order=self.spline_order, mode='reflect') for c in m]\n return np.stack(channels, axis=0)\n\n return m\n\n\ndef blur_boundary(boundary, sigma):\n boundary = gaussian(boundary, sigma=sigma)\n boundary[boundary >= 0.5] = 1\n boundary[boundary < 0.5] = 0\n return boundary\n\n\nclass CropToFixed:\n def __init__(self, random_state, size=(256, 256), centered=False, **kwargs):\n self.random_state = random_state\n self.crop_y, self.crop_x = size\n self.centered = centered\n\n def __call__(self, m):\n def _padding(pad_total):\n half_total = pad_total // 2\n return (half_total, pad_total - half_total)\n\n def _rand_range_and_pad(crop_size, max_size):\n \"\"\"\n Returns a tuple:\n max_value (int) for the corner dimension. The corner dimension is chosen as `self.random_state(max_value)`\n pad (int): padding in both directions; if crop_size is lt max_size the pad is 0\n \"\"\"\n if crop_size < max_size:\n return max_size - crop_size, (0, 0)\n else:\n return 1, _padding(crop_size - max_size)\n\n def _start_and_pad(crop_size, max_size):\n if crop_size < max_size:\n return (max_size - crop_size) // 2, (0, 0)\n else:\n return 0, _padding(crop_size - max_size)\n\n _, y, x = m.shape\n\n if not self.centered:\n y_range, y_pad = _rand_range_and_pad(self.crop_y, y)\n x_range, x_pad = _rand_range_and_pad(self.crop_x, x)\n\n y_start = self.random_state.randint(y_range)\n x_start = self.random_state.randint(x_range)\n\n else:\n y_start, y_pad = _start_and_pad(self.crop_y, y)\n x_start, x_pad = _start_and_pad(self.crop_x, x)\n\n result = m[:, y_start:y_start + self.crop_y, x_start:x_start + self.crop_x]\n return np.pad(result, pad_width=((0, 0), y_pad, x_pad), mode='reflect')\n\n\nclass AbstractLabelToBoundary:\n AXES_TRANSPOSE = [\n (0, 1, 2), # X\n (0, 2, 1), # Y\n (2, 0, 1) # Z\n ]\n\n def __init__(self, ignore_index=None, aggregate_affinities=False, append_label=False, **kwargs):\n \"\"\"\n :param ignore_index: label to be ignored in the output, i.e. after computing the boundary the label ignore_index\n will be restored where is was in the patch originally\n :param aggregate_affinities: aggregate affinities with the same offset across Z,Y,X axes\n :param append_label: if True append the orignal ground truth labels to the last channel\n :param blur: Gaussian blur the boundaries\n :param sigma: standard deviation for Gaussian kernel\n \"\"\"\n self.ignore_index = ignore_index\n self.aggregate_affinities = aggregate_affinities\n self.append_label = append_label\n\n def __call__(self, m):\n \"\"\"\n Extract boundaries from a given 3D label tensor.\n :param m: input 3D tensor\n :return: binary mask, with 1-label corresponding to the boundary and 0-label corresponding to the background\n \"\"\"\n assert m.ndim == 3\n\n kernels = self.get_kernels()\n boundary_arr = [np.where(np.abs(convolve(m, kernel)) > 0, 1, 0) for kernel in kernels]\n channels = np.stack(boundary_arr)\n results = []\n if self.aggregate_affinities:\n assert len(kernels) % 3 == 0, \"Number of kernels must be divided by 3 (one kernel per offset per Z,Y,X axes\"\n # aggregate affinities with the same offset\n for i in range(0, len(kernels), 3):\n # merge across X,Y,Z axes (logical OR)\n xyz_aggregated_affinities = np.logical_or.reduce(channels[i:i + 3, ...]).astype(np.int)\n # recover ignore index\n xyz_aggregated_affinities = _recover_ignore_index(xyz_aggregated_affinities, m, self.ignore_index)\n results.append(xyz_aggregated_affinities)\n else:\n results = [_recover_ignore_index(channels[i], m, self.ignore_index) for i in range(channels.shape[0])]\n\n if self.append_label:\n # append original input data\n results.append(m)\n\n # stack across channel dim\n return np.stack(results, axis=0)\n\n @staticmethod\n def create_kernel(axis, offset):\n # create conv kernel\n k_size = offset + 1\n k = np.zeros((1, 1, k_size), dtype=np.int)\n k[0, 0, 0] = 1\n k[0, 0, offset] = -1\n return np.transpose(k, axis)\n\n def get_kernels(self):\n raise NotImplementedError\n\n\nclass StandardLabelToBoundary:\n def __init__(self, ignore_index=None, append_label=False, blur=False, sigma=1, mode='thick', blobs=False, **kwargs):\n self.ignore_index = ignore_index\n self.append_label = append_label\n self.blur = blur\n self.sigma = sigma\n self.mode = mode\n self.blobs = blobs\n\n def __call__(self, m):\n assert m.ndim == 3\n\n boundaries = find_boundaries(m, connectivity=2, mode=self.mode)\n if self.blur:\n boundaries = blur_boundary(boundaries, self.sigma)\n\n results = []\n if self.blobs:\n blobs = (m > 0).astype('uint8')\n results.append(_recover_ignore_index(blobs, m, self.ignore_index))\n\n results.append(_recover_ignore_index(boundaries, m, self.ignore_index))\n\n if self.append_label:\n # append original input data\n results.append(m)\n\n return np.stack(results, axis=0)\n\n\nclass BlobsWithBoundary:\n def __init__(self, mode=None, append_label=False, blur=False, sigma=1, **kwargs):\n if mode is None:\n mode = ['thick', 'inner', 'outer']\n self.mode = mode\n self.append_label = append_label\n self.blur = blur\n self.sigma = sigma\n\n def __call__(self, m):\n assert m.ndim == 3\n\n # get the segmentation mask\n results = [(m > 0).astype('uint8')]\n\n for bm in self.mode:\n boundary = find_boundaries(m, connectivity=2, mode=bm)\n if self.blur:\n boundary = blur_boundary(boundary, self.sigma)\n results.append(boundary)\n\n if self.append_label:\n results.append(m)\n\n return np.stack(results, axis=0)\n\n\nclass BlobsToMask:\n \"\"\"\n Returns binary mask from labeled image, i.e. every label greater than 0 is treated as foreground.\n\n \"\"\"\n\n def __init__(self, append_label=False, boundary=False, cross_entropy=False, **kwargs):\n self.cross_entropy = cross_entropy\n self.boundary = boundary\n self.append_label = append_label\n\n def __call__(self, m):\n assert m.ndim == 3\n\n # get the segmentation mask\n mask = (m > 0).astype('uint8')\n results = [mask]\n\n if self.boundary:\n outer = find_boundaries(m, connectivity=2, mode='outer')\n if self.cross_entropy:\n # boundary is class 2\n mask[outer > 0] = 2\n results = [mask]\n else:\n results.append(outer)\n\n if self.append_label:\n results.append(m)\n\n return np.stack(results, axis=0)\n\n\nclass RandomLabelToAffinities(AbstractLabelToBoundary):\n \"\"\"\n Converts a given volumetric label array to binary mask corresponding to borders between labels.\n One specify the max_offset (thickness) of the border. Then the offset is picked at random every time you call\n the transformer (offset is picked form the range 1:max_offset) for each axis and the boundary computed.\n One may use this scheme in order to make the network more robust against various thickness of borders in the ground\n truth (think of it as a boundary denoising scheme).\n \"\"\"\n\n def __init__(self, random_state, max_offset=10, ignore_index=None, append_label=False, z_offset_scale=2, **kwargs):\n super().__init__(ignore_index=ignore_index, append_label=append_label, aggregate_affinities=False)\n self.random_state = random_state\n self.offsets = tuple(range(1, max_offset + 1))\n self.z_offset_scale = z_offset_scale\n\n def get_kernels(self):\n rand_offset = self.random_state.choice(self.offsets)\n axis_ind = self.random_state.randint(3)\n # scale down z-affinities due to anisotropy\n if axis_ind == 2:\n rand_offset = max(1, rand_offset // self.z_offset_scale)\n\n rand_axis = self.AXES_TRANSPOSE[axis_ind]\n # return a single kernel\n return [self.create_kernel(rand_axis, rand_offset)]\n\n\nclass LabelToAffinities(AbstractLabelToBoundary):\n \"\"\"\n Converts a given volumetric label array to binary mask corresponding to borders between labels (which can be seen\n as an affinity graph: https://arxiv.org/pdf/1706.00120.pdf)\n One specify the offsets (thickness) of the border. The boundary will be computed via the convolution operator.\n \"\"\"\n\n def __init__(self, offsets, ignore_index=None, append_label=False, aggregate_affinities=False, z_offsets=None,\n **kwargs):\n super().__init__(ignore_index=ignore_index, append_label=append_label,\n aggregate_affinities=aggregate_affinities)\n\n assert isinstance(offsets, list) or isinstance(offsets, tuple), 'offsets must be a list or a tuple'\n assert all(a > 0 for a in offsets), \"'offsets must be positive\"\n assert len(set(offsets)) == len(offsets), \"'offsets' must be unique\"\n if z_offsets is not None:\n assert len(offsets) == len(z_offsets), 'z_offsets length must be the same as the length of offsets'\n else:\n # if z_offsets is None just use the offsets for z-affinities\n z_offsets = list(offsets)\n self.z_offsets = z_offsets\n\n self.kernels = []\n # create kernel for every axis-offset pair\n for xy_offset, z_offset in zip(offsets, z_offsets):\n for axis_ind, axis in enumerate(self.AXES_TRANSPOSE):\n final_offset = xy_offset\n if axis_ind == 2:\n final_offset = z_offset\n # create kernels for a given offset in every direction\n self.kernels.append(self.create_kernel(axis, final_offset))\n\n def get_kernels(self):\n return self.kernels\n\n\nclass LabelToZAffinities(AbstractLabelToBoundary):\n \"\"\"\n Converts a given volumetric label array to binary mask corresponding to borders between labels (which can be seen\n as an affinity graph: https://arxiv.org/pdf/1706.00120.pdf)\n One specify the offsets (thickness) of the border. The boundary will be computed via the convolution operator.\n \"\"\"\n\n def __init__(self, offsets, ignore_index=None, append_label=False, **kwargs):\n super().__init__(ignore_index=ignore_index, append_label=append_label)\n\n assert isinstance(offsets, list) or isinstance(offsets, tuple), 'offsets must be a list or a tuple'\n assert all(a > 0 for a in offsets), \"'offsets must be positive\"\n assert len(set(offsets)) == len(offsets), \"'offsets' must be unique\"\n\n self.kernels = []\n z_axis = self.AXES_TRANSPOSE[2]\n # create kernels\n for z_offset in offsets:\n self.kernels.append(self.create_kernel(z_axis, z_offset))\n\n def get_kernels(self):\n return self.kernels\n\n\nclass LabelToBoundaryAndAffinities:\n \"\"\"\n Combines the StandardLabelToBoundary and LabelToAffinities in the hope\n that that training the network to predict both would improve the main task: boundary prediction.\n \"\"\"\n\n def __init__(self, xy_offsets, z_offsets, append_label=False, blur=False, sigma=1, ignore_index=None, mode='thick',\n blobs=False, **kwargs):\n # blur only StandardLabelToBoundary results; we don't want to blur the affinities\n self.l2b = StandardLabelToBoundary(blur=blur, sigma=sigma, ignore_index=ignore_index, mode=mode, blobs=blobs)\n self.l2a = LabelToAffinities(offsets=xy_offsets, z_offsets=z_offsets, append_label=append_label,\n ignore_index=ignore_index)\n\n def __call__(self, m):\n boundary = self.l2b(m)\n affinities = self.l2a(m)\n return np.concatenate((boundary, affinities), axis=0)\n\n\nclass FlyWingBoundary:\n \"\"\"\n Use if the volume contains a single pixel boundaries between labels. Gives the single pixel boundary in the 1st\n channel and the 'thick' boundary in the 2nd channel and optional z-affinities\n \"\"\"\n\n def __init__(self, append_label=False, thick_boundary=True, ignore_index=None, z_offsets=None, **kwargs):\n self.append_label = append_label\n self.thick_boundary = thick_boundary\n self.ignore_index = ignore_index\n self.lta = None\n if z_offsets is not None:\n self.lta = LabelToZAffinities(z_offsets, ignore_index=ignore_index)\n\n def __call__(self, m):\n boundary = (m == 0).astype('uint8')\n results = [boundary]\n\n if self.thick_boundary:\n t_boundary = find_boundaries(m, connectivity=1, mode='outer', background=0)\n results.append(t_boundary)\n\n if self.lta is not None:\n z_affs = self.lta(m)\n for z_aff in z_affs:\n results.append(z_aff)\n\n if self.ignore_index is not None:\n for b in results:\n b[m == self.ignore_index] = self.ignore_index\n\n if self.append_label:\n # append original input data\n results.append(m)\n\n return np.stack(results, axis=0)\n\n\nclass LabelToMaskAndAffinities:\n def __init__(self, xy_offsets, z_offsets, append_label=False, background=0, ignore_index=None, **kwargs):\n self.background = background\n self.l2a = LabelToAffinities(offsets=xy_offsets, z_offsets=z_offsets, append_label=append_label,\n ignore_index=ignore_index)\n\n def __call__(self, m):\n mask = m > self.background\n mask = np.expand_dims(mask.astype(np.uint8), axis=0)\n affinities = self.l2a(m)\n return np.concatenate((mask, affinities), axis=0)\n\n\nclass Standardize:\n \"\"\"\n Apply Z-score normalization to a given input tensor, i.e. re-scaling the values to be 0-mean and 1-std.\n Mean and std parameter have to be provided explicitly.\n \"\"\"\n\n def __init__(self, mean, std, eps=1e-6, **kwargs):\n self.mean = mean\n self.std = std\n self.eps = eps\n\n def __call__(self, m):\n return (m - self.mean) / np.clip(self.std, a_min=self.eps, a_max=None)\n\n\nclass Normalize:\n \"\"\"\n Apply simple min-max scaling to a given input tensor, i.e. shrinks the range of the data in a fixed range of [-1, 1].\n \"\"\"\n\n def __init__(self, min_value, max_value, **kwargs):\n assert max_value > min_value\n self.min_value = min_value\n self.value_range = max_value - min_value\n\n def __call__(self, m):\n norm_0_1 = (m - self.min_value) / self.value_range\n return np.clip(2 * norm_0_1 - 1, -1, 1)\n\n\nclass AdditiveGaussianNoise:\n def __init__(self, random_state, scale=(0.0, 1.0), execution_probability=0.1, **kwargs):\n self.execution_probability = execution_probability\n self.random_state = random_state\n self.scale = scale\n\n def __call__(self, m):\n if self.random_state.uniform() < self.execution_probability:\n std = self.random_state.uniform(self.scale[0], self.scale[1])\n gaussian_noise = self.random_state.normal(0, std, size=m.shape)\n return m + gaussian_noise\n return m\n\n\nclass AdditivePoissonNoise:\n def __init__(self, random_state, lam=(0.0, 1.0), execution_probability=0.1, **kwargs):\n self.execution_probability = execution_probability\n self.random_state = random_state\n self.lam = lam\n\n def __call__(self, m):\n if self.random_state.uniform() < self.execution_probability:\n lam = self.random_state.uniform(self.lam[0], self.lam[1])\n poisson_noise = self.random_state.poisson(lam, size=m.shape)\n return m + poisson_noise\n return m\n\n\nclass ToTensor:\n \"\"\"\n Converts a given input numpy.ndarray into torch.Tensor. Adds additional 'channel' axis when the input is 3D\n and expand_dims=True (use for raw data of the shape (D, H, W)).\n \"\"\"\n\n def __init__(self, expand_dims, dtype=np.float32, **kwargs):\n self.expand_dims = expand_dims\n self.dtype = dtype\n\n def __call__(self, m):\n assert m.ndim in [3, 4], 'Supports only 3D (DxHxW) or 4D (CxDxHxW) images'\n # add channel dimension\n if self.expand_dims and m.ndim == 3:\n m = np.expand_dims(m, axis=0)\n\n return torch.from_numpy(m.astype(dtype=self.dtype))\n\n\nclass Relabel:\n \"\"\"\n Relabel a numpy array of labels into a consecutive numbers, e.g.\n [10,10, 0, 6, 6] -> [2, 2, 0, 1, 1]. Useful when one has an instance segmentation volume\n at hand and would like to create a one-hot-encoding for it. Without a consecutive labeling the task would be harder.\n \"\"\"\n\n def __init__(self, **kwargs):\n pass\n\n def __call__(self, m):\n _, unique_labels = np.unique(m, return_inverse=True)\n m = unique_labels.reshape(m.shape)\n return m\n\n\nclass Identity:\n def __init__(self, **kwargs):\n pass\n\n def __call__(self, m):\n return m\n\n\ndef get_transformer(config, min_value, max_value, mean, std):\n base_config = {'min_value': min_value, 'max_value': max_value, 'mean': mean, 'std': std}\n return Transformer(config, base_config)\n\n\nclass Transformer:\n def __init__(self, phase_config, base_config):\n self.phase_config = phase_config\n self.config_base = base_config\n self.seed = GLOBAL_RANDOM_STATE.randint(10000000)\n\n def raw_transform(self):\n return self._create_transform('raw')\n\n def label_transform(self):\n return self._create_transform('label')\n\n def weight_transform(self):\n return self._create_transform('weight')\n\n @staticmethod\n def _transformer_class(class_name):\n m = importlib.import_module('pytorch3dunet.augment.transforms')\n clazz = getattr(m, class_name)\n return clazz\n\n def _create_transform(self, name):\n assert name in self.phase_config, f'Could not find {name} transform'\n return Compose([\n self._create_augmentation(c) for c in self.phase_config[name]\n ])\n\n def _create_augmentation(self, c):\n config = dict(self.config_base)\n config.update(c)\n config['random_state'] = np.random.RandomState(self.seed)\n aug_class = self._transformer_class(config['name'])\n return aug_class(**config)\n\n\ndef _recover_ignore_index(input, orig, ignore_index):\n if ignore_index is not None:\n mask = orig == ignore_index\n input[mask] = ignore_index\n\n return input\n" ]
[ [ "numpy.rot90", "numpy.expand_dims", "numpy.pad", "numpy.clip", "numpy.unique", "numpy.arange", "numpy.stack", "scipy.ndimage.rotate", "numpy.concatenate", "numpy.logical_or.reduce", "numpy.zeros_like", "scipy.ndimage.map_coordinates", "numpy.flip", "numpy.transpose", "scipy.ndimage.filters.convolve", "numpy.random.RandomState", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "0.15", "1.4", "0.10", "1.3", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16" ], "tensorflow": [] } ]
krevas/ET-BERT
[ "464ce3e7942d4450f55021e267ceb9dd48a36b1f" ]
[ "uer/layers/layer_norm.py" ]
[ "import torch\nimport torch.nn as nn\n\n\nclass LayerNorm(nn.Module):\n \"\"\"\n Layer Normalization.\n https://arxiv.org/abs/1607.06450\n \"\"\"\n def __init__(self, hidden_size, eps=1e-6):\n super(LayerNorm, self).__init__()\n self.eps = eps\n self.gamma = nn.Parameter(torch.ones(hidden_size))\n self.beta = nn.Parameter(torch.zeros(hidden_size))\n\n def forward(self, x):\n mean = x.mean(-1, keepdim=True)\n std = x.std(-1, keepdim=True)\n hidden_states = self.gamma * (x-mean) / (std + self.eps)\n\n return hidden_states + self.beta\n\n\nclass T5LayerNorm(nn.Module):\n \"\"\"\n Construct a layernorm module in the T5 style No bias and no subtraction of mean.\n \"\"\"\n def __init__(self, hidden_size, eps=1e-6):\n\n super().__init__()\n self.weight = nn.Parameter(torch.ones(hidden_size))\n self.variance_epsilon = eps\n\n def forward(self, hidden_states):\n # layer norm should always be calculated in float32\n variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)\n hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)\n\n return self.weight * hidden_states.type_as(self.weight)\n" ]
[ [ "torch.rsqrt", "torch.ones", "torch.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
xupsh/pp4fpgas-cn-hls
[ "d14bd0769ce7f9674f206faf93b7622c5bf905bf" ]
[ "hw/ip/mono_fm/transform.py" ]
[ "import numpy as np\ndetection_file = 'samples.npy'\ndetections = None\nif detection_file is not None:\n detections = np.load(detection_file)\nnp.savetxt('samples.txt', detections, fmt='%0.18f')\n\nf = open('samples.txt')\nout = open('complex.txt', \"w\")\nlines = f.readlines()\nfor line in lines:\n for i in line:\n if i == \"+\":\n out.write(\" \")\n elif i == \"-\":\n out.write(\" -\")\n elif i == \"(\":\n i = i\n elif i == \")\":\n i = i\n elif i == \"j\":\n i = i\n else:\n out.write(str(i))\n #out.write(\"\\n\")\n\n #print(line)\n\nf.close\n" ]
[ [ "numpy.savetxt", "numpy.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Emieeel/OpenFermion
[ "865d8591cad9b0681f6dd25a391a5292ed2de1d4", "865d8591cad9b0681f6dd25a391a5292ed2de1d4", "c19d9667c5970473893f9bc0183556c4cd354dd7", "865d8591cad9b0681f6dd25a391a5292ed2de1d4", "865d8591cad9b0681f6dd25a391a5292ed2de1d4" ]
[ "src/openfermion/utils/rdm_mapping_functions_test.py", "src/openfermion/circuits/trotter_exp_to_qgates.py", "src/openfermion/measurements/vpe_estimators_test.py", "src/openfermion/testing/testing_utils.py", "src/openfermion/ops/operators/binary_code.py" ]
[ "# 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\"\"\"Tests for rdm_mapping_functions.py\"\"\"\nimport os\nimport unittest\n\nimport numpy\nimport h5py\nfrom openfermion.config import DATA_DIRECTORY, THIS_DIRECTORY\nfrom openfermion.chem import MolecularData\nfrom openfermion.utils.rdm_mapping_functions import (\n kronecker_delta, map_two_pdm_to_two_hole_dm, map_two_pdm_to_one_pdm,\n map_one_pdm_to_one_hole_dm, map_one_hole_dm_to_one_pdm,\n map_two_pdm_to_particle_hole_dm, map_two_hole_dm_to_two_pdm,\n map_two_hole_dm_to_one_hole_dm, map_particle_hole_dm_to_one_pdm,\n map_particle_hole_dm_to_two_pdm)\n\n\nclass RDMMappingTest(unittest.TestCase):\n\n def setUp(self):\n # load files and marginals from testing folder\n tqdm_h2_sto3g = os.path.join(THIS_DIRECTORY,\n 'testing/tqdm_H2_sto-3g_singlet_1.4.hdf5')\n with h5py.File(tqdm_h2_sto3g, 'r') as fid:\n self.tqdm_h2_sto3g = fid['tqdm'][...]\n\n phdm_h2_sto3g = os.path.join(THIS_DIRECTORY,\n 'testing/phdm_H2_sto-3g_singlet_1.4.hdf5')\n with h5py.File(phdm_h2_sto3g, 'r') as fid:\n self.phdm_h2_sto3g = fid['phdm'][...]\n\n tqdm_h2_6_31g = os.path.join(THIS_DIRECTORY,\n 'testing/tqdm_H2_6-31g_singlet_0.75.hdf5')\n with h5py.File(tqdm_h2_6_31g, 'r') as fid:\n self.tqdm_h2_6_31g = fid['tqdm'][...]\n\n phdm_h2_6_31g = os.path.join(THIS_DIRECTORY,\n 'testing/phdm_H2_6-31g_singlet_0.75.hdf5')\n with h5py.File(phdm_h2_6_31g, 'r') as fid:\n self.phdm_h2_6_31g = fid['phdm'][...]\n\n tqdm_lih_sto3g = os.path.join(\n THIS_DIRECTORY, 'testing/tqdm_H1-Li1_sto-3g_singlet_1.45.hdf5')\n with h5py.File(tqdm_lih_sto3g, 'r') as fid:\n self.tqdm_lih_sto3g = fid['tqdm'][...]\n\n phdm_lih_sto3g = os.path.join(\n THIS_DIRECTORY, 'testing/phdm_H1-Li1_sto-3g_singlet_1.45.hdf5')\n with h5py.File(phdm_lih_sto3g, 'r') as fid:\n self.phdm_lih_sto3g = fid['phdm'][...]\n\n def test_kronecker_delta_00(self):\n assert kronecker_delta(0, 0) == 1\n\n def test_kronecker_delta_01(self):\n assert kronecker_delta(0, 1) == 0\n\n def test_kronecker_delta_10(self):\n assert kronecker_delta(1, 0) == 0\n\n def test_kronecker_delta_11(self):\n assert kronecker_delta(1, 1) == 1\n\n def test_kronecker_delta_nonunit_args(self):\n assert kronecker_delta(3, 3) == 1\n\n def test_tpdm_to_opdm(self):\n # for all files in datadirectory check if this map holds\n for file in filter(lambda x: x.endswith(\".hdf5\"),\n os.listdir(DATA_DIRECTORY)):\n molecule = MolecularData(\n filename=os.path.join(DATA_DIRECTORY, file))\n if (molecule.fci_one_rdm is not None and\n molecule.fci_two_rdm is not None):\n test_opdm = map_two_pdm_to_one_pdm(molecule.fci_two_rdm,\n molecule.n_electrons)\n assert numpy.allclose(test_opdm, molecule.fci_one_rdm)\n\n def test_opdm_to_oqdm(self):\n for file in filter(lambda x: x.endswith(\".hdf5\"),\n os.listdir(DATA_DIRECTORY)):\n molecule = MolecularData(\n filename=os.path.join(DATA_DIRECTORY, file))\n if molecule.fci_one_rdm is not None:\n test_oqdm = map_one_pdm_to_one_hole_dm(molecule.fci_one_rdm)\n true_oqdm = numpy.eye(molecule.n_qubits) - molecule.fci_one_rdm\n assert numpy.allclose(test_oqdm, true_oqdm)\n\n def test_oqdm_to_opdm(self):\n for file in filter(lambda x: x.endswith(\".hdf5\"),\n os.listdir(DATA_DIRECTORY)):\n molecule = MolecularData(\n filename=os.path.join(DATA_DIRECTORY, file))\n if molecule.fci_one_rdm is not None:\n true_oqdm = numpy.eye(molecule.n_qubits) - molecule.fci_one_rdm\n test_opdm = map_one_hole_dm_to_one_pdm(true_oqdm)\n assert numpy.allclose(test_opdm, molecule.fci_one_rdm)\n\n def test_tqdm_conversions_h2_631g(self):\n # construct the 2-hole-RDM for LiH the slow way\n # TODO: speed up this calculation by directly contracting from the wf.\n filename = \"H2_6-31g_singlet_0.75.hdf5\"\n molecule = MolecularData(\n filename=os.path.join(DATA_DIRECTORY, filename))\n true_tqdm = self.tqdm_h2_6_31g\n\n test_tqdm = map_two_pdm_to_two_hole_dm(molecule.fci_two_rdm,\n molecule.fci_one_rdm)\n assert numpy.allclose(true_tqdm, test_tqdm)\n\n true_oqdm = numpy.eye(molecule.n_qubits) - molecule.fci_one_rdm\n test_oqdm = map_two_hole_dm_to_one_hole_dm(\n true_tqdm, molecule.n_qubits - molecule.n_electrons)\n assert numpy.allclose(true_oqdm, test_oqdm)\n\n test_tpdm = map_two_hole_dm_to_two_pdm(true_tqdm, molecule.fci_one_rdm)\n assert numpy.allclose(test_tpdm, molecule.fci_two_rdm)\n\n def test_tqdm_conversions_h2_sto3g(self):\n filename = \"H2_sto-3g_singlet_1.4.hdf5\"\n molecule = MolecularData(\n filename=os.path.join(DATA_DIRECTORY, filename))\n true_tqdm = self.tqdm_h2_sto3g\n\n test_tqdm = map_two_pdm_to_two_hole_dm(molecule.fci_two_rdm,\n molecule.fci_one_rdm)\n assert numpy.allclose(true_tqdm, test_tqdm)\n\n true_oqdm = numpy.eye(molecule.n_qubits) - molecule.fci_one_rdm\n test_oqdm = map_two_hole_dm_to_one_hole_dm(\n true_tqdm, molecule.n_qubits - molecule.n_electrons)\n assert numpy.allclose(true_oqdm, test_oqdm)\n\n test_tpdm = map_two_hole_dm_to_two_pdm(true_tqdm, molecule.fci_one_rdm)\n assert numpy.allclose(test_tpdm, molecule.fci_two_rdm)\n\n def test_tqdm_conversions_lih_sto3g(self):\n filename = \"H1-Li1_sto-3g_singlet_1.45.hdf5\"\n molecule = MolecularData(\n filename=os.path.join(DATA_DIRECTORY, filename))\n true_tqdm = self.tqdm_lih_sto3g\n\n test_tqdm = map_two_pdm_to_two_hole_dm(molecule.fci_two_rdm,\n molecule.fci_one_rdm)\n assert numpy.allclose(true_tqdm, test_tqdm)\n\n true_oqdm = numpy.eye(molecule.n_qubits) - molecule.fci_one_rdm\n test_oqdm = map_two_hole_dm_to_one_hole_dm(\n true_tqdm, molecule.n_qubits - molecule.n_electrons)\n assert numpy.allclose(true_oqdm, test_oqdm)\n\n test_tpdm = map_two_hole_dm_to_two_pdm(true_tqdm, molecule.fci_one_rdm)\n assert numpy.allclose(test_tpdm, molecule.fci_two_rdm)\n\n def test_phdm_conversions_h2_631g(self):\n filename = \"H2_6-31g_singlet_0.75.hdf5\"\n molecule = MolecularData(\n filename=os.path.join(DATA_DIRECTORY, filename))\n true_phdm = self.phdm_h2_6_31g\n\n test_phdm = map_two_pdm_to_particle_hole_dm(molecule.fci_two_rdm,\n molecule.fci_one_rdm)\n assert numpy.allclose(test_phdm, true_phdm)\n\n test_opdm = map_particle_hole_dm_to_one_pdm(true_phdm,\n molecule.n_electrons,\n molecule.n_qubits)\n assert numpy.allclose(test_opdm, molecule.fci_one_rdm)\n\n test_tpdm = map_particle_hole_dm_to_two_pdm(true_phdm,\n molecule.fci_one_rdm)\n assert numpy.allclose(test_tpdm, molecule.fci_two_rdm)\n\n def test_phdm_conversions_h2_sto3g(self):\n filename = \"H2_sto-3g_singlet_1.4.hdf5\"\n molecule = MolecularData(\n filename=os.path.join(DATA_DIRECTORY, filename))\n true_phdm = self.phdm_h2_sto3g\n\n test_phdm = map_two_pdm_to_particle_hole_dm(molecule.fci_two_rdm,\n molecule.fci_one_rdm)\n assert numpy.allclose(test_phdm, true_phdm)\n\n test_opdm = map_particle_hole_dm_to_one_pdm(true_phdm,\n molecule.n_electrons,\n molecule.n_qubits)\n assert numpy.allclose(test_opdm, molecule.fci_one_rdm)\n\n test_tpdm = map_particle_hole_dm_to_two_pdm(true_phdm,\n molecule.fci_one_rdm)\n assert numpy.allclose(test_tpdm, molecule.fci_two_rdm)\n\n def test_phdm_conversions_lih_sto3g(self):\n filename = \"H1-Li1_sto-3g_singlet_1.45.hdf5\"\n molecule = MolecularData(\n filename=os.path.join(DATA_DIRECTORY, filename))\n true_phdm = self.phdm_lih_sto3g\n\n test_phdm = map_two_pdm_to_particle_hole_dm(molecule.fci_two_rdm,\n molecule.fci_one_rdm)\n assert numpy.allclose(test_phdm, true_phdm)\n\n test_opdm = map_particle_hole_dm_to_one_pdm(true_phdm,\n molecule.n_electrons,\n molecule.n_qubits)\n assert numpy.allclose(test_opdm, molecule.fci_one_rdm)\n\n test_tpdm = map_particle_hole_dm_to_two_pdm(true_phdm,\n molecule.fci_one_rdm)\n assert numpy.allclose(test_tpdm, molecule.fci_two_rdm)\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\"\"\"Module to perform Trotter-Suzuki decompositions to output as circuits.\"\"\"\n\nimport collections\nimport copy\nimport numpy\nfrom openfermion.ops.operators import QubitOperator\nimport openfermion.utils as utils\n\"\"\"\nDescription:\n Functions for estimating the exponential of an operator\n composed of Pauli matrices, by Trotterization. Outputs QASM\n format to a python stream.\n\n Change-of-basis gates:\n H : Z to X basis (and back)\n Rx(pi/2) : Z to Y basis .....\n Rx(-pi/2) : Y to Z basis .....\n\"\"\"\n\n\ndef _third_order_trotter_helper(op_list):\n \"\"\"Iteratively find 3rd-order Trotter ordering of a QubitOperator.\n\n This Trotter ordering is done according to the scheme:\n e^(A+B) = e^(7/24 * A) e^(2/3 * B) e^(3/4 * A) * e^(-2/3 * B)\n * e^(-1/24 * A) e^(B)\n\n Note:\n See N. Hatano and M. Suzuki Lect. Notes Phys 679, 37-68 (2005)\n\n Args:\n op_list (list of QubitOperator's): the terms in the\n hamiltonian as a list of QubitOperators\n Returns:\n list of QubitOperators giving the trotterized hamiltonian\n \"\"\"\n # Create list to hold return value\n ret_val = collections.deque([\n 7.0 / 24.0 * op_list[-2], 2.0 / 3.0 * op_list[-1],\n 3.0 / 4.0 * op_list[-2], -2.0 / 3.0 * op_list[-1],\n -1.0 / 24.0 * op_list[-2], 1.0 * op_list[-1]\n ])\n\n for i in reversed(range(len(op_list) - 2)):\n temp_ret_val = copy.deepcopy(ret_val)\n ret_val = collections.deque()\n ret_val.appendleft(7.0 / 24.0 * op_list[i])\n ret_val.extend([2.0 / 3.0 * qubop for qubop in temp_ret_val])\n ret_val.append(3.0 / 4.0 * op_list[i])\n ret_val.extend([-2.0 / 3.0 * qubop for qubop in temp_ret_val])\n ret_val.append(-1.0 / 24.0 * op_list[i])\n ret_val.extend([1.0 * qubop for qubop in temp_ret_val])\n return ret_val\n\n\ndef trotter_operator_grouping(hamiltonian,\n trotter_number=1,\n trotter_order=1,\n term_ordering=None,\n k_exp=1.0):\n \"\"\"Trotter-decomposes operators into groups without exponentiating.\n\n Operators are still Hermitian at the end of this method but have been\n multiplied by k_exp.\n\n Note:\n The default term_ordering is simply the ordered keys of\n the QubitOperators.terms dict.\n\n Args:\n hamiltonian (QubitOperator): full hamiltonian\n trotter_number (int): optional number of trotter steps -\n default is 1\n trotter_order (int): optional order of trotterization as\n an integer from 1-3 - default is 1\n term_ordering (list of (tuples of tuples)): optional list\n of QubitOperator terms dictionary keys that specifies\n order of terms when trotterizing\n k_exp (float): optional exponential factor\n to all terms when trotterizing\n\n Yields:\n QubitOperator generator\n\n Raises:\n ValueError if order > 3 or order <= 0,\n TypeError for incorrect types\n \"\"\"\n # Check for default arguments and type errors\n if (trotter_order > 3) or (trotter_order <= 0):\n raise ValueError(\"Invalid trotter order: \" + str(trotter_order))\n if not isinstance(hamiltonian, QubitOperator):\n raise TypeError(\"Hamiltonian must be a QubitOperator.\")\n if len(hamiltonian.terms) == 0:\n raise TypeError(\"Hamiltonian must be a non-empty QubitOperator.\")\n if term_ordering is None:\n # To have consistent default behavior, ordering = sorted keys.\n term_ordering = sorted(list(hamiltonian.terms.keys()))\n if len(term_ordering) == 0:\n raise TypeError(\"term_ordering must None or non-empty list.\")\n\n # Enforce float\n k_exp = float(k_exp)\n\n # First order trotter\n if trotter_order == 1:\n for _ in range(trotter_number):\n for op in term_ordering:\n yield QubitOperator(\n op, hamiltonian.terms[op] * k_exp / trotter_number)\n\n # Second order trotter\n elif trotter_order == 2:\n if len(term_ordering) < 2:\n raise ValueError(\"Not enough terms in the Hamiltonian to do \" +\n \"second order trotterization\")\n for _ in range(trotter_number):\n for op in term_ordering[:-1]:\n yield QubitOperator(\n op, hamiltonian.terms[op] * k_exp / (2.0 * trotter_number))\n\n yield QubitOperator(\n term_ordering[-1],\n hamiltonian.terms[term_ordering[-1]] * k_exp / trotter_number)\n\n for op in reversed(term_ordering[:-1]):\n yield QubitOperator(\n op, hamiltonian.terms[op] * k_exp / (2.0 * trotter_number))\n\n # Third order trotter\n elif trotter_order == 3:\n if len(term_ordering) < 2:\n raise ValueError(\"Not enough terms in the Hamiltonian to do \" +\n \"third order trotterization\")\n # Make sure original hamiltonian is not modified\n ham = hamiltonian * k_exp / float(trotter_number)\n ham_temp = []\n for term in term_ordering:\n ham_temp.append(QubitOperator(term, ham.terms[term]))\n for _ in range(trotter_number):\n for returned_op in _third_order_trotter_helper(ham_temp):\n yield returned_op\n\n\ndef pauli_exp_to_qasm(qubit_operator_list,\n evolution_time=1.0,\n qubit_list=None,\n ancilla=None):\n \"\"\"Exponentiate a list of QubitOperators to a QASM string generator.\n\n Exponentiates a list of QubitOperators, and yields string generators in\n QASM format using the formula: exp(-1.0j * evolution_time * op).\n\n Args:\n qubit_operator_list (list of QubitOperators): list of single Pauli-term\n QubitOperators to be exponentiated\n evolution_time (float): evolution time of the operators in\n the list\n qubit_list: (list/tuple or None)Specifies the labels for the qubits\n to be output in qasm.\n If a list/tuple, must have length greater than or equal to the\n number of qubits in the QubitOperator. Entries in the\n list must be castable to string.\n If None, qubits are labeled by index (i.e. an integer).\n ancilla (string or None): if any, an ancilla qubit to perform\n the rotation conditional on (for quantum phase estimation)\n\n Yields:\n string\n \"\"\"\n\n num_qubits = max([\n utils.count_qubits(qubit_operator)\n for qubit_operator in qubit_operator_list\n ])\n if qubit_list is None:\n qubit_list = list(range(num_qubits))\n else:\n if type(qubit_list) is not tuple and type(qubit_list) is not list:\n raise TypeError('qubit_list must be one of None, tuple, or list.')\n if len(qubit_list) < num_qubits:\n raise TypeError('qubit_list must have an entry for every qubit')\n\n for qubit_operator in qubit_operator_list:\n # ret_val = \"\"\n ret_list = []\n\n for term in qubit_operator.terms:\n\n term_coeff = qubit_operator.terms[term]\n\n # Force float\n term_coeff = float(numpy.real(term_coeff))\n\n # List of operators and list of qubit ids\n ops = []\n qids = []\n string_basis_1 = [] # Basis rotations 1\n string_basis_2 = [] # Basis rotations 2\n\n for p in term: # p = single pauli term\n qid = qubit_list[p[0]]\n pop = p[1] # Pauli op\n\n qids.append(qid) # Qubit index\n ops.append(pop) # Pauli operator\n\n if pop == 'X':\n string_basis_1.append(\"H {}\".format(qid)) # Hadamard\n string_basis_2.append(\"H {}\".format(qid)) # Hadamard\n elif pop == 'Y':\n string_basis_1.append(\n \"Rx 1.5707963267948966 {}\".format(qid))\n string_basis_2.append(\n \"Rx -1.5707963267948966 {}\".format(qid))\n\n # Prep for CNOTs\n cnot_pairs = numpy.vstack((qids[:-1], qids[1:]))\n cnots1 = []\n cnots2 = []\n for i in range(cnot_pairs.shape[1]):\n pair = cnot_pairs[:, i]\n cnots1.append(\"CNOT {} {}\".format(pair[0], pair[1]))\n for i in numpy.arange(cnot_pairs.shape[1])[::-1]:\n pair = cnot_pairs[:, i]\n cnots2.append(\"CNOT {} {}\".format(pair[0], pair[1]))\n\n # Exponentiating each Pauli string requires five parts\n\n # 1. Perform basis rotations\n ret_list = ret_list + string_basis_1\n\n # 2. First set CNOTs\n ret_list = ret_list + cnots1\n\n # 3. Rotation (Note kexp & Ntrot)\n if ancilla is not None:\n if len(qids) > 0:\n ret_list = ret_list + [\n \"C-Phase {} {} {}\".format(\n -2 * term_coeff * evolution_time, ancilla, qids[-1])\n ]\n ret_list = ret_list + [\n \"Rz {} {}\".format(1 * term_coeff * evolution_time,\n ancilla)\n ]\n else:\n ret_list = ret_list + [\n \"Rz {} {}\".format(1 * term_coeff * evolution_time,\n ancilla)\n ]\n else:\n if len(qids) > 0:\n ret_list = ret_list + [\n \"Rz {} {}\".format(term_coeff * evolution_time, qids[-1])\n ]\n\n # 4. Second set of CNOTs\n ret_list = ret_list + cnots2\n\n # 5. Rotate back to Z basis\n ret_list = ret_list + string_basis_2\n\n for gate in ret_list:\n yield gate\n\n\ndef trotterize_exp_qubop_to_qasm(hamiltonian,\n evolution_time=1,\n trotter_number=1,\n trotter_order=1,\n term_ordering=None,\n k_exp=1.0,\n qubit_list=None,\n ancilla=None):\n \"\"\"Trotterize a Qubit hamiltonian and write it to QASM format.\n\n Assumes input hamiltonian is still hermitian and -1.0j has not yet been\n applied. Therefore, signs of coefficients should reflect this. Returns\n a generator which generates a QASM file.\n\n Args:\n hamiltonian (QubitOperator): hamiltonian\n trotter_number (int): optional number of trotter steps (slices) for\n trotterization as an integer - default = 1\n trotter_order: optional order of trotterization as an integer -\n default = 1\n term_ordering (list of (tuples of tuples)): list of tuples\n (QubitOperator terms dictionary keys) that specifies\n order of terms when trotterizing\n qubit_list: (list/tuple or None)Specifies the labels for the qubits\n to be output in qasm.\n If a list/tuple, must have length greater than or equal to the\n number of qubits in the QubitOperator. Entries in the\n list must be castable to string.\n If None, qubits are labeled by index (i.e. an integer).\n k_exp (float): optional exponential factor to all\n terms when trotterizing\n\n Yields:\n string generator\n\n \"\"\"\n\n for trotterized_op in trotter_operator_grouping(hamiltonian, trotter_number,\n trotter_order,\n term_ordering, k_exp):\n for exponentiated_qasm_string in pauli_exp_to_qasm(\n [trotterized_op],\n evolution_time=evolution_time,\n qubit_list=qubit_list,\n ancilla=ancilla):\n yield exponentiated_qasm_string\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\"\"\"Tests for vpe_estimators.py\"\"\"\n\nimport pytest\nimport numpy\nimport pandas\nimport cirq\n\nfrom .vpe_estimators import (\n PhaseFitEstimator,\n get_phase_function,\n)\n\nrng = numpy.random.RandomState(seed=42)\n\n\ndef test_requests_simulation_at_pi_for_pauli():\n estimator = PhaseFitEstimator(evals=[-1, +1])\n sim_points = estimator.get_simulation_points()\n assert len(sim_points) == 2\n assert numpy.isclose(sim_points[0], 0)\n assert numpy.isclose(sim_points[1], numpy.pi / 2)\n\n\ndef test_estimates_expectation_value_pauli_nonoise():\n evals = numpy.array([-1, +1])\n true_amps = numpy.array([0.2, 0.8])\n true_expectation_value = numpy.dot(evals, true_amps)\n\n estimator = PhaseFitEstimator(evals)\n sim_points = estimator.get_simulation_points()\n phase_function = numpy.array([\n numpy.sum([\n amp * numpy.exp(1j * ev * time)\n for ev, amp in zip(evals, true_amps)\n ])\n for time in sim_points\n ])\n print(phase_function)\n test_expectation_value = estimator.get_expectation_value(phase_function)\n assert numpy.isclose(true_expectation_value, test_expectation_value)\n\n\ndef test_estimates_expectation_value_scattered_nonoise():\n evals = rng.uniform(-1, 1, 10)\n true_amps = rng.uniform(0, 1, 10)\n true_amps = true_amps / numpy.sum(true_amps)\n true_expectation_value = numpy.dot(evals, true_amps)\n\n estimator = PhaseFitEstimator(evals)\n sim_points = estimator.get_simulation_points()\n phase_function = numpy.array([\n numpy.sum([\n amp * numpy.exp(1j * ev * time)\n for ev, amp in zip(evals, true_amps)\n ])\n for time in sim_points\n ])\n test_expectation_value = estimator.get_expectation_value(phase_function)\n\n assert numpy.isclose(true_expectation_value, test_expectation_value)\n\n\ndef test_phase_function_gen_raises_error():\n results = [0, 0]\n qubits = [cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)]\n target_qid = 0\n with pytest.raises(ValueError):\n get_phase_function(results, qubits, target_qid)\n\n\ndef test_phase_function_gen():\n\n class FakeResult:\n\n def __init__(self, data):\n self.data = {'msmt': pandas.Series(data)}\n\n datasets = [[] for j in range(8)]\n for xindex in [2, 3, 6, 7]:\n datasets[xindex] = [0] * 50 + [2] * 50\n for z0index in [0, 4]:\n datasets[z0index] = [0] * 100\n for z1index in [1, 5]:\n datasets[z1index] = [2] * 100\n\n results = [FakeResult(dataset) for dataset in datasets]\n qubits = [cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)]\n target_qid = 0\n phase_function_est = get_phase_function(results, qubits, target_qid)\n assert phase_function_est == 1\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\"\"\"Functions useful for tests.\"\"\"\n\nimport collections\nimport itertools\n\nimport numpy\nfrom scipy.linalg import qr\n\nfrom openfermion.ops.operators import QubitOperator\nfrom openfermion.ops.representations import (DiagonalCoulombHamiltonian,\n QuadraticHamiltonian,\n InteractionOperator)\n\n\ndef haar_random_vector(n, seed=None):\n \"\"\"Generate an n dimensional Haar randomd vector.\"\"\"\n if seed is not None:\n numpy.random.seed(seed)\n vector = numpy.random.randn(n).astype(complex)\n vector += 1.j * numpy.random.randn(n).astype(complex)\n normalization = numpy.sqrt(vector.dot(numpy.conjugate(vector)))\n return vector / normalization\n\n\ndef random_antisymmetric_matrix(n, real=False, seed=None):\n \"\"\"Generate a random n x n antisymmetric matrix.\"\"\"\n if seed is not None:\n numpy.random.seed(seed)\n\n if real:\n rand_mat = numpy.random.randn(n, n)\n else:\n rand_mat = numpy.random.randn(n, n) + 1.j * numpy.random.randn(n, n)\n antisymmetric_mat = rand_mat - rand_mat.T\n return antisymmetric_mat\n\n\ndef random_hermitian_matrix(n, real=False, seed=None):\n \"\"\"Generate a random n x n Hermitian matrix.\"\"\"\n if seed is not None:\n numpy.random.seed(seed)\n\n if real:\n rand_mat = numpy.random.randn(n, n)\n else:\n rand_mat = numpy.random.randn(n, n) + 1.j * numpy.random.randn(n, n)\n hermitian_mat = rand_mat + rand_mat.T.conj()\n return hermitian_mat\n\n\ndef random_unitary_matrix(n, real=False, seed=None):\n \"\"\"Obtain a random n x n unitary matrix.\"\"\"\n if seed is not None:\n numpy.random.seed(seed)\n\n if real:\n rand_mat = numpy.random.randn(n, n)\n else:\n rand_mat = numpy.random.randn(n, n) + 1.j * numpy.random.randn(n, n)\n Q, _ = qr(rand_mat)\n return Q\n\n\ndef random_qubit_operator(n_qubits=16,\n max_num_terms=16,\n max_many_body_order=16,\n seed=None):\n prng = numpy.random.RandomState(seed)\n op = QubitOperator()\n num_terms = prng.randint(1, max_num_terms + 1)\n for _ in range(num_terms):\n many_body_order = prng.randint(max_many_body_order + 1)\n term = []\n for _ in range(many_body_order):\n index = prng.randint(n_qubits)\n action = prng.choice(('X', 'Y', 'Z'))\n term.append((index, action))\n coefficient = prng.randn()\n op += QubitOperator(term, coefficient)\n return op\n\n\ndef random_diagonal_coulomb_hamiltonian(n_qubits, real=False, seed=None):\n \"\"\"Generate a random instance of DiagonalCoulombHamiltonian.\n\n Args:\n n_qubits: The number of qubits\n real: Whether to use only real numbers in the one-body term\n \"\"\"\n if seed is not None:\n numpy.random.seed(seed)\n\n one_body = random_hermitian_matrix(n_qubits, real=real)\n two_body = random_hermitian_matrix(n_qubits, real=True)\n constant = numpy.random.randn()\n return DiagonalCoulombHamiltonian(one_body, two_body, constant)\n\n\ndef random_interaction_operator(n_orbitals,\n expand_spin=False,\n real=True,\n seed=None):\n \"\"\"Generate a random instance of InteractionOperator.\n\n Args:\n n_orbitals: The number of orbitals.\n expand_spin: Whether to expand each orbital symmetrically into two\n spin orbitals. Note that if this option is set to True, then\n the total number of orbitals will be doubled.\n real: Whether to use only real numbers.\n seed: A random number generator seed.\n \"\"\"\n if seed is not None:\n numpy.random.seed(seed)\n\n if real:\n dtype = float\n else:\n dtype = complex\n\n # The constant has to be real.\n constant = numpy.random.randn()\n\n # The one-body tensor is a random Hermitian matrix.\n one_body_coefficients = random_hermitian_matrix(n_orbitals, real)\n\n # Generate random two-body coefficients.\n two_body_coefficients = numpy.zeros(\n (n_orbitals, n_orbitals, n_orbitals, n_orbitals), dtype)\n for p, q, r, s in itertools.product(range(n_orbitals), repeat=4):\n coeff = numpy.random.randn()\n if not real and len(set([p, q, r, s])) >= 3:\n coeff += 1.j * numpy.random.randn()\n\n # Four point symmetry.\n two_body_coefficients[p, q, r, s] = coeff\n two_body_coefficients[q, p, s, r] = coeff\n two_body_coefficients[s, r, q, p] = coeff.conjugate()\n two_body_coefficients[r, s, p, q] = coeff.conjugate()\n\n # Eight point symmetry.\n if real:\n two_body_coefficients[r, q, p, s] = coeff\n two_body_coefficients[p, s, r, q] = coeff\n two_body_coefficients[s, p, q, r] = coeff\n two_body_coefficients[q, r, s, p] = coeff\n\n # If requested, expand to spin orbitals.\n if expand_spin:\n n_spin_orbitals = 2 * n_orbitals\n\n # Expand one-body tensor.\n one_body_coefficients = numpy.kron(one_body_coefficients, numpy.eye(2))\n\n # Expand two-body tensor.\n new_two_body_coefficients = numpy.zeros(\n (n_spin_orbitals, n_spin_orbitals, n_spin_orbitals,\n n_spin_orbitals),\n dtype=complex)\n for p, q, r, s in itertools.product(range(n_orbitals), repeat=4):\n coefficient = two_body_coefficients[p, q, r, s]\n\n # Mixed spin.\n new_two_body_coefficients[2 * p, 2 * q + 1, 2 * r + 1, 2 *\n s] = (coefficient)\n new_two_body_coefficients[2 * p + 1, 2 * q, 2 * r, 2 * s +\n 1] = (coefficient)\n\n # Same spin.\n new_two_body_coefficients[2 * p, 2 * q, 2 * r, 2 * s] = coefficient\n new_two_body_coefficients[2 * p + 1, 2 * q + 1, 2 * r + 1, 2 * s +\n 1] = coefficient\n two_body_coefficients = new_two_body_coefficients\n\n # Create the InteractionOperator.\n interaction_operator = InteractionOperator(constant, one_body_coefficients,\n two_body_coefficients)\n\n return interaction_operator\n\n\ndef random_quadratic_hamiltonian(n_orbitals,\n conserves_particle_number=False,\n real=False,\n expand_spin=False,\n seed=None):\n \"\"\"Generate a random instance of QuadraticHamiltonian.\n\n Args:\n n_orbitals(int): the number of orbitals\n conserves_particle_number(bool): whether the returned Hamiltonian\n should conserve particle number\n real(bool): whether to use only real numbers\n expand_spin: Whether to expand each orbital symmetrically into two\n spin orbitals. Note that if this option is set to True, then\n the total number of orbitals will be doubled.\n\n Returns:\n QuadraticHamiltonian\n \"\"\"\n if seed is not None:\n numpy.random.seed(seed)\n\n constant = numpy.random.randn()\n chemical_potential = numpy.random.randn()\n hermitian_mat = random_hermitian_matrix(n_orbitals, real)\n\n if conserves_particle_number:\n antisymmetric_mat = None\n else:\n antisymmetric_mat = random_antisymmetric_matrix(n_orbitals, real)\n\n if expand_spin:\n hermitian_mat = numpy.kron(hermitian_mat, numpy.eye(2))\n if antisymmetric_mat is not None:\n antisymmetric_mat = numpy.kron(antisymmetric_mat, numpy.eye(2))\n\n return QuadraticHamiltonian(hermitian_mat, antisymmetric_mat, constant,\n chemical_potential)\n\n\nclass EqualsTester(object):\n \"\"\"Tests equality against user-provided disjoint equivalence groups.\"\"\"\n\n def __init__(self, test_case):\n self.groups = [(_ClassUnknownToSubjects(),)]\n self.test_case = test_case\n\n def add_equality_group(self, *group_items):\n \"\"\"Tries to add a disjoint equivalence group to the equality tester.\n This methods asserts that items within the group must all be equal to\n each other, but not equal to any items in other groups that have been\n or will be added.\n\n Args:\n *group_items: The items making up the equivalence group.\n\n Raises:\n AssertError: Items within the group are not equal to each other, or\n items in another group are equal to items within the new group,\n or the items violate the equals-implies-same-hash rule.\n \"\"\"\n\n self.test_case.assertIsNotNone(group_items)\n\n # Check that group items are equivalent to each other.\n for v1, v2 in itertools.product(group_items, repeat=2):\n # Binary operators should always work.\n self.test_case.assertTrue(v1 == v2)\n self.test_case.assertTrue(not v1 != v2)\n\n # __eq__ and __ne__ should both be correct or not implemented.\n self.test_case.assertTrue(\n hasattr(v1, '__eq__') == hasattr(v1, '__ne__'))\n # Careful: python2 int doesn't have __eq__ or __ne__.\n if hasattr(v1, '__eq__'):\n eq = v1.__eq__(v2)\n ne = v1.__ne__(v2)\n self.test_case.assertIn((eq, ne),\n [(True, False), (NotImplemented, False),\n (NotImplemented, NotImplemented)])\n\n # Check that this group's items don't overlap with other groups.\n for other_group in self.groups:\n for v1, v2 in itertools.product(group_items, other_group):\n # Binary operators should always work.\n self.test_case.assertTrue(not v1 == v2)\n self.test_case.assertTrue(v1 != v2)\n\n # __eq__ and __ne__ should both be correct or not implemented.\n self.test_case.assertTrue(\n hasattr(v1, '__eq__') == hasattr(v1, '__ne__'))\n # Careful: python2 int doesn't have __eq__ or __ne__.\n if hasattr(v1, '__eq__'):\n eq = v1.__eq__(v2)\n ne = v1.__ne__(v2)\n self.test_case.assertIn((eq, ne),\n [(False, True),\n (NotImplemented, True),\n (NotImplemented, NotImplemented)])\n\n # Check that group items hash to the same thing, or are all unhashable.\n hashes = [\n hash(v) if isinstance(v, collections.abc.Hashable) else None\n for v in group_items\n ]\n if len(set(hashes)) > 1:\n examples = ((v1, h1, v2, h2)\n for v1, h1 in zip(group_items, hashes)\n for v2, h2 in zip(group_items, hashes)\n if h1 != h2)\n example = next(examples)\n raise AssertionError(\n 'Items in the same group produced different hashes. '\n 'Example: hash({}) is {} but hash({}) is {}.'.format(*example))\n\n # Remember this group, to enable disjoint checks vs later groups.\n self.groups.append(group_items)\n\n def make_equality_pair(self, factory):\n \"\"\"Tries to add a disjoint (item, item) group to the equality tester.\n Uses the factory method to produce two different objects containing\n equal items. Asserts that the two object are equal, but not equal to\n any items in other groups that have been or will be added. Adds the\n pair as a group.\n\n Args:\n factory (Callable[[], Any]): A method for producing independent\n copies of an item.\n\n Raises:\n AssertError: The factory produces items not equal to each other, or\n items in another group are equal to items from the factory, or\n the items violate the equal-implies-same-hash rule.\n \"\"\"\n self.add_equality_group(factory(), factory())\n\n\nclass _ClassUnknownToSubjects(object):\n \"\"\"Equality methods should be able to deal with the unexpected.\"\"\"\n\n def __eq__(self, other):\n return isinstance(other, _ClassUnknownToSubjects)\n\n def __ne__(self, other):\n return not self == other\n\n def __hash__(self):\n return hash(_ClassUnknownToSubjects)\n\n\ndef module_importable(module):\n \"\"\"Without importing it, returns whether python module is importable.\n\n Args:\n module (string): Name of module.\n\n Returns:\n bool\n\n \"\"\"\n import sys\n if sys.version_info >= (3, 4):\n from importlib import util\n plug_spec = util.find_spec(module)\n else:\n # Won't enter unless Python<3.4, so ignore for testing\n import pkgutil # pragma: ignore\n plug_spec = pkgutil.find_loader(module) # pragma: no cover\n if plug_spec is None:\n return False\n else:\n return True\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\"\"\" Binary code class for Fermion-qubit mappings (arXiv:1712.07067) \"\"\"\n\nimport copy\n\nimport numpy\nimport scipy\nimport scipy.sparse\n\nfrom openfermion.ops.operators import BinaryPolynomial\n# import openfermion.ops.operators._binary_polynomial as bp\n\n\ndef shift_decoder(decoder, shift_constant):\n \"\"\" Shifts the indices of a decoder by a constant.\n\n Args:\n decoder (iterable): list of BinaryPolynomial; the decoder\n shift_constant (int): the qubit index that corresponds to the offset.\n\n Returns (list): list of BinaryPolynomial shifted decoder\n \"\"\"\n decode_shifted = []\n if not isinstance(shift_constant, (numpy.int64, numpy.int32, int)):\n raise TypeError('the shift to the decoder must be integer. got {}'\n 'of type {}'.format(shift_constant,\n type(shift_constant)))\n for entry in decoder:\n tmp_entry = copy.deepcopy(entry)\n tmp_entry.shift(shift_constant)\n decode_shifted.append(tmp_entry)\n return decode_shifted\n\n\ndef double_decoding(decoder_1, decoder_2):\n \"\"\" Concatenates two decodings\n\n Args:\n decoder_1 (iterable): list of BinaryPolynomial\n decoding of the outer code layer\n decoder_2 (iterable): list of BinaryPolynomial\n decoding of the inner code layer\n\n Returns (list): list of BinaryPolynomial the decoding defined by\n w -> decoder_1( decoder_2(w) )\n \"\"\"\n doubled_decoder = []\n for entry in decoder_1:\n tmp_sum = 0\n for summand in entry.terms:\n tmp_term = BinaryPolynomial('1')\n for factor in summand:\n if isinstance(factor, (numpy.int32, numpy.int64, int)):\n tmp_term *= decoder_2[factor]\n tmp_sum = tmp_term + tmp_sum\n doubled_decoder += [tmp_sum]\n return doubled_decoder\n\n\nclass BinaryCodeError(Exception):\n pass\n\n\nclass BinaryCode(object):\n r\"\"\"The BinaryCode class provides a representation of an encoding-decoding\n pair for binary vectors of different lengths, where the decoding is allowed\n to be non-linear.\n\n As the occupation number of fermionic mode is effectively binary,\n a length-N vector (v) of binary number can be utilized to describe\n a configuration of a many-body fermionic state on N modes.\n An n-qubit product state configuration \\|w0> \\|w1> \\|w2> ... \\|wn-1>,\n on the other hand is described by a length-n binary vector\n w=(w0, w1, ..., wn-1). To map a subset of N-Orbital Fermion states\n to n-qubit states we define a binary code, which consists of a\n (here: linear) encoding (e) and a (non-linear) decoding (d), such\n that for every v from that subset, w = e(v) is a length-n binary\n vector with d(w) = v. This can be used to save qubits given a\n Hamiltonian that dictates such a subset, otherwise n=N.\n\n Two binary codes (e,d) and (e',d') can construct a third code (e\",d\")\n by two possible operations:\n\n Concatenation: (e\",d\") = (e,d) * (e',d')\n which means e\": v\" -> e'( e(v\") ) and d\": w\" -> d( d'(w\") )\n where n\" = n' and N\" = N, with n = N' as necessary condition.\n\n Appendage: (e\",d\") = (e,d) + (e',d')\n which means e\": (v + v') -> e(v) + e'(v') and d\": (w + w') -> d(w) + d'(\n w')\n where the addition is to be understood as appending two vectors together,\n so N\" = N' + N and n\" = n + n'.\n\n Appending codes is particularly useful when considering segment codes or\n segmented transforms.\n\n A BinaryCode-instance is initialized by BinaryCode(A,d),\n given the encoding (e) as n x N array or matrix-like nested lists A,\n such that e(v) = (A v) mod 2. The decoding d is an array or a list\n input of length N, which has entries either of type BinaryPolynomial, or of\n valid type for an input of the BinaryPolynomial-constructor.\n\n The signs + and \\*, += and \\*= are overloaded to implement concatenation\n and appendage on BinaryCode-objects.\n\n NOTE: multiplication of a BinaryCode with an integer yields a\n multiple appending of the same code, the multiplication with another\n BinaryCode their concatenation.\n\n Attributes:\n decoder (list): list of BinaryPolynomial: Outputs the decoding\n functions as components.\n encoder (scipy.sparse.csc_matrix): Outputs A, the linear matrix that\n implements the encoding function.\n n_modes (int): Outputs the number of modes.\n n_qubits (int): Outputs the number of qubits.\n \"\"\"\n\n def __init__(self, encoding, decoding):\n \"\"\" Initialization of a binary code.\n\n Args:\n encoding (np.ndarray or list): nested lists or binary 2D-array\n decoding (array or list): list of BinaryPolynomial (list or str).\n\n Raises:\n TypeError: non-list, array like encoding or decoding, unsuitable\n BinaryPolynomial generators,\n BinaryCodeError: in case of decoder/encoder size mismatch or\n decoder size, qubits indexed mismatch\n \"\"\"\n if not isinstance(encoding, (numpy.ndarray, list)):\n raise TypeError('encoding must be a list or array.')\n\n if not isinstance(decoding, (numpy.ndarray, list)):\n raise TypeError('decoding must be a list or array.')\n\n self.encoder = scipy.sparse.csc_matrix(encoding)\n self.n_qubits, self.n_modes = numpy.shape(encoding)\n\n if self.n_modes != len(decoding):\n raise BinaryCodeError(\n 'size mismatch, decoder and encoder should have the same'\n ' first dimension')\n\n decoder_qubits = set()\n self.decoder = []\n\n for symbolic_binary in decoding:\n if isinstance(symbolic_binary,\n (tuple, list, str, int, numpy.int32, numpy.int64)):\n symbolic_binary = BinaryPolynomial(symbolic_binary)\n if isinstance(symbolic_binary, BinaryPolynomial):\n self.decoder.append(symbolic_binary)\n decoder_qubits = decoder_qubits | set(\n symbolic_binary.enumerate_qubits())\n else:\n raise TypeError(\n 'decoder component provided '\n 'is not a suitable for BinaryPolynomial', symbolic_binary)\n\n if len(decoder_qubits) != self.n_qubits:\n raise BinaryCodeError(\n 'decoder and encoder provided has different number of qubits')\n\n if max(decoder_qubits) + 1 > self.n_qubits:\n raise BinaryCodeError('decoder is not indexing some qubits. Qubits'\n 'indexed are: {}'.format(decoder_qubits))\n\n def __iadd__(self, appendix):\n \"\"\" In-place appending a binary code with +=.\n\n Args:\n appendix (BinaryCode): The code to append to the present one.\n\n Returns (BinaryCode): A global binary code with size\n (n_modes1 + n_modes2), (n_qubits1,n_qubits2)\n\n Raises:\n TypeError: Appendix must be a BinaryCode.\n \"\"\"\n if not isinstance(appendix, BinaryCode):\n raise TypeError('argument must be a BinaryCode.')\n\n self.decoder = numpy.append(\n self.decoder, shift_decoder(appendix.decoder,\n self.n_qubits)).tolist()\n self.encoder = scipy.sparse.bmat([[self.encoder, None],\n [None, appendix.encoder]])\n self.n_qubits, self.n_modes = numpy.shape(self.encoder)\n return self\n\n def __add__(self, appendix):\n \"\"\"Appends two binary codes via addition +.\n\n Args:\n appendix (BinaryCode): The code to append to the present one.\n\n Returns (BinaryCode): global binary code\n \"\"\"\n twin = copy.deepcopy(self)\n twin += appendix\n return twin\n\n def __imul__(self, factor):\n \"\"\"In-place code concatenation or appendage via *= .\n Multiplication with integer will yield appendage, otherwise\n concatenation.\n\n Args:\n factor (int or BinaryCode): the BinaryCode to concatenate. In case\n of int, it will append the code to itself factor times.\n\n Returns (BinaryCode): segmented or concatenated code\n\n Raises:\n TypeError: factor must be an integer or a BinaryCode\n BinaryCodeError: size mismatch between self and factor\n ValueError: in case of an integer factor that is < 1\n \"\"\"\n if not isinstance(factor, (BinaryCode, numpy.int32, numpy.int64, int)):\n raise TypeError('argument must be a BinaryCode or integer')\n\n if isinstance(factor, BinaryCode):\n if self.n_qubits != factor.n_modes:\n raise BinaryCodeError(\n 'size mismatch between inner and outer code layer')\n\n self.decoder = double_decoding(self.decoder, factor.decoder)\n self.encoder = factor.encoder.dot(self.encoder)\n self.n_qubits, self.n_modes = numpy.shape(self.encoder)\n return self\n\n elif isinstance(factor, (numpy.int32, numpy.int64, int)):\n if factor < 1:\n raise ValueError('integer factor has to be positive, '\n 'non-zero ')\n\n self.encoder = scipy.sparse.kron(\n scipy.sparse.identity(factor, format='csc', dtype=int),\n self.encoder, 'csc')\n tmp_decoder = self.decoder\n for index in numpy.arange(1, factor):\n self.decoder = numpy.append(\n self.decoder,\n shift_decoder(tmp_decoder, index * self.n_qubits))\n self.n_qubits *= factor\n self.n_modes *= factor\n return self\n\n def __mul__(self, factor):\n \"\"\" Concatenation of two codes or appendage the same code factor times\n in case of integer factor.\n\n Args:\n factor (int or BinaryCode): the BinaryCode to concatenate. In case\n of int, it will append the code to itself factor times.\n\n Returns (BinaryCode): segmented or concatenated code\n \"\"\"\n twin = copy.deepcopy(self)\n twin *= factor\n return twin\n\n def __rmul__(self, factor):\n \"\"\" Appending the same code factor times.\n\n Args:\n factor (int): integer defining number of appendages.\n\n Returns (BinaryCode): Segmented code.\n\n Raises:\n TypeError: factor must be an integer\n \"\"\"\n if isinstance(factor, (numpy.int32, numpy.int64, int)):\n return self * factor\n else:\n raise TypeError('the left multiplier must be an integer to a'\n 'BinaryCode. Was given {} of '\n 'type {}'.format(factor, type(factor)))\n\n def __str__(self):\n \"\"\" Return an easy-to-read string representation.\"\"\"\n string_return = [list(map(list, self.encoder.toarray()))]\n\n dec_str = '['\n for term in self.decoder:\n dec_str += term.__str__() + ','\n dec_str = dec_str[:-1]\n string_return.append(dec_str + ']')\n return str(string_return)\n\n def __repr__(self):\n return str(self)\n" ]
[ [ "numpy.eye", "numpy.allclose" ], [ "numpy.arange", "numpy.real", "numpy.vstack" ], [ "numpy.dot", "pandas.Series", "numpy.exp", "numpy.array", "numpy.sum", "numpy.random.RandomState", "numpy.isclose" ], [ "scipy.linalg.qr", "numpy.random.seed", "numpy.eye", "numpy.random.randn", "numpy.random.RandomState", "numpy.zeros", "numpy.conjugate" ], [ "scipy.sparse.csc_matrix", "numpy.arange", "scipy.sparse.identity", "numpy.shape", "scipy.sparse.bmat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.14", "0.15", "0.12", "0.10" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
NTR0314/botorch
[ "f0310c9a415947f3264dac7f3438744784843323", "f0310c9a415947f3264dac7f3438744784843323", "f0310c9a415947f3264dac7f3438744784843323" ]
[ "botorch/test_functions/multi_objective.py", "test/acquisition/test_utils.py", "test/models/test_converter.py" ]
[ "#! /usr/bin/env python3\n# 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\nr\"\"\"\nMulti-objective optimization benchmark problems.\n\nReferences\n\n.. [Deb2005dtlz]\n K. Deb, L. Thiele, M. Laumanns, E. Zitzler, A. Abraham, L. Jain, R. Goldberg.\n \"Scalable test problems for evolutionary multi-objective optimization\"\n in Evolutionary Multiobjective Optimization, London, U.K.: Springer-Verlag,\n pp. 105-145, 2005.\n\n.. [GarridoMerchan2020]\n E. C. Garrido-Merch ́an and D. Hern ́andez-Lobato. Parallel Predictive Entropy\n Search for Multi-objective Bayesian Optimization with Constraints.\n arXiv e-prints, arXiv:2004.00601, Apr. 2020.\n\n.. [Gelbart2014]\n Michael A. Gelbart, Jasper Snoek, and Ryan P. Adams. 2014. Bayesian\n optimization with unknown constraints. In Proceedings of the Thirtieth\n Conference on Uncertainty in Artificial Intelligence (UAI’14).\n AUAI Press, Arlington, Virginia, USA, 250–259.\n\n.. [Oszycka1995]\n A. Osyczka, S. Kundu. 1995. A new method to solve generalized multicriteria\n optimization problems using the simple genetic algorithm. In Structural\n Optimization 10. 94–99.\n\n.. [Tanabe2020]\n Ryoji Tanabe, Hisao Ishibuchi, An easy-to-use real-world multi-objective\n optimization problem suite, Applied Soft Computing,Volume 89, 2020.\n\n.. [Yang2019a]\n K. Yang, M. Emmerich, A. Deutz, and T. Bäck. 2019.\n \"Multi-Objective Bayesian Global Optimization using expected hypervolume\n improvement gradient\" in Swarm and evolutionary computation 44, pp. 945--956,\n 2019.\n\n.. [Zitzler2000]\n E. Zitzler, K. Deb, and L. Thiele, “Comparison of multiobjective\n evolutionary algorithms: Empirical results,” Evol. Comput., vol. 8, no. 2,\n pp. 173–195, 2000.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport math\nfrom typing import Optional\n\nimport torch\nfrom botorch.test_functions.base import (\n ConstrainedBaseTestProblem,\n MultiObjectiveTestProblem,\n)\nfrom botorch.test_functions.synthetic import Branin\nfrom botorch.utils.sampling import sample_hypersphere, sample_simplex\nfrom botorch.utils.transforms import unnormalize\nfrom scipy.special import gamma\nfrom torch import Tensor\n\n\nclass BraninCurrin(MultiObjectiveTestProblem):\n r\"\"\"Two objective problem composed of the Branin and Currin functions.\n\n Branin (rescaled):\n\n f(x) = (\n 15*x_1 - 5.1 * (15 * x_0 - 5) ** 2 / (4 * pi ** 2) + 5 * (15 * x_0 - 5)\n / pi - 5\n ) ** 2 + (10 - 10 / (8 * pi)) * cos(15 * x_0 - 5))\n\n Currin:\n\n f(x) = (1 - exp(-1 / (2 * x_1))) * (\n 2300 * x_0 ** 3 + 1900 * x_0 ** 2 + 2092 * x_0 + 60\n ) / 100 * x_0 ** 3 + 500 * x_0 ** 2 + 4 * x_0 + 20\n\n \"\"\"\n\n dim = 2\n num_objectives = 2\n _bounds = [(0.0, 1.0), (0.0, 1.0)]\n _ref_point = [18.0, 6.0]\n _max_hv = 59.36011874867746 # this is approximated using NSGA-II\n\n def __init__(self, noise_std: Optional[float] = None, negate: bool = False) -> None:\n r\"\"\"Constructor for Branin-Currin.\n\n Args:\n noise_std: Standard deviation of the observation noise.\n negate: If True, negate the objectives.\n \"\"\"\n super().__init__(noise_std=noise_std, negate=negate)\n self._branin = Branin()\n\n def _rescaled_branin(self, X: Tensor) -> Tensor:\n # return to Branin bounds\n x_0 = 15 * X[..., 0] - 5\n x_1 = 15 * X[..., 1]\n return self._branin(torch.stack([x_0, x_1], dim=-1))\n\n @staticmethod\n def _currin(X: Tensor) -> Tensor:\n x_0 = X[..., 0]\n x_1 = X[..., 1]\n factor1 = 1 - torch.exp(-1 / (2 * x_1))\n numer = 2300 * x_0.pow(3) + 1900 * x_0.pow(2) + 2092 * x_0 + 60\n denom = 100 * x_0.pow(3) + 500 * x_0.pow(2) + 4 * x_0 + 20\n return factor1 * numer / denom\n\n def evaluate_true(self, X: Tensor) -> Tensor:\n # branin rescaled with inputsto [0,1]^2\n branin = self._rescaled_branin(X=X)\n currin = self._currin(X=X)\n return torch.stack([branin, currin], dim=-1)\n\n\nclass DTLZ(MultiObjectiveTestProblem):\n r\"\"\"Base class for DTLZ problems.\n\n See [Deb2005dtlz]_ for more details on DTLZ.\n \"\"\"\n\n def __init__(\n self,\n dim: int,\n num_objectives: int = 2,\n noise_std: Optional[float] = None,\n negate: bool = False,\n ) -> None:\n if dim <= num_objectives:\n raise ValueError(\n f\"dim must be > num_objectives, but got {dim} and {num_objectives}\"\n )\n self.num_objectives = num_objectives\n self.dim = dim\n self.k = self.dim - self.num_objectives + 1\n self._bounds = [(0.0, 1.0) for _ in range(self.dim)]\n self._ref_point = [self._ref_val for _ in range(num_objectives)]\n super().__init__(noise_std=noise_std, negate=negate)\n\n\nclass DTLZ1(DTLZ):\n r\"\"\"DLTZ1 test problem.\n\n d-dimensional problem evaluated on `[0, 1]^d`:\n\n f_0(x) = 0.5 * x_0 * (1 + g(x))\n f_1(x) = 0.5 * (1 - x_0) * (1 + g(x))\n g(x) = 100 * \\sum_{i=m}^{n-1} (\n k + (x_i - 0.5)^2 - cos(20 * pi * (x_i - 0.5))\n )\n\n where k = n - m + 1.\n\n The pareto front is given by the line (or hyperplane) \\sum_i f_i(x) = 0.5.\n The goal is to minimize both objectives. The reference point comes from [Yang2019]_.\n \"\"\"\n\n _ref_val = 400.0\n\n @property\n def _max_hv(self) -> float:\n return self._ref_val ** self.num_objectives - 1 / 2 ** self.num_objectives\n\n def evaluate_true(self, X: Tensor) -> Tensor:\n X_m = X[..., -self.k :]\n X_m_minus_half = X_m - 0.5\n sum_term = (\n X_m_minus_half.pow(2) - torch.cos(20 * math.pi * X_m_minus_half)\n ).sum(dim=-1)\n g_X_m = 100 * (self.k + sum_term)\n g_X_m_term = 0.5 * (1 + g_X_m)\n fs = []\n for i in range(self.num_objectives):\n idx = self.num_objectives - 1 - i\n f_i = g_X_m_term * X[..., :idx].prod(dim=-1)\n if i > 0:\n f_i *= 1 - X[..., idx]\n fs.append(f_i)\n return torch.stack(fs, dim=-1)\n\n def gen_pareto_front(self, n: int) -> Tensor:\n r\"\"\"Generate `n` pareto optimal points.\n\n The pareto points randomly sampled from the hyperplane sum_i f(x_i) = 0.5.\n \"\"\"\n f_X = 0.5 * sample_simplex(\n n=n,\n d=self.num_objectives,\n qmc=True,\n dtype=self.ref_point.dtype,\n device=self.ref_point.device,\n )\n if self.negate:\n f_X *= -1\n return f_X\n\n\nclass DTLZ2(DTLZ):\n r\"\"\"DLTZ2 test problem.\n\n d-dimensional problem evaluated on `[0, 1]^d`:\n\n f_0(x) = (1 + g(x)) * cos(x_0 * pi / 2)\n f_1(x) = (1 + g(x)) * sin(x_0 * pi / 2)\n g(x) = \\sum_{i=m}^{n-1} (x_i - 0.5)^2\n\n The pareto front is given by the unit hypersphere \\sum{i} f_i^2 = 1.\n Note: the pareto front is completely concave. The goal is to minimize\n both objectives.\n \"\"\"\n\n _ref_val = 1.1\n\n @property\n def _max_hv(self) -> float:\n # hypercube - volume of hypersphere in R^n such that all coordinates are\n # positive\n hypercube_vol = self._ref_val ** self.num_objectives\n pos_hypersphere_vol = (\n math.pi ** (self.num_objectives / 2)\n / gamma(self.num_objectives / 2 + 1)\n / 2 ** self.num_objectives\n )\n return hypercube_vol - pos_hypersphere_vol\n\n def evaluate_true(self, X: Tensor) -> Tensor:\n X_m = X[..., -self.k :]\n g_X = (X_m - 0.5).pow(2).sum(dim=-1)\n g_X_plus1 = 1 + g_X\n fs = []\n pi_over_2 = math.pi / 2\n for i in range(self.num_objectives):\n idx = self.num_objectives - 1 - i\n f_i = g_X_plus1.clone()\n f_i *= torch.cos(X[..., :idx] * pi_over_2).prod(dim=-1)\n if i > 0:\n f_i *= torch.sin(X[..., idx] * pi_over_2)\n fs.append(f_i)\n return torch.stack(fs, dim=-1)\n\n def gen_pareto_front(self, n: int) -> Tensor:\n r\"\"\"Generate `n` pareto optimal points.\n\n The pareto points are randomly sampled from the hypersphere's\n positive section.\n \"\"\"\n f_X = sample_hypersphere(\n n=n,\n d=self.num_objectives,\n dtype=self.ref_point.dtype,\n device=self.ref_point.device,\n qmc=True,\n ).abs()\n if self.negate:\n f_X *= -1\n return f_X\n\n\nclass VehicleSafety(MultiObjectiveTestProblem):\n r\"\"\"Optimize Vehicle crash-worthiness.\n\n See [Tanabe2020]_ for details.\n\n The reference point is 1.1 * the nadir point from\n approximate front provided by [Tanabe2020]_.\n\n The maximum hypervolume is computed using the approximate\n pareto front from [Tanabe2020]_.\n \"\"\"\n\n _ref_point = [1864.72022, 11.81993945, 0.2903999384]\n _max_hv = 246.81607081187002\n _bounds = [(1.0, 3.0)] * 5\n dim = 5\n num_objectives = 3\n\n def evaluate_true(self, X: Tensor) -> Tensor:\n X1, X2, X3, X4, X5 = torch.split(X, 1, -1)\n f1 = (\n 1640.2823\n + 2.3573285 * X1\n + 2.3220035 * X2\n + 4.5688768 * X3\n + 7.7213633 * X4\n + 4.4559504 * X5\n )\n f2 = (\n 6.5856\n + 1.15 * X1\n - 1.0427 * X2\n + 0.9738 * X3\n + 0.8364 * X4\n - 0.3695 * X1 * X4\n + 0.0861 * X1 * X5\n + 0.3628 * X2 * X4\n - 0.1106 * X1.pow(2)\n - 0.3437 * X3.pow(2)\n + 0.1764 * X4.pow(2)\n )\n f3 = (\n -0.0551\n + 0.0181 * X1\n + 0.1024 * X2\n + 0.0421 * X3\n - 0.0073 * X1 * X2\n + 0.024 * X2 * X3\n - 0.0118 * X2 * X4\n - 0.0204 * X3 * X4\n - 0.008 * X3 * X5\n - 0.0241 * X2.pow(2)\n + 0.0109 * X4.pow(2)\n )\n f_X = torch.cat([f1, f2, f3], dim=-1)\n return f_X\n\n\nclass ZDT(MultiObjectiveTestProblem):\n r\"\"\"Base class for ZDT problems.\n\n See [Zitzler2000]_ for more details on ZDT.\n \"\"\"\n\n _ref_point = [11.0, 11.0]\n\n def __init__(\n self,\n dim: int,\n num_objectives: int = 2,\n noise_std: Optional[float] = None,\n negate: bool = False,\n ) -> None:\n if num_objectives != 2:\n raise NotImplementedError(\n f\"{type(self).__name__} currently only supports 2 objectives.\"\n )\n if dim < num_objectives:\n raise ValueError(\n f\"dim must be >= num_objectives, but got {dim} and {num_objectives}\"\n )\n self.num_objectives = num_objectives\n self.dim = dim\n self._bounds = [(0.0, 1.0) for _ in range(self.dim)]\n super().__init__(noise_std=noise_std, negate=negate)\n\n @staticmethod\n def _g(X: Tensor) -> Tensor:\n return 1 + 9 * X[..., 1:].mean(dim=-1)\n\n\nclass ZDT1(ZDT):\n r\"\"\"ZDT1 test problem.\n\n d-dimensional problem evaluated on `[0, 1]^d`:\n\n f_0(x) = x_0\n f_1(x) = g(x) * (1 - sqrt(x_0 / g(x))\n g(x) = 1 + 9 / (d - 1) * \\sum_{i=1}^{d-1} x_i\n\n The reference point comes from [Yang2019a]_.\n\n The pareto front is convex.\n \"\"\"\n\n _max_hv = 120 + 2 / 3\n\n def evaluate_true(self, X: Tensor) -> Tensor:\n f_0 = X[..., 0]\n g = self._g(X=X)\n f_1 = g * (1 - (f_0 / g).sqrt())\n return torch.stack([f_0, f_1], dim=-1)\n\n def gen_pareto_front(self, n: int) -> Tensor:\n f_0 = torch.linspace(\n 0, 1, n, dtype=self.bounds.dtype, device=self.bounds.device\n )\n f_1 = 1 - f_0.sqrt()\n f_X = torch.stack([f_0, f_1], dim=-1)\n if self.negate:\n f_X *= -1\n return f_X\n\n\nclass ZDT2(ZDT):\n r\"\"\"ZDT2 test problem.\n\n d-dimensional problem evaluated on `[0, 1]^d`:\n\n f_0(x) = x_0\n f_1(x) = g(x) * (1 - (x_0 / g(x))^2)\n g(x) = 1 + 9 / (d - 1) * \\sum_{i=1}^{d-1} x_i\n\n The reference point comes from [Yang2019a]_.\n\n The pareto front is concave.\n \"\"\"\n\n _max_hv = 120 + 1 / 3\n\n def evaluate_true(self, X: Tensor) -> Tensor:\n f_0 = X[..., 0]\n g = self._g(X=X)\n f_1 = g * (1 - (f_0 / g).pow(2))\n return torch.stack([f_0, f_1], dim=-1)\n\n def gen_pareto_front(self, n: int) -> Tensor:\n f_0 = torch.linspace(\n 0, 1, n, dtype=self.bounds.dtype, device=self.bounds.device\n )\n f_1 = 1 - f_0.pow(2)\n f_X = torch.stack([f_0, f_1], dim=-1)\n if self.negate:\n f_X *= -1\n return f_X\n\n\nclass ZDT3(ZDT):\n r\"\"\"ZDT3 test problem.\n\n d-dimensional problem evaluated on `[0, 1]^d`:\n\n f_0(x) = x_0\n f_1(x) = 1 - sqrt(x_0 / g(x)) - x_0 / g * sin(10 * pi * x_0)\n g(x) = 1 + 9 / (d - 1) * \\sum_{i=1}^{d-1} x_i\n\n The reference point comes from [Yang2019a]_.\n\n The pareto front consists of several discontinuous convex parts.\n \"\"\"\n\n _max_hv = 128.77811613069076060\n _parts = [\n # this interval includes both end points\n [0, 0.0830015349],\n # this interval includes only the right end points\n [0.1822287280, 0.2577623634],\n [0.4093136748, 0.4538821041],\n [0.6183967944, 0.6525117038],\n [0.8233317983, 0.8518328654],\n ]\n # nugget to make sure linspace returns elements within the specified range\n _eps = 1e-6\n\n def evaluate_true(self, X: Tensor) -> Tensor:\n f_0 = X[..., 0]\n g = self._g(X=X)\n f_1 = 1 - (f_0 / g).sqrt() - f_0 / g * torch.sin(10 * math.pi * f_0)\n return torch.stack([f_0, f_1], dim=-1)\n\n def gen_pareto_front(self, n: int) -> Tensor:\n n_parts = len(self._parts)\n n_per_part = torch.full(\n torch.Size([n_parts]),\n n // n_parts,\n dtype=torch.long,\n device=self.bounds.device,\n )\n left_over = n % n_parts\n n_per_part[:left_over] += 1\n f_0s = []\n for i, p in enumerate(self._parts):\n left, right = p\n f_0s.append(\n torch.linspace(\n left + self._eps,\n right - self._eps,\n n_per_part[i],\n dtype=self.bounds.dtype,\n device=self.bounds.device,\n )\n )\n f_0 = torch.cat(f_0s, dim=0)\n f_1 = 1 - f_0.sqrt() - f_0 * torch.sin(10 * math.pi * f_0)\n f_X = torch.stack([f_0, f_1], dim=-1)\n if self.negate:\n f_X *= -1\n return f_X\n\n\n# ------ Constrained Multi-Objective Test Problems ----- #\n\n\nclass BNH(MultiObjectiveTestProblem, ConstrainedBaseTestProblem):\n r\"\"\"The constrained BNH problem.\n\n See [GarridoMerchan2020]_ for more details on this problem. Note that this is a\n minimization problem.\n \"\"\"\n\n dim = 2\n num_objectives = 2\n num_constraints = 2\n _bounds = [(0.0, 5.0), (0.0, 3.0)]\n _ref_point = [0.0, 0.0] # TODO: Determine proper reference point\n\n def evaluate_true(self, X: Tensor) -> Tensor:\n return torch.stack(\n [4.0 * (X ** 2).sum(dim=-1), ((X - 5.0) ** 2).sum(dim=-1)], dim=-1\n )\n\n def evaluate_slack_true(self, X: Tensor) -> Tensor:\n c1 = 25.0 - (X[..., 0] - 5.0) ** 2 - X[..., 1] ** 2\n c2 = (X[..., 0] - 8.0) ** 2 + (X[..., 1] + 3.0) ** 2 - 7.7\n return torch.stack([c1, c2], dim=-1)\n\n\nclass SRN(MultiObjectiveTestProblem, ConstrainedBaseTestProblem):\n r\"\"\"The constrained SRN problem.\n\n See [GarridoMerchan2020]_ for more details on this problem. Note that this is a\n minimization problem.\n \"\"\"\n\n dim = 2\n num_objectives = 2\n num_constraints = 2\n _bounds = [(-20.0, 20.0), (-20.0, 20.0)]\n _ref_point = [0.0, 0.0] # TODO: Determine proper reference point\n\n def evaluate_true(self, X: Tensor) -> Tensor:\n obj1 = 2.0 + ((X - 2.0) ** 2).sum(dim=-1)\n obj2 = 9.0 * X[..., 0] - (X[..., 1] - 1.0) ** 2\n return torch.stack([obj1, obj2], dim=-1)\n\n def evaluate_slack_true(self, X: Tensor) -> Tensor:\n c1 = 225.0 - ((X ** 2) ** 2).sum(dim=-1)\n c2 = -10.0 - X[..., 0] + 3 * X[..., 1]\n return torch.stack([c1, c2], dim=-1)\n\n\nclass CONSTR(MultiObjectiveTestProblem, ConstrainedBaseTestProblem):\n r\"\"\"The constrained CONSTR problem.\n\n See [GarridoMerchan2020]_ for more details on this problem. Note that this is a\n minimization problem.\n \"\"\"\n\n dim = 2\n num_objectives = 2\n num_constraints = 2\n _bounds = [(0.1, 10.0), (0.0, 5.0)]\n _ref_point = [10.0, 10.0]\n\n def evaluate_true(self, X: Tensor) -> Tensor:\n obj1 = X[..., 0]\n obj2 = (1.0 + X[..., 1]) / X[..., 0]\n return torch.stack([obj1, obj2], dim=-1)\n\n def evaluate_slack_true(self, X: Tensor) -> Tensor:\n c1 = 9.0 * X[..., 0] + X[..., 1] - 6.0\n c2 = 9.0 * X[..., 0] - X[..., 1] - 1.0\n return torch.stack([c1, c2], dim=-1)\n\n\nclass ConstrainedBraninCurrin(BraninCurrin, ConstrainedBaseTestProblem):\n r\"\"\"Constrained Branin Currin Function.\n\n This uses the disk constraint from [Gelbart2014]_.\n \"\"\"\n\n dim = 2\n num_objectives = 2\n num_constraints = 1\n _bounds = [(0.0, 1.0), (0.0, 1.0)]\n _con_bounds = [(-5.0, 10.0), (0.0, 15.0)]\n _ref_point = [80.0, 12.0]\n _max_hv = 608.4004237022673 # from NSGA-II with 90k evaluations\n\n def __init__(self, noise_std: Optional[float] = None, negate: bool = False) -> None:\n super().__init__(noise_std=noise_std, negate=negate)\n con_bounds = torch.tensor(self._con_bounds, dtype=torch.float).transpose(-1, -2)\n self.register_buffer(\"con_bounds\", con_bounds)\n\n def evaluate_slack_true(self, X: Tensor) -> Tensor:\n X_tf = unnormalize(X, self.con_bounds)\n return 50 - (X_tf[..., 0:1] - 2.5).pow(2) - (X_tf[..., 1:2] - 7.5).pow(2)\n\n\nclass C2DTLZ2(DTLZ2, ConstrainedBaseTestProblem):\n\n num_constraints = 1\n _r = 0.2\n # approximate from nsga-ii, TODO: replace with analytic\n _max_hv = 0.3996406303723544\n\n def evaluate_slack_true(self, X: Tensor) -> Tensor:\n if X.ndim > 2:\n raise NotImplementedError(\"Batch X is not supported.\")\n f_X = self.evaluate_true(X)\n term1 = (f_X - 1).pow(2)\n mask = ~(torch.eye(f_X.shape[-1], device=f_X.device).bool())\n indices = torch.arange(f_X.shape[1], device=f_X.device).repeat(f_X.shape[1], 1)\n indexer = indices[mask].view(f_X.shape[1], f_X.shape[-1] - 1)\n term2_inner = (\n f_X.unsqueeze(1)\n .expand(f_X.shape[0], f_X.shape[-1], f_X.shape[-1])\n .gather(dim=-1, index=indexer.repeat(f_X.shape[0], 1, 1))\n )\n term2 = (term2_inner.pow(2) - self._r ** 2).sum(dim=-1)\n min1 = (term1 + term2).min(dim=-1).values\n min2 = ((f_X - 1 / math.sqrt(f_X.shape[-1])).pow(2) - self._r ** 2).sum(dim=-1)\n return -torch.min(min1, min2).unsqueeze(-1)\n\n\nclass OSY(MultiObjectiveTestProblem, ConstrainedBaseTestProblem):\n r\"\"\"\n The OSY test problem from [Oszycka1995]_.\n Implementation from\n https://github.com/msu-coinlab/pymoo/blob/master/pymoo/problems/multi/osy.py\n Note that this implementation assumes minimization, so please choose negate=True.\n \"\"\"\n\n dim = 6\n num_constraints = 6\n num_objectives = 2\n _bounds = [\n (0.0, 10.0),\n (0.0, 10.0),\n (1.0, 5.0),\n (0.0, 6.0),\n (1.0, 5.0),\n (0.0, 10.0),\n ]\n _ref_point = [-75.0, 75.0]\n\n def evaluate_true(self, X: Tensor) -> Tensor:\n f1 = -(\n 25 * (X[..., 0] - 2) ** 2\n + (X[..., 1] - 2) ** 2\n + (X[..., 2] - 1) ** 2\n + (X[..., 3] - 4) ** 2\n + (X[..., 4] - 1) ** 2\n )\n f2 = (X ** 2).sum(-1)\n return torch.stack([f1, f2], dim=-1)\n\n def evaluate_slack_true(self, X: Tensor) -> Tensor:\n g1 = X[..., 0] + X[..., 1] - 2.0\n g2 = 6.0 - X[..., 0] - X[..., 1]\n g3 = 2.0 - X[..., 1] + X[..., 0]\n g4 = 2.0 - X[..., 0] + 3.0 * X[..., 1]\n g5 = 4.0 - (X[..., 2] - 3.0) ** 2 - X[..., 3]\n g6 = (X[..., 4] - 3.0) ** 2 + X[..., 5] - 4.0\n return torch.stack([g1, g2, g3, g4, g5, g6], dim=-1)\n", "#!/usr/bin/env python3\n# 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 itertools\nimport warnings\nfrom contextlib import ExitStack\nfrom unittest import mock\n\nimport torch\nfrom botorch import settings\nfrom botorch.acquisition import monte_carlo\nfrom botorch.acquisition.multi_objective import (\n MCMultiOutputObjective,\n monte_carlo as moo_monte_carlo,\n)\nfrom botorch.acquisition.objective import GenericMCObjective, MCAcquisitionObjective\nfrom botorch.acquisition.utils import (\n expand_trace_observations,\n get_acquisition_function,\n get_infeasible_cost,\n project_to_sample_points,\n project_to_target_fidelity,\n prune_inferior_points,\n)\nfrom botorch.exceptions.errors import UnsupportedError\nfrom botorch.exceptions.warnings import SamplingWarning\nfrom botorch.sampling.samplers import IIDNormalSampler, SobolQMCNormalSampler\nfrom botorch.utils.multi_objective.box_decompositions.non_dominated import (\n FastNondominatedPartitioning,\n NondominatedPartitioning,\n)\nfrom botorch.utils.testing import BotorchTestCase, MockModel, MockPosterior\nfrom torch import Tensor\n\n\nclass DummyMCObjective(MCAcquisitionObjective):\n def forward(self, samples: Tensor) -> Tensor:\n return samples.sum(-1)\n\n\nclass DummyMCMultiOutputObjective(MCMultiOutputObjective):\n def forward(self, samples: Tensor) -> Tensor:\n return samples\n\n\nclass TestGetAcquisitionFunction(BotorchTestCase):\n def setUp(self):\n super().setUp()\n self.model = mock.MagicMock()\n self.objective = DummyMCObjective()\n self.X_observed = torch.tensor([[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]])\n self.X_pending = torch.tensor([[1.0, 3.0, 4.0]])\n self.mc_samples = 250\n self.qmc = True\n self.ref_point = [0.0, 0.0]\n self.mo_objective = DummyMCMultiOutputObjective()\n self.Y = torch.tensor([[1.0, 2.0]])\n self.seed = 1\n\n @mock.patch(f\"{monte_carlo.__name__}.qExpectedImprovement\")\n def test_GetQEI(self, mock_acqf):\n self.model = MockModel(MockPosterior(mean=torch.zeros(1, 2)))\n acqf = get_acquisition_function(\n acquisition_function_name=\"qEI\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=self.seed,\n marginalize_dim=0,\n )\n self.assertTrue(acqf == mock_acqf.return_value)\n best_f = self.objective(self.model.posterior(self.X_observed).mean).max().item()\n mock_acqf.assert_called_once_with(\n model=self.model,\n best_f=best_f,\n sampler=mock.ANY,\n objective=self.objective,\n X_pending=self.X_pending,\n )\n # test batched model\n self.model = MockModel(MockPosterior(mean=torch.zeros(1, 2, 1)))\n acqf = get_acquisition_function(\n acquisition_function_name=\"qEI\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=self.seed,\n )\n self.assertTrue(acqf == mock_acqf.return_value)\n # test batched model without marginalize dim\n args, kwargs = mock_acqf.call_args\n self.assertEqual(args, ())\n sampler = kwargs[\"sampler\"]\n self.assertIsInstance(sampler, SobolQMCNormalSampler)\n self.assertEqual(sampler.sample_shape, torch.Size([self.mc_samples]))\n self.assertEqual(sampler.seed, 1)\n self.assertTrue(torch.equal(kwargs[\"X_pending\"], self.X_pending))\n\n @mock.patch(f\"{monte_carlo.__name__}.qProbabilityOfImprovement\")\n def test_GetQPI(self, mock_acqf):\n # basic test\n self.model = MockModel(MockPosterior(mean=torch.zeros(1, 2)))\n acqf = get_acquisition_function(\n acquisition_function_name=\"qPI\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=self.seed,\n )\n self.assertTrue(acqf == mock_acqf.return_value)\n best_f = self.objective(self.model.posterior(self.X_observed).mean).max().item()\n mock_acqf.assert_called_once_with(\n model=self.model,\n best_f=best_f,\n sampler=mock.ANY,\n objective=self.objective,\n X_pending=self.X_pending,\n tau=1e-3,\n )\n args, kwargs = mock_acqf.call_args\n self.assertEqual(args, ())\n sampler = kwargs[\"sampler\"]\n self.assertIsInstance(sampler, SobolQMCNormalSampler)\n self.assertEqual(sampler.sample_shape, torch.Size([self.mc_samples]))\n self.assertEqual(sampler.seed, 1)\n self.assertTrue(torch.equal(kwargs[\"X_pending\"], self.X_pending))\n # test with different tau, non-qmc\n acqf = get_acquisition_function(\n acquisition_function_name=\"qPI\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n qmc=False,\n seed=2,\n tau=1.0,\n )\n self.assertTrue(mock_acqf.call_count, 2)\n args, kwargs = mock_acqf.call_args\n self.assertEqual(args, ())\n self.assertEqual(kwargs[\"tau\"], 1.0)\n sampler = kwargs[\"sampler\"]\n self.assertIsInstance(sampler, IIDNormalSampler)\n self.assertEqual(sampler.sample_shape, torch.Size([self.mc_samples]))\n self.assertEqual(sampler.seed, 2)\n self.assertTrue(torch.equal(kwargs[\"X_pending\"], self.X_pending))\n acqf = get_acquisition_function(\n acquisition_function_name=\"qPI\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n qmc=False,\n seed=2,\n tau=1.0,\n )\n # test batched model\n self.model = MockModel(MockPosterior(mean=torch.zeros(1, 2, 1)))\n acqf = get_acquisition_function(\n acquisition_function_name=\"qPI\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=self.seed,\n )\n self.assertTrue(acqf == mock_acqf.return_value)\n\n @mock.patch(f\"{monte_carlo.__name__}.qNoisyExpectedImprovement\")\n def test_GetQNEI(self, mock_acqf):\n # basic test\n acqf = get_acquisition_function(\n acquisition_function_name=\"qNEI\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=self.seed,\n marginalize_dim=0,\n )\n self.assertTrue(acqf == mock_acqf.return_value)\n self.assertTrue(mock_acqf.call_count, 1)\n args, kwargs = mock_acqf.call_args\n self.assertEqual(args, ())\n self.assertTrue(torch.equal(kwargs[\"X_baseline\"], self.X_observed))\n self.assertTrue(torch.equal(kwargs[\"X_pending\"], self.X_pending))\n sampler = kwargs[\"sampler\"]\n self.assertIsInstance(sampler, SobolQMCNormalSampler)\n self.assertEqual(sampler.sample_shape, torch.Size([self.mc_samples]))\n self.assertEqual(sampler.seed, 1)\n self.assertEqual(kwargs[\"marginalize_dim\"], 0)\n # test with non-qmc, no X_pending\n acqf = get_acquisition_function(\n acquisition_function_name=\"qNEI\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=None,\n mc_samples=self.mc_samples,\n qmc=False,\n seed=2,\n )\n self.assertTrue(mock_acqf.call_count, 2)\n args, kwargs = mock_acqf.call_args\n self.assertEqual(args, ())\n self.assertTrue(torch.equal(kwargs[\"X_baseline\"], self.X_observed))\n self.assertEqual(kwargs[\"X_pending\"], None)\n sampler = kwargs[\"sampler\"]\n self.assertIsInstance(sampler, IIDNormalSampler)\n self.assertEqual(sampler.sample_shape, torch.Size([self.mc_samples]))\n self.assertEqual(sampler.seed, 2)\n self.assertTrue(torch.equal(kwargs[\"X_baseline\"], self.X_observed))\n\n @mock.patch(f\"{monte_carlo.__name__}.qSimpleRegret\")\n def test_GetQSR(self, mock_acqf):\n # basic test\n acqf = get_acquisition_function(\n acquisition_function_name=\"qSR\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=self.seed,\n )\n self.assertTrue(acqf == mock_acqf.return_value)\n mock_acqf.assert_called_once_with(\n model=self.model,\n sampler=mock.ANY,\n objective=self.objective,\n X_pending=self.X_pending,\n )\n args, kwargs = mock_acqf.call_args\n self.assertEqual(args, ())\n sampler = kwargs[\"sampler\"]\n self.assertIsInstance(sampler, SobolQMCNormalSampler)\n self.assertEqual(sampler.sample_shape, torch.Size([self.mc_samples]))\n self.assertEqual(sampler.seed, 1)\n self.assertTrue(torch.equal(kwargs[\"X_pending\"], self.X_pending))\n # test with non-qmc\n acqf = get_acquisition_function(\n acquisition_function_name=\"qSR\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n qmc=False,\n seed=2,\n )\n self.assertTrue(mock_acqf.call_count, 2)\n args, kwargs = mock_acqf.call_args\n self.assertEqual(args, ())\n sampler = kwargs[\"sampler\"]\n self.assertIsInstance(sampler, IIDNormalSampler)\n self.assertEqual(sampler.sample_shape, torch.Size([self.mc_samples]))\n self.assertEqual(sampler.seed, 2)\n self.assertTrue(torch.equal(kwargs[\"X_pending\"], self.X_pending))\n\n @mock.patch(f\"{monte_carlo.__name__}.qUpperConfidenceBound\")\n def test_GetQUCB(self, mock_acqf):\n # make sure beta is specified\n with self.assertRaises(ValueError):\n acqf = get_acquisition_function(\n acquisition_function_name=\"qUCB\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=self.seed,\n )\n acqf = get_acquisition_function(\n acquisition_function_name=\"qUCB\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=self.seed,\n beta=0.3,\n )\n self.assertTrue(acqf == mock_acqf.return_value)\n mock_acqf.assert_called_once_with(\n model=self.model,\n beta=0.3,\n sampler=mock.ANY,\n objective=self.objective,\n X_pending=self.X_pending,\n )\n args, kwargs = mock_acqf.call_args\n self.assertEqual(args, ())\n sampler = kwargs[\"sampler\"]\n self.assertIsInstance(sampler, SobolQMCNormalSampler)\n self.assertEqual(sampler.sample_shape, torch.Size([self.mc_samples]))\n self.assertEqual(sampler.seed, 1)\n self.assertTrue(torch.equal(kwargs[\"X_pending\"], self.X_pending))\n # test with different tau, non-qmc\n acqf = get_acquisition_function(\n acquisition_function_name=\"qUCB\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n qmc=False,\n seed=2,\n beta=0.2,\n )\n self.assertTrue(mock_acqf.call_count, 2)\n args, kwargs = mock_acqf.call_args\n self.assertEqual(args, ())\n self.assertEqual(kwargs[\"beta\"], 0.2)\n sampler = kwargs[\"sampler\"]\n self.assertIsInstance(sampler, IIDNormalSampler)\n self.assertEqual(sampler.sample_shape, torch.Size([self.mc_samples]))\n self.assertEqual(sampler.seed, 2)\n self.assertTrue(torch.equal(kwargs[\"X_pending\"], self.X_pending))\n\n @mock.patch(f\"{moo_monte_carlo.__name__}.qExpectedHypervolumeImprovement\")\n def test_GetQEHVI(self, mock_acqf):\n # make sure ref_point is specified\n with self.assertRaises(ValueError):\n acqf = get_acquisition_function(\n acquisition_function_name=\"qEHVI\",\n model=self.model,\n objective=self.mo_objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=self.seed,\n Y=self.Y,\n )\n # make sure Y is specified\n with self.assertRaises(ValueError):\n acqf = get_acquisition_function(\n acquisition_function_name=\"qEHVI\",\n model=self.model,\n objective=self.mo_objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=self.seed,\n ref_point=self.ref_point,\n )\n acqf = get_acquisition_function(\n acquisition_function_name=\"qEHVI\",\n model=self.model,\n objective=self.mo_objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=self.seed,\n ref_point=self.ref_point,\n Y=self.Y,\n )\n self.assertTrue(acqf == mock_acqf.return_value)\n mock_acqf.assert_called_once_with(\n constraints=None,\n model=self.model,\n objective=self.mo_objective,\n ref_point=self.ref_point,\n partitioning=mock.ANY,\n sampler=mock.ANY,\n X_pending=self.X_pending,\n )\n args, kwargs = mock_acqf.call_args\n self.assertEqual(args, ())\n sampler = kwargs[\"sampler\"]\n self.assertIsInstance(sampler, SobolQMCNormalSampler)\n self.assertEqual(sampler.sample_shape, torch.Size([self.mc_samples]))\n self.assertEqual(sampler.seed, 1)\n # test with non-qmc\n acqf = get_acquisition_function(\n acquisition_function_name=\"qEHVI\",\n model=self.model,\n objective=self.mo_objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=2,\n qmc=False,\n ref_point=self.ref_point,\n Y=self.Y,\n )\n self.assertTrue(mock_acqf.call_count, 2)\n args, kwargs = mock_acqf.call_args\n self.assertEqual(args, ())\n self.assertEqual(kwargs[\"ref_point\"], self.ref_point)\n sampler = kwargs[\"sampler\"]\n self.assertIsInstance(sampler, IIDNormalSampler)\n self.assertIsInstance(kwargs[\"objective\"], DummyMCMultiOutputObjective)\n partitioning = kwargs[\"partitioning\"]\n self.assertIsInstance(partitioning, FastNondominatedPartitioning)\n self.assertEqual(sampler.sample_shape, torch.Size([self.mc_samples]))\n self.assertEqual(sampler.seed, 2)\n # test that approximate partitioning is used when alpha > 0\n # test with non-qmc\n acqf = get_acquisition_function(\n acquisition_function_name=\"qEHVI\",\n model=self.model,\n objective=self.mo_objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=2,\n qmc=False,\n ref_point=self.ref_point,\n Y=self.Y,\n alpha=0.1,\n )\n _, kwargs = mock_acqf.call_args\n partitioning = kwargs[\"partitioning\"]\n self.assertIsInstance(partitioning, NondominatedPartitioning)\n self.assertEqual(partitioning.alpha, 0.1)\n # test constraints\n acqf = get_acquisition_function(\n acquisition_function_name=\"qEHVI\",\n model=self.model,\n objective=self.mo_objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n constraints=[lambda Y: Y[..., -1]],\n seed=2,\n qmc=False,\n ref_point=self.ref_point,\n Y=self.Y,\n )\n _, kwargs = mock_acqf.call_args\n partitioning = kwargs[\"partitioning\"]\n self.assertEqual(partitioning.pareto_Y.shape[0], 0)\n\n @mock.patch(f\"{moo_monte_carlo.__name__}.qNoisyExpectedHypervolumeImprovement\")\n def test_GetQNEHVI(self, mock_acqf):\n # make sure ref_point is specified\n with self.assertRaises(ValueError):\n acqf = get_acquisition_function(\n acquisition_function_name=\"qNEHVI\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=self.seed,\n )\n acqf = get_acquisition_function(\n acquisition_function_name=\"qNEHVI\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=self.seed,\n ref_point=self.ref_point,\n )\n self.assertTrue(acqf == mock_acqf.return_value)\n mock_acqf.assert_called_once_with(\n constraints=None,\n model=self.model,\n X_baseline=self.X_observed,\n objective=self.objective,\n ref_point=self.ref_point,\n sampler=mock.ANY,\n prune_baseline=True,\n alpha=0.0,\n X_pending=self.X_pending,\n marginalize_dim=None,\n )\n args, kwargs = mock_acqf.call_args\n self.assertEqual(args, ())\n sampler = kwargs[\"sampler\"]\n self.assertIsInstance(sampler, SobolQMCNormalSampler)\n self.assertEqual(sampler.sample_shape, torch.Size([self.mc_samples]))\n self.assertEqual(sampler.seed, 1)\n # test with non-qmc\n acqf = get_acquisition_function(\n acquisition_function_name=\"qNEHVI\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=2,\n qmc=False,\n ref_point=self.ref_point,\n )\n self.assertTrue(mock_acqf.call_count, 2)\n args, kwargs = mock_acqf.call_args\n self.assertEqual(args, ())\n self.assertEqual(kwargs[\"ref_point\"], self.ref_point)\n sampler = kwargs[\"sampler\"]\n self.assertIsInstance(sampler, IIDNormalSampler)\n ref_point = kwargs[\"ref_point\"]\n self.assertEqual(ref_point, self.ref_point)\n\n self.assertEqual(sampler.sample_shape, torch.Size([self.mc_samples]))\n self.assertEqual(sampler.seed, 2)\n\n # test passing alpha\n acqf = get_acquisition_function(\n acquisition_function_name=\"qNEHVI\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=2,\n qmc=False,\n ref_point=self.ref_point,\n alpha=0.01,\n )\n self.assertTrue(mock_acqf.call_count, 3)\n args, kwargs = mock_acqf.call_args\n self.assertEqual(kwargs[\"alpha\"], 0.01)\n\n def test_GetUnknownAcquisitionFunction(self):\n with self.assertRaises(NotImplementedError):\n get_acquisition_function(\n acquisition_function_name=\"foo\",\n model=self.model,\n objective=self.objective,\n X_observed=self.X_observed,\n X_pending=self.X_pending,\n mc_samples=self.mc_samples,\n seed=self.seed,\n )\n\n\nclass TestGetInfeasibleCost(BotorchTestCase):\n def test_get_infeasible_cost(self):\n for dtype in (torch.float, torch.double):\n X = torch.zeros(5, 1, device=self.device, dtype=dtype)\n means = torch.tensor(\n [1.0, 2.0, 3.0, 4.0, 5.0], device=self.device, dtype=dtype\n )\n variances = torch.tensor(\n [0.09, 0.25, 0.36, 0.25, 0.09], device=self.device, dtype=dtype\n )\n mm = MockModel(MockPosterior(mean=means, variance=variances))\n # means - 6 * std = [-0.8, -1, -0.6, 1, 3.2]. After applying the\n # objective, the minimum becomes -6.0, so 6.0 should be returned.\n M = get_infeasible_cost(\n X=X, model=mm, objective=lambda Y: Y.squeeze(-1) - 5.0\n )\n self.assertEqual(M, 6.0)\n # test default objective (squeeze last dim)\n M2 = get_infeasible_cost(X=X, model=mm)\n self.assertEqual(M2, 1.0)\n\n\nclass TestPruneInferiorPoints(BotorchTestCase):\n def test_prune_inferior_points(self):\n for dtype in (torch.float, torch.double):\n X = torch.rand(3, 2, device=self.device, dtype=dtype)\n # the event shape is `q x t` = 3 x 1\n samples = torch.tensor(\n [[-1.0], [0.0], [1.0]], device=self.device, dtype=dtype\n )\n mm = MockModel(MockPosterior(samples=samples))\n # test that a batched X raises errors\n with self.assertRaises(UnsupportedError):\n prune_inferior_points(model=mm, X=X.expand(2, 3, 2))\n # test marginalize_dim\n mm2 = MockModel(MockPosterior(samples=samples.expand(2, 3, 1)))\n X_pruned = prune_inferior_points(model=mm2, X=X, marginalize_dim=-3)\n with self.assertRaises(UnsupportedError):\n # test error raised when marginalize_dim is not specified with\n # a batch model\n prune_inferior_points(model=mm2, X=X)\n self.assertTrue(torch.equal(X_pruned, X[[-1]]))\n # test that a batched model raises errors when there are multiple batch dims\n mm2 = MockModel(MockPosterior(samples=samples.expand(1, 2, 3, 1)))\n with self.assertRaises(UnsupportedError):\n prune_inferior_points(model=mm2, X=X)\n # test that invalid max_frac is checked properly\n with self.assertRaises(ValueError):\n prune_inferior_points(model=mm, X=X, max_frac=1.1)\n # test basic behaviour\n X_pruned = prune_inferior_points(model=mm, X=X)\n self.assertTrue(torch.equal(X_pruned, X[[-1]]))\n # test custom objective\n neg_id_obj = GenericMCObjective(lambda Y, X: -(Y.squeeze(-1)))\n X_pruned = prune_inferior_points(model=mm, X=X, objective=neg_id_obj)\n self.assertTrue(torch.equal(X_pruned, X[[0]]))\n # test non-repeated samples (requires mocking out MockPosterior's rsample)\n samples = torch.tensor(\n [[[3.0], [0.0], [0.0]], [[0.0], [2.0], [0.0]], [[0.0], [0.0], [1.0]]],\n device=self.device,\n dtype=dtype,\n )\n with mock.patch.object(MockPosterior, \"rsample\", return_value=samples):\n mm = MockModel(MockPosterior(samples=samples))\n X_pruned = prune_inferior_points(model=mm, X=X)\n self.assertTrue(torch.equal(X_pruned, X))\n # test max_frac limiting\n with mock.patch.object(MockPosterior, \"rsample\", return_value=samples):\n mm = MockModel(MockPosterior(samples=samples))\n X_pruned = prune_inferior_points(model=mm, X=X, max_frac=2 / 3)\n if self.device == torch.device(\"cuda\"):\n # sorting has different order on cuda\n self.assertTrue(torch.equal(X_pruned, torch.stack([X[2], X[1]], dim=0)))\n else:\n self.assertTrue(torch.equal(X_pruned, X[:2]))\n # test that zero-probability is in fact pruned\n samples[2, 0, 0] = 10\n with mock.patch.object(MockPosterior, \"rsample\", return_value=samples):\n mm = MockModel(MockPosterior(samples=samples))\n X_pruned = prune_inferior_points(model=mm, X=X)\n self.assertTrue(torch.equal(X_pruned, X[:2]))\n # test high-dim sampling\n with ExitStack() as es:\n mock_event_shape = es.enter_context(\n mock.patch(\n \"botorch.utils.testing.MockPosterior.base_sample_shape\",\n new_callable=mock.PropertyMock,\n )\n )\n mock_event_shape.return_value = torch.Size(\n [1, 1, torch.quasirandom.SobolEngine.MAXDIM + 1]\n )\n es.enter_context(\n mock.patch.object(MockPosterior, \"rsample\", return_value=samples)\n )\n mm = MockModel(MockPosterior(samples=samples))\n with warnings.catch_warnings(record=True) as ws, settings.debug(True):\n prune_inferior_points(model=mm, X=X)\n self.assertTrue(issubclass(ws[-1].category, SamplingWarning))\n\n\nclass TestFidelityUtils(BotorchTestCase):\n def test_project_to_target_fidelity(self):\n for batch_shape, dtype in itertools.product(\n ([], [2]), (torch.float, torch.double)\n ):\n X = torch.rand(*batch_shape, 3, 4, device=self.device, dtype=dtype)\n # test default behavior\n X_proj = project_to_target_fidelity(X)\n ones = torch.ones(*X.shape[:-1], 1, device=self.device, dtype=dtype)\n self.assertTrue(torch.equal(X_proj[..., :, [-1]], ones))\n self.assertTrue(torch.equal(X_proj[..., :-1], X[..., :-1]))\n # test custom target fidelity\n target_fids = {2: 0.5}\n X_proj = project_to_target_fidelity(X, target_fidelities=target_fids)\n self.assertTrue(torch.equal(X_proj[..., :, [2]], 0.5 * ones))\n # test multiple target fidelities\n target_fids = {2: 0.5, 0: 0.1}\n X_proj = project_to_target_fidelity(X, target_fidelities=target_fids)\n self.assertTrue(torch.equal(X_proj[..., :, [0]], 0.1 * ones))\n self.assertTrue(torch.equal(X_proj[..., :, [2]], 0.5 * ones))\n # test gradients\n X.requires_grad_(True)\n X_proj = project_to_target_fidelity(X, target_fidelities=target_fids)\n out = (X_proj ** 2).sum()\n out.backward()\n self.assertTrue(torch.all(X.grad[..., [0, 2]] == 0))\n self.assertTrue(torch.equal(X.grad[..., [1, 3]], 2 * X[..., [1, 3]]))\n\n def test_expand_trace_observations(self):\n for batch_shape, dtype in itertools.product(\n ([], [2]), (torch.float, torch.double)\n ):\n q, d = 3, 4\n X = torch.rand(*batch_shape, q, d, device=self.device, dtype=dtype)\n # test nullop behavior\n self.assertTrue(torch.equal(expand_trace_observations(X), X))\n self.assertTrue(\n torch.equal(expand_trace_observations(X, fidelity_dims=[1]), X)\n )\n # test default behavior\n num_tr = 2\n X_expanded = expand_trace_observations(X, num_trace_obs=num_tr)\n self.assertEqual(\n X_expanded.shape, torch.Size(batch_shape + [q * (1 + num_tr), d])\n )\n for i in range(num_tr):\n X_sub = X_expanded[..., q * i : q * (i + 1), :]\n self.assertTrue(torch.equal(X_sub[..., :-1], X[..., :-1]))\n X_sub_expected = (1 - i / (num_tr + 1)) * X[..., :q, -1]\n self.assertTrue(torch.equal(X_sub[..., -1], X_sub_expected))\n # test custom fidelity dims\n fdims = [0, 2]\n num_tr = 3\n X_expanded = expand_trace_observations(\n X, fidelity_dims=fdims, num_trace_obs=num_tr\n )\n self.assertEqual(\n X_expanded.shape, torch.Size(batch_shape + [q * (1 + num_tr), d])\n )\n for j, i in itertools.product([1, 3], range(num_tr)):\n X_sub = X_expanded[..., q * i : q * (i + 1), j]\n self.assertTrue(torch.equal(X_sub, X[..., j]))\n for j, i in itertools.product(fdims, range(num_tr)):\n X_sub = X_expanded[..., q * i : q * (i + 1), j]\n X_sub_expected = (1 - i / (1 + num_tr)) * X[..., :q, j]\n self.assertTrue(torch.equal(X_sub, X_sub_expected))\n # test gradients\n num_tr = 2\n fdims = [1]\n X.requires_grad_(True)\n X_expanded = expand_trace_observations(\n X, fidelity_dims=fdims, num_trace_obs=num_tr\n )\n out = X_expanded.sum()\n out.backward()\n grad_exp = torch.full_like(X, 1 + num_tr)\n grad_exp[..., fdims] = 1 + sum(\n (i + 1) / (num_tr + 1) for i in range(num_tr)\n )\n self.assertTrue(torch.allclose(X.grad, grad_exp))\n\n def test_project_to_sample_points(self):\n for batch_shape, dtype in itertools.product(\n ([], [2]), (torch.float, torch.double)\n ):\n q, d, p, d_prime = 1, 12, 7, 4\n X = torch.rand(*batch_shape, q, d, device=self.device, dtype=dtype)\n sample_points = torch.rand(p, d_prime, device=self.device, dtype=dtype)\n X_augmented = project_to_sample_points(X=X, sample_points=sample_points)\n self.assertEqual(X_augmented.shape, torch.Size(batch_shape + [p, d]))\n if batch_shape == [2]:\n self.assertTrue(\n torch.allclose(X_augmented[0, :, -d_prime:], sample_points)\n )\n else:\n self.assertTrue(\n torch.allclose(X_augmented[:, -d_prime:], sample_points)\n )\n", "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\nimport torch\nfrom botorch.exceptions import UnsupportedError\nfrom botorch.models import (\n FixedNoiseGP,\n HeteroskedasticSingleTaskGP,\n ModelListGP,\n SingleTaskGP,\n SingleTaskMultiFidelityGP,\n)\nfrom botorch.models.converter import (\n batched_to_model_list,\n model_list_to_batched,\n batched_multi_output_to_single_output,\n)\nfrom botorch.models.transforms.input import Normalize\nfrom botorch.models.transforms.outcome import Standardize\nfrom botorch.utils.testing import BotorchTestCase\nfrom gpytorch.likelihoods import GaussianLikelihood\n\nfrom .test_gpytorch import SimpleGPyTorchModel\n\n\nclass TestConverters(BotorchTestCase):\n def test_batched_to_model_list(self):\n for dtype in (torch.float, torch.double):\n # test SingleTaskGP\n train_X = torch.rand(10, 2, device=self.device, dtype=dtype)\n train_Y1 = train_X.sum(dim=-1)\n train_Y2 = train_X[:, 0] - train_X[:, 1]\n train_Y = torch.stack([train_Y1, train_Y2], dim=-1)\n batch_gp = SingleTaskGP(train_X, train_Y)\n list_gp = batched_to_model_list(batch_gp)\n self.assertIsInstance(list_gp, ModelListGP)\n # test FixedNoiseGP\n batch_gp = FixedNoiseGP(train_X, train_Y, torch.rand_like(train_Y))\n list_gp = batched_to_model_list(batch_gp)\n self.assertIsInstance(list_gp, ModelListGP)\n # test SingleTaskMultiFidelityGP\n for lin_trunc in (False, True):\n batch_gp = SingleTaskMultiFidelityGP(\n train_X, train_Y, iteration_fidelity=1, linear_truncated=lin_trunc\n )\n list_gp = batched_to_model_list(batch_gp)\n self.assertIsInstance(list_gp, ModelListGP)\n # test HeteroskedasticSingleTaskGP\n batch_gp = HeteroskedasticSingleTaskGP(\n train_X, train_Y, torch.rand_like(train_Y)\n )\n with self.assertRaises(NotImplementedError):\n batched_to_model_list(batch_gp)\n # test input transform\n input_tf = Normalize(\n d=2,\n bounds=torch.tensor(\n [[0.0, 0.0], [1.0, 1.0]], device=self.device, dtype=dtype\n ),\n )\n batch_gp = SingleTaskGP(train_X, train_Y, input_transform=input_tf)\n list_gp = batched_to_model_list(batch_gp)\n for m in list_gp.models:\n self.assertIsInstance(m.input_transform, Normalize)\n self.assertTrue(torch.equal(m.input_transform.bounds, input_tf.bounds))\n\n def test_model_list_to_batched(self):\n for dtype in (torch.float, torch.double):\n # basic test\n train_X = torch.rand(10, 2, device=self.device, dtype=dtype)\n train_Y1 = train_X.sum(dim=-1, keepdim=True)\n train_Y2 = (train_X[:, 0] - train_X[:, 1]).unsqueeze(-1)\n gp1 = SingleTaskGP(train_X, train_Y1)\n gp2 = SingleTaskGP(train_X, train_Y2)\n list_gp = ModelListGP(gp1, gp2)\n batch_gp = model_list_to_batched(list_gp)\n self.assertIsInstance(batch_gp, SingleTaskGP)\n # test degenerate (single model)\n batch_gp = model_list_to_batched(ModelListGP(gp1))\n self.assertEqual(batch_gp._num_outputs, 1)\n # test different model classes\n gp2 = FixedNoiseGP(train_X, train_Y1, torch.ones_like(train_Y1))\n with self.assertRaises(UnsupportedError):\n model_list_to_batched(ModelListGP(gp1, gp2))\n # test non-batched models\n gp1_ = SimpleGPyTorchModel(train_X, train_Y1)\n gp2_ = SimpleGPyTorchModel(train_X, train_Y2)\n with self.assertRaises(UnsupportedError):\n model_list_to_batched(ModelListGP(gp1_, gp2_))\n # test list of multi-output models\n train_Y = torch.cat([train_Y1, train_Y2], dim=-1)\n gp2 = SingleTaskGP(train_X, train_Y)\n with self.assertRaises(UnsupportedError):\n model_list_to_batched(ModelListGP(gp1, gp2))\n # test different training inputs\n gp2 = SingleTaskGP(2 * train_X, train_Y2)\n with self.assertRaises(UnsupportedError):\n model_list_to_batched(ModelListGP(gp1, gp2))\n # check scalar agreement\n gp2 = SingleTaskGP(train_X, train_Y2)\n gp2.likelihood.noise_covar.noise_prior.rate.fill_(1.0)\n with self.assertRaises(UnsupportedError):\n model_list_to_batched(ModelListGP(gp1, gp2))\n # check tensor shape agreement\n gp2 = SingleTaskGP(train_X, train_Y2)\n gp2.covar_module.raw_outputscale = torch.nn.Parameter(\n torch.tensor([0.0], device=self.device, dtype=dtype)\n )\n with self.assertRaises(UnsupportedError):\n model_list_to_batched(ModelListGP(gp1, gp2))\n # test HeteroskedasticSingleTaskGP\n gp2 = HeteroskedasticSingleTaskGP(\n train_X, train_Y1, torch.ones_like(train_Y1)\n )\n with self.assertRaises(NotImplementedError):\n model_list_to_batched(ModelListGP(gp2))\n # test custom likelihood\n gp2 = SingleTaskGP(train_X, train_Y2, likelihood=GaussianLikelihood())\n with self.assertRaises(NotImplementedError):\n model_list_to_batched(ModelListGP(gp2))\n # test FixedNoiseGP\n train_X = torch.rand(10, 2, device=self.device, dtype=dtype)\n train_Y1 = train_X.sum(dim=-1, keepdim=True)\n train_Y2 = (train_X[:, 0] - train_X[:, 1]).unsqueeze(-1)\n gp1_ = FixedNoiseGP(train_X, train_Y1, torch.rand_like(train_Y1))\n gp2_ = FixedNoiseGP(train_X, train_Y2, torch.rand_like(train_Y2))\n list_gp = ModelListGP(gp1_, gp2_)\n batch_gp = model_list_to_batched(list_gp)\n # test SingleTaskMultiFidelityGP\n gp1_ = SingleTaskMultiFidelityGP(train_X, train_Y1, iteration_fidelity=1)\n gp2_ = SingleTaskMultiFidelityGP(train_X, train_Y2, iteration_fidelity=1)\n list_gp = ModelListGP(gp1_, gp2_)\n batch_gp = model_list_to_batched(list_gp)\n gp2_ = SingleTaskMultiFidelityGP(train_X, train_Y2, iteration_fidelity=2)\n list_gp = ModelListGP(gp1_, gp2_)\n with self.assertRaises(UnsupportedError):\n model_list_to_batched(list_gp)\n # test input transform\n input_tf = Normalize(\n d=2,\n bounds=torch.tensor(\n [[0.0, 0.0], [1.0, 1.0]], device=self.device, dtype=dtype\n ),\n )\n gp1_ = SingleTaskGP(train_X, train_Y1, input_transform=input_tf)\n gp2_ = SingleTaskGP(train_X, train_Y2, input_transform=input_tf)\n list_gp = ModelListGP(gp1_, gp2_)\n batch_gp = model_list_to_batched(list_gp)\n self.assertIsInstance(batch_gp.input_transform, Normalize)\n self.assertTrue(\n torch.equal(batch_gp.input_transform.bounds, input_tf.bounds)\n )\n # test different input transforms\n input_tf2 = Normalize(\n d=2,\n bounds=torch.tensor(\n [[-1.0, -1.0], [1.0, 1.0]], device=self.device, dtype=dtype\n ),\n )\n gp1_ = SingleTaskGP(train_X, train_Y1, input_transform=input_tf)\n gp2_ = SingleTaskGP(train_X, train_Y2, input_transform=input_tf2)\n list_gp = ModelListGP(gp1_, gp2_)\n with self.assertRaises(UnsupportedError):\n model_list_to_batched(list_gp)\n\n # test batched input transform\n input_tf2 = Normalize(\n d=2,\n bounds=torch.tensor(\n [[-1.0, -1.0], [1.0, 1.0]], device=self.device, dtype=dtype\n ),\n batch_shape=torch.Size([3]),\n )\n gp1_ = SingleTaskGP(train_X, train_Y1, input_transform=input_tf2)\n gp2_ = SingleTaskGP(train_X, train_Y2, input_transform=input_tf2)\n list_gp = ModelListGP(gp1_, gp2_)\n with self.assertRaises(UnsupportedError):\n model_list_to_batched(list_gp)\n\n def test_roundtrip(self):\n for dtype in (torch.float, torch.double):\n train_X = torch.rand(10, 2, device=self.device, dtype=dtype)\n train_Y1 = train_X.sum(dim=-1)\n train_Y2 = train_X[:, 0] - train_X[:, 1]\n train_Y = torch.stack([train_Y1, train_Y2], dim=-1)\n # SingleTaskGP\n batch_gp = SingleTaskGP(train_X, train_Y)\n list_gp = batched_to_model_list(batch_gp)\n batch_gp_recov = model_list_to_batched(list_gp)\n sd_orig = batch_gp.state_dict()\n sd_recov = batch_gp_recov.state_dict()\n self.assertTrue(set(sd_orig) == set(sd_recov))\n self.assertTrue(all(torch.equal(sd_orig[k], sd_recov[k]) for k in sd_orig))\n # FixedNoiseGP\n batch_gp = FixedNoiseGP(train_X, train_Y, torch.rand_like(train_Y))\n list_gp = batched_to_model_list(batch_gp)\n batch_gp_recov = model_list_to_batched(list_gp)\n sd_orig = batch_gp.state_dict()\n sd_recov = batch_gp_recov.state_dict()\n self.assertTrue(set(sd_orig) == set(sd_recov))\n self.assertTrue(all(torch.equal(sd_orig[k], sd_recov[k]) for k in sd_orig))\n # SingleTaskMultiFidelityGP\n for lin_trunc in (False, True):\n batch_gp = SingleTaskMultiFidelityGP(\n train_X, train_Y, iteration_fidelity=1, linear_truncated=lin_trunc\n )\n list_gp = batched_to_model_list(batch_gp)\n batch_gp_recov = model_list_to_batched(list_gp)\n sd_orig = batch_gp.state_dict()\n sd_recov = batch_gp_recov.state_dict()\n self.assertTrue(set(sd_orig) == set(sd_recov))\n self.assertTrue(\n all(torch.equal(sd_orig[k], sd_recov[k]) for k in sd_orig)\n )\n\n def test_batched_multi_output_to_single_output(self):\n for dtype in (torch.float, torch.double):\n # basic test\n train_X = torch.rand(10, 2, device=self.device, dtype=dtype)\n train_Y = torch.stack(\n [\n train_X.sum(dim=-1),\n (train_X[:, 0] - train_X[:, 1]),\n ],\n dim=1,\n )\n batched_mo_model = SingleTaskGP(train_X, train_Y)\n batched_so_model = batched_multi_output_to_single_output(batched_mo_model)\n self.assertIsInstance(batched_so_model, SingleTaskGP)\n self.assertEqual(batched_so_model.num_outputs, 1)\n # test non-batched models\n non_batch_model = SimpleGPyTorchModel(train_X, train_Y[:, :1])\n with self.assertRaises(UnsupportedError):\n batched_multi_output_to_single_output(non_batch_model)\n gp2 = HeteroskedasticSingleTaskGP(\n train_X, train_Y, torch.ones_like(train_Y)\n )\n with self.assertRaises(NotImplementedError):\n batched_multi_output_to_single_output(gp2)\n # test custom likelihood\n gp2 = SingleTaskGP(train_X, train_Y, likelihood=GaussianLikelihood())\n with self.assertRaises(NotImplementedError):\n batched_multi_output_to_single_output(gp2)\n # test FixedNoiseGP\n train_X = torch.rand(10, 2, device=self.device, dtype=dtype)\n batched_mo_model = FixedNoiseGP(train_X, train_Y, torch.rand_like(train_Y))\n batched_so_model = batched_multi_output_to_single_output(batched_mo_model)\n self.assertIsInstance(batched_so_model, FixedNoiseGP)\n self.assertEqual(batched_so_model.num_outputs, 1)\n # test SingleTaskMultiFidelityGP\n batched_mo_model = SingleTaskMultiFidelityGP(\n train_X, train_Y, iteration_fidelity=1\n )\n batched_so_model = batched_multi_output_to_single_output(batched_mo_model)\n self.assertIsInstance(batched_so_model, SingleTaskMultiFidelityGP)\n self.assertEqual(batched_so_model.num_outputs, 1)\n # test input transform\n input_tf = Normalize(\n d=2,\n bounds=torch.tensor(\n [[0.0, 0.0], [1.0, 1.0]], device=self.device, dtype=dtype\n ),\n )\n batched_mo_model = SingleTaskGP(train_X, train_Y, input_transform=input_tf)\n batch_so_model = batched_multi_output_to_single_output(batched_mo_model)\n self.assertIsInstance(batch_so_model.input_transform, Normalize)\n self.assertTrue(\n torch.equal(batch_so_model.input_transform.bounds, input_tf.bounds)\n )\n\n # test batched input transform\n input_tf2 = Normalize(\n d=2,\n bounds=torch.tensor(\n [[-1.0, -1.0], [1.0, 1.0]], device=self.device, dtype=dtype\n ),\n batch_shape=torch.Size([2]),\n )\n batched_mo_model = SingleTaskGP(train_X, train_Y, input_transform=input_tf2)\n batched_so_model = batched_multi_output_to_single_output(batched_mo_model)\n self.assertIsInstance(batch_so_model.input_transform, Normalize)\n self.assertTrue(\n torch.equal(batch_so_model.input_transform.bounds, input_tf.bounds)\n )\n # test outcome transform\n batched_mo_model = SingleTaskGP(\n train_X, train_Y, outcome_transform=Standardize(m=2)\n )\n with self.assertRaises(NotImplementedError):\n batched_multi_output_to_single_output(batched_mo_model)\n" ]
[ [ "torch.linspace", "torch.Size", "scipy.special.gamma", "torch.cat", "torch.sin", "torch.min", "torch.eye", "torch.arange", "torch.tensor", "torch.exp", "torch.split", "torch.stack", "torch.cos" ], [ "torch.all", "torch.Size", "torch.ones", "torch.zeros", "torch.allclose", "torch.equal", "torch.tensor", "torch.rand", "torch.full_like", "torch.device", "torch.stack" ], [ "torch.Size", "torch.rand_like", "torch.cat", "torch.equal", "torch.tensor", "torch.rand", "torch.stack", "torch.ones_like" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mmoussallam/bird
[ "6a362de7d3a52dfcddaed13e8c736d039b03fbb4" ]
[ "bird/tests/test_mdct_tools.py" ]
[ "# Authors: Alexandre Gramfort <[email protected]>\n# Manuel Moussallam <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport numpy as np\nfrom numpy.testing import assert_array_almost_equal\nfrom bird.mdct_tools import mdct, imdct\n\n\ndef test_mdct():\n \"Test mdct and imdct tight frame property\"\n sfreq = 1000. # Hz\n f = 7. # Hz\n x1 = np.sin(2. * np.pi * f * np.arange(128, dtype=float) / sfreq)\n x2 = np.sin(2. * np.pi * f * np.arange(512, dtype=float) / sfreq)\n\n rng = np.random.RandomState(42)\n x3 = rng.standard_normal(x1.shape)\n\n wsize = 32\n\n for x in [x1, x2, x3]:\n X = mdct(x, wsize)\n xp = imdct(X, wsize)\n\n assert_array_almost_equal(x, xp, decimal=12)\n" ]
[ [ "numpy.arange", "numpy.random.RandomState", "numpy.testing.assert_array_almost_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
anicokatz/PyMultiNestPlus
[ "d223ac90bef7c1b61e337b70c2bdb41ed46cb2b7" ]
[ "example_workspace/inverted_hierarchy/model.py" ]
[ "# INVERTED HIERARCHY\nimport prior_handler as phandle\nimport math\nimport numpy as np\nimport os\ncwd = os.path.dirname(os.path.realpath(__file__))\nprint(cwd)\n\nprior_handler = phandle.PriorHandler(cwd)\ncon = prior_handler.c\nn_pars = prior_handler.n_pars\n\ndef prior(cube, n_dims, n_pars):\n return prior_handler.scale(cube)\n\ndef observables(pars):\n # get the nuisances from the par-based seed\n nui = prior_handler.get_nui(pars)\n \n # get mt value\n c13 = math.cos(pars[4])\n \n a1 = abs(math.cos(pars[3]*c13))**2\n a2 = abs(math.sin(pars[3]*c13))**2\n a3 = abs(math.sin(pars[4]))**2\n \n dm2 = pars[5]\n Dm2 = pars[6]\n \n m3 = pars[0]\n m2 = math.sqrt(max([0, m3**2 + Dm2 + dm2/2]))\n m1 = math.sqrt(max([0, m3**2 + Dm2 - dm2/2]))\n \n # with pars, nui, con, start calculation:\n return [abs(a1*m1*np.exp(-1j*pars[1]) + a2*m2*np.exp(-1j*pars[2]) + a3*m3 )]\n\ndef loglikelihood(pars, n_dims, n_pars):\n mval = observables(pars)\n mval = mval[0]\n loglikelihood = (-((mval-con[0])**2)/(2*(con[1]**2)))\n return loglikelihood" ]
[ [ "numpy.exp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
elke0011/OpenFlightSim
[ "1e28c54864ffd188f27425c8a71cce8b70a4bd7f" ]
[ "Utilities/JSBSimWriteXml.py" ]
[ "\"\"\"\nUniversity of Minnesota\nAerospace Engineering and Mechanics - UAV Lab\nCopyright 2019 Regents of the University of Minnesota.\nSee: LICENSE.md for complete license details.\n\nAuthor: Louis Mueller, Chris Regan\n\"\"\"\n\nimport os.path\nfrom xml.etree import ElementTree as ET\n\nimport numpy as np\n\n\nft2m = 0.3048\npsf2pa = 47.88026\n\n#%% Save the XML in pretty-ish print\ndef SaveXml(elem, saveFile):\n from xml.dom import minidom\n\n uglyXml = ET.tostring(elem, 'utf-8')\n prettyXml = minidom.parseString(uglyXml).toprettyxml(indent=' ', newl = '\\r\\n')\n\n os.makedirs(os.path.dirname(saveFile), exist_ok=True)\n with open(saveFile, 'w') as saveXML:\n saveXML.write(prettyXml)\n\n saveXML.close()\n\n#%% Function\n\ndef Aircraft(oFdm, convertFdm2Jsb, saveJsbPath, aircraftName):\n\n\n # Start JSB-ML with etree\n elemAircraft = ET.Element('fdm_config', version = '2.0', release = 'Alpha')\n\n\n # Create the Pilot input as a seperate XML file, direct the Aircraft definition to use\n fcsFile = 'FlightControl.xml'\n ET.SubElement(elemAircraft, 'flight_control', file = fcsFile)\n\n SaveXml(FlightControl(oFdm), os.path.join(saveJsbPath, fcsFile))\n\n\n # Effectors as a seperate XML file, direct the Aircraft definition to use\n effFile = 'Effectors.xml'\n ET.SubElement(elemAircraft, 'system', file = effFile)\n\n SaveXml(Effectors(oFdm), os.path.join(saveJsbPath, effFile))\n\n\n # Create the Mass Properties input as a seperate XML file, direct the Aircraft definition to use\n massFile = 'Mass.xml'\n ET.SubElement(elemAircraft, 'mass_balance', file = massFile)\n\n SaveXml(MassBalance(oFdm), os.path.join(saveJsbPath, massFile))\n\n\n # Create the Gear input as a seperate XML file, direct the Aircraft definition to use\n gearFile = 'Gear.xml'\n ET.SubElement(elemAircraft, 'ground_reactions', file = gearFile)\n\n SaveXml(GroundReactions(oFdm), os.path.join(saveJsbPath, gearFile))\n\n\n # Create the Propulsion input as a seperate XML file, direct the Aircraft definition to use\n propFile = 'Propulsion.xml'\n ET.SubElement(elemAircraft, 'propulsion', file = propFile)\n\n SaveXml(Propulsion(oFdm), os.path.join(saveJsbPath, propFile))\n\n\n # Metrics and Aerodynamics as a seperate XML file, direct the Aircraft definition to use\n # Group the Metrics and Aero by similar naming; the dimensionalization inherent to Aero is provided by the Metrics\n metricsFile = 'Metrics.xml'\n ET.SubElement(elemAircraft, 'metrics', file = metricsFile)\n\n SaveXml(Metrics(oFdm), os.path.join(saveJsbPath, metricsFile))\n\n\n aeroFile = 'Aero.xml'\n ET.SubElement(elemAircraft, 'aerodynamics', file = aeroFile)\n\n SaveXml(Aerodynamics(oFdm, convertFdm2Jsb), os.path.join(saveJsbPath, aeroFile))\n\n\n # Launcher as a seperate XML file, direct the Aircraft definition to use\n if 'Winch' in oFdm.keys() :\n winchFile = 'Winch.xml'\n ET.SubElement(elemAircraft, 'external_reactions', file = winchFile)\n\n SaveXml(Winch(oFdm), os.path.join(saveJsbPath, winchFile))\n\n\n # Imu as a seperate XML file, direct the Aircraft definition to use\n if 'Imu' in oFdm['Sensor'].keys() :\n imuFile = 'SensorImu.xml'\n ET.SubElement(elemAircraft, 'system', file = imuFile)\n\n SaveXml(SensorImu(oFdm), os.path.join(saveJsbPath, imuFile))\n\n\n # Gps as a seperate XML file, direct the Aircraft definition to use\n if 'Gps' in oFdm['Sensor'].keys() :\n gpsFile = 'SensorGps.xml'\n ET.SubElement(elemAircraft, 'system', file = gpsFile)\n\n SaveXml(SensorGps(oFdm), os.path.join(saveJsbPath, gpsFile))\n\n\n # Pitot as a seperate XML file, direct the Aircraft definition to use\n if 'Pitot' in oFdm['Sensor'].keys() :\n pitotFile = 'SensorPitot.xml'\n ET.SubElement(elemAircraft, 'system', file = pitotFile)\n\n SaveXml(SensorPitot(oFdm), os.path.join(saveJsbPath, pitotFile))\n\n\n # 5Hole as a seperate XML file, direct the Aircraft definition to use\n if '5Hole' in oFdm['Sensor'].keys() :\n fiveHoleFile = 'Sensor5Hole.xml'\n ET.SubElement(elemAircraft, 'system', file = fiveHoleFile)\n\n SaveXml(Sensor5Hole(oFdm), os.path.join(saveJsbPath, fiveHoleFile))\n\n # Write the Aircraft XML file\n saveFile = os.path.join(saveJsbPath, aircraftName + '.xml')\n SaveXml(elemAircraft, saveFile)\n\n\n return(elemAircraft)\n\n\n\n\n#%% Table Generator, Wrapper\ndef TableGen(elemParent, tableArray, tableSignals, tableBreakPts):\n\n s = tableArray.shape\n iAxisRemList = []\n for iAxis in range(0, len(s)):\n if s[iAxis] == 1:\n iAxisRemList.append(iAxis)\n\n # for iRem in iAxisRemList: # XXX\n # tableArray = tableArray.squeeze(axis=iRem)\n # del tableSignals[iRem]\n # del tableBreakPts[iRem]\n\n if len(tableArray.shape)==3:\n table = TableGen3D(elemParent, tableArray, tableSignals, tableBreakPts)\n elif len(tableArray.shape)==2:\n table = TableGen2D(elemParent, tableArray, tableSignals, tableBreakPts)\n elif (len(tableArray.shape)==1) & (tableArray.size > 1):\n table = TableGen1D(elemParent, tableArray, tableSignals, tableBreakPts)\n else:\n table = ET.SubElement(elemParent, 'value').text = str(tableArray)\n\n\n return table\n\n#%% Table Generator, 3D\ndef TableGen3D(elemParent, tableArray, tableSignals, tableBreakPts):\n table = ET.SubElement(elemParent, 'table')\n #table = ET.Element('table')\n\n ET.SubElement(table, 'independentVar', lookup = 'row').text = tableSignals[0]\n ET.SubElement(table, 'independentVar', lookup = 'column').text = tableSignals[1]\n ET.SubElement(table, 'independentVar', lookup = 'table').text = tableSignals[2]\n\n indentSpace = ' '*4\n indentLvl = 4\n\n numRows, numColumns, numTables = np.shape(tableArray)\n\n columnHeader = indentSpace*(indentLvl)\n for columnVal in tableBreakPts[1]:\n columnHeader += ' '*6 + str(columnVal)\n\n\n for iTable in range(0, numTables):\n tableStr = ['\\n' + columnHeader]\n for iRow in range(0, numRows):\n rowStr = str(tableArray[iRow, :, iTable]).replace('[','').replace(']','').replace('\\n', '')\n tableStr.append(indentLvl*indentSpace + str(tableBreakPts[0][iRow]) + indentSpace + rowStr)\n\n tableStr = '\\n'.join(tableStr) + '\\n' + indentLvl*indentSpace # Replace list lines with '/n' strings\n ET.SubElement(table, 'tableData', breakPoint = str(tableBreakPts[2][iTable])).text = tableStr\n\n\n return table\n\n\n#%% Table Generator, 2D\ndef TableGen2D(elemParent, tableArray, tableSignals, tableBreakPts):\n table = ET.SubElement(elemParent, 'table')\n\n ET.SubElement(table, 'independentVar', lookup = 'row').text = tableSignals[0]\n ET.SubElement(table, 'independentVar', lookup = 'column').text = tableSignals[1]\n indentSpace = ' '*4\n indentLvl = 4\n\n tableArray = tableArray.transpose()\n numRows, numColumns = np.shape(tableArray)\n\n columnHeader = indentSpace*(indentLvl)\n for columnVal in tableBreakPts[1]:\n columnHeader += ' '*6 + str(columnVal)\n\n tableStr = ['\\n' + columnHeader]\n for iRow in range(0, numRows):\n rowStr = str(tableArray[iRow]).replace('[','').replace(']','').replace('\\n', '')\n tableStr.append(indentLvl*indentSpace + str(tableBreakPts[0][iRow]) + indentSpace + rowStr)\n\n tableStr = '\\n'.join(tableStr) + '\\n' + indentLvl*indentSpace # Replace list lines with '/n' strings\n ET.SubElement(table, 'tableData').text = tableStr\n\n return table\n\n\n#%% Table Generator, 1D\ndef TableGen1D(elemParent, tableArray, tableSignals, tableBreakPts):\n table = ET.SubElement(elemParent, 'table')\n\n ET.SubElement(table, 'independentVar', lookup = 'row').text = tableSignals\n indentSpace = ' '*4\n indentLvl = 4\n\n numRows = np.shape(tableArray)[0]\n\n tableStr = ['\\n']\n for iRow in range(0, numRows):\n rowStr = str(tableArray[iRow]).replace('[','').replace(']','').replace('\\n', '')\n tableStr.append(indentLvl*indentSpace + str(tableBreakPts[iRow]) + indentSpace + rowStr)\n\n tableStr = '\\n'.join(tableStr) + '\\n' + indentLvl*indentSpace # Replace list lines with '/n' strings\n ET.SubElement(table, 'tableData').text = tableStr\n\n return table\n\n\n#%%\ndef MassBalance(oFdm):\n mass_balance = ET.Element('mass_balance')\n\n # Mass\n ET.SubElement(mass_balance, 'emptywt', unit = 'KG').text = str(oFdm['MassProp']['mass_kg'])\n\n # CG\n location = ET.SubElement(mass_balance, 'location', name = 'CG', unit = 'M')\n ET.SubElement(location, 'x').text = str(oFdm['MassProp']['rCG_S_m'][0])\n ET.SubElement(location, 'y').text = str(oFdm['MassProp']['rCG_S_m'][1])\n ET.SubElement(location, 'z').text = str(oFdm['MassProp']['rCG_S_m'][2])\n\n # Inertia\n ET.SubElement(mass_balance, 'ixx', unit = 'KG*M2').text = str(oFdm['MassProp']['inertia_kgm2'][0,0])\n ET.SubElement(mass_balance, 'iyy', unit = 'KG*M2').text = str(oFdm['MassProp']['inertia_kgm2'][1,1])\n ET.SubElement(mass_balance, 'izz', unit = 'KG*M2').text = str(oFdm['MassProp']['inertia_kgm2'][2,2])\n ET.SubElement(mass_balance, 'ixy', unit = 'KG*M2').text = str(oFdm['MassProp']['inertia_kgm2'][0,1])\n ET.SubElement(mass_balance, 'ixz', unit = 'KG*M2').text = str(oFdm['MassProp']['inertia_kgm2'][0,2])\n ET.SubElement(mass_balance, 'iyz', unit = 'KG*M2').text = str(oFdm['MassProp']['inertia_kgm2'][1,2])\n\n return(mass_balance)\n\n#%%\ndef GroundReactions(oFdm):\n ground_reactions = ET.Element('ground_reactions')\n\n # Loop Each Gear\n for gear in oFdm['Gear'].keys():\n contact = ET.SubElement(ground_reactions, 'contact', type = 'BOGEY', name = gear)\n\n location = ET.SubElement(contact, 'location', unit = 'M')\n ET.SubElement(location, 'x').text = str(oFdm['Gear'][gear]['rGear_S_m'][0])\n ET.SubElement(location, 'y').text = str(oFdm['Gear'][gear]['rGear_S_m'][1])\n ET.SubElement(location, 'z').text = str(oFdm['Gear'][gear]['rGear_S_m'][2])\n\n ET.SubElement(contact, 'static_friction').text = str(oFdm['Gear'][gear]['FricStatic'])\n ET.SubElement(contact, 'dynamic_friction').text = str(oFdm['Gear'][gear]['FricDynamic'])\n ET.SubElement(contact, 'rolling_friction').text = str(oFdm['Gear'][gear]['FricRoll'])\n ET.SubElement(contact, 'spring_coeff', unit = 'N/M').text = str(oFdm['Gear'][gear]['kSpring_Npm'])\n ET.SubElement(contact, 'damping_coeff', unit = 'N/M/SEC').text = str(oFdm['Gear'][gear]['dampSpring_Nspm'])\n\n ET.SubElement(contact, 'max_steer', unit = 'DEG').text = '0.0'\n\n return(ground_reactions)\n\n\n#%%\ndef Metrics(oFdm):\n metrics = ET.Element('metrics')\n\n # Dimensions\n ET.SubElement(metrics, 'wingarea', unit = 'M2').text = str(oFdm['Aero']['Ref']['S_m2'])\n ET.SubElement(metrics, 'wingspan', unit = 'M').text = str(oFdm['Aero']['Ref']['b_m'])\n ET.SubElement(metrics, 'chord', unit = 'M').text = str(oFdm['Aero']['Ref']['cBar_m'])\n\n location = ET.SubElement(metrics, 'location', name = 'AERORP', unit = 'M')\n ET.SubElement(location, 'x').text = str(oFdm['Aero']['Ref']['rAero_S_m'][0])\n ET.SubElement(location, 'y').text = str(oFdm['Aero']['Ref']['rAero_S_m'][1])\n ET.SubElement(location, 'z').text = str(oFdm['Aero']['Ref']['rAero_S_m'][2])\n\n location = ET.SubElement(metrics, 'location', name = 'EYEPOINT', unit = 'M')\n ET.SubElement(location, 'x').text = str(oFdm['Aero']['Ref']['rAero_S_m'][0])\n ET.SubElement(location, 'y').text = str(oFdm['Aero']['Ref']['rAero_S_m'][1])\n ET.SubElement(location, 'z').text = str(oFdm['Aero']['Ref']['rAero_S_m'][2])\n\n location = ET.SubElement(metrics, 'location', name = 'VRP', unit = 'M')\n ET.SubElement(location, 'x').text = '0.0'\n ET.SubElement(location, 'y').text = '0.0'\n ET.SubElement(location, 'z').text = '0.0'\n\n return(metrics)\n\n\n#%%\ndef Aerodynamics(oFdm, convertFdm2Jsb):\n\n import copy\n\n # Aero Coef definitions\n coefNamesFdm = convertFdm2Jsb['Coef']['oFdm']\n\n # Aero Deriv dependencies definitions\n depNamesFdm = convertFdm2Jsb['Dep']['oFdm']\n depNamesJsb = convertFdm2Jsb['Dep']['jsb']\n depScale = convertFdm2Jsb['Dep']['scale']\n\n coefNamesFdm = convertFdm2Jsb['Coef']['oFdm']\n\n # Aero Breakpoint Table defintions\n indVarTable = convertFdm2Jsb['TableDef']['jsb']\n breakPtsTable = convertFdm2Jsb['TableDef']['brkPts']\n\n # Aero Table data to use\n aeroTable = oFdm['Aero']['Coef']\n\n # Define the conversion from oFdm to JSB-ML # FIXIT - switch to a CDo+CDi drag computation\n coefTable = {'CL': {'axis': 'LIFT', 'scale': None, 'type': 'force', 'deriv': 'dCL'}, \\\n 'CD': {'axis': 'DRAG', 'scale': None, 'type': 'force', 'deriv': 'dCD'}, \\\n 'CY': {'axis': 'SIDE', 'scale': None, 'type': 'force', 'deriv': 'dCY'}, \\\n 'CMl': {'axis': 'ROLL', 'scale': 'metrics/bw-ft', 'type': 'moment', 'deriv': 'dCMl'}, \\\n 'CMm': {'axis': 'PITCH', 'scale': 'metrics/cbarw-ft', 'type': 'moment', 'deriv': 'dCMm'}, \\\n 'CMn': {'axis': 'YAW', 'scale': 'metrics/bw-ft', 'type': 'moment', 'deriv': 'dCMn'}}\n\n\n aerodynamics = ET.Element('aerodynamics')\n\n #\n # Create each coefficient individually, just the table look-up\n coefNames = coefTable.keys()\n for iCoef, coef in enumerate(coefNames):\n convertCoef = coefTable[coef]\n\n # For each coefficient: create just the table look-up, then the Multiplication, then the summation\n for iDep, dep in enumerate(coefNamesFdm):\n function = ET.SubElement(aerodynamics, 'function', name = str('aero/coefficient/' + coef + '__' + dep))\n ET.SubElement(function, 'description').text = str(coef + '__' + dep)\n\n # Use the Table Generator to create the properly formated Table for JSB-ML\n tableArray = aeroTable[coef][dep]\n tableSignals = indVarTable\n tableBreakPts = breakPtsTable\n\n table = TableGen(function, copy.deepcopy(tableArray), copy.deepcopy(tableSignals), copy.deepcopy(tableBreakPts))\n\n # For each derivative: create just the table look-up, then the Multiplication, then the summation\n deriv = convertCoef['deriv']\n\n for iDep, dep in enumerate(depNamesFdm):\n function = ET.SubElement(aerodynamics, 'function', name = str('aero/coefficient/' + deriv + '__' + dep))\n ET.SubElement(function, 'description').text = str(deriv + '__' + dep)\n\n # Use the Table Generator to create the properly formated Table for JSB-ML\n tableArray = aeroTable[deriv][dep]\n tableSignals = indVarTable\n tableBreakPts = breakPtsTable\n\n table = TableGen(function, copy.deepcopy(tableArray), copy.deepcopy(tableSignals), copy.deepcopy(tableBreakPts))\n\n # Multiply each derivative by it's dependent variable\n function = ET.SubElement(aerodynamics, 'function', name = str('aero/coefficient/' + coef + '__' + dep))\n ET.SubElement(function, 'description').text = str(coef + '__' + dep + ' = ' + deriv + '__' + dep + ' * ' + dep)\n\n #print(coef + '__' + dep + ' = ' + deriv + '__' + dep + ' * ' + dep)\n\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'aero/coefficient/' + deriv + '__' + dep\n\n #print(deriv + '__' + dep)\n\n depSignal = depNamesJsb[iDep]\n #print(depSignal)\n if depSignal != None:\n ET.SubElement(product, 'property').text = depSignal # Dependent Variable/Signal\n\n scale = depScale[iDep]\n if scale != None:\n if isinstance(scale, str):\n ET.SubElement(product, 'property').text = str(scale) # Dependent Variable Scaling\n else:\n ET.SubElement(product, 'value').text = str(scale) # Dependent Variable Scaling\n\n\n\n # Sum the Coeficients\n function = ET.SubElement(aerodynamics, 'function', name = str('aero/coefficient/' + coef))\n ET.SubElement(function, 'description').text = str(coef + ' summation')\n #print(coef + ' summation')\n\n summation = ET.SubElement(function, 'sum')\n for iDep, dep in enumerate(coefNamesFdm):\n ET.SubElement(summation, 'property').text = 'aero/coefficient/' + coef + '__' + dep\n #print(coef + '__' + dep)\n\n for iDep, dep in enumerate(depNamesFdm):\n ET.SubElement(summation, 'property').text = 'aero/coefficient/' + coef + '__' + dep\n #print(coef + '__' + dep)\n\n #\n # Dimensionalize the Coefficients into Forces and Moments\n for iCoef, coef in enumerate(coefNames):\n convertCoef = coefTable[coef]\n\n axis = ET.SubElement(aerodynamics, 'axis', name = convertCoef['axis'])\n\n function = ET.SubElement(axis, 'function', name = str('aero/' + convertCoef['type'] + '/' + convertCoef['axis'] + '__' + coef))\n ET.SubElement(function, 'description').text = str(convertCoef['axis'] + ' from ' + coef)\n\n product = ET.SubElement(function, 'product')\n\n ET.SubElement(product, 'property').text = 'aero/qbar-area' # qBar * sRef\n\n if convertCoef['scale'] != None:\n ET.SubElement(product, 'property').text = convertCoef['scale'] # Coefficient Scaling\n\n ET.SubElement(product, 'property').text = 'aero/coefficient/' + coef\n\n\n return(aerodynamics)\n\n#%%\ndef Propulsion(oFdm):\n propulsion = ET.Element('propulsion')\n\n for key in oFdm['Prop'].keys():\n\n prop = oFdm['Prop'][key]\n\n # Motor/Engine\n engine = ET.SubElement(propulsion, 'engine', file = prop['nameMotor'])\n# location = ET.SubElement(engine, 'location', unit = 'M')\n# ET.SubElement(location, 'x').text = str(prop['rMotor_S_m'][0])\n# ET.SubElement(location, 'y').text = str(prop['rMotor_S_m'][1])\n# ET.SubElement(location, 'z').text = str(prop['rMotor_S_m'][2])\n# orient = ET.SubElement(engine, 'orient', unit = 'DEG')\n# ET.SubElement(orient, 'roll').text = str(prop['sMotor_deg'][0])\n# ET.SubElement(orient, 'pitch').text = str(prop['sMotor_deg'][1])\n# ET.SubElement(orient, 'yaw').text = str(prop['sMotor_deg'][2])\n\n # Thruster/Prop as an element of the Engine\n thruster = ET.SubElement(engine, 'thruster', file = prop['nameProp'])\n location = ET.SubElement(thruster, 'location', unit = 'M')\n ET.SubElement(location, 'x').text = str(prop['rProp_S_m'][0])\n ET.SubElement(location, 'y').text = str(prop['rProp_S_m'][1])\n ET.SubElement(location, 'z').text = str(prop['rProp_S_m'][2])\n orient = ET.SubElement(thruster, 'orient', unit = 'DEG')\n ET.SubElement(orient, 'roll').text = str(prop['sProp_deg'][0])\n ET.SubElement(orient, 'pitch').text = str(prop['sProp_deg'][1])\n ET.SubElement(orient, 'yaw').text = str(prop['sProp_deg'][2])\n\n ET.SubElement(thruster, 'sense').text = str(prop['sense']) # 1 = CW as viewed from cockpit, -1 = CCW\n ET.SubElement(thruster, 'p_factor').text = str(prop['p_factor'])\n\n\n return(propulsion)\n\n\n#%% FCS\ndef FlightControl(oFdm):\n\n # Define all the Pilot input definition\n # Pilot Inputs, us the FG normalized sticks\n fcsPilotDef = {}\n fcsPilotDef['summer'] = {}\n fcsPilotDef['gain'] = {}\n\n fcsPilotDef['summer']['pilotRoll_norm'] = {}\n fcsPilotDef['summer']['pilotRoll_norm']['inputList'] = ['fcs/aileron-cmd-norm', 'fcs/roll-trim-cmd-norm']\n fcsPilotDef['summer']['pilotRoll_norm']['min'] = -1.0\n fcsPilotDef['summer']['pilotRoll_norm']['max'] = 1.0\n\n fcsPilotDef['gain']['cmdRoll_rps'] = {}\n fcsPilotDef['gain']['cmdRoll_rps']['input'] = 'fcs/pilotRoll_norm'\n fcsPilotDef['gain']['cmdRoll_rps']['gain'] = oFdm['FCS']['Pilot']['kRoll']\n\n fcsPilotDef['summer']['pilotPitch_norm'] = {}\n fcsPilotDef['summer']['pilotPitch_norm']['inputList'] = ['fcs/elevator-cmd-norm', 'fcs/pitch-trim-cmd-norm']\n fcsPilotDef['summer']['pilotPitch_norm']['min'] = -1.0\n fcsPilotDef['summer']['pilotPitch_norm']['max'] = 1.0\n\n fcsPilotDef['gain']['cmdPitch_rps'] = {}\n fcsPilotDef['gain']['cmdPitch_rps']['input'] = 'fcs/pilotPitch_norm'\n fcsPilotDef['gain']['cmdPitch_rps']['gain'] = oFdm['FCS']['Pilot']['kPitch']\n\n fcsPilotDef['summer']['pilotYaw_norm'] = {}\n fcsPilotDef['summer']['pilotYaw_norm']['inputList'] = ['fcs/rudder-cmd-norm', 'fcs/yaw-trim-cmd-norm']\n fcsPilotDef['summer']['pilotYaw_norm']['min'] = -1.0\n fcsPilotDef['summer']['pilotYaw_norm']['max'] = 1.0\n\n fcsPilotDef['gain']['cmdYaw_rps'] = {}\n fcsPilotDef['gain']['cmdYaw_rps']['input'] = 'fcs/pilotYaw_norm'\n fcsPilotDef['gain']['cmdYaw_rps']['gain'] = oFdm['FCS']['Pilot']['kYaw']\n\n fcsPilotDef['summer']['pilotFlap_norm'] = {}\n fcsPilotDef['summer']['pilotFlap_norm']['inputList'] = ['fcs/flap-cmd-norm']\n fcsPilotDef['summer']['pilotFlap_norm']['min'] = -1.0\n fcsPilotDef['summer']['pilotFlap_norm']['max'] = 1.0\n\n fcsPilotDef['gain']['cmdFlap_rad'] = {}\n fcsPilotDef['gain']['cmdFlap_rad']['input'] = 'fcs/pilotFlap_norm'\n fcsPilotDef['gain']['cmdFlap_rad']['gain'] = oFdm['FCS']['Pilot']['kFlap']\n\n\n # Create the JSB-ML\n elemFCS = ET.Element('flight_control', name = 'Generic Flight Control')\n\n pilot = ET.SubElement(elemFCS, 'channel', name = 'Pilot_Inputs')\n for type in fcsPilotDef:\n if type == 'summer':\n for key in fcsPilotDef['summer'].keys():\n entry = fcsPilotDef['summer'][key]\n\n summer = ET.SubElement(pilot, 'summer', name = key)\n\n for input in entry['inputList']:\n ET.SubElement(summer, 'input').text = input\n\n if ('min' in entry.keys()) or ('max' in entry.keys()):\n clipto = ET.SubElement(summer, 'clipto')\n if ('min' in entry.keys()): ET.SubElement(clipto, 'min').text = str(entry['min'])\n if ('max' in entry.keys()): ET.SubElement(clipto, 'max').text = str(entry['max'])\n\n ET.SubElement(summer, 'output').text = 'fcs/' + key\n\n if type == 'gain':\n for key in fcsPilotDef['gain'].keys():\n entry = fcsPilotDef['gain'][key]\n\n gain = ET.SubElement(pilot, 'pure_gain', name = key)\n\n ET.SubElement(gain, 'input').text = entry['input']\n ET.SubElement(gain, 'gain').text = str(entry['gain'])\n\n if ('min' in entry.keys()) or ('max' in entry.keys()):\n clipto = ET.SubElement(gain, 'clipto')\n if ('min' in entry.keys()): ET.SubElement(clipto, 'min').text = str(entry['min'])\n if ('max' in entry.keys()): ET.SubElement(clipto, 'max').text = str(entry['max'])\n\n ET.SubElement(gain, 'output').text = 'fcs/' + key\n\n\n # Control System Surface Mixer\n mixer = ET.SubElement(elemFCS, 'channel', name = 'Control Mixer')\n\n fcsMixerDef = oFdm['FCS']['Mixer']\n\n for iSurf, surf in enumerate(fcsMixerDef['surfNames']):\n cmdSurf = 'cmd' + surf + '_rad'\n keyList = []\n for iInput, input in enumerate(fcsMixerDef['inputs']):\n val = fcsMixerDef['surfMix'][iSurf][iInput]\n\n key = input + '_2_' + surf\n\n if val != 0.0:\n keyList.append(key)\n gain = ET.SubElement(mixer, 'pure_gain', name = key.replace('fcs/',''))\n\n ET.SubElement(gain, 'input').text = 'fcs/' + input\n ET.SubElement(gain, 'gain').text = str(val)\n\n ET.SubElement(gain, 'output').text = 'fcs/' + key\n\n if any(keyList):\n summer = ET.SubElement(mixer, 'summer', name = cmdSurf)\n for key in keyList:\n ET.SubElement(summer, 'input').text = 'fcs/' + key\n ET.SubElement(summer, 'output').text = 'fcs/' + cmdSurf\n\n\n\n # Inputs for External Commands, this just add property to create the node in the tree\n for iSurf, surf in enumerate(fcsMixerDef['surfNames']):\n cmdSurfExt = 'cmd' + surf + '_ext_rad'\n prop = ET.SubElement(elemFCS, 'property').text = 'fcs/' + cmdSurfExt\n\n name = 'Motor'\n cmdMotorExt = 'cmd' + name + '_ext_nd'\n motor = ET.SubElement(elemFCS, 'property').text = 'fcs/' + cmdMotorExt # Add the Motor external command\n\n\n # Inputs for External Commands, this just add property to create the node in the tree\n extern = ET.SubElement(elemFCS, 'channel', name = 'External Input Summations')\n for iSurf, surf in enumerate(fcsMixerDef['surfNames']):\n cmdSurf = 'cmd' + surf + '_rad'\n cmdSurfExt = 'cmd' + surf + '_ext_rad'\n\n summer = ET.SubElement(extern, 'summer')\n ET.SubElement(summer, 'input').text = 'fcs/' + cmdSurf\n ET.SubElement(summer, 'input').text = 'fcs/' + cmdSurfExt\n ET.SubElement(summer, 'output').text = 'fcs/' + cmdSurf\n\n name = 'Motor'\n cmdMotor = 'cmd' + name + '_nd'\n cmdMotorExt = 'cmd' + name + '_ext_nd'\n summer = ET.SubElement(extern, 'summer')\n ET.SubElement(summer, 'input').text = 'fcs/throttle-cmd-norm'\n ET.SubElement(summer, 'input').text = 'fcs/' + cmdMotorExt\n ET.SubElement(summer, 'output').text = 'fcs/throttle-pos-norm'\n\n return(elemFCS)\n\n\n#%% Effectors, for each surface define the 2nd order TF, and an 'actuator'\ndef Effectors(oFdm):\n\n sysEffDef = oFdm['Act']\n\n effectors = ET.Element('system', name = 'Effectors')\n channel = ET.SubElement(effectors, 'channel', name = 'Actuator Models')\n\n for surf in sysEffDef.keys():\n cmdSurf = 'cmd' + surf + '_rad'\n posSurf = 'pos' + surf + '_rad'\n\n entry = sysEffDef[surf]\n\n # Actuator - delay and freeplay\n actuator = ET.SubElement(channel, 'actuator', name = 'act' + surf)\n ET.SubElement(actuator, 'input').text = 'fcs/' + cmdSurf\n\n ET.SubElement(actuator, 'lag').text = str(entry['lag_nd'])\n ET.SubElement(actuator, 'hysteresis_width').text = str(entry['freeplay_rad'])\n ET.SubElement(actuator, 'delay').text = str(entry['delay_s'])\n\n if ('min' in entry.keys()) or ('max' in entry.keys()):\n clipto = ET.SubElement(actuator, 'clipto')\n if ('min' in entry.keys()): ET.SubElement(clipto, 'min').text = str(entry['min'])\n if ('max' in entry.keys()): ET.SubElement(clipto, 'max').text = str(entry['max'])\n\n ET.SubElement(actuator, 'output').text = 'fcs/' + posSurf\n\n return(effectors)\n\n\n#%%\ndef Winch(oFdm):\n external_reactions = ET.Element('external_reactions')\n\n # Winch\n force = ET.SubElement(external_reactions, 'force', name='hitch' , frame = 'BODY', unit='N')\n location = ET.SubElement(force, 'location', unit = 'M')\n ET.SubElement(location, 'x').text = str(oFdm['Winch']['rHook_S_m'][0])\n ET.SubElement(location, 'y').text = str(oFdm['Winch']['rHook_S_m'][1])\n ET.SubElement(location, 'z').text = str(oFdm['Winch']['rHook_S_m'][2])\n direction = ET.SubElement(force, 'direction')\n ET.SubElement(direction, 'x').text = str(oFdm['Winch']['sHook_deg'][0])\n ET.SubElement(direction, 'y').text = str(oFdm['Winch']['sHook_deg'][1])\n ET.SubElement(direction, 'z').text = str(oFdm['Winch']['sHook_deg'][2])\n\n return(external_reactions)\n\n\n#%% IMU\ndef SensorImu(oFdm):\n imu = ET.Element('system', name = 'Sensor - IMU')\n\n # Create time in us\n function = ET.SubElement(imu, 'function', name = 'sensor/imu/time_us')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'simulation/sim-time-sec'\n ET.SubElement(product, 'value').text = str(1e6)\n\n # Accelerometers\n if 'Accel' in oFdm['Sensor']['Imu'].keys() :\n channel = ET.SubElement(imu, 'channel', name = 'Temp Accelerometers')\n\n axisList = ['X', 'Y', 'Z']\n\n for axisName in axisList:\n accel = ET.SubElement(channel, 'accelerometer', name = 'Accel' + axisName)\n\n ET.SubElement(accel, 'axis').text = axisName\n\n location = ET.SubElement(accel, 'location', unit = 'M')\n ET.SubElement(location, 'x').text = str(oFdm['Sensor']['Imu']['Accel']['r_S_m'][0])\n ET.SubElement(location, 'y').text = str(oFdm['Sensor']['Imu']['Accel']['r_S_m'][1])\n ET.SubElement(location, 'z').text = str(oFdm['Sensor']['Imu']['Accel']['r_S_m'][2])\n\n orientation = ET.SubElement(accel, 'orientation', unit='DEG')\n ET.SubElement(orientation, 'roll').text = str(oFdm['Sensor']['Imu']['Accel']['s_deg'][0])\n ET.SubElement(orientation, 'pitch').text = str(oFdm['Sensor']['Imu']['Accel']['s_deg'][1])\n ET.SubElement(orientation, 'yaw').text = str(oFdm['Sensor']['Imu']['Accel']['s_deg'][2])\n\n ET.SubElement(accel, 'output').text = 'sensor/imu/accel' + axisName + '_true_fps2'\n\n\n # Convert Units Accelerometer to mps2\n for axisName in axisList:\n function = ET.SubElement(imu, 'function', name = 'sensor/imu/accel' + axisName + '_true_mps2')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'sensor/imu/accel' + axisName + '_true_fps2'\n ET.SubElement(product, 'value').text = str(ft2m)\n\n\n # Accelerometer Error Model\n channel = ET.SubElement(imu, 'channel', name = 'Accelerometer Error Model')\n\n errMod = oFdm['Sensor']['Imu']['Accel']\n for iAxis, axisName in enumerate(axisList):\n sensor = ET.SubElement(channel, 'sensor', name = 'Accel' + axisName)\n ET.SubElement(sensor, 'input').text = 'sensor/imu/accel' + axisName + '_true_mps2'\n\n ET.SubElement(sensor, 'lag').text = str(errMod['lag'][iAxis])\n ET.SubElement(sensor, 'noise', variation='ABSOLUTE', distribution = 'GAUSSIAN').text = str((1.0 / 3.0) * errMod['noiseVar'][iAxis])\n ET.SubElement(sensor, 'drift_rate').text = str(errMod['drift_ps'][iAxis])\n ET.SubElement(sensor, 'gain').text = str(errMod['gain_nd'][iAxis])\n ET.SubElement(sensor, 'bias').text = str(errMod['bias'][iAxis])\n ET.SubElement(sensor, 'delay').text = str(errMod['delay_s'][iAxis])\n\n ET.SubElement(sensor, 'output').text = 'sensor/imu/accel' + axisName + '_mps2'\n\n\n # Gyros\n if 'Gyro' in oFdm['Sensor']['Imu'].keys() :\n errMod = oFdm['Sensor']['Imu']['Gyro']\n channel = ET.SubElement(imu, 'channel', name = 'Gyros')\n\n for iAxis, axisName in enumerate(axisList):\n gyro = ET.SubElement(channel, 'gyro', name = 'Gyro' + axisName)\n\n ET.SubElement(gyro, 'axis').text = axisName\n\n location = ET.SubElement(gyro, 'location', unit = 'M')\n ET.SubElement(location, 'x').text = str(errMod['r_S_m'][0])\n ET.SubElement(location, 'y').text = str(errMod['r_S_m'][1])\n ET.SubElement(location, 'z').text = str(errMod['r_S_m'][2])\n\n orientation = ET.SubElement(gyro, 'orientation', unit='DEG')\n ET.SubElement(orientation, 'roll').text = str(errMod['s_deg'][0])\n ET.SubElement(orientation, 'pitch').text = str(errMod['s_deg'][1])\n ET.SubElement(orientation, 'yaw').text = str(errMod['s_deg'][2])\n\n ET.SubElement(gyro, 'lag').text = str(errMod['lag'][iAxis])\n ET.SubElement(gyro, 'noise', variation='ABSOLUTE', distribution = 'GAUSSIAN').text = str((1.0 / 3.0) * errMod['noiseVar'][iAxis])\n ET.SubElement(gyro, 'drift_rate').text = str(errMod['drift_ps'][iAxis])\n ET.SubElement(gyro, 'gain').text = str(errMod['gain_nd'][iAxis])\n ET.SubElement(gyro, 'bias').text = str(errMod['bias'][iAxis])\n ET.SubElement(gyro, 'delay').text = str(errMod['delay_s'][iAxis])\n\n ET.SubElement(gyro, 'output').text = 'sensor/imu/gyro' + axisName + '_rps'\n\n # Magnetometers\n if 'Mag' in oFdm['Sensor']['Imu'].keys() :\n errMod = oFdm['Sensor']['Imu']['Mag']\n channel = ET.SubElement(imu, 'channel', name = 'Magnetometers')\n\n for iAxis, axisName in enumerate(axisList):\n mag = ET.SubElement(channel, 'magnetometer', name = 'Mag' + axisName)\n\n ET.SubElement(mag, 'axis').text = axisName\n\n location = ET.SubElement(mag, 'location', unit = 'M')\n ET.SubElement(location, 'x').text = str(errMod['r_S_m'][0])\n ET.SubElement(location, 'y').text = str(errMod['r_S_m'][1])\n ET.SubElement(location, 'z').text = str(errMod['r_S_m'][2])\n\n orientation = ET.SubElement(mag, 'orientation', unit='DEG')\n ET.SubElement(orientation, 'roll').text = str(errMod['s_deg'][0])\n ET.SubElement(orientation, 'pitch').text = str(errMod['s_deg'][1])\n ET.SubElement(orientation, 'yaw').text = str(errMod['s_deg'][2])\n\n ET.SubElement(mag, 'lag').text = str(errMod['lag'][iAxis])\n ET.SubElement(mag, 'noise', variation='ABSOLUTE', distribution = 'GAUSSIAN').text = str((1.0 / 3.0) * errMod['noiseVar'][iAxis])\n ET.SubElement(mag, 'drift_rate').text = str(errMod['drift_ps'][iAxis])\n ET.SubElement(mag, 'gain').text = str(errMod['gain_nd'][iAxis])\n ET.SubElement(mag, 'bias').text = str(errMod['bias'][iAxis])\n ET.SubElement(mag, 'delay').text = str(errMod['delay_s'][iAxis])\n\n ET.SubElement(mag, 'output').text = 'sensor/imu/mag' + axisName + '_nT'\n\n # Magnetometer unit conversion\n for axisName in axisList:\n function = ET.SubElement(imu, 'function', name = 'sensor/imu/mag' + axisName + '_uT')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'sensor/imu/mag' + axisName + '_nT'\n ET.SubElement(product, 'value').text = str(0.001)\n\n return(imu)\n\n#%% GPS\ndef SensorGps(oFdm):\n\n gps = ET.Element('system', name = 'Sensor - GPS')\n\n # Create time in us\n function = ET.SubElement(gps, 'function', name = 'sensor/gps/time_us')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'simulation/sim-time-sec'\n ET.SubElement(product, 'value').text = str(1e6)\n\n # GPS Position\n function = ET.SubElement(gps, 'function', name = 'sensor/gps/lat_true_rad')\n ET.SubElement(function, 'property').text = 'position/lat-geod-rad'\n function = ET.SubElement(gps, 'function', name = 'sensor/gps/long_true_rad')\n ET.SubElement(function, 'property').text = 'position/long-gc-rad'\n\n function = ET.SubElement(gps, 'function', name = 'sensor/gps/alt_true_m')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'position/h-sl-ft'\n ET.SubElement(product, 'value').text = str(ft2m)\n\n # GPS Velocity\n function = ET.SubElement(gps, 'function', name = 'sensor/gps/vNorth_true_mps')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'velocities/v-north-fps'\n ET.SubElement(product, 'value').text = str(ft2m)\n\n function = ET.SubElement(gps, 'function', name = 'sensor/gps/vEast_true_mps')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'velocities/v-east-fps'\n ET.SubElement(product, 'value').text = str(ft2m)\n\n function = ET.SubElement(gps, 'function', name = 'sensor/gps/vDown_true_mps')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'velocities/v-down-fps'\n ET.SubElement(product, 'value').text = str(ft2m)\n\n\n # GPS Error Model\n channel = ET.SubElement(gps, 'channel', name = 'GPS Error Models')\n\n axisList = ['lat_rad', 'long_rad', 'alt_m']\n errMod = oFdm['Sensor']['Gps']['Pos']\n for iAxis, axisName in enumerate(axisList):\n sensor = ET.SubElement(channel, 'sensor', name = axisName)\n\n ET.SubElement(sensor, 'input').text = 'sensor/gps/' + axisName.replace('_', '_true_')\n\n ET.SubElement(sensor, 'lag').text = str(errMod['lag'][iAxis])\n ET.SubElement(sensor, 'noise', variation='ABSOLUTE', distribution = 'GAUSSIAN').text = str((1.0 / 3.0) * errMod['noiseVar'][iAxis])\n ET.SubElement(sensor, 'drift_rate').text = str(errMod['drift_ps'][iAxis])\n ET.SubElement(sensor, 'gain').text = str(errMod['gain_nd'][iAxis])\n ET.SubElement(sensor, 'bias').text = str(errMod['bias'][iAxis])\n ET.SubElement(sensor, 'delay').text = str(errMod['delay_s'][iAxis])\n\n ET.SubElement(sensor, 'output').text = 'sensor/gps/' + axisName\n\n axisList = ['vNorth_mps', 'vEast_mps', 'vDown_mps']\n errMod = oFdm['Sensor']['Gps']['Vel']\n for iAxis, axisName in enumerate(axisList):\n sensor = ET.SubElement(channel, 'sensor', name = axisName)\n\n ET.SubElement(sensor, 'input').text = 'sensor/gps/' + axisName.replace('_', '_true_')\n\n ET.SubElement(sensor, 'lag').text = str(errMod['lag'][iAxis])\n ET.SubElement(sensor, 'noise', variation='ABSOLUTE', distribution = 'GAUSSIAN').text = str((1.0 / 3.0) * errMod['noiseVar'][iAxis])\n ET.SubElement(sensor, 'drift_rate').text = str(errMod['drift_ps'][iAxis])\n ET.SubElement(sensor, 'gain').text = str(errMod['gain_nd'][iAxis])\n ET.SubElement(sensor, 'bias').text = str(errMod['bias'][iAxis])\n ET.SubElement(sensor, 'delay').text = str(errMod['delay_s'][iAxis])\n\n ET.SubElement(sensor, 'output').text = 'sensor/gps/' + axisName\n\n\n return(gps)\n\n#%%\n\ndef SensorPitot(oFdm):\n\n pitot = ET.Element('system', name = 'Sensor - Pitot-Static Probe')\n\n # Create time in us\n function = ET.SubElement(pitot, 'function', name = 'sensor/pitot/time_us')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'simulation/sim-time-sec'\n ET.SubElement(product, 'value').text = str(1e6)\n\n # Airdata Static\n function = ET.SubElement(pitot, 'function', name = 'sensor/pitot/presStatic_true_Pa')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'atmosphere/P-psf'\n ET.SubElement(product, 'value').text = str(psf2pa)\n\n # Airdata Tip (Dynamic ~= Impact)\n function = ET.SubElement(pitot, 'function', name = 'sensor/pitot/presTip_true_Pa')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'aero/qbar-psf'\n ET.SubElement(product, 'value').text = str(psf2pa)\n\n # Airdata Temperature\n function = ET.SubElement(pitot, 'function', name = 'sensor/pitot/temp_true_C')\n product = ET.SubElement(function, 'product')\n summation = ET.SubElement(product, 'sum')\n ET.SubElement(summation, 'property').text = 'atmosphere/T-R'\n ET.SubElement(summation, 'value').text = str(-491.67)\n ET.SubElement(product, 'value').text = str(5.0/9.0)\n\n # Pitot Error Model\n channel = ET.SubElement(pitot, 'channel', name = 'Pitot Error Models')\n\n axisList = ['presStatic_Pa', 'presTip_Pa', 'temp_C']\n errMod = oFdm['Sensor']['Gps']['Vel']\n for iAxis, axisName in enumerate(axisList):\n sensor = ET.SubElement(channel, 'sensor', name = axisName)\n\n ET.SubElement(sensor, 'input').text = 'sensor/pitot/' + axisName.replace('_', '_true_')\n\n ET.SubElement(sensor, 'lag').text = str(errMod['lag'][iAxis])\n ET.SubElement(sensor, 'noise', variation='ABSOLUTE', distribution = 'GAUSSIAN').text = str((1.0 / 3.0) * errMod['noiseVar'][iAxis])\n ET.SubElement(sensor, 'drift_rate').text = str(errMod['drift_ps'][iAxis])\n ET.SubElement(sensor, 'gain').text = str(errMod['gain_nd'][iAxis])\n ET.SubElement(sensor, 'bias').text = str(errMod['bias'][iAxis])\n ET.SubElement(sensor, 'delay').text = str(errMod['delay_s'][iAxis])\n\n ET.SubElement(sensor, 'output').text = 'sensor/pitot/' + axisName\n\n\n return(pitot)\n\n#%%\n\ndef Sensor5Hole(oFdm):\n\n fiveHole = ET.Element('system', name = 'Sensor - 5Hole Probe')\n\n # Determine whether method #1 or method #2\n\n if 'alphaK1' and 'betaK1' in oFdm['Sensor']['5Hole'].keys():\n method = 1\n elif 'alphaK2' and 'betaK2' in oFdm['Sensor']['5Hole'].keys():\n method = 2\n else:\n print('5Hole Probe: Need either (alphaK1 and betaK1) or (alphaK2 and betaK2)')\n\n # Create time in us\n function = ET.SubElement(fiveHole, 'function', name = 'sensor/fiveHole/time_us')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'simulation/sim-time-sec'\n ET.SubElement(product, 'value').text = str(1e6)\n\n # Airdata Static\n function = ET.SubElement(fiveHole, 'function', name = 'sensor/fiveHole/presStatic_true_Pa')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'atmosphere/P-psf'\n ET.SubElement(product, 'value').text = str(psf2pa)\n\n # Airdata Tip (Dynamic ~= Impact)\n function = ET.SubElement(fiveHole, 'function', name = 'sensor/fiveHole/presTip_true_Pa')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'aero/qbar-psf'\n ET.SubElement(product, 'value').text = str(psf2pa)\n\n # Airdata Temperature\n function = ET.SubElement(fiveHole, 'function', name = 'sensor/fiveHole/temp_true_C')\n product = ET.SubElement(function, 'product')\n summation = ET.SubElement(product, 'sum')\n ET.SubElement(summation, 'property').text = 'atmosphere/T-R'\n ET.SubElement(summation, 'value').text = str(-491.67)\n ET.SubElement(product, 'value').text = str(5.0/9.0)\n\n\n # [Method 1]\n if method == 1:\n axisList = ['presStatic_Pa', 'presTip_Pa', 'presAlphaBot_Pa', 'presAlphaTop_Pa', 'presBetaRight_Pa', 'presBetaLeft_Pa', 'temp_C']\n\n # Alpha Difference (presAlphaBot - presAlphaTop)\n function = ET.SubElement(fiveHole, 'function', name = 'sensor/fiveHole/presAlphaBot_true_Pa')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'aero/alpha-deg'\n ET.SubElement(product, 'property').text = 'aero/qbar-psf'\n ET.SubElement(product, 'value').text = str(psf2pa)\n ET.SubElement(product, 'value').text = str(oFdm['Sensor']['5Hole']['alphaK1'][0])\n\n function = ET.SubElement(fiveHole, 'function', name = 'sensor/fiveHole/presAlphaTop_true_Pa')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'aero/alpha-deg'\n ET.SubElement(product, 'property').text = 'aero/qbar-psf'\n ET.SubElement(product, 'value').text = str(psf2pa)\n ET.SubElement(product, 'value').text = str(oFdm['Sensor']['5Hole']['alphaK1'][1])\n\n # [Method 2] Beta Difference (presBetaRight - presBetaLeft)\n function = ET.SubElement(fiveHole, 'function', name = 'sensor/fiveHole/presBetaRight_true_Pa')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'aero/beta-deg'\n ET.SubElement(product, 'property').text = 'aero/qbar-psf'\n ET.SubElement(product, 'value').text = str(psf2pa)\n ET.SubElement(product, 'value').text = str(oFdm['Sensor']['5Hole']['betaK1'][0])\n\n function = ET.SubElement(fiveHole, 'function', name = 'sensor/fiveHole/presBetaLeft_true_Pa')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'aero/beta-deg'\n ET.SubElement(product, 'property').text = 'aero/qbar-psf'\n ET.SubElement(product, 'value').text = str(psf2pa)\n ET.SubElement(product, 'value').text = str(oFdm['Sensor']['5Hole']['betaK1'][1])\n\n\n # [Method 2]\n elif method == 2:\n axisList = ['presStatic_Pa', 'presTip_Pa', 'presAlpha_Pa', 'presBeta_Pa', 'temp_C']\n\n # Alpha Difference (presAlphaBot - presAlphaTop)\n function = ET.SubElement(fiveHole, 'function', name = 'sensor/fiveHole/presAlpha_true_Pa')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'aero/alpha-deg'\n ET.SubElement(product, 'property').text = 'aero/qbar-psf'\n ET.SubElement(product, 'value').text = str(psf2pa)\n ET.SubElement(product, 'value').text = str(oFdm['Sensor']['5Hole']['alphaK2'])\n\n # [Method 2] Beta Difference (presBetaRight - presBetaLeft)\n function = ET.SubElement(fiveHole, 'function', name = 'sensor/fiveHole/presBeta_true_Pa')\n product = ET.SubElement(function, 'product')\n ET.SubElement(product, 'property').text = 'aero/beta-deg'\n ET.SubElement(product, 'property').text = 'aero/qbar-psf'\n ET.SubElement(product, 'value').text = str(psf2pa)\n ET.SubElement(product, 'value').text = str(oFdm['Sensor']['5Hole']['betaK2'])\n\n\n # 5Hole Error Model\n channel = ET.SubElement(fiveHole, 'channel', name = '5Hole Error Models')\n\n errMod = oFdm['Sensor']['5Hole']\n for iAxis, axisName in enumerate(axisList):\n sensor = ET.SubElement(channel, 'sensor', name = axisName)\n\n ET.SubElement(sensor, 'input').text = 'sensor/fiveHole/' + axisName.replace('_', '_true_')\n\n ET.SubElement(sensor, 'lag').text = str(errMod['lag'][iAxis])\n ET.SubElement(sensor, 'noise', variation='ABSOLUTE', distribution = 'GAUSSIAN').text = str((1.0 / 3.0) * errMod['noiseVar'][iAxis])\n ET.SubElement(sensor, 'drift_rate').text = str(errMod['drift_ps'][iAxis])\n ET.SubElement(sensor, 'gain').text = str(errMod['gain_nd'][iAxis])\n ET.SubElement(sensor, 'bias').text = str(errMod['bias'][iAxis])\n ET.SubElement(sensor, 'delay').text = str(errMod['delay_s'][iAxis])\n\n ET.SubElement(sensor, 'output').text = 'sensor/fiveHole/' + axisName\n\n\n return(fiveHole)\n" ]
[ [ "numpy.shape" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
CBICA/MUSE
[ "edd01964078f957101130993899c7f4de13d48b6" ]
[ "src/muse-combineRoiMapsIter.py" ]
[ "#!/usr/bin/env python\n#\n# @file muse_combineRoiMapsIter.py\n# @brief Combine roi probability maps for a single subject\n#\n# Copyright (c) 2011, 2012 University of Pennsylvania. All rights reserved.<br />\n# See http://www.cbica.upenn.edu/sbia/software/license.html or COPYING file.\n#\n# Contact: SBIA Group <sbia-software at uphs.upenn.edu>\n#\n\n\n\n#Usage \n# ############################################ #\n# muse_combineRoiMapsIter.py /Path/To/Input/List.txt /Path/To/Destination/outImgName\n################################################\n# will read roi files listed in 'List.txt' file\n#The list file must have full paths to the files\n\nimport nibabel as nib\nimport numpy as np\nimport sys\nimport re\nimport time\n\nprint(str(sys.argv))\n\nInputList=str(sys.argv[1])\nDestFile=str(sys.argv[2])\n\n### Sanity check on the arguments\nif not InputList or not DestFile:\n\tprint(\"ERROR: Required input options not provided!!!\")\n\tsys.exit(0) \n\n### Printing input arguments\nprint('\\n\\n')\nprint('Subject Input List :', InputList)\nprint('Destination File :', DestFile)\nprint('\\n\\n')\n\n### Reading input file first line\nf=open(InputList)\nfline = f.readline()\nf.close()\n\n### Extract roi no\nmatch=re.search('([\\w.-]+)ROI_(\\d+)_([\\w.-]+)', fline)\nif match:\n\trnos = match.group(2)\n\trno = int(rnos)\nelse:\n\tprint('ERROR: No ROI_{roino} in file name !')\n\texit(1)\n\n### Read img, vectorize\nimg = nib.load(str.rstrip(fline))\na=img.get_data()\nb=np.reshape(a,-1)\nisize = a.shape\nvsize = b.shape\n\n### Set index of voxels belonging to that roi, set also max values\nimgMAX = b\nimgIND = np.zeros(vsize)\nimgIND[b>0] = rno\n\n### Reading input file list\nf=open(InputList)\nlines = f.readlines()\nf.close()\nctr=1\n\n### Combine roi images\nfor line in lines:\n \n\tprint(line)\n\t\n\t### Extract roi no\n\tmatch=re.search('([\\w.-]+)ROI_(\\d+)_([\\w.-]+)', line)\n\tif match:\n\t\trnos = match.group(2)\n\t\trno = int(rnos)\n\telse:\n\t\tprint('ERROR: No ROI_{roino} in file name !')\n\t\texit(1)\n\t\n\t### Read img, vectorize\n\timg = nib.load(str.rstrip(line))\n\ta=img.get_data()\n\tb=np.reshape(a,-1)\n\n\t### Set index of voxels belonging to that roi, set also max values\n\timgIND.put((b>imgMAX).nonzero(), rno)\n\timgMAX = np.maximum(b,imgMAX)\n\n\n### Write out img\nimgINDM = np.reshape(imgIND,isize)\n\naff = img.get_affine()\nhdr = img.get_header()\n#hdr.set_data_dtype(np.int16)\nimg2 = nib.Nifti1Image(imgINDM, aff, hdr)\nimg2.to_filename(DestFile);\n" ]
[ [ "numpy.reshape", "numpy.maximum", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
y3sar/painter_gan
[ "374fb91927ca584b4ef3fd8ba10922c7b5201780" ]
[ "generator.py" ]
[ "import torch\nimport torch.nn as nn\nfrom torchvision.transforms import ToTensor, ToPILImage\n\n\n\n\nclass Generator(nn.Module):\n def __init__(self):\n super().__init__()\n\n\n self.conv_block = nn.Sequential(\n\n nn.ConvTranspose2d(100, 512, 4, 1, 0),\n nn.BatchNorm2d(512),\n nn.ReLU(True),\n\n nn.ConvTranspose2d(512, 256, 4, 2, 1),\n nn.BatchNorm2d(256),\n nn.ReLU(True),\n\n nn.ConvTranspose2d(256, 128, 4, 2, 1),\n nn.BatchNorm2d(128),\n nn.ReLU(True),\n\n nn.ConvTranspose2d(128, 64, 4, 2, 1),\n nn.BatchNorm2d(64),\n nn.ReLU(True),\n\n nn.ConvTranspose2d(64, 3, 4, 2, 1),\n nn.BatchNorm2d(3),\n nn.ReLU(True),\n\n nn.ConvTranspose2d(3, 3, 4, 2, 1),\n nn.Tanh(),\n\n \n\n )\n\n def forward(self, x):\n x = self.conv_block(x)\n \n\n\n return x\n\n\nif __name__ == '__main__':\n\n img = torch.randn(1, 100, 1, 1)\n\n gen = Generator()\n\n print(gen(img).shape)\n\n" ]
[ [ "torch.nn.ConvTranspose2d", "torch.randn", "torch.nn.Tanh", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
siemens/drace
[ "2679067783b1d8f39e4c370cd72a7626ebf5f8e8" ]
[ "tools/ReportConverter/ReportConverter.py" ]
[ "# \n# ReportConverter: A graphical report generator for DRace\n# \n# Copyright 2019 Siemens AG\n# \n# Authors:\n# <Philip Harr> <[email protected]>\n# \n# SPDX-License-Identifier: MIT\n#\n\n## \\package ReportConverter\n## \\brief Python XML to HTML report converter for the better visualization of drace result data\n\n\n\nimport xml.etree.ElementTree as ET\nimport shutil\nimport argparse\nimport pathlib\nimport datetime\nimport html\nimport sys\nfrom subprocess import check_call, STDOUT, DEVNULL\nfrom functools import lru_cache\n\ntry:\n import matplotlib\n import matplotlib.pyplot as plt\n from matplotlib.lines import Line2D\n noMatplotLib = False\nexcept ImportError:\n noMatplotLib = True\n print(\"Matplotlib is not installed.\")\n\n#look for resources path\nif getattr(sys, 'frozen', False):\n SCRIPTPATH = pathlib.Path(sys.executable)\n SCRIPTPATH = pathlib.Path(SCRIPTPATH / \"..\")\nelse :\n SCRIPTPATH = pathlib.Path(pathlib.Path(__file__).resolve().parents[0])\n\n\nif pathlib.Path(SCRIPTPATH / '../resources').is_dir():\n resourcesPath = pathlib.Path(SCRIPTPATH / '../resources')\n\nelse:\n if pathlib.Path(SCRIPTPATH / 'resources').is_dir():\n resourcesPath = pathlib.Path(SCRIPTPATH / 'resources')\n else:\n print(\"path of resources not found\")\n sys.exit(-1)\n\n#Paths\ng_HTMLTEMPLATES = resourcesPath / \"entries.xml\"\ng_CSSPATH = resourcesPath / \"css\"\ng_JSPATH = resourcesPath / \"js\"\n\nDEBUG = False\n\n#info: blacklisting overrules whitelisting\nSOURCEFILE_BL = list()\nSOURCEFILE_WL = list()\nWHITELISTING = False\nNUMBEROFCODELINES = 400\nif NUMBEROFCODELINES % 2:\n print('Number of maximum of displayed code lines must be even, but is:')\n print(str(NUMBEROFCODELINES))\n sys.exit(-1)\n\n#Source Directories\nSOURCE_DIRECTORIES = list()\n\nclass ReportCreator:\n _htmlTemplatesPath = str(g_HTMLTEMPLATES)\n _topStackGraphFileName = 'topStackBarchart.png'\n _errorTimesPlot = 'errorTimes.png'\n\n\n try:\n if check_call(['code', '--version'], stdout=DEVNULL, stderr=STDOUT, shell=True) == 0: #check if vscode is installed, for sourcefile linking\n _vscodeFlag = True\n else:\n _vscodeFlag = False\n except:\n _vscodeFlag = False\n\n\n def __init__(self, pathOfReport, target):\n self.sourcefileList = list()\n self._callStackNumber = 0\n self._errorNumber = 0\n self._snippets = str()\n self.succesfullReportCreation = True\n \n try:\n self._htmlTemplates = (ET.parse(self._htmlTemplatesPath)).getroot()\n except FileNotFoundError:\n print(\"template file is missing\")\n self.succesfullReportCreation = False\n return\n \n self.SCM = SourceCodeManagement()\n self._pathOfReport = pathOfReport\n \n if self._inputValidation():\n hasErrors = self._reportRoot.find('error') != None\n if not noMatplotLib and hasErrors:\n self._makeHistogramm(target)\n self._countTopStackOccurences(target)\n \n self._createReport()\n else:\n print(\"input file is not valid\")\n self.succesfullReportCreation = False\n\n def _inputValidation(self):\n\n \n try:\n self._reportContent = ET.parse(self._pathOfReport)\n except ET.ParseError:\n return 0\n\n self._reportRoot = self._reportContent.getroot()\n \n if self._reportRoot.find('protocolversion') != None and \\\n self._reportRoot.find('protocoltool') != None and \\\n self._reportRoot.find('preamble') != None and \\\n self._reportRoot.find('pid') != None and \\\n self._reportRoot.find('tool') != None and \\\n self._reportRoot.find('args') != None and \\\n self._reportRoot.find('status') != None and \\\n self._reportRoot.tag == 'valgrindoutput':\n\n return 1\n else:\n return 0\n\n def _getHeader(self):\n header = list()\n status = self._reportRoot.findall('status')\n if len(status) == 2:\n status = status[1] ##second status contains finishing values\n strDatetime = status.find('time').text\n if \"T\" in strDatetime:\n date = strDatetime.split('T')[0]\n time = (strDatetime.split('T')[1])[0:-1] #last digit is 'Z' -> not needed\n else:\n date = \"\"\n time = strDatetime\n\n header.append(adjText(date))\n header.append(adjText(time))\n if status.find('duration') != None:\n header.append(adjText(status.find('duration').text))\n header.append(adjText(status.find('duration').get('unit')))\n else:\n header.append(\"\")\n header.append(\"\") \n else:\n header.append(\"\")\n header.append(\"\")\n header.append(\"\")\n header.append(\"\")\n\n arguments = str()\n for arg in self._reportRoot.find('args').find('vargv').findall('arg'):\n arguments += arg.text\n arguments += ' '\n header.append(adjText(arguments[0:-1])) #remove last ' '\n \n header.append(adjText(self._reportRoot.find('args').find('argv').find('exe').text))\n header.append(adjText(self._reportRoot.find('protocolversion').text))\n header.append(adjText(self._reportRoot.find('protocoltool').text))\n\n return header\n\n def _makeFileEntry(self, frame):\n strDir = adjText(self._frameValues[\"dir\"])\n strFile = adjText(self._frameValues[\"file\"])\n strLine = adjText(self._frameValues[\"line\"])\n offset = adjText(self._frameValues[\"offset\"])\n\n if self._vscodeFlag:\n entry = \"<a href='vscode://file/\" + strDir + \"/\" + strFile + \":\" + strLine + \":\" + offset +\"'>\"+ strFile +\":\" + strLine + \":\" + offset + \"</a>\"\n else:\n entry = \"<a href='file://\"+ strDir + \"/\" + strFile + \"'>\" + strFile + \":\" + strLine + \"</a>\"\n \n return entry\n\n def _readFrame(self, frame):\n \n if frame is None:\n self._frameValues = {\"obj\":\"\", \"fn\":\"\", \"ip\":\"\", \"dir\":\"\", \"file\":\"\", \"line\":\"\", \"offset\":\"\"}\n return\n\n obj = frame.find('obj')\n if obj is None:\n obj = \"\"\n else:\n if obj.text is None:\n obj = \"\"\n else:\n obj = obj.text\n fn = frame.find('fn')\n if fn is None:\n fn = \"\"\n else:\n if fn.text is None:\n fn = \"\"\n else:\n fn = fn.text\n ip = frame.find('ip')\n if ip is None:\n ip = \"\"\n else:\n if ip.text is None:\n ip = \"\"\n else:\n ip = ip.text \n\n direc = frame.find('dir')\n if direc is None:\n direc = \"\"\n else:\n if direc.text is None:\n direc = \"\"\n else:\n direc = direc.text \n\n filename = frame.find('file')\n if filename is None:\n filename = \"\"\n else:\n if filename.text is None:\n filename = \"\"\n else:\n filename = filename.text \n\n line = frame.find('line')\n if line is None:\n line = \"0\"\n else:\n if line.text is None:\n line = \"0\"\n else:\n line = line.text \n\n offset = frame.find('offset')\n if offset is None:\n offset = \"0\"\n else:\n if offset.text is None:\n offset = \"0\"\n else:\n offset = offset.text \n\n self._frameValues = {\"obj\":obj, \"fn\":fn, \"ip\":ip, \"dir\":direc, \"file\":filename, \"line\":line, \"offset\":offset}\n\n\n def _createSnippetEntry(self, frame, elementNumber, tag, codeIndex, buttonID):\n \n\n newSnippet = self._htmlTemplates.find('snippet_entry').text\n\n newSnippet = newSnippet.replace('*SNIPPET_VAR*', (\"snippet_\" + str(self._callStackNumber)))\n newSnippet = newSnippet.replace('*STACK_NUMBER*', adjText(hex(elementNumber)))\n newSnippet = newSnippet.replace('*OBJ*', adjText(self._frameValues[\"obj\"]))\n newSnippet = newSnippet.replace('*FUNCTION*', adjText(self._frameValues[\"fn\"]))\n newSnippet = newSnippet.replace('*INSTRUCTION_POINTER*', adjText(self._frameValues[\"ip\"]))\n newSnippet = newSnippet.replace('*CODE_TAG*', tag)\n newSnippet = newSnippet.replace('*SNIPPET_BUTTON_ID*', buttonID)\n\n if (self._frameValues[\"file\"] != \"\"):\n newSnippet = newSnippet.replace('*FILE_NAME_ENTRY*', self._makeFileEntry(frame))\n newSnippet = newSnippet.replace('*DIRECTORY*', adjText(self._frameValues[\"dir\"]))\n newSnippet = newSnippet.replace('*SHORT_DIR*', adjText(self._makeShortDir(self._frameValues[\"dir\"])))\n newSnippet = newSnippet.replace('*LINE_OF_CODE*', adjText(self._frameValues[\"line\"]))\n\n\n if(codeIndex != -1):\n newSnippet = newSnippet.replace('*CODE_ID_VAR*', \"snippet_\"+str(self._callStackNumber)+\"_code\")\n newSnippet = newSnippet.replace('*LANGUAGE*', self.SCM.determineLanguage(adjText(self._frameValues[\"file\"])))\n newSnippet = newSnippet.replace('*FIRST_LINE*', str(self.SCM.getFirstLineOfCodeSnippet(codeIndex)))\n else:\n newSnippet = newSnippet.replace('*CODE_ID_VAR*', \"'None'\")\n\n else:\n newSnippet = newSnippet.replace('*FILE_NAME_ENTRY*', 'no filename avail.')\n newSnippet = newSnippet.replace('*DIRECTORY*', 'no directory avail.')\n newSnippet = newSnippet.replace('*SHORT_DIR*', 'no directory avail.')\n\n self._snippets += newSnippet #append referenced code snippet\n\n def _makeShortDir(self, strDir):\n elements = None\n if \"\\\\\" in strDir:\n elements = strDir.split(\"\\\\\")\n else:\n if \"/\" in strDir:\n elements = strDir.split(\"/\")\n \n if elements != None:\n return elements[0] + \"/\" + elements[1] + \"/.../\" + elements[-1]\n else:\n return \"\"\n\n def _createCallStack(self, errorEntry, position, outputID):\n \n callStack = str()\n stackTemplate = self._htmlTemplates.find('stack_entry').text\n stackArray = errorEntry.findall('stack')\n stack = stackArray[position]\n elementNumber = 0\n\n frames = stack.findall('frame')\n if frames is None:\n return \"\"\n\n for frame in frames:\n self._readFrame(frame) #reads all frame values and fills member var\n \n # updates frame dir if valid sourceDirectories are given, otherwise returns same value\n newDir = self.SCM.searchSourceDirectories(self._frameValues[\"dir\"], self._frameValues[\"file\"])\n self._frameValues[\"dir\"] = adjText(newDir)\n\n noPreview = False \n buttonID = \"button_\" + str(self._errorNumber) + \"_\" + str(position) + \"_\" + str(elementNumber)\n strOutputID = outputID+str(position)\n \n if elementNumber == 0:\n ###make heading for the red box### \n if len(self._errorHeading) == 0:\n self._errorHeading += \"<br> Obj. 1: \" + (adjText(self._frameValues[\"obj\"]) + ': \"' + adjText(self._frameValues[\"fn\"])) + '\" <br> '\n else:\n self._errorHeading += \"Obj. 2: \" + (adjText(self._frameValues[\"obj\"]) + ': \"' + adjText(self._frameValues[\"fn\"])) + '\"'\n \n #general entries (always available)\n newStackElement = stackTemplate.replace('*STACK_NUMBER*', adjText(hex(elementNumber))+\":\")\n newStackElement = newStackElement.replace('*SNIPPET_VAR*', (\"snippet_\" + str(self._callStackNumber)))\n newStackElement = newStackElement.replace('*OUTPUT_ID*', strOutputID)\n newStackElement = newStackElement.replace('*FUNCTION*', adjText(self._frameValues['fn']))\n newStackElement = newStackElement.replace('*BUTTON_ID*', buttonID)\n \n\n if (self._frameValues[\"file\"]!= \"\"): #file is in xml report defined\n codeIndex, tag = self.SCM.handleSourceCode(self._frameValues[\"file\"], self._frameValues[\"dir\"], self._frameValues[\"line\"])\n newStackElement = newStackElement.replace('*FILE*', adjText(self._frameValues[\"file\"]))\n\n if(codeIndex != -1):\n newStackElement = newStackElement.replace('*CODE_VAR*', str(codeIndex))\n newStackElement = newStackElement.replace('*CODE_ID_VAR*', \"'snippet_\"+str(self._callStackNumber)+\"_code'\")\n newStackElement = newStackElement.replace('*LINE_OF_CODE*', adjText(self._frameValues[\"line\"]))\n newStackElement = newStackElement.replace('*FIRST_LINE*', str(self.SCM.getFirstLineOfCodeSnippet(codeIndex))) \n \n else: #file is not available on device or file is blacklisted or not whitelisted\n noPreview = True\n \n \n else: #no filepath for file in xml is given \n codeIndex = -1\n tag = self._htmlTemplates.find('no_code_entry').text\n newStackElement = newStackElement.replace('*FILE*', 'no filename avail.')\n noPreview = True\n\n if noPreview:\n newStackElement = newStackElement.replace('*CODE_VAR*', \"'None'\")\n newStackElement = newStackElement.replace('*CODE_ID_VAR*', \"'None'\")\n newStackElement = newStackElement.replace('*LINE_OF_CODE*', \"'None'\")\n newStackElement = newStackElement.replace('*FIRST_LINE*', \"'NONE'\") \n searchStr = 'class=\"'\n insertPosition = newStackElement.find(searchStr)+len(searchStr) #to add the \".grey\" class the position before after class\n #insertPosition += newStackElement[insertPosition:].find('\"')\n newStackElement = newStackElement[:insertPosition] + \"grey-button \" + newStackElement[insertPosition:] \n\n \n self._createSnippetEntry(frame, elementNumber, tag, codeIndex, buttonID)\n callStack += newStackElement #append stack element\n elementNumber += 1\n self._callStackNumber += 1 #increase global call stack number (used for reference variables)\n\n return callStack\n\n def _makeHistogramm(self, target):\n errorTimes = dict()\n statusNode = self._reportRoot.findall('status')[1]\n \n if statusNode.find('duration') is None:\n self._errorTimesPlot = \"\"\n return\n \n totalDuration = int(statusNode.find('duration').text)\n errors = self._reportRoot.findall('error')\n \n for error in errors:\n timePoint = (round(float(100 * int(error.find('timestamp').text) /totalDuration))) #get occurance in %\n if errorTimes.get(timePoint) != None:\n value = errorTimes.pop(timePoint)\n errorTimes.update({timePoint: int(value)+1})\n else:\n errorTimes.update({timePoint: 1})\n \n x = list(errorTimes.keys())\n y = list(errorTimes.values())\n #make plot \n fig = plt.figure(figsize=(10,4)) \n ax = plt.axes() \n ax.scatter(x, y, color='#009999', edgecolor='black')\n\n xRangeEnd = max(y)+1\n if xRangeEnd < 3: #0, 1, 2 shall be always visible, even if max(y) is only 1\n xRangeEnd = 3\n ax.set_yticks([i for i in range(0, xRangeEnd)])\n ax.set_xticks([i for i in range(0, 110, 10)])\n \n plt.title('Error occurrences by time',fontfamily=\"monospace\", fontweight='bold')\n plt.ylabel('Occurrences', fontfamily=\"monospace\",fontweight='bold')\n plt.xlabel('Execution of program in %. \\n Total execution time = ' + str(totalDuration) + 'ms', fontfamily=\"monospace\",fontweight='bold') \n\n fig.add_axes(ax)\n #plt.show()\n figPath = pathlib.Path(target+'/'+self._errorTimesPlot)\n plt.savefig(str(figPath), dpi=300, format='png', bbox_inches='tight', orientation='landscape') # use format='svg' or 'pdf' for vectorial pictures\n\n def _countTopStackOccurences(self, target):\n topStackOccurences = dict()\n errors = self._reportRoot.findall('error')\n \n for error in errors:\n stacks = error.findall('stack')\n for i in range(0,2): \n topFrame = stacks[i].find('frame') #returns first element of with frame tag\n \n if(topFrame != None):\n self._readFrame(topFrame)\n tmp1 = self._frameValues[\"file\"]\n tmp2 = self._frameValues[\"fn\"]\n\n if(tmp1 != \"None\" and tmp2 != \"None\"):\n if(len(tmp2) > 20): #split function name in half if it is too long\n tmp2 = tmp2[:len(tmp2)//2] + '\\n' + tmp2[len(tmp2)//2:]\n identifier = tmp1 + \":\\n\" + tmp2\n\n if topStackOccurences.get(identifier) != None:\n value = topStackOccurences.pop(identifier)\n topStackOccurences.update({identifier: int(value)+1})\n else:\n topStackOccurences.update({identifier: 1})\n\n \n #sort dict\n sortedOccurences = sorted(topStackOccurences.items(), key=lambda kv: kv[1])\n x=list()\n y=list()\n for ele in sortedOccurences[-5:]: #append the 5 largest values in ascending order\n if len(ele[0]) < 250:\n x.append(ele[0]) #x values (basically the function names)\n else:\n x.append(ele[0][:250]+\". . .\")\n y.append(ele[1]) #y values occurrences (bar height)\n\n #make plot \n fig = plt.figure(figsize=(10,4)) \n ax = plt.axes() \n barWidth = 0.9 # the width of the bars \n xLoc = list(range(len(y))) # the x locations for the groups\n ax.barh([loc for loc in xLoc], y, barWidth, color='#009999')\n ax.set_yticks([loc for loc in xLoc])\n ax.set_yticklabels(reversed(['#'+str(rank) for rank in range(1,len(y)+1)]), minor=False)\n legend_lines = [Line2D([0], [0], color='#009999', lw=rank) for rank in range(len(y)+1, 1, -1)]\n ax.legend(legend_lines, reversed(x), loc='center', bbox_to_anchor=(0.5, -0.1*(len(y)+2)))\n \n plt.title('Top five functions by top of stack occurrences',fontfamily=\"monospace\", fontweight='bold')\n plt.xlabel('No. of top of stack occurrences', fontfamily=\"monospace\",fontweight='bold') \n\n for i,v in enumerate(y):\n ax.text(v, i, str(v), ha='left',color='black', fontweight='bold')\n \n \n fig.add_axes(ax)\n #plt.show()\n figPath = pathlib.Path(target+'/'+self._topStackGraphFileName)\n plt.savefig(str(figPath), dpi=300, format='png', bbox_inches='tight', orientation='landscape') # use format='svg' or 'pdf' for vectorial pictures\n \n def _createErrorList(self):\n self._strErrors = str()\n \n errorTemplate = self._htmlTemplates.find('error_entry').text\n errorList = self._reportRoot.findall('error')\n self._numberOfErrors = len(errorList)\n \n for error in errorList:\n \n outputID = \"output_\"+str(self._errorNumber)+\"_\"\n newError = errorTemplate.replace('*ERROR_ID*', adjText(error.find('unique').text))\n newError = newError.replace('*ERROR_TYPE*', adjText(error.find('kind').text))\n \n xwhat = error.findall('xwhat')\n errortext1 = xwhat[0].find('text').text\n #fall back to xauxhwaht -> valgrind format\n if(len(xwhat) == 1):\n element = error.find('xauxwhat')\n if element != None:\n errortext2 = element.find('text').text\n else:\n errortext2 = \"\"\n else:\n errortext2 = xwhat[1].find('text').text\n\n newError = newError.replace('*XWHAT_TEXT_1*', adjText(errortext1))\n newError = newError.replace('*XWHAT_TEXT_2*', adjText(errortext2))\n\n # Resolved Address info\n resolvedaddress = error.find('resolvedaddress')\n if resolvedaddress != None:\n raModname = resolvedaddress.find('modname')\n resolvedaddressEntry = \"<h5>Resolved Address</h5>\" + \"<p class='reduced-margin'><b>Module Name: </b>\" \\\n + adjText(raModname.text) + \"</p>\"\n \n raSymname = resolvedaddress.find('symname')\n if raSymname != None:\n resolvedaddressEntry = resolvedaddressEntry + \"<p class='reduced-margin'><b>Symbol Name: </b>\" \\\n + adjText(raSymname.text) + \"</p>\"\n\n raFile = resolvedaddress.find('file')\n if raFile != None:\n raLine = resolvedaddress.find('line')\n raOffset = resolvedaddress.find('offset')\n resolvedaddressEntry = resolvedaddressEntry + \"<p class='reduced-margin'><b>File: </b>\" + adjText(raFile.text) + \"</p> <p class='reduced-margin'><b>Line: </b>\" \\\n + adjText(raLine.text) + \"</p> <p class='reduced-margin'><b>Offset: </b>\" + adjText(raOffset.text) + \"</p>\"\n \n else:\n resolvedaddressEntry = \"\"\n\n newError = newError.replace('*RESOLVED_ADDRESS_ENTRY*', resolvedaddressEntry)\n\n self._errorHeading = str() #reset errorHeading, will be filled filled by _createCallStack\n newError = newError.replace('*CALL_STACK_ENTRIES_1*', self._createCallStack(error, 0, outputID))\n if errortext2 != \"\":\n newError = newError.replace('*CALL_STACK_ENTRIES_2*', self._createCallStack(error, 1, outputID))\n else:\n newError = newError.replace('*CALL_STACK_ENTRIES_2*', \"No Callstack Available\")\n \n newError = newError.replace('*OUTPUT_ID_1*', outputID+'0')\n newError = newError.replace('*OUTPUT_ID_2*', outputID+'1')\n newError = newError.replace('*ERROR_HEADING*', self._errorHeading)\n\n self._errorNumber += 1\n self._strErrors += newError\n\n self.SCM.searchSourceDirectories.cache_clear()\n\n def _createHeader(self):\n hasErrors = self._reportRoot.find('error') != None\n headerInformation = self._getHeader()\n self.htmlReport = self._htmlTemplates.find('base_entry').text\n self.htmlReport = self.htmlReport.replace('*DATE*', headerInformation[0])\n self.htmlReport = self.htmlReport.replace('*TIME*', headerInformation[1])\n self.htmlReport = self.htmlReport.replace('*DURATION*', headerInformation[2])\n self.htmlReport = self.htmlReport.replace('*DURATION_UNIT*', headerInformation[3])\n self.htmlReport = self.htmlReport.replace('*ARGS*', headerInformation[4])\n self.htmlReport = self.htmlReport.replace('*EXE*', headerInformation[5])\n self.htmlReport = self.htmlReport.replace('*PROTOCOLVERSION*', headerInformation[6])\n self.htmlReport = self.htmlReport.replace('*PROTOCOLTOOL*', headerInformation[7])\n self.htmlReport = self.htmlReport.replace('*NUMBER_OF_ERRORS*', str(self._numberOfErrors))\n self.htmlReport = self.htmlReport.replace('*ERROR_ENTRIES*', self._strErrors)\n if not noMatplotLib and hasErrors:\n matplotlib_snippet = self._htmlTemplates.find('matplotlib_entries').text\n matplotlib_snippet = matplotlib_snippet.replace('*TOP_OF_STACK_GRAPH*', self._topStackGraphFileName)\n matplotlib_snippet = matplotlib_snippet.replace('*ERROR_TIMES_PLOT*', self._errorTimesPlot)\n self.htmlReport = self.htmlReport.replace('*MATPLOTLIB_PICTURES*', matplotlib_snippet)\n else:\n self.htmlReport = self.htmlReport.replace('*MATPLOTLIB_PICTURES*', '')\n\n def _createReport(self):\n self._createErrorList()\n self._createHeader()\n self.htmlReport = self.htmlReport.replace(\"*SNIPPET_VARIABLES*\", self._snippets)\n self.htmlReport = self.SCM.createCodeVars(self.htmlReport)\n\n\nclass SourceCodeManagement:\n def __init__(self):\n self._sourcefilelist = list()\n self._htmlTemplatesPath = str(g_HTMLTEMPLATES)\n self._htmlTemplates = (ET.parse(self._htmlTemplatesPath)).getroot()\n\n def _createSourcefileEntry(self, path, line):\n #one entry consists of the full file path the line number of interest \n sourceFile = open(path, mode='r')\n sourceLineList = sourceFile.readlines()\n if len(sourceLineList) > NUMBEROFCODELINES:\n newElement = [path, int(line), False]\n else:\n newElement = [path, int(line), True]\n \n self._sourcefilelist.append(newElement)\n return self._sourcefilelist.index(newElement)\n\n \n def _returnCode(self, fullPath, justExistance, line = 0):\n returnSrc = False\n try: #may throw an an exception in earlier version (until 3.6), therefore try-catch \n fp = pathlib.Path(fullPath).resolve() #returns absolute path\n except FileNotFoundError:\n return -1\n except OSError: #if path is available, but for any reason not reachable (e.g. locked by bitlocker) OSError is thrown\n return -1\n\n if fp.is_file():\n for element in SOURCEFILE_BL: #blacklisting routine\n if str(element) in str(fp): #both are absoulte paths, so comparing is valid\n return -1\n \n if WHITELISTING:\n for element in SOURCEFILE_WL:\n if str(element) in str(fullPath):\n returnSrc = True\n break\n if not returnSrc:\n return -1\n if justExistance:\n sourceCode = self._getLines(fullPath, line)\n if sourceCode == -1: ##line was not found\n return -1\n return 0\n else:\n return -1\n \n #if we are here we want to return the source code\n return adjText(self._getLines(fullPath, line))\n\n\n def _getLines(self, path, line):\n sourceFile = open(path, mode='r')\n sourceLineList = sourceFile.readlines()\n\n if len(sourceLineList) < line: #the found file contains less lines than the target (e.g. wrong line number from drace)\n return -1\n\n if len(sourceLineList) > NUMBEROFCODELINES:\n if line <= NUMBEROFCODELINES//2:\n begin = 0\n end = NUMBEROFCODELINES\n else:\n begin = (line - NUMBEROFCODELINES//2) - 1 #-1 because array starts with 0\n end = begin + NUMBEROFCODELINES\n\n sourceLineList = sourceLineList[begin:end]\n \n sourceCode = str()\n for sourceLine in sourceLineList:\n sourceCode += sourceLine\n\n sourceFile.close()\n return sourceCode\n\n\n def handleSourceCode(self, filename, directory, line):\n fullPath = pathlib.Path(directory +'/'+ filename)\n\n src = self._returnCode(fullPath, 1, int(line))\n if src == -1:\n return -1, self._htmlTemplates.find('no_code_entry').text\n\n index = -1\n #check if source file is already in the list\n for item in self._sourcefilelist:\n if item[0] == fullPath:\n if item[2] or (int(line) - NUMBEROFCODELINES//10) <= item[1] <= (int(line) + NUMBEROFCODELINES//10): \n index = self._sourcefilelist.index(item)\n #entry = item\n\n if index == -1:\n index = self._createSourcefileEntry(fullPath, line)\n \n strIndex = 'code_' + str(index) \n return strIndex, (self._htmlTemplates.find('code_entry').text)\n\n def createCodeVars(self, report):\n codeString = str()\n\n for sourceObject in self._sourcefilelist:\n src = self._returnCode(sourceObject[0], justExistance=0, line = sourceObject[1])\n tmpCode = \"code_\" + str(self._sourcefilelist.index(sourceObject)) + ' = \"' + src + '\";\\n'\n codeString += tmpCode\n\n report = report.replace(\"*CODE_VARIABLES*\", codeString)\n return report\n\n def determineLanguage(self, filename):\n fileParts = filename.split('.')\n if len(fileParts) == 1:\n return 'cpp' #files without file endigs are treated as cpp files\n else:\n ending = fileParts[-1]\n if ending == 'c':\n return 'c'\n elif ending == 'cpp':\n return 'cpp'\n elif ending == 'h':\n return 'cpp'\n elif ending == 'cs':\n return 'csharp'\n elif ending == 'css':\n return 'css'\n elif ending == 'js':\n return 'javascript'\n elif ending == 'html':\n return 'markup'\n else:\n return 'cpp' \n\n def getFirstLineOfCodeSnippet(self, index):\n codeSnippet = int(index.split(\"_\")[-1]) #index is e.g. code_3\n srcObject = self._sourcefilelist[codeSnippet]\n\n if srcObject[2]:\n return 1\n else:\n firstLine = srcObject[1] - NUMBEROFCODELINES//2\n return firstLine #srcObject[1] is line of interest of snippet\n\n @lru_cache(maxsize=100)\n def searchSourceDirectories(self, dir, file): \n if pathlib.Path(pathlib.Path(dir) / file).is_file():\n # path to file in xml file is valid\n return dir \n else:\n # path to file in xml file is NOT valid\n if not SOURCE_DIRECTORIES:\n # no sourceDirectories args given\n print(f\"Cannot find file '{file}' in directory '{dir}'.\")\n return dir\n else:\n print(f\"Cannot find file '{file}' in directory '{dir}'. Searching through given source directories ...\")\n # search in sourceDirectories given from args if applicable\n for customDirPath in SOURCE_DIRECTORIES:\n customDir = pathlib.Path(customDirPath) \n fileInstances = customDir.glob(f'**/{file}') # generator for found file instances\n try:\n f1 = next(fileInstances)\n try:\n f2 = next(fileInstances)\n # Check if next found file f2 has a parent directory which supersets that of first found file f1\n if str(f1.resolve().parent) == str(f2.resolve().parent)[:len(str(f1.resolve().parent))]:\n return str(f2.resolve().parent) # second valid file instance in customDirPath\n else:\n return str(f1.resolve().parent) # first valid file instance in customDirPath\n\n except StopIteration:\n # Only one valid file instance found in customDirPath\n return str(f1.resolve().parent)\n except StopIteration:\n # No file instance found in customDirPath element\n continue\n\n # Search for file instances in given sourceDirectories failed \n print(f\"Cannot find file '{file}' in given source directories.\")\n return dir\n\n\ndef adjText(text): #change html symbols e.g. & -> &amp;\n text = text.replace('`', '\\'')\n text = text.replace('\\\\', '/')\n text = text.replace('\\n', '\\\\n')\n return html.escape(text)\n\ndef parseArgumentString(fileList, strEntries):\n strEntries = strEntries.replace(\"\\\\\",\"/\")\n listEntries = strEntries.split(',')\n for entry in listEntries: \n #remove potential leading and trailing whitespaces\n while entry[0] == ' ':\n entry = entry[1:]\n while entry[-1] == ' ':\n entry = entry[:-1]\n\n newObject = pathlib.Path(entry)\n newObject = newObject.resolve()\n fileList.append(newObject) \n\n return \n\ndef returnDateString():\n date = datetime.datetime.utcnow()\n return date.strftime('%Y%m%d_%H%M')\n\ndef main():\n global SOURCEFILE_BL, SOURCEFILE_WL, WHITELISTING, SOURCE_DIRECTORIES, DEBUG\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", \"--inputFile\", help='define <input_file>', type=str)\n parser.add_argument(\"-o\", \"--outputDirectory\", help='define <output_directory>', type=str)\n parser.add_argument(\"-b\", \"--blacklist\", help='add blacklist entries <entry1,entry2 ...>', type=str)\n parser.add_argument(\"-w\", \"--whitelist\", help='add whitelist entries <entry1,entry2 ...>', type=str)\n parser.add_argument(\"-s\", \"--sourceDirectories\", help='add source directories <entry1,entry2 ...>', type=str)\n parser.add_argument(\"--Debug\", help='Debug Mode', action=\"store_true\")\n args = parser.parse_args()\n \n ###args handling\n if args.Debug:\n print(\"Debug Mode is on\")\n inFile = pathlib.Path(SCRIPTPATH / 'test_files/test.xml') \n targetDirectory = pathlib.Path(SCRIPTPATH / 'test_files/output') \n\n else:\n if args.inputFile != None:\n inFile = pathlib.Path(args.inputFile)\n else:\n print(\"You must specify an input file\")\n print()\n parser.print_help()\n sys.exit(-1)\n\n if not inFile.is_file():\n print(\"Your input file does not exist\")\n parser.print_help()\n sys.exit(-1)\n\n strDate = returnDateString()\n\n if not args.Debug:\n if args.outputDirectory != None:\n targetDirectory = pathlib.Path(args.outputDirectory+'/drace_report_'+strDate)\n else:\n targetDirectory = pathlib.Path('./drace_report_'+strDate)\n\n if args.blacklist != None:\n parseArgumentString(SOURCEFILE_BL, args.blacklist)\n \n if args.whitelist != None:\n parseArgumentString(SOURCEFILE_WL, args.whitelist)\n WHITELISTING = True\n \n if args.sourceDirectories != None:\n parseArgumentString(SOURCE_DIRECTORIES, args.sourceDirectories)\n #end of args handling\n\n \n if not targetDirectory.is_dir():\n targetDirectory.mkdir()\n\n #report gets generated here\n report = ReportCreator(str(inFile), str(targetDirectory))\n\n if report.succesfullReportCreation:\n\n #write report to destination\n output = open(str(targetDirectory)+'/index.html', mode='w')\n output.write(report.htmlReport)\n output.close()\n\n #copy needed files to destination\n cssPath = pathlib.Path(str(targetDirectory)+\"/css\")\n jsPath = pathlib.Path(str(targetDirectory)+\"/js\")\n\n if cssPath.is_dir():\n shutil.rmtree(str(cssPath))\n \n if jsPath.is_dir():\n shutil.rmtree(str(jsPath))\n\n shutil.copytree(str(g_CSSPATH.resolve()), str(targetDirectory / \"css\"))\n shutil.copytree(str(g_JSPATH.resolve()), str(targetDirectory / \"js\"))\n shutil.copy(str((resourcesPath / 'legend.png').resolve()), str(targetDirectory))\n print(\"Report creation successful\")\n print(\"Report is at:\")\n print(targetDirectory)\n return 0\n\n else:\n print(\"Report creation was NOT successful\")\n targetDirectory.rmdir()\n return -1\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "matplotlib.pyplot.title", "matplotlib.pyplot.figure", "matplotlib.lines.Line2D", "matplotlib.pyplot.axes", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
chao1224/SGNN-EBM
[ "bda4c486e8ecb9775b635757dbe1071878be7b8a" ]
[ "src/models/SGNN_EBM_models.py" ]
[ "import torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch_scatter import scatter_add\n\n\nclass NCE_C_Parameter(torch.nn.Module):\n def __init__(self, N):\n super(NCE_C_Parameter, self).__init__()\n self.NCE_C = nn.Parameter(torch.zeros(N, requires_grad=True))\n\n\nclass GNN_EBM_Layer_01(torch.nn.Module):\n def __init__(self, input_dim, output_dim):\n super(GNN_EBM_Layer_01, self).__init__()\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.edge_layer = torch.nn.Linear(input_dim, output_dim)\n self.node_layer = torch.nn.Linear(input_dim, output_dim)\n self.mlp = torch.nn.Linear(input_dim, output_dim)\n\n def node_message_passing(self, x, x_2nd_agg, edge):\n T = x.size()[1]\n node_in, node_out = edge[0], edge[1] # M, M\n\n update = (scatter_add(x_2nd_agg, node_out, dim=1, dim_size=T) +\n scatter_add(x_2nd_agg, node_in, dim=1, dim_size=T)) / 2 # B, T, d\n x = x + update # B, T, d\n\n return x\n\n def forward(self, x_1st, x_2nd, edge):\n '''\n :param x: (B, T, 2, d)\n :param x_2nd: (B, M, 4, d)\n :param edge: (M, 2)\n :return: (B, T, 2, d_out)\n '''\n aggregate_indice = torch.LongTensor([0, 0, 1, 1]).to(x_1st.device)\n node_i_indice = torch.LongTensor([0, 0, 1, 1]).to(x_1st.device)\n node_j_indice = torch.LongTensor([0, 1, 0, 1]).to(x_1st.device)\n\n x_1st_neg = x_1st[:, :, 0, :] # B, T, d\n x_1st_pos = x_1st[:, :, 1, :] # B, T, d\n\n x_2nd_agg = scatter_add(x_2nd, aggregate_indice, dim=2) # B, T, 2, d\n x_2nd_neg = x_2nd_agg[:, :, 0, :] # B, M, d\n x_2nd_pos = x_2nd_agg[:, :, 1, :] # B, M, d\n\n x_neg = self.node_message_passing(x_1st_neg, x_2nd_neg, edge) # B, T, d\n x_pos = self.node_message_passing(x_1st_pos, x_2nd_pos, edge) # B, T, d\n x = torch.stack([x_neg, x_pos], dim=2) # B, T, 2, d\n x = self.node_layer(x) # B, T, 2, d\n\n edge_i = torch.index_select(x_1st, 1, edge[0]) # B, M, 2, dim\n edge_i = torch.index_select(edge_i, 2, node_i_indice) # B, M, 4, dim\n\n edge_j = torch.index_select(x_1st, 1, edge[1]) # B, M, 2, dim\n edge_j = torch.index_select(edge_j, 2, node_j_indice) # B, M, 4, dim\n\n edge = x_2nd + self.mlp(edge_i + edge_j) # B, M, 4, d\n edge = self.edge_layer(edge)\n\n return x, edge\n\n\nclass GNN_Energy_Model_1st_Order_01(torch.nn.Module):\n def __init__(self, ebm_GNN_dim, ebm_GNN_layer_num, output_dim, dropout=0, concat=False):\n super(GNN_Energy_Model_1st_Order_01, self).__init__()\n self.ebm_GNN_dim = ebm_GNN_dim\n self.ebm_GNN_layer_num = ebm_GNN_layer_num - 1\n self.dropout = dropout\n self.output_dim = output_dim\n self.concat = concat\n\n hidden_layers_dim = [ebm_GNN_dim] * ebm_GNN_layer_num\n\n self.hidden_layers = torch.nn.ModuleList()\n for in_, out_ in zip(hidden_layers_dim[:-1], hidden_layers_dim[1:]):\n self.hidden_layers.append(GNN_EBM_Layer_01(in_, out_))\n\n if self.concat:\n hidden_dim_sum = sum(hidden_layers_dim)\n else:\n hidden_dim_sum = ebm_GNN_dim\n self.node_readout = torch.nn.Sequential(\n torch.nn.Linear(2 * hidden_dim_sum, 2 * hidden_dim_sum),\n torch.nn.ReLU(),\n torch.nn.Linear(2 * hidden_dim_sum, hidden_dim_sum),\n torch.nn.ReLU(),\n torch.nn.Linear(hidden_dim_sum, output_dim)\n )\n return\n\n def forward(self, x_1st, x_2nd, edge):\n '''\n :param x_1st: B,T,2,dim\n :param x_2nd: B,M,4,dim\n :param edge: 2,M\n :return: B,T,1\n '''\n B, T = x_1st.size()[:2]\n h_node_list = [x_1st]\n x_node, x_edge = x_1st, x_2nd\n\n for i in range(self.ebm_GNN_layer_num):\n x_node, x_edge = self.hidden_layers[i](x_node, x_edge, edge)\n if i < self.ebm_GNN_layer_num - 1:\n x_node = F.relu(x_node)\n # x_edge = F.relu(x_edge)\n x_node = F.dropout(x_node, self.dropout, training=self.training)\n # x_edge = F.dropout(x_edge, self.dropout, training=self.training)\n h_node_list.append(x_node)\n\n if self.concat:\n h = torch.cat(h_node_list, dim=3).view(B, T, -1) # B, T, 2*layer_num*d\n else:\n h = x_node.view(B, T, -1) # B, T, 2*d\n h = self.node_readout(h) # B, T, 1\n return h\n\n\nclass GNN_Energy_Model_1st_Order_02(torch.nn.Module):\n def __init__(self, ebm_GNN_dim, ebm_GNN_layer_num, output_dim, dropout=0, concat=False):\n super(GNN_Energy_Model_1st_Order_02, self).__init__()\n self.ebm_GNN_dim = ebm_GNN_dim\n self.ebm_GNN_layer_num = ebm_GNN_layer_num - 1\n self.dropout = dropout\n self.output_dim = output_dim\n self.concat = concat\n\n hidden_layers_dim = [ebm_GNN_dim] * ebm_GNN_layer_num\n\n self.hidden_layers = torch.nn.ModuleList()\n for in_, out_ in zip(hidden_layers_dim[:-1], hidden_layers_dim[1:]):\n self.hidden_layers.append(GNN_EBM_Layer_01(in_, out_))\n\n if self.concat:\n hidden_dim_sum = sum(hidden_layers_dim)\n else:\n hidden_dim_sum = ebm_GNN_dim\n self.node_readout = torch.nn.Linear(2 * hidden_dim_sum, output_dim)\n return\n\n def forward(self, x_1st, x_2nd, edge):\n '''\n :param x_1st: B,T,2,dim\n :param x_2nd: B,M,4,dim\n :param edge: 2,M\n :return: B,T,1\n '''\n B, T = x_1st.size()[:2]\n h_node_list = [x_1st]\n x_node, x_edge = x_1st, x_2nd\n\n for i in range(self.ebm_GNN_layer_num):\n x_node, x_edge = self.hidden_layers[i](x_node, x_edge, edge)\n if i < self.ebm_GNN_layer_num - 1:\n x_node = F.relu(x_node)\n # x_edge = F.relu(x_edge)\n x_node = F.dropout(x_node, self.dropout, training=self.training)\n # x_edge = F.dropout(x_edge, self.dropout, training=self.training)\n h_node_list.append(x_node)\n\n if self.concat:\n h = torch.cat(h_node_list, dim=3).view(B, T, -1) # B, T, 2*layer_num*d\n else:\n h = x_node.view(B, T, -1) # B, T, 2*d\n h = self.node_readout(h) # B, T, 1\n return h\n\n\nclass GNN_Energy_Model_2nd_Order_01(torch.nn.Module):\n def __init__(self, ebm_GNN_dim, ebm_GNN_layer_num, dropout=0, concat=False):\n super(GNN_Energy_Model_2nd_Order_01, self).__init__()\n self.ebm_GNN_dim = ebm_GNN_dim\n self.ebm_GNN_layer_num = ebm_GNN_layer_num - 1\n self.dropout = dropout\n self.concat = concat\n\n hidden_layers_dim = [ebm_GNN_dim] * ebm_GNN_layer_num\n\n self.hidden_layers = torch.nn.ModuleList()\n for in_, out_ in zip(hidden_layers_dim[:-1], hidden_layers_dim[1:]):\n self.hidden_layers.append(GNN_EBM_Layer_01(in_, out_))\n\n if self.concat:\n hidden_dim_sum = sum(hidden_layers_dim)\n else:\n hidden_dim_sum = ebm_GNN_dim\n self.node_readout = torch.nn.Sequential(\n torch.nn.Linear(hidden_dim_sum, 2 * hidden_dim_sum),\n torch.nn.ReLU(),\n torch.nn.Linear(2 * hidden_dim_sum, hidden_dim_sum),\n torch.nn.ReLU(),\n torch.nn.Linear(hidden_dim_sum, 1)\n )\n self.edge_readout = torch.nn.Sequential(\n torch.nn.Linear(hidden_dim_sum, 2 * hidden_dim_sum),\n torch.nn.ReLU(),\n torch.nn.Linear(2 * hidden_dim_sum, hidden_dim_sum),\n torch.nn.ReLU(),\n torch.nn.Linear(hidden_dim_sum, 1)\n )\n return\n\n def forward(self, x_1st, x_2nd, edge):\n '''\n :param x_1st: B,T,2,dim\n :param x_2nd: B,M,4,dim\n :param edge: 2,M\n :return: (B,T,2), (B,M,4)\n '''\n B, T = x_1st.size()[:2]\n M = edge.size()[1]\n h_node_list = [x_1st]\n h_edge_list = [x_2nd]\n x_node, x_edge = x_1st, x_2nd\n\n for i in range(self.ebm_GNN_layer_num):\n x_node, x_edge = self.hidden_layers[i](x_node, x_edge, edge)\n if i < self.ebm_GNN_layer_num - 1:\n x_node = F.relu(x_node)\n # x_edge = F.relu(x_edge)\n x_node = F.dropout(x_node, self.dropout, training=self.training)\n # x_edge = F.dropout(x_edge, self.dropout, training=self.training)\n h_node_list.append(x_node)\n h_edge_list.append(x_edge)\n\n if self.concat:\n h_node = torch.cat(h_node_list, dim=3) # B, T, 2, layer_num*d\n h_edge = torch.cat(h_edge_list, dim=3) # B, M, 4, layer_num*d\n else:\n h_node = x_node # B, T, 2, d\n h_edge = x_edge # B, M, 4, d\n h_node = self.node_readout(h_node) # B, T, 2, 1\n h_edge = self.edge_readout(h_edge) # B, M, 4, 1\n h_node = h_node.squeeze(3) # B, T, 2\n h_edge = h_edge.squeeze(3) # B, M, 4\n return h_node, h_edge\n\n\nclass GNN_Energy_Model_2nd_Order_02(torch.nn.Module):\n def __init__(self, ebm_GNN_dim, ebm_GNN_layer_num, dropout=0, concat=False):\n super(GNN_Energy_Model_2nd_Order_02, self).__init__()\n self.ebm_GNN_dim = ebm_GNN_dim\n self.ebm_GNN_layer_num = ebm_GNN_layer_num - 1\n self.dropout = dropout\n self.concat = concat\n\n hidden_layers_dim = [ebm_GNN_dim] * ebm_GNN_layer_num\n\n self.hidden_layers = torch.nn.ModuleList()\n for in_, out_ in zip(hidden_layers_dim[:-1], hidden_layers_dim[1:]):\n self.hidden_layers.append(GNN_EBM_Layer_01(in_, out_))\n\n if self.concat:\n hidden_dim_sum = sum(hidden_layers_dim)\n else:\n hidden_dim_sum = ebm_GNN_dim\n self.node_readout = torch.nn.Sequential(\n torch.nn.Linear(2 * hidden_dim_sum, 2 * hidden_dim_sum),\n torch.nn.ReLU(),\n torch.nn.Linear(2 * hidden_dim_sum, hidden_dim_sum),\n torch.nn.ReLU(),\n torch.nn.Linear(hidden_dim_sum, 2)\n )\n self.edge_readout = torch.nn.Sequential(\n torch.nn.Linear(4 * hidden_dim_sum, 2 * hidden_dim_sum),\n torch.nn.ReLU(),\n torch.nn.Linear(2 * hidden_dim_sum, hidden_dim_sum),\n torch.nn.ReLU(),\n torch.nn.Linear(hidden_dim_sum, 4)\n )\n return\n\n def forward(self, x_1st, x_2nd, edge):\n '''\n :param x_1st: B,T,2,dim\n :param x_2nd: B,M,4,dim\n :param edge: 2,M\n :return: (B,T,2), (B,M,4)\n '''\n B, T = x_1st.size()[:2]\n M = x_2nd.size()[1]\n h_node_list = [x_1st]\n h_edge_list = [x_2nd]\n x_node, x_edge = x_1st, x_2nd\n\n for i in range(self.ebm_GNN_layer_num):\n x_node, x_edge = self.hidden_layers[i](x_node, x_edge, edge)\n if i < self.ebm_GNN_layer_num - 1:\n x_node = F.relu(x_node)\n # x_edge = F.relu(x_edge)\n x_node = F.dropout(x_node, self.dropout, training=self.training)\n # x_edge = F.dropout(x_edge, self.dropout, training=self.training)\n h_node_list.append(x_node)\n h_edge_list.append(x_edge)\n\n if self.concat:\n h_node = torch.cat(h_node_list, dim=3).view(B, T, -1) # B, T, 2*layer_num*d\n h_edge = torch.cat(h_edge_list, dim=3).view(B, M, -1) # B, M, 4*layer_num*d\n else:\n h_node = x_node.view(B, T, -1) # B, T, 2*d\n h_edge = x_edge.view(B, M, -1) # B, M, 4*d\n h_node = self.node_readout(h_node) # B, T, 2\n h_edge = self.edge_readout(h_edge) # B, M, 4\n return h_node, h_edge\n\n\nclass GNN_Energy_Model_2nd_Order_03(torch.nn.Module):\n def __init__(self, ebm_GNN_dim, ebm_GNN_layer_num, dropout=0, concat=False):\n super(GNN_Energy_Model_2nd_Order_03, self).__init__()\n self.ebm_GNN_dim = ebm_GNN_dim\n self.ebm_GNN_layer_num = ebm_GNN_layer_num - 1\n self.dropout = dropout\n self.concat = concat\n\n hidden_layers_dim = [ebm_GNN_dim] * ebm_GNN_layer_num\n\n self.hidden_layers = torch.nn.ModuleList()\n for in_, out_ in zip(hidden_layers_dim[:-1], hidden_layers_dim[1:]):\n self.hidden_layers.append(GNN_EBM_Layer_01(in_, out_))\n\n if self.concat:\n hidden_dim_sum = sum(hidden_layers_dim)\n else:\n hidden_dim_sum = ebm_GNN_dim\n\n self.node_readout = nn.Linear(2 * hidden_dim_sum, 2)\n self.edge_readout = nn.Linear(4 * hidden_dim_sum, 4)\n return\n\n def forward(self, x_1st, x_2nd, edge):\n '''\n :param x_1st: B,T,2,dim\n :param x_2nd: B,M,4,dim\n :param edge: 2,M\n :return: (B,T,2), (B,M,4)\n '''\n B, T = x_1st.size()[:2]\n M = edge.size()[1]\n h_node_list = [x_1st]\n h_edge_list = [x_2nd]\n x_node, x_edge = x_1st, x_2nd\n\n for i in range(self.ebm_GNN_layer_num):\n x_node, x_edge = self.hidden_layers[i](x_node, x_edge, edge)\n if i < self.ebm_GNN_layer_num - 1:\n x_node = F.relu(x_node)\n # x_edge = F.relu(x_edge)\n x_node = F.dropout(x_node, self.dropout, training=self.training)\n # x_edge = F.dropout(x_edge, self.dropout, training=self.training)\n h_node_list.append(x_node)\n h_edge_list.append(x_edge)\n\n if self.concat:\n h_node = torch.cat(h_node_list, dim=3) # B, T, 2, layer_num*d\n h_edge = torch.cat(h_edge_list, dim=3) # B, M, 4, layer_num*d\n else:\n h_node = x_node # B, T, 2, d\n h_edge = x_edge # B, M, 4, d\n\n h_node = h_node.view(B, T, -1) # B, T, 2*d\n h_edge = h_edge.view(B, M, -1) # B, M, 4*d\n\n h_node = self.node_readout(h_node) # B, T, 2\n h_edge = self.edge_readout(h_edge) # B, M, 4\n return h_node, h_edge\n\n\n# class GATNet(torch.nn.Module):\n# def __init__(self, embedding_dim=10, hidden_dim=10, num_head=8):\n# super(GATNet, self).__init__()\n# self.conv1 = GATConv(embedding_dim, hidden_dim, heads=num_head, dropout=0.6)\n# self.conv2 = GATConv(hidden_dim * num_head, hidden_dim, heads=1, concat=False, dropout=0.6)\n\n# def forward(self, data):\n# x = data.x\n# x = F.dropout(x, p=0.6, training=self.training)\n# x = F.elu(self.conv1(x, data.edge_index))\n# x = F.dropout(x, p=0.6, training=self.training)\n# x = self.conv2(x, data.edge_index)\n# return x\n\n\n# class MLP(nn.Sequential):\n# def __init__(self, input_dim, output_dim, hidden_dims=[1024, 512], dropout=0.1, use_batch_norm=False):\n# super(MLP, self).__init__()\n\n# self.input_dim = input_dim\n# self.output_dim = output_dim\n# self.hidden_dims = hidden_dims\n# self.use_batch_norm = use_batch_norm\n# self.dropout = nn.Dropout(0.1)\n\n# self.layer_size = len(self.hidden_dims) + 1\n# dims = [self.input_dim] + self.hidden_dims + [self.output_dim]\n\n# self.predictor = nn.ModuleList([nn.Linear(dims[i], dims[i + 1]) for i in range(self.layer_size)])\n# if use_batch_norm:\n# self.batch_norms = nn.ModuleList([nn.BatchNorm1d(dims[i + 1]) for i in range(self.layer_size)])\n# for m in self.modules():\n# if isinstance(m, nn.Linear):\n# nn.init.xavier_uniform_(m.weight.data)\n# if m.bias is not None:\n# m.bias.data.fill_(0.0)\n\n# def norm(self):\n# with torch.no_grad():\n# norm = 0\n# for m in self.modules():\n# if isinstance(m, nn.Linear):\n# norm += torch.norm(m.weight.data).item()\n# return norm\n\n# def forward(self, v):\n# '''\n# : params x: (batch_size, *, input_dim)\n# : output : (batch_size, *, output_dim)\n# '''\n# B, t, _ = v.size()\n# v = v.flatten(0, -2)\n# # print('input norm: %.5f' % (torch.norm(v).item()))\n# for i, l in enumerate(self.predictor):\n# v = l(v)\n# if i != self.layer_size - 1:\n# if self.use_batch_norm:\n# v = self.batch_norms[i](v)\n# v = F.relu(v)\n# v = self.dropout(v)\n# # print('layer %d norm: %.5f' % (i, torch.norm(v).item()))\n# v = v.reshape(B, t, -1)\n# return v\n\n\n# class GradKnowledgeGraphModel(nn.Module):\n# def __init__(self, num_tasks, args):\n# super(GradKnowledgeGraphModel, self).__init__()\n\n# self.num_tasks = num_tasks\n\n# self.weights = nn.Parameter(torch.ones(self.num_tasks, 1), requires_grad=True)\n# self.register_parameter('grad_KG', self.weights)\n# self.softmax = nn.Softmax(dim=0)\n# self.normalize_method = args.grad_KG_normalize_method\n\n# def forward(self, task_repr):\n# # ########## This won't train ##########\n# # task_repr = task_repr * self.weights.data\n# task_repr = task_repr * self.weights\n# return task_repr\n\n# def renormalize(self):\n# if self.normalize_method == 'sum':\n# ########## TODO: there might be negatives after backward ##########\n# normalize_coeff = self.num_tasks / self.weights.data.sum()\n# self.weights.data *= normalize_coeff\n# elif self.normalize_method == 'softmax':\n# self.weights.data = self.softmax(self.weights.data) * self.num_tasks\n# return\n\n# def reset_param(self):\n# self.weights.data.fill_(1)\n# return\n" ]
[ [ "torch.LongTensor", "torch.zeros", "torch.nn.functional.dropout", "torch.cat", "torch.nn.ModuleList", "torch.nn.Linear", "torch.nn.functional.relu", "torch.stack", "torch.nn.ReLU", "torch.index_select" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kathoma/AutomaticKneeMRISegmentation
[ "72ea3fa96fa5de34461b5999814aa706360f4a79", "72ea3fa96fa5de34461b5999814aa706360f4a79" ]
[ "calculate_t2.py", "loss_functions.py" ]
[ "from __future__ import print_function, division\n\nimport sys\nsys.path.insert(0, 'lib')\nimport numpy as np\nimport random\nimport scipy.io as sio\nimport os\nimport pandas as pd\nimport scipy.ndimage as ndimage\nimport math\nimport os\nimport scipy.linalg as la\nfrom joblib import Parallel, delayed\nfrom scipy.optimize import curve_fit\nfrom skimage import measure\nimport scipy.stats as ss\nimport skimage\n\n\n#########################################################\n# Calculating T2 Values for Segmented Voxels\n#########################################################\n\ndef exp_func(mri_time, A, m, b):\n return A*np.exp(-m*mri_time)\n\ndef running_mean(x):\n kernel = np.ones((3,))/3\n conv = np.convolve(x, kernel, mode = 'valid')\n temp = np.copy(x)\n temp[1:-1]=conv\n \n # Avoid boundary effects of convolution\n temp[0]=np.mean(x[0:2])\n temp[-1]=np.mean(x[-2:])\n \n return temp\n\ndef strictly_decreasing(vec):\n return np.all(np.diff(vec)<0)\n\ndef fit_t2(t2imgs, t2times, segmentation = None, n_jobs = 4, show_bad_pixels = True):\n \n '''\n Fits T2 curves to the T2_weighted images in each slice.\n IN:\n t2imgs - with T2 weighted images in numpy array (nr_slices, time_steps, width, heigth)\n t2times - list with aquisition times\n segmentation - segmentation matrix (nr_slices, width, heigth)\n n_jobs - number of parallel jobs\n OUT:\n matrix (nr_slices, width, heigth) with T2 values\n '''\n t2_tensor = np.zeros((t2imgs.shape[0], t2imgs.shape[2], t2imgs.shape[3]))\n\n def fit_per_slice(slice_idx, show_bad_pixels):\n scan = t2imgs[slice_idx,:,:,:]\n \n mri_time = np.array(t2times[slice_idx]) - t2times[slice_idx][0] #np.array(t2times[slice_idx])#\n \n if not segmentation is None: # if we have a segmentation\n segmentation_mask = segmentation[slice_idx,:,:]\n (cartilage_indices_r, cartilage_indices_c) = np.where(segmentation_mask)\n\n t2_matrix = np.full((scan.shape[1], scan.shape[2]), np.nan) \n if len(cartilage_indices_r)> 0:\n for i in np.arange(len(cartilage_indices_r)):\n ir = cartilage_indices_r[i]\n ic = cartilage_indices_c[i] \n \n if all(scan[:,ir,ic] == scan[0,ir,ic]): # if constant value, decay is 0 \n continue\n \n try:\n if strictly_decreasing(scan[1:,ir,ic]):\n echo_corrected = scan[1:,ir,ic]\n else:\n echo_corrected = running_mean(scan[1:,ir,ic])\n \n parameters,_ = curve_fit(exp_func, \n mri_time[1:], \n echo_corrected, \n p0 = [scan[0,ir,ic], .03, 0])#, \n# bounds = ([-np.inf, 0, -np.inf], [np.inf, 100, np.inf]))\n m = parameters[1]\n t2_ = 1./m\n t2_matrix[ir, ic] = t2_\n if show_bad_pixels:\n if ((t2_ > .100) or (t2_< -.100)): \n print(t2_)\n plt.plot(mri_time, scan[:,ir,ic])\n plt.plot(mri_time, exp_func(mri_time, *parameters), 'r-')\n plt.show()\n \n \n except RuntimeError:\n if show_bad_pixels:\n plt.plot(mri_time, scan[:,ir,ic])\n plt.title(\"Did not converge\")\n plt.show() \n\n return t2_matrix\n\n for i in range(t2imgs.shape[0]):\n t2_tensor[i,:,:] = fit_per_slice(i, show_bad_pixels)*1000 # in ms\n return t2_tensor", "import numpy as np\nimport keras as k\nimport math\n\n\n\n# Dice function loss optimizer\ndef dice_loss(y_true, y_pred):\n\n# szp = k.get_variable_shape(y_pred)\n szp = k.backend.int_shape(y_pred)\n img_len = szp[1]*szp[2]*szp[3]\n\n y_true = k.backend.reshape(y_true,(-1,img_len))\n y_pred = k.backend.reshape(y_pred,(-1,img_len))\n\n ovlp = k.backend.sum(y_true*y_pred,axis=-1)\n\n mu = k.backend.epsilon()\n dice = (2.0 * ovlp + mu) / (k.backend.sum(y_true,axis=-1) + k.backend.sum(y_pred,axis=-1) + mu)\n loss = -1*dice\n\n return loss\n\n# Dice function loss optimizer\n# During test time since it includes a discontinuity\n# def dice_loss_test(y_true, y_pred, thresh = 0.5):\n \n# recon = np.squeeze(y_true)\n# y_pred = np.squeeze(y_pred)\n# y_pred = (y_pred > thresh)*y_pred\n\n# szp = y_pred.shape\n# img_len = szp[1]*szp[2]*szp[3]\n\n# y_true = np.reshape(y_true,(-1,img_len))\n# y_pred = np.reshape(y_pred,(-1,img_len))\n\n# ovlp = np.sum(y_true*y_pred,axis=-1)\n\n# mu = k.backend.epsilon()\n# dice = (2.0 * ovlp + mu) / (np.sum(y_true,axis=-1) + np.sum(y_pred,axis=-1) + mu)\n\n# return dice\n\ndef dice_loss_test(y_true, y_pred, thresh = 0.5):\n \n recon = np.squeeze(y_true)\n y_pred = np.squeeze(y_pred)\n y_pred = (y_pred > thresh)*y_pred\n\n szp = y_pred.shape\n img_len = np.product(szp[1:])\n\n y_true = np.reshape(y_true,(-1,img_len))\n y_pred = np.reshape(y_pred,(-1,img_len))\n\n ovlp = np.sum(y_true*y_pred,axis=-1)\n\n mu = k.backend.epsilon()\n dice = (2.0 * ovlp + mu) / (np.sum(y_true,axis=-1) + np.sum(y_pred,axis=-1) + mu)\n \n\n return np.mean(dice)\n\ndef dice_loss_test_volume(y_true, y_pred, thresh = 0.5):\n # Designed to work with one volume, not a batch of volumes\n \n g = np.squeeze(y_true)\n p = np.squeeze(y_pred)\n p = (y_pred > thresh)*1#*y_pred\n \n g = g.flatten()\n p = p.flatten()\n\n ovlp = np.sum(g*p)\n\n mu = k.backend.epsilon()\n dice = (2.0 * ovlp + mu) / (np.sum(g) + np.sum(p) + mu)\n\n return dice\n\ndef jaccard(vol1, vol2):\n return np.sum(np.logical_and(vol1,vol2))/np.sum((np.logical_or(vol1,vol2)))\n\ndef coefficient_of_variation(y_true, y_pred):\n return ((np.mean((y_pred-y_true)**2))**.5) / np.mean(np.abs(y_true)) \n\ndef cohen_d(y_true,y_pred):\n nTrue = len(y_true)\n nPred = len(y_pred)\n dof = nTrue + nPred - 2\n return (np.mean(y_pred) - np.mean(y_true)) / np.sqrt(((nTrue-1)*np.std(y_true, ddof=1) ** 2 + (nPred-1)*np.std(y_pred, ddof=1) ** 2) / dof)\n\n\ndef rohan_loss(y_true, y_pred):\n\n\n# szp = k.get_variable_shape(y_pred)\n szp = k.backend.int_shape(y_pred)\n img_len = szp[1]*szp[2]*szp[3]\n\n y_true = k.backend.reshape(y_true,(-1,img_len))\n y_pred = k.backend.reshape(y_pred,(-1,img_len))\n loss = (.9 * np.mean(-1*np.log(y_pred[y_true == 1]))) + (.1*np.mean(-1*np.log(1 - y_pred[y_true == 0])))\n\n\n return loss\n\ndef weighted_binary_crossentropy(y_true, y_pred):\n \n szp = k.backend.int_shape(y_pred)\n img_len = szp[1]*szp[2]*szp[3]\n\n y_true = k.backend.reshape(y_true,(-1,img_len))\n y_pred = k.backend.reshape(y_pred,(-1,img_len))\n\n # Original binary crossentropy (see losses.py):\n # K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1)\n\n # Calculate the binary crossentropy\n b_ce = k.backend.binary_crossentropy(y_true, y_pred)\n\n # Apply the weights\n weight_vector = y_true * .9999 + (1. - y_true) * .0001\n weighted_b_ce = weight_vector * b_ce\n\n # Return the mean error\n return k.backend.mean(weighted_b_ce)\n\n" ]
[ [ "numpy.convolve", "numpy.ones", "numpy.full", "scipy.optimize.curve_fit", "numpy.copy", "numpy.mean", "numpy.diff", "numpy.array", "numpy.exp", "numpy.zeros", "numpy.where" ], [ "numpy.log", "numpy.product", "numpy.abs", "numpy.reshape", "numpy.squeeze", "numpy.logical_or", "numpy.std", "numpy.mean", "numpy.logical_and", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
uchida-takumi/recommender_system_verification
[ "a079e0c8764926e5dc66da01a809c6ba4fde7fb7", "a079e0c8764926e5dc66da01a809c6ba4fde7fb7", "a079e0c8764926e5dc66da01a809c6ba4fde7fb7" ]
[ "src/module/DeepFM.py", "src/module/knowledge_graph_attention_network/Model/utility/loader_nfm.py", "src/module/tensorflow_DeepFM/example/main.py" ]
[ "\"\"\"\n# install the package\npip install deepctr\n\n# tutorial\nhttps://deepctr-doc.readthedocs.io/en/latest/Quick-Start.html#getting-started-4-steps-to-deepctr\n\n# github\nhttps://github.com/shenweichen/DeepCTR\n\nしかし、これは binary しか出来ないので適応不可能。\nbinary を無理矢理適応させるばあいは、非クリックデータを何らかの方法で生成する必要がある。\n\n# ---- 次のアイデア ----\n# github\nhttps://github.com/ChenglongChen/tensorflow-DeepFM\n\"\"\"\n\nimport tensorflow as tf\nimport os\nimport pickle\nimport pandas as pd\nimport numpy as np\nimport copy\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import mean_absolute_error\nfrom src.module.tensorflow_DeepFM.DeepFM import DeepFM as DeepFM_\n\n# インターフェース\nclass DeepFM:\n def __init__(self, set_train_test_users, set_train_test_items, dict_genre=None, first_half_fit_only_fm=False, ctr_prediction=True):\n \"\"\"\n import pandas as pd\n DIR_DATA = 'src/module/knowledge_graph_attention_network/Data/ml'\n df_train = pd.read_csv(os.path.join(DIR_DATA, 'train_rating.csv'))\n df_test = pd.read_csv(os.path.join(DIR_DATA, 'test_rating.csv'))\n\n set_train_test_users = set(np.concatenate([df_train['UserID'], df_test['UserID']]))\n set_train_test_items = set(np.concatenate([df_train['MovieID'], df_test['MovieID']]))\n dict_genre = pickle.load(open(os.path.join(DIR_DATA, 'genre.pickle'), 'rb'))\n \n self = DeepFM(set_train_test_users, set_train_test_items, dict_genre)\n self.dfm_params['epoch'] = 10\n self.dfm_params['batch_size'] = 64\n \n users = df_train['UserID'].values\n items = df_train['UserID'].values\n ratings = df_train['Rating'].values\n self.fit(users, items, ratings)\n predicted = self.predict(df_test['UserID'].values, df_test['UserID'].values)\n \n\n # MAE of test-set\n print( np.mean(np.abs(predicted - df_test['Rating'])) )\n\n # MAE of mean-prediction\n print( np.mean(np.abs(df_test['Rating'].mean() - df_test['Rating'])) ) \n\n\n ## まぁ、実際のテストをクリアできればOKとする。\n \"\"\"\n \n \"\"\"\n 参考として、Movielens1Mデータで検証されたハイパーパラメータは以下の通り\n Deep Matrix Factorization Approach for\n Collaborative Filtering Recommender Systems\n \n k(hidden-factor) = 8, γ(learning-rate) = 0.01, λ(regularization) = 0.045\n K = [9, 3, 3]; Γ= [0.01, 0.01, 0.01]; Λ = [0.1, 0.01, 0.1]\n \"\"\"\n self.set_train_test_users = set(set_train_test_users)\n self.set_train_test_items = set(set_train_test_items)\n \n self.dict_genre = dict_genre\n self.first_half_fit_only_fm = first_half_fit_only_fm\n self.data_manager = Data_manager(set_train_test_users, set_train_test_items, dict_genre)\n feature_size, field_size = self.data_manager.get_feature_size_field_size()\n self.dfm_params = {\n \"feature_size\" : feature_size,\n \"field_size\" : field_size,\n \"loss_type\" : \"mse\", # \"logloss\" なら {0,1} の判別問題。 \"mse\" なら regression。\n \"use_fm\": True, # fm-layer を使用\n \"use_deep\": True, # deep-layer を使用\n \"embedding_size\": 8,\n \"dropout_fm\": [1.0, 1.0],\n \"deep_layers\": [32, 32],\n \"dropout_deep\": [0.5, 0.5, 0.5],\n \"deep_layers_activation\": tf.nn.relu,\n \"epoch\": 30,\n \"batch_size\": 64,\n \"learning_rate\": 0.001,\n \"optimizer_type\": \"adam\",\n \"batch_norm\": 1,\n \"batch_norm_decay\": 0.995,\n \"l2_reg\": 0.0001,\n \"l2_reg_embedding\": 0.0001,\n \"l2_reg_bias\": 0.0001,\n \"verbose\": True,\n \"eval_metric\": mean_absolute_error,\n \"greater_is_better\": False, # 学習における損失スコアが大きい方が良いかどうか\n \"random_seed\": 2017,\n }\n self.ctr_prediction = ctr_prediction\n if self.ctr_prediction:\n self.dfm_params[\"loss_type\"] = \"logloss\"\n \n\n def fit(self, users, items, ratings, test_users=[], test_items=[], test_ratings=[], **kargs):\n \"\"\"\n users = [0,0,1]\n items = [0,3,3]\n ratings = [3.,4.,5.]\n \"\"\"\n global_mean_bias_init = np.float32(np.mean(ratings))\n global_mean_bias_init = 0.01\n self.model = DeepFM_(**self.dfm_params, global_mean_bias_init=global_mean_bias_init, first_half_fit_only_fm=self.first_half_fit_only_fm)\n \n # もし、CTR予測の場合は、y=0のデータをランダム生成する。\n if self.ctr_prediction:\n users = list(users) + list(np.random.choice(list(set(users)), size=len(users)))\n items = list(items) + list(np.random.choice(list(set(items)), size=len(items)))\n ratings = list((np.array(ratings)>0).astype(int)) + [0]*len(ratings)\n test_ratings = list((np.array(test_ratings)>0).astype(int))\n \n Xi, Xv = self.data_manager.transform_users_and_items_to_Xi_Xv(users, items)\n \n if len(test_users)>0:\n test_Xi, test_Xv = self.data_manager.transform_users_and_items_to_Xi_Xv(test_users, test_items)\n self.model.fit(Xi, Xv, ratings, test_Xi, test_Xv, test_ratings, early_stopping=True)\n else:\n self.model.fit(Xi, Xv, ratings, early_stopping=True, **kargs)\n \n # load data\n self.trained_users = list(set(users))\n self.trained_items = list(set(items))\n self.global_mean = self.model.predict(Xi, Xv).mean()\n \n \n def predict(self, users, items, *args, **kargs):\n Xi, Xv = self.data_manager.transform_users_and_items_to_Xi_Xv(users, items)\n predicted = self.model.predict(Xi, Xv)\n return predicted\n\n# prepare training and validation data in the required format\nclass Data_manager:\n def __init__(self, users, items, dict_genre=None):\n \"\"\"\n users [array like object]:\n train, test set に含まれる user_id\n items [array like object]:\n train, test set に含まれる item_id\n dict_genre [dictionary]:\n ex) {item_id: [genre_id1, genre_id2]}\n \n tensorflow_DeepFM/example 内部のプログラム、特にDataReader.pyを読み、データの形式を解読した。\n 結論として、 item, user, genre の各IDは以下のように変換すればよい。\n 1) user = {0,1,2} → {0,1,2} *未変更\n 2) item = {0,1} → {3,4} *userからのインクリメントID\n 3) genre = {0,1} → {5,6} *itemからのインクリメントID\n 4) a interaction-sample [u,i,g] = [0,1,0]→[0,4,5]\n 5) Xi_train (X-index trainset) = [変換した[u,i,g]1, 変換した[u,i,g]2, ...]\n 6) Xv_train (X-value trainset) = [[1.,1.,1.], [1.,1.,1.], ...]\n user,item,genre はカテゴリ変数なのですべて1.となる。\n 7) y_train = [rating-score1, rating-score2, ...] *変換不要\n \n EXAMPLE\n -------------\n import pandas as pd\n df_rating = pd.read_csv(os.path.join(DIR_DATA, 'train_rating.csv'))\n dict_genre = pickle.load(open(os.path.join(DIR_DATA, 'genre.pickle'), 'rb'))\n users = df_rating['UserID']\n items = df_rating['MovieID']\n\n self = Data_manager(users, items, dict_genre=dict_genre)\n \"\"\" \n self.dict_genre = dict_genre\n # インクリメントインデックスを生成するオブジェクト self.inclement_index を生成する。\n if dict_genre:\n dict_genre = {i:gs for i,gs in dict_genre.items() if i in items}\n n_genre = max([max(gs) for i,gs in dict_genre.items() if gs]) + 1\n genres = list(range(n_genre))\n else:\n dict_genre = {}\n n_genre = 0\n genres = []\n \n self.inclement_index = inclement_index(users, items, genres)\n\n # userとitemをインクリメントIDに変更する\n dict_genre = {self.inclement_index.transform([i], field='item')[0]:gs for i,gs in dict_genre.items()}\n\n # user, itemはそれぞれで2フィールド、ジャンルはジャンルラベルごとに別々のフィールドにわける。\n self.re_dict_genre = {} \n for i,gs in dict_genre.items():\n # re_dict は {item_id:(field_id, genru_id)}となる。\n genre_one_hot_vec = [0] * n_genre\n for g in gs:\n genre_one_hot_vec[g] = 1 # カテゴリ変数はかならず整数の1とする。\n self.re_dict_genre[i] = genre_one_hot_vec\n \n self.genre_indexes = self.inclement_index.transform(genres, field='genre')\n self.feature_size = self.inclement_index.get_feature_size()\n self.field_size = 2 + n_genre\n \n def get_feature_size_field_size(self):\n return self.feature_size, self.field_size\n\n def transform_users_and_items_to_Xi_Xv(self, users, items):\n \"\"\"\n users = [0,0,1]\n items = [1,5,5]\n \"\"\"\n Xi, Xv = [], []\n users = self.inclement_index.transform(users, field='user')\n items = self.inclement_index.transform(items, field='item')\n for u,i in zip(users, items):\n if self.dict_genre:\n Xi.append([u, i] + self.genre_indexes)\n Xv.append([1, 1] + self.re_dict_genre[i])\n else:\n Xi.append([u, i])\n Xv.append([1, 1]) \n return Xi, Xv\n \n \n\nclass inclement_index:\n def __init__(self, users, items, genres=[]):\n \"\"\"\n users = ['u0','u1',3]\n items = ['i0', 3]\n genres = ['pop', 'sf']\n \n self = inclement_index(users, items, genres)\n self.transform(['u0', 'u1', 3], field='user', inverse=False)\n self.transform(['i0', 3], field='item', inverse=False)\n self.transform(['pop', 'sf'], field='genre', inverse=False)\n \n transformed = self.transform(['u0', 'u1', 3], field='user', inverse=False)\n self.transform(transformed, field='user', inverse=True)\n\n \"\"\"\n users = set(users)\n items = set(items)\n genres = set(genres)\n self.increment_cnt = 0\n self.user_dict = {u:self.get_incremate_index() for u in users}\n self.user_inverse_dict = {v:k for k,v in self.user_dict.items()}\n self.item_dict = {i:self.get_incremate_index() for i in items}\n self.item_inverse_dict = {v:k for k,v in self.item_dict.items()}\n self.genre_dict = {g:self.get_incremate_index() for g in genres}\n self.genre_inverse_dict = {v:k for k,v in self.genre_dict.items()}\n\n def transform(self, xs, field='user', inverse=False):\n \"\"\"\n xs = [0,2]\n\n self.transform(xs, type='user')\n \"\"\"\n if inverse:\n if field == 'user':\n _dict = self.user_inverse_dict\n elif field == 'item':\n _dict = self.item_inverse_dict\n elif field == 'genre':\n _dict = self.genre_inverse_dict\n else:\n if field == 'user':\n _dict = self.user_dict\n elif field == 'item':\n _dict = self.item_dict\n elif field == 'genre':\n _dict = self.genre_dict\n\n return [_dict[x] for x in xs] \n \n def get_incremate_index(self):\n now_index = copy.deepcopy(self.increment_cnt)\n self.increment_cnt += 1\n return now_index\n \n def get_feature_size(self):\n return self.increment_cnt\n\n\n \nif __name__ == 'how to use it.':\n ###########################\n # --- かなりシンプルなテスト ---\n sample_size = 1000\n users = np.random.choice(range(100), size=sample_size) \n items = np.random.choice(range(100), size=sample_size) \n genre_dict = None\n ratings = users - items\n \n self = DeepFM(set(users), set(items))\n self.dfm_params['batch_size'] = 64\n self.dfm_params['epoch'] = 100\n self.fit(users, items, ratings) \n self.predict([10, 5, 10], [10, 10, 2]) # 正解は [0, -5, 8] である\n # 十分に小さなbatch_sizeかどうかは非常に重要\n # これは学習テストのロス減少によって確認できる。\n \n ###########################\n # --- シンプルなテスト1 ---\n sample_size = 1000\n n_user = 500\n n_item = 20\n users = np.random.choice(range(n_user), size=sample_size) \n items = np.random.choice(range(n_item), size=sample_size) \n \n user_embedding = {u:np.random.rand(5)-0.5 for u in range(n_user)}\n item_embedding = {i:np.random.rand(5)-0.5 for i in range(n_item)}\n \n def rating(u, i):\n return 10*sum(user_embedding[u] * item_embedding[i]) + 3\n \n ratings = [rating(u, i) for u,i in zip(users, items)]\n \n self = DeepFM(list(range(n_user)), list(range(n_item)))\n self.dfm_params['epoch'] = 100\n self.dfm_params['embedding_size'] = 200\n self.dfm_params['l2_reg'] = 0.0045\n self.fit(users, items, ratings)\n \n test_users = np.random.choice(range(n_user), size=sample_size) \n test_items = np.random.choice(range(n_item), size=sample_size) \n test_ratings = [rating(u, i) for u,i in zip(users, items)]\n\n predicted = self.predict(test_users, test_items)\n print( np.mean(np.abs(test_ratings - predicted)) ) \n print( np.mean(np.abs(test_ratings - np.mean(ratings))) )\n \n # scaler を導入すると改善されるか? → 特に改善はされていない。\n from sklearn.preprocessing import StandardScaler\n scaler = StandardScaler()\n scaler.fit([[r] for r in ratings])\n s_ratings = scaler.transform([[r] for r in ratings])[:,0]\n \n self.fit(users, items, s_ratings) \n predicted = self.predict(test_users, test_items)\n predicted = scaler.inverse_transform(predicted[:,None])\n print( np.mean(np.abs(test_ratings - predicted)) ) \n print( np.mean(np.abs(test_ratings - np.mean(ratings))) )\n\n ###########################\n # --- シンプルなテスト2 bias とembedding あり ---\n sample_size = 1000\n n_user = 500\n n_item = 20\n users = np.random.choice(range(n_user), size=sample_size) \n items = np.random.choice(range(n_item), size=sample_size) \n \n user_embedding = {u:np.random.rand(5)-0.5 for u in range(n_user)}\n item_embedding = {i:np.random.rand(5)-0.5 for i in range(n_item)}\n user_bias = {u:u/10 for u in range(n_user)} # 単純にidが大きいほどバイアスが大きい\n item_bias = {i:i for i in range(n_item)} # 単純にidが大きいほどバイアスが大きい\n \n def rating(u, i):\n return 10*sum(user_embedding[u] * item_embedding[i]) + user_bias[u] + item_bias[i] \n ratings = [rating(u, i) for u,i in zip(users, items)]\n\n test_users = np.random.choice(range(n_user), size=sample_size) \n test_items = np.random.choice(range(n_item), size=sample_size) \n test_ratings = [rating(u, i) for u,i in zip(users, items)]\n \n self = DeepFM(list(range(n_user)), list(range(n_item)))\n self.dfm_params['epoch'] = 100\n self.dfm_params['embedding_size'] = 200\n self.fit(users, items, ratings, test_users, test_items, test_ratings)\n \n \n # 平均性能との比較\n predicted = self.predict(test_users, test_items)\n print( np.mean(np.abs(test_ratings - predicted)) ) \n print( np.mean(np.abs(test_ratings - np.mean(ratings))) )\n \n # オラクルとの比較\n predicted = self.predict([200]*n_item, list(range(n_item)))\n answer = [rating(200,i) for i in range(n_item)]\n print(predicted)\n print(answer)\n print(predicted - answer)\n \n ## 内部の embedding を確認する。\n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n \n\n ###########################\n # --- シンプルなテスト3 head-tail-new ID ---\n sample_size = 1000\n n_user = 200\n n_item = 50\n ## id が後半になるほど学習セット中の出現率が低くなる。\n p_user = 1/np.array(range(1, n_user+1)); p_user /= p_user.sum()\n p_item = 1/np.array(range(1, n_item+1)); p_item /= p_item.sum()\n users = np.random.choice(range(n_user), size=sample_size, p=p_user) \n items = np.random.choice(range(n_item), size=sample_size, p=p_item) \n\n user_embedding = {u:np.random.rand(5)-0.5 for u in range(n_user)}\n item_embedding = {i:np.random.rand(5)-0.5 for i in range(n_item)}\n user_bias = {u:u/10 for u in range(n_user)} # 単純にidが大きいほどバイアスが大きい\n item_bias = {i:i for i in range(n_item)} # 単純にidが大きいほどバイアスが大きい\n def rating(u, i):\n return 10*sum(user_embedding[u] * item_embedding[i]) + user_bias[u] + item_bias[i] \n ratings = [rating(u, i) for u,i in zip(users, items)]\n\n ## user=500 と item=20 はそれぞれ新規IDとなる\n test_users = np.random.choice(range(n_user), size=sample_size) \n test_items = np.random.choice(range(n_item), size=sample_size) \n test_ratings = [rating(u, i) for u,i in zip(users, items)]\n\n self = DeepFM(list(range(n_user+1)), list(range(n_item+1)))\n self.dfm_params['epoch'] = 300\n self.dfm_params['embedding_size'] = 4\n self.fit(users, items, ratings, test_users, test_items, test_ratings)\n \n # 平均値予測との比較\n predicted = self.predict(test_users, test_items)\n print( np.mean(np.abs(test_ratings - predicted)) ) \n print( np.mean(np.abs(test_ratings - np.mean(ratings))) )\n\n ## 内部の embedding を確認する。\n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n\n ## 可視化する(ID=500 まではユーザーで、それ以降はアイテム)\n import pandas as pd\n # [正常] 一部のembeddingがIDの増加に合わせて線形に変化している。これらはバイアス効果を一部学習している。\n pd.DataFrame(feature_embeddings).plot() \n # [成功] DeepFM のバイアスの初期値を0付近にすることで、userのバイアスはオラクルに近くなった。\n # [?] itemのバイアスはオラクルと逆にidが増加するほど減少している → おそらくembeddingがバイアスを学習してしまったゆえか?\n pd.DataFrame(feature_bias).plot() \n \n # 新規IDを確認する → ほぼ、初期値の0付近か?\n ## 新規ユーザー\n feature_embeddings[200]\n feature_bias[200]\n ## 新規アイテム\n feature_embeddings[-1]\n feature_bias[-1]\n \n ############################################## \n # --- IDとは無関係なランダムなバイアスで学習してみる ---\n sample_size = 1000\n n_user = 200\n n_item = 50\n ## id が後半になるほど学習セット中の出現率が低くなる。\n p_user = 1/np.array(range(1, n_user+1)); p_user /= p_user.sum()\n p_item = 1/np.array(range(1, n_item+1)); p_item /= p_item.sum()\n users = np.random.choice(range(n_user), size=sample_size, p=p_user) \n items = np.random.choice(range(n_item), size=sample_size, p=p_item) \n user_bias = {u:np.random.rand() for u in range(n_user)} \n item_bias = {i:np.random.rand() for i in range(n_item)} \n user_embedding = {u:np.random.rand(5)-0.5 for u in range(n_user)}\n item_embedding = {i:np.random.rand(5)-0.5 for i in range(n_item)}\n def rating(u, i):\n return 3*(sum(user_embedding[u] * item_embedding[i]) + user_bias[u] + item_bias[i]) \n ratings = [rating(u, i) for u,i in zip(users, items)]\n\n ## user=500 と item=20 はそれぞれ新規IDとなる\n test_users = np.random.choice(range(n_user), size=sample_size) \n test_items = np.random.choice(range(n_item), size=sample_size) \n test_ratings = [rating(u, i) for u,i in zip(users, items)] \n # ------------------------------\n ############################################## \n\n self = DeepFM(list(range(n_user+1)), list(range(n_item+1)))\n self.dfm_params['epoch'] = 100\n self.dfm_params['embedding_size'] = 4\n self.dfm_params['l2_reg'] = 0.001\n self.fit(users, items, ratings, test_users, test_items, test_ratings)\n\n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n\n \"\"\" デバック\n self.predict([1]*n_item, range(n_item))\n self.predict([0]*n_item, range(n_item))\n [rating(1, i) for i in range(n_item)]\n \"\"\"\n pd.DataFrame(feature_embeddings).plot() \n pd.DataFrame(feature_bias).plot() \n \"\"\"\n 本テストは想定どおりの結果となり、成功したといえる。\n その成功要因は、以下の変更を加えたことによる。\n [1] 各id の embedding, bias の初期値を0付近のものに変更した。\n [2] l2_reg の対象として embedding, bias を追加した。(おそらく、マイナーIDのweightが抑制されると思われるが、詳細は不明)\n \"\"\"\n\n # --- パラメータごとの影響を確認する。\n self = DeepFM(list(range(n_user+1)), list(range(n_item+1)))\n self.dfm_params['epoch'] = 10\n self.dfm_params['embedding_size'] = 4\n self.dfm_params['use_deep'] = False\n self.fit(users, items, ratings, test_users, test_items, test_ratings)\n \n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n\n pd.DataFrame(feature_embeddings).plot() \n pd.DataFrame(feature_bias).plot() \n\n\n self = DeepFM(list(range(n_user+1)), list(range(n_item+1)))\n self.dfm_params['epoch'] = 10\n self.dfm_params['embedding_size'] = 4\n self.dfm_params['l2_reg'] = 0.001\n self.dfm_params['learning_rate'] = 0.001\n self.fit(users, items, ratings, test_users, test_items, test_ratings)\n \n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n\n pd.DataFrame(feature_embeddings).plot() \n pd.DataFrame(feature_bias).plot() \n\n self = DeepFM(list(range(n_user+1)), list(range(n_item+1)))\n self.dfm_params['epoch'] = 10\n self.dfm_params['embedding_size'] = 4\n self.dfm_params['l2_reg'] = 0.100\n self.dfm_params['learning_rate'] = 0.001\n self.fit(users, items, ratings, test_users, test_items, test_ratings)\n \n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n\n pd.DataFrame(feature_embeddings).plot() \n pd.DataFrame(feature_bias).plot() \n\n self = DeepFM(list(range(n_user+1)), list(range(n_item+1)))\n self.dfm_params['epoch'] = 10\n self.dfm_params['embedding_size'] = 4\n self.dfm_params['l2_reg'] = 0.001\n self.dfm_params['learning_rate'] = 0.010\n self.fit(users, items, ratings, test_users, test_items, test_ratings)\n \n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n concat_bias = self.model.sess.run(self.model.weights[\"concat_bias\"])\n\n pd.DataFrame(feature_embeddings).plot() \n pd.DataFrame(feature_bias).plot() \n\n\n self = DeepFM(list(range(n_user+1)), list(range(n_item+1)), first_half_fit_only_fm=True)\n self.dfm_params['epoch'] = 20\n self.dfm_params['embedding_size'] = 4\n self.dfm_params['l2_reg'] = 0.010\n self.dfm_params['learning_rate'] = 0.010\n self.fit(users, items, ratings, test_users, test_items, test_ratings)\n \n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n concat_bias = self.model.sess.run(self.model.weights[\"concat_bias\"])\n\n pd.DataFrame(feature_embeddings).plot() \n pd.DataFrame(feature_bias).plot() \n\n\n # --- only fm \n self = DeepFM(list(range(n_user+1)), list(range(n_item+1)), first_half_fit_only_fm=True)\n self.dfm_params['epoch'] = 20\n self.dfm_params['embedding_size'] = 4\n self.dfm_params['l2_reg'] = 0.010\n self.dfm_params['learning_rate'] = 0.010\n self.dfm_params['use_deep'] = False\n self.fit(users, items, ratings, test_users, test_items, test_ratings)\n \n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n concat_bias = self.model.sess.run(self.model.weights[\"concat_bias\"])\n\n pd.DataFrame(feature_embeddings).plot() \n pd.DataFrame(feature_bias).plot() \n \n # ---- high l2-reg\n self = DeepFM(list(range(n_user+1)), list(range(n_item+1)), first_half_fit_only_fm=True)\n self.dfm_params['epoch'] = 20\n self.dfm_params['embedding_size'] = 4\n self.dfm_params['l2_reg'] = 0.100\n self.dfm_params['learning_rate'] = 0.010\n self.dfm_params['use_deep'] = False\n self.fit(users, items, ratings, test_users, test_items, test_ratings)\n \n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n concat_bias = self.model.sess.run(self.model.weights[\"concat_bias\"])\n\n pd.DataFrame(feature_embeddings).plot() \n pd.DataFrame(feature_bias).plot() \n\n # ---- high learning_rate\n self = DeepFM(list(range(n_user+1)), list(range(n_item+1)), first_half_fit_only_fm=False)\n self.dfm_params['epoch'] = 20\n self.dfm_params['embedding_size'] = 4\n self.dfm_params['l2_reg'] = 0.0100\n self.dfm_params['l2_reg_embedding'] = 0.0100\n self.dfm_params['l2_reg_bias'] = 0.0100\n self.dfm_params['learning_rate'] = 0.0100\n self.dfm_params['use_deep'] = False\n \n self.fit(users, items, ratings, test_users, test_items, test_ratings)\n \n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n concat_bias = self.model.sess.run(self.model.weights[\"concat_bias\"])\n\n pd.DataFrame(feature_embeddings).plot() \n pd.DataFrame(feature_bias).plot() \n \n ## 結論、頻度の違いがバイアスに影響を与えることはない。\n\n \n\n # ---- high learning_rate\n self = DeepFM(list(range(n_user+1)), list(range(n_item+1)), first_half_fit_only_fm=False)\n self.dfm_params['epoch'] = 20\n self.dfm_params['embedding_size'] = 4\n self.dfm_params['l2_reg'] = 0.0100\n #self.dfm_params['l2_reg_embedding'] = 0.0100\n #self.dfm_params['l2_reg_bias'] = 0.0100\n self.dfm_params['learning_rate'] = 0.0020\n self.dfm_params['use_deep'] = False\n self.dfm_params['batch_size'] = 32\n self.dfm_params['loss_type'] = 'mse'\n self.dfm_params['optimizer_type'] = 'sgd'\n #self.dfm_params['optimizer_type'] = 'adam'\n \n self.fit(users, items, ratings)\n \n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n concat_bias = self.model.sess.run(self.model.weights[\"concat_bias\"])\n\n pd.DataFrame(feature_embeddings).plot() \n pd.DataFrame(feature_bias).plot() \n \n self.predict([0,0,150,150],[0,10,0,10])\n\n\n\n ##########################\n # MovieLensのCTR問題として定義し直して、性能を比較する\n import numpy as np \n ctr_users = list(users) + list(np.random.choice(list(set(users)), size=len(users)))\n ctr_items = list(items) + list(np.random.choice(list(set(items)), size=len(items)))\n ctrs = [1]*len(users) + [0]*len(users)\n \n self = DeepFM(list(range(n_user+1)), list(range(n_item+1)), first_half_fit_only_fm=True)\n self.dfm_params['epoch'] = 20\n self.dfm_params['embedding_size'] = 4\n self.dfm_params['l2_reg'] = 0.0010\n #self.dfm_params['l2_reg_embedding'] = 0.0020\n #self.dfm_params['l2_reg_bias'] = 0.0020\n self.dfm_params['learning_rate'] = 0.00010\n #self.dfm_params['use_deep'] = False\n self.dfm_params['batch_size'] = 16\n self.dfm_params['loss_type'] = 'logloss'\n self.dfm_params['greater_is_better'] = True\n \n self.fit(ctr_users, ctr_items, ctrs)\n\n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n concat_bias = self.model.sess.run(self.model.weights[\"concat_bias\"])\n\n pd.DataFrame(feature_embeddings).plot() \n pd.DataFrame(feature_bias).plot() \n\n self.predict([0,0,150,150],[0,10,0,10])\n \n ########################\n # CTR 対応型のテスト\n self = DeepFM(list(range(n_user+1)), list(range(n_item+1)), first_half_fit_only_fm=False, ctr_prediction=True)\n self.dfm_params['epoch'] = 30\n self.dfm_params['embedding_size'] = 4\n self.dfm_params['batch_size'] = 32\n self.dfm_params['dropout_fm'] = [0.5, 0.5]\n self.dfm_params['l2_reg'] = 0.0\n self.dfm_params['l2_reg_embedding'] = 0.0\n self.dfm_params['l2_reg_bias'] = 0.0\n \n self.fit(users, items, ratings)\n \n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n concat_bias = self.model.sess.run(self.model.weights[\"concat_bias\"])\n\n pd.DataFrame(feature_embeddings).plot() \n pd.DataFrame(feature_bias).plot() \n pd.DataFrame(self.predict([200]*50,list(range(50)))).plot() # 新規ユーザーだけ常に一定になる。\n \n self.predict([0,0,150,150],[0,10,0,10])\n\n self.predict([50]*50,list(range(50)))\n self.predict([100]*50,list(range(50)))\n self.predict([150]*50,list(range(50)))\n self.predict([200]*50,list(range(50))) # 新規ユーザーだけ常に一定になる。\n self.predict([199]*50,list(range(50))) # 新規ユーザーだけ常に一定になる。\n self.predict([198]*50,list(range(50))) # 新規ユーザーだけ常に一定になる。\n self.predict([197]*50,list(range(50))) # 新規ユーザーだけ常に一定になる。\n self.predict(list(range(200)),[50]*200) # 新規ユーザーだけ常に一定になる。\n\n feature_embeddings[200]\n feature_bias[200]\n \n feature_embeddings[150]\n feature_bias[150]\n\n feature_embeddings[220]\n feature_embeddings[222]\n \n feature_embeddings[223]\n \n ########################\n # tensorflow の動作テスト\n weight = tf.Variable(initial_value=[[0,1,2,3], [0,10,20,30], [0,100,200,300]], trainable=True, name='test', dtype=tf.float32)\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n sess.run(weight)\n op = weight[1,3].assign(9999.)\n sess.run(op)\n sess.run(weight)\n \n ########################\n # 上手く行かなかったので、テスト\n # 実際のデータで確認する\n ############################################## \n # --- 疑似データの生成 ---\n sample_size = 10000\n n_user = 2000\n n_item = 500\n ## id が後半になるほど学習セット中の出現率が低くなる。\n p_user = 1/np.array(range(1, n_user+1)); p_user /= p_user.sum()\n p_item = 1/np.array(range(1, n_item+1)); p_item /= p_item.sum()\n users = np.random.choice(range(n_user), size=sample_size, p=p_user) \n items = np.random.choice(range(n_item), size=sample_size, p=p_item) \n user_bias = {u:np.random.rand() for u in range(n_user)} \n item_bias = {i:np.random.rand() for i in range(n_item)} \n user_embedding = {u:np.random.rand(5)-0.5 for u in range(n_user)}\n item_embedding = {i:np.random.rand(5)-0.5 for i in range(n_item)}\n def rating(u, i):\n return 3*(sum(user_embedding[u] * item_embedding[i]) + user_bias[u] + item_bias[i]) \n ratings = [rating(u, i) for u,i in zip(users, items)]\n\n ## user=500 と item=20 はそれぞれ新規IDとなる\n test_users = np.random.choice(range(n_user), size=sample_size) \n test_items = np.random.choice(range(n_item), size=sample_size) \n test_ratings = [rating(u, i) for u,i in zip(users, items)] \n # ------------------------------\n ############################################## \n\n \n for i in range(5):\n self = DeepFM(list(range(n_user+1)), list(range(n_item+1)), first_half_fit_only_fm=False, ctr_prediction=False)\n self.dfm_params['epoch'] = 10\n self.dfm_params['embedding_size'] = 4\n self.dfm_params['deep_layers'] = [16, 16]\n self.dfm_params['l2_reg'] = 0.0100 #0.0040\n self.dfm_params['l2_reg_embedding'] = 0.0000 #0.001\n self.dfm_params['l2_reg_bias'] = 0.000 #0.001\n self.dfm_params['learning_rate'] = 0.00100 #0.001\n self.dfm_params['use_deep'] = False\n self.dfm_params['batch_size'] = 128\n self.dfm_params['loss_type'] = 'mse'\n #self.dfm_params['optimizer_type'] = 'sgd'\n \n self.fit(users, items, ratings)\n \n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n concat_bias = self.model.sess.run(self.model.weights[\"concat_bias\"])\n concat_projection = self.model.sess.run(self.model.weights[\"concat_projection\"]) # [0,1]がuser,itemのbiasに対する重み\n \n #pd.DataFrame(feature_embeddings).plot() \n pd.DataFrame(feature_bias).plot() \n pd.DataFrame(concat_projection).plot() \n #pd.DataFrame(self.predict([200]*50,list(range(50)))).plot() # 新規ユーザーだけ常に一定になる。\n df_result = pd.DataFrame()\n df_result['u=10'] = self.predict([10]*n_item,list(range(n_item)))\n df_result['u=100'] = self.predict([100]*n_item,list(range(n_item)))\n df_result['u=1000'] = self.predict([1000]*n_item,list(range(n_item)))\n df_result['u=2000'] = self.predict([2000]*n_item,list(range(n_item)))\n df_result.plot()\n\n\n\n\n \"\"\" Best setting? \n self = DeepFM(list(range(n_user+1)), list(range(n_item+1)), first_half_fit_only_fm=False, ctr_prediction=False)\n self.dfm_params['epoch'] = 10\n self.dfm_params['embedding_size'] = 4\n self.dfm_params['deep_layers'] = [16, 16]\n self.dfm_params['l2_reg'] = 0.04 #0.0040\n self.dfm_params['l2_reg_embedding'] = 0.001 #0.001\n self.dfm_params['l2_reg_bias'] = 0.001 #0.001\n self.dfm_params['learning_rate'] = 0.0010 #0.001\n self.dfm_params['use_deep'] = True\n self.dfm_params['batch_size'] = 64\n self.dfm_params['loss_type'] = 'mse'\n #self.dfm_params['optimizer_type'] = 'sgd'\n \n self.fit(users, items, ratings)\n \n feature_embeddings = self.model.sess.run(self.model.weights[\"feature_embeddings\"])\n feature_bias = self.model.sess.run(self.model.weights[\"feature_bias\"])\n concat_bias = self.model.sess.run(self.model.weights[\"concat_bias\"])\n \n #pd.DataFrame(feature_embeddings).plot() \n #pd.DataFrame(feature_bias).plot() \n pd.DataFrame(self.predict([200]*50,list(range(50)))).plot() # 新規ユーザーだけ常に一定になる。\n \"\"\"", "'''\nCreated on Dec 18, 2018\nTensorflow Implementation of the Baseline model, NFM, in:\nWang Xiang et al. KGAT: Knowledge Graph Attention Network for Recommendation. In KDD 2019.\n@author: Xiang Wang ([email protected])\n'''\nimport numpy as np\nimport random as rd\nfrom .load_data import Data\nimport scipy.sparse as sp\n\nclass NFM_loader(Data):\n def __init__(self, args, path):\n super().__init__(args, path)\n # generate the sparse matrix for the knowledge graph features.\n kg_feat_file = path + '/kg_feat.npz'\n self.kg_feat_mat = self.get_kg_feature(kg_feat_file)\n\n # generate the one-hot sparse matrix for the users.\n self.user_one_hot = sp.identity(self.n_users).tocsr()\n\n def get_kg_feature(self, kg_feat_file):\n try:\n kg_feat_mat = sp.load_npz(kg_feat_file)\n print('already load item kg feature mat', kg_feat_mat.shape)\n except Exception:\n kg_feat_mat = self._create_kg_feat_mat()\n sp.save_npz(kg_feat_file, kg_feat_mat)\n print('already save item kg feature mat:', kg_feat_file)\n return kg_feat_mat\n\n def _create_kg_feat_mat(self):\n cat_rows = []\n cat_cols = []\n cat_data = []\n\n for i_id in range(self.n_items):\n # One-hot encoding for items.\n cat_rows.append(i_id)\n cat_cols.append(i_id)\n cat_data.append(1)\n\n # Multi-hot encoding for kg features of items.\n if i_id not in self.kg_dict.keys(): continue\n triples = self.kg_dict[i_id]\n for trip in triples:\n # ... only consider the tail entities.\n t_id = trip[0]\n # ... relations are ignored.\n r_id = trip[1]\n\n cat_rows.append(i_id)\n cat_cols.append(t_id)\n cat_data.append(1.)\n\n kg_feat_mat = sp.coo_matrix((cat_data, (cat_rows, cat_cols)), shape=(self.n_items, self.n_entities)).tocsr()\n return kg_feat_mat\n\n def generate_train_batch(self):\n\n users, pos_items, neg_items = self._generate_train_cf_batch()\n u_sp = self.user_one_hot[users]\n pos_i_sp = self.kg_feat_mat[pos_items]\n neg_i_sp = self.kg_feat_mat[neg_items]\n\n\n # Horizontally stack sparse matrices to get single positive & negative feature matrices\n pos_feats = sp.hstack([u_sp, pos_i_sp])\n neg_feats = sp.hstack([u_sp, neg_i_sp])\n\n batch_data = {}\n batch_data['pos_feats'] = pos_feats\n batch_data['neg_feats'] = neg_feats\n return batch_data\n\n def _extract_sp_info(self, sp_feats):\n sp_indices = np.hstack((sp_feats.nonzero()[0][:, None],\n sp_feats.nonzero()[1][:, None]))\n sp_values = sp_feats.data\n sp_shape = sp_feats.shape\n return sp_indices, sp_values, sp_shape\n\n def generate_train_feed_dict(self, model, batch_data):\n\n pos_indices, pos_values, pos_shape = self._extract_sp_info(batch_data['pos_feats'])\n neg_indices, neg_values, neg_shape = self._extract_sp_info(batch_data['neg_feats'])\n\n feed_dict = {\n model.pos_indices: pos_indices,\n model.pos_values: pos_values,\n model.pos_shape: pos_shape,\n\n model.neg_indices: neg_indices,\n model.neg_values: neg_values,\n model.neg_shape: neg_shape,\n\n model.mess_dropout: eval(self.args.mess_dropout)\n }\n\n return feed_dict\n\n def generate_test_feed_dict(self, model, user_batch, item_batch, drop_flag=True):\n user_list = np.repeat(user_batch, len(item_batch)).tolist()\n item_list = list(item_batch) * len(user_batch)\n\n u_sp = self.user_one_hot[user_list]\n pos_i_sp = self.kg_feat_mat[item_list]\n\n # Horizontally stack sparse matrices to get single positive & negative feature matrices\n pos_feats = sp.hstack([u_sp, pos_i_sp])\n pos_indices, pos_values, pos_shape = self._extract_sp_info(pos_feats)\n\n feed_dict = {\n model.pos_indices: pos_indices,\n model.pos_values: pos_values,\n model.pos_shape: pos_shape,\n\n model.mess_dropout: [0.] * len(eval(self.args.layer_size))\n }\n\n return feed_dict\n\n\n\n", "\nimport os\nimport sys\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nfrom sklearn.metrics import make_scorer\nfrom sklearn.model_selection import StratifiedKFold\n\nimport config\nfrom metrics import gini_norm\nfrom DataReader import FeatureDictionary, DataParser\nsys.path.append(\"..\")\nfrom DeepFM import DeepFM\n\ngini_scorer = make_scorer(gini_norm, greater_is_better=True, needs_proba=True)\n\n\ndef _load_data():\n\n dfTrain = pd.read_csv(config.TRAIN_FILE)\n dfTest = pd.read_csv(config.TEST_FILE)\n\n def preprocess(df):\n cols = [c for c in df.columns if c not in [\"id\", \"target\"]]\n df[\"missing_feat\"] = np.sum((df[cols] == -1).values, axis=1)\n df[\"ps_car_13_x_ps_reg_03\"] = df[\"ps_car_13\"] * df[\"ps_reg_03\"]\n return df\n\n dfTrain = preprocess(dfTrain)\n dfTest = preprocess(dfTest)\n\n cols = [c for c in dfTrain.columns if c not in [\"id\", \"target\"]]\n cols = [c for c in cols if (not c in config.IGNORE_COLS)]\n\n X_train = dfTrain[cols].values\n y_train = dfTrain[\"target\"].values\n X_test = dfTest[cols].values\n ids_test = dfTest[\"id\"].values\n cat_features_indices = [i for i,c in enumerate(cols) if c in config.CATEGORICAL_COLS]\n\n return dfTrain, dfTest, X_train, y_train, X_test, ids_test, cat_features_indices\n\n\ndef _run_base_model_dfm(dfTrain, dfTest, folds, dfm_params):\n fd = FeatureDictionary(dfTrain=dfTrain, dfTest=dfTest,\n numeric_cols=config.NUMERIC_COLS,\n ignore_cols=config.IGNORE_COLS)\n data_parser = DataParser(feat_dict=fd)\n Xi_train, Xv_train, y_train = data_parser.parse(df=dfTrain, has_label=True)\n Xi_test, Xv_test, ids_test = data_parser.parse(df=dfTest)\n\n dfm_params[\"feature_size\"] = fd.feat_dim\n dfm_params[\"field_size\"] = len(Xi_train[0])\n\n y_train_meta = np.zeros((dfTrain.shape[0], 1), dtype=float)\n y_test_meta = np.zeros((dfTest.shape[0], 1), dtype=float)\n _get = lambda x, l: [x[i] for i in l]\n gini_results_cv = np.zeros(len(folds), dtype=float)\n gini_results_epoch_train = np.zeros((len(folds), dfm_params[\"epoch\"]), dtype=float)\n gini_results_epoch_valid = np.zeros((len(folds), dfm_params[\"epoch\"]), dtype=float)\n for i, (train_idx, valid_idx) in enumerate(folds):\n # i, (train_idx, valid_idx) = 0, folds[0]\n Xi_train_, Xv_train_, y_train_ = _get(Xi_train, train_idx), _get(Xv_train, train_idx), _get(y_train, train_idx)\n Xi_valid_, Xv_valid_, y_valid_ = _get(Xi_train, valid_idx), _get(Xv_train, valid_idx), _get(y_train, valid_idx)\n\n dfm = DeepFM(**dfm_params)\n dfm.fit(Xi_train_, Xv_train_, y_train_, Xi_valid_, Xv_valid_, y_valid_)\n\n y_train_meta[valid_idx,0] = dfm.predict(Xi_valid_, Xv_valid_)\n y_test_meta[:,0] += dfm.predict(Xi_test, Xv_test)\n\n gini_results_cv[i] = gini_norm(y_valid_, y_train_meta[valid_idx])\n gini_results_epoch_train[i] = dfm.train_result\n gini_results_epoch_valid[i] = dfm.valid_result\n\n y_test_meta /= float(len(folds))\n\n # save result\n if dfm_params[\"use_fm\"] and dfm_params[\"use_deep\"]:\n clf_str = \"DeepFM\"\n elif dfm_params[\"use_fm\"]:\n clf_str = \"FM\"\n elif dfm_params[\"use_deep\"]:\n clf_str = \"DNN\"\n print(\"%s: %.5f (%.5f)\"%(clf_str, gini_results_cv.mean(), gini_results_cv.std()))\n filename = \"%s_Mean%.5f_Std%.5f.csv\"%(clf_str, gini_results_cv.mean(), gini_results_cv.std())\n _make_submission(ids_test, y_test_meta, filename)\n\n _plot_fig(gini_results_epoch_train, gini_results_epoch_valid, clf_str)\n\n return y_train_meta, y_test_meta\n\n\ndef _make_submission(ids, y_pred, filename=\"submission.csv\"):\n pd.DataFrame({\"id\": ids, \"target\": y_pred.flatten()}).to_csv(\n os.path.join(config.SUB_DIR, filename), index=False, float_format=\"%.5f\")\n\n\ndef _plot_fig(train_results, valid_results, model_name):\n colors = [\"red\", \"blue\", \"green\"]\n xs = np.arange(1, train_results.shape[1]+1)\n plt.figure()\n legends = []\n for i in range(train_results.shape[0]):\n plt.plot(xs, train_results[i], color=colors[i], linestyle=\"solid\", marker=\"o\")\n plt.plot(xs, valid_results[i], color=colors[i], linestyle=\"dashed\", marker=\"o\")\n legends.append(\"train-%d\"%(i+1))\n legends.append(\"valid-%d\"%(i+1))\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Normalized Gini\")\n plt.title(\"%s\"%model_name)\n plt.legend(legends)\n plt.savefig(\"./fig/%s.png\"%model_name)\n plt.close()\n\n\n# load data\ndfTrain, dfTest, X_train, y_train, X_test, ids_test, cat_features_indices = _load_data()\n\n# folds\nfolds = list(StratifiedKFold(n_splits=config.NUM_SPLITS, shuffle=True,\n random_state=config.RANDOM_SEED).split(X_train, y_train))\n\n\n# ------------------ DeepFM Model ------------------\n# params\ndfm_params = {\n \"use_fm\": True,\n \"use_deep\": True,\n \"embedding_size\": 8,\n \"dropout_fm\": [1.0, 1.0],\n \"deep_layers\": [32, 32],\n \"dropout_deep\": [0.5, 0.5, 0.5],\n \"deep_layers_activation\": tf.nn.relu,\n \"epoch\": 30,\n \"batch_size\": 1024,\n \"learning_rate\": 0.001,\n \"optimizer_type\": \"adam\",\n \"batch_norm\": 1,\n \"batch_norm_decay\": 0.995,\n \"l2_reg\": 0.01,\n \"verbose\": True,\n \"eval_metric\": gini_norm,\n \"random_seed\": config.RANDOM_SEED\n}\ny_train_dfm, y_test_dfm = _run_base_model_dfm(dfTrain, dfTest, folds, dfm_params)\n\n# ------------------ FM Model ------------------\nfm_params = dfm_params.copy()\nfm_params[\"use_deep\"] = False\ny_train_fm, y_test_fm = _run_base_model_dfm(dfTrain, dfTest, folds, fm_params)\n\n\n# ------------------ DNN Model ------------------\ndnn_params = dfm_params.copy()\ndnn_params[\"use_fm\"] = False\ny_train_dnn, y_test_dnn = _run_base_model_dfm(dfTrain, dfTest, folds, dnn_params)\n\n\n\n" ]
[ [ "numpy.abs", "tensorflow.Variable", "pandas.DataFrame", "tensorflow.global_variables_initializer", "numpy.mean", "numpy.random.rand", "tensorflow.Session", "sklearn.preprocessing.StandardScaler", "numpy.array" ], [ "scipy.sparse.coo_matrix", "scipy.sparse.load_npz", "scipy.sparse.identity", "scipy.sparse.hstack", "scipy.sparse.save_npz" ], [ "matplotlib.pyplot.legend", "pandas.read_csv", "matplotlib.pyplot.title", "numpy.arange", "matplotlib.pyplot.savefig", "sklearn.model_selection.StratifiedKFold", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "sklearn.metrics.make_scorer", "matplotlib.pyplot.close", "matplotlib.pyplot.xlabel", "numpy.zeros", "numpy.sum", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [ "1.10", "1.4", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.10", "1.4", "1.3", "1.9", "0.19", "1.5", "1.7", "1.0", "1.2", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
AlexKoff88/open_model_zoo
[ "8944a46653427cfa53db10fa91d677826adf31e1", "8944a46653427cfa53db10fa91d677826adf31e1" ]
[ "demos/smartlab_demo/python/segmentor.py", "demos/colorization_demo/python/colorization_demo.py" ]
[ "\"\"\"\n Copyright (C) 2021-2022 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\nimport cv2\nimport numpy as np\nimport logging as log\nfrom pathlib import Path\nfrom scipy.special import softmax\nfrom openvino.runtime import PartialShape\n\nclass SegmentorMstcn:\n def __init__(self, ie, device, i3d_path, mstcn_path):\n self.ActionTerms = [\n \"background\",\n \"noise_action\",\n \"remove_support_sleeve\",\n \"remove_pointer_sleeve\",\n \"adjust_rider\",\n \"adjust_nut\",\n \"adjust_balancing\",\n \"open_box\",\n \"close_box\",\n \"choose_weight\",\n \"put_left\",\n \"put_right\",\n \"take_left\",\n \"take_right\",\n \"install_support_sleeve\",\n \"install_pointer_sleeve\",\n ]\n\n self.EmbedBufferTop = np.zeros((1024, 0))\n self.EmbedBufferFront = np.zeros((1024, 0))\n self.ImgSizeHeight = 224\n self.ImgSizeWidth = 224\n self.EmbedBatchSize = 1\n self.SegBatchSize = 24\n self.EmbedWindowLength = 16\n self.EmbedWindowStride = 1\n self.EmbedWindowAtrous = 3\n self.TemporalLogits = np.zeros((0, len(self.ActionTerms)))\n\n net = ie.read_model(i3d_path)\n net.reshape({net.inputs[0]: PartialShape(\n [self.EmbedBatchSize, self.EmbedWindowLength, self.ImgSizeHeight, self.ImgSizeWidth, 3])})\n nodes = net.get_ops()\n net.add_outputs(nodes[13].output(0))\n self.i3d = ie.compile_model(model=net, device_name=device)\n\n self.mstcn_net = ie.read_model(mstcn_path)\n self.mstcn = ie.compile_model(model=self.mstcn_net, device_name=device)\n self.mstcn_input_keys = self.mstcn.inputs\n self.mstcn_output_key = self.mstcn.outputs\n self.mstcn_net.reshape({'input': PartialShape([1, 2048, 1])})\n self.reshape_mstcn = ie.compile_model(model=self.mstcn_net, device_name=device)\n file_path = Path(__file__).parent / 'init_his.npz'\n init_his_feature = np.load(file_path)\n self.his_fea = {f'fhis_in_{i}': init_his_feature[f'arr_{i}'] for i in range(4)}\n\n def inference(self, buffer_top, buffer_front, frame_index):\n \"\"\"\n Args:\n buffer_top: buffers of the input image arrays for the top view\n buffer_front: buffers of the input image arrays for the front view\n frame_index: frame index of the latest frame\n Returns: the temporal prediction results for each frame (including the historical predictions),\n length of predictions == frame_index()\n \"\"\"\n ### run encoder ###\n self.EmbedBufferTop = self.feature_embedding(\n img_buffer=buffer_top,\n embedding_buffer=self.EmbedBufferTop,\n frame_index=frame_index)\n self.EmbedBufferFront = self.feature_embedding(\n img_buffer=buffer_front,\n embedding_buffer=self.EmbedBufferFront,\n frame_index=frame_index)\n\n ### run mstcn++ only batch size 1###\n if min(self.EmbedBufferTop.shape[-1], self.EmbedBufferFront.shape[-1]) > 0:\n self.action_segmentation()\n\n # ### get label ###\n valid_index = self.TemporalLogits.shape[0]\n if valid_index == 0:\n return []\n else:\n frame_predictions = [self.ActionTerms[i] for i in np.argmax(self.TemporalLogits, axis=1)]\n frame_predictions = [\"background\" for i in range(self.EmbedWindowLength - 1)] + frame_predictions\n\n return frame_predictions[-1]\n\n def feature_embedding(self, img_buffer, embedding_buffer, frame_index):\n # minimal temporal length for processor\n min_t = (self.EmbedWindowLength - 1) * self.EmbedWindowAtrous\n\n infer_request = self.i3d.create_infer_request()\n if frame_index > min_t:\n num_embedding = embedding_buffer.shape[-1]\n img_buffer = list(img_buffer)\n curr_t = self.EmbedWindowStride * num_embedding + (self.EmbedWindowLength - 1) * self.EmbedWindowAtrous\n while curr_t < frame_index:\n # absolute index in temporal shaft\n start_index = self.EmbedWindowStride * num_embedding\n\n if frame_index > len(img_buffer):\n # absolute index in buffer shaft\n start_index = start_index - (frame_index - len(img_buffer))\n\n input_data = [\n [cv2.resize(img_buffer[start_index + i * self.EmbedWindowAtrous],\n (self.ImgSizeHeight, self.ImgSizeWidth)) for i in range(self.EmbedWindowLength)]\n for j in range(self.EmbedBatchSize)]\n input_data = np.asarray(input_data).transpose((0, 4, 1, 2, 3))\n input_data = input_data * 127.5 + 127.5\n\n input_dict = {self.i3d.inputs[0]: input_data}\n out_logits = infer_request.infer(input_dict)[self.i3d.outputs[1]]\n out_logits = out_logits.squeeze((0, 3, 4))\n\n # ndarray: C x num_embedding\n embedding_buffer = np.concatenate((embedding_buffer, out_logits), axis=1)\n\n curr_t += self.EmbedWindowStride\n return embedding_buffer\n\n def action_segmentation(self):\n # read buffer\n embed_buffer_top = self.EmbedBufferTop\n embed_buffer_front = self.EmbedBufferFront\n batch_size = self.SegBatchSize\n start_index = self.TemporalLogits.shape[0]\n end_index = min(embed_buffer_top.shape[-1], embed_buffer_front.shape[-1])\n num_batch = (end_index - start_index) // batch_size\n\n infer_request = self.reshape_mstcn.create_infer_request()\n if num_batch < 0:\n log.debug(\"Waiting for the next frame ...\")\n elif num_batch == 0:\n log.debug(f\"start_index: {start_index} end_index: {end_index}\")\n unit1 = embed_buffer_top[:, start_index:end_index]\n unit2 = embed_buffer_front[:, start_index:end_index]\n feature_unit = np.concatenate([unit1[:, ], unit2[:, ]], axis=0)\n input_mstcn = np.expand_dims(feature_unit, 0)\n\n feed_dict = {}\n if len(self.his_fea) != 0:\n for key in self.mstcn_input_keys:\n if 'fhis_in_' in str(key.names):\n string = list(key.names)[0]\n feed_dict[string] = self.his_fea[string]\n feed_dict['input'] = input_mstcn\n if input_mstcn.shape == (1, 2048, 1):\n out = infer_request.infer(feed_dict)\n\n predictions = out[list(out.keys())[-1]]\n for key in self.mstcn_output_key:\n if 'fhis_in_' in str(key.names):\n string = list(key.names)[0]\n self.his_fea[string] = out[string]\n\n \"\"\"\n predictions --> 4x1x64x24\n his_fea --> [12*[1x64x2048], 11*[1x64x2048], 11*[1x64x2048], 11*[1x64x2048]]\n \"\"\"\n temporal_logits = predictions[:, :, :len(self.ActionTerms), :] # 4x1x16xN\n temporal_logits = softmax(temporal_logits[-1], 1) # 1x16xN\n temporal_logits = temporal_logits.transpose((0, 2, 1)).squeeze(axis=0)\n self.TemporalLogits = np.concatenate([self.TemporalLogits, temporal_logits], axis=0)\n else:\n for batch_idx in range(num_batch):\n unit1 = embed_buffer_top[:,\n start_index + batch_idx * batch_size:start_index + batch_idx * batch_size + batch_size]\n unit2 = embed_buffer_front[:,\n start_index + batch_idx * batch_size:start_index + batch_idx * batch_size + batch_size]\n feature_unit = np.concatenate([unit1[:, ], unit2[:, ]], axis=0)\n\n feed_dict = {}\n if len(self.his_fea) != 0:\n for key in self.mstcn_input_keys:\n if 'fhis_in_' in str(key.names):\n string = list(key.names)[0]\n feed_dict[key] = self.his_fea[string]\n feed_dict['input'] = feature_unit\n out = infer_request.infer(feed_dict)\n predictions = out[list(out.keys())[-1]]\n for key in self.mstcn_output_key:\n if 'fhis_in_' in str(key.names):\n string = list(key.names)[0]\n self.his_fea[string] = out[string]\n\n temporal_logits = predictions[:, :, :len(self.ActionTerms), :] # 4x1x16xN\n temporal_logits = softmax(temporal_logits[-1], 1) # 1x16xN\n temporal_logits = temporal_logits.transpose((0, 2, 1)).squeeze(axis=0)\n self.TemporalLogits = np.concatenate([self.TemporalLogits, temporal_logits], axis=0)\n", "#!/usr/bin/env python3\n\"\"\"\n Copyright (c) 2018-2021 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\nfrom openvino.runtime import Core, get_version\nimport cv2 as cv\nimport numpy as np\nimport logging as log\nfrom time import perf_counter\nimport sys\nfrom argparse import ArgumentParser, SUPPRESS\nfrom pathlib import Path\n\nsys.path.append(str(Path(__file__).resolve().parents[2] / 'common/python'))\n\nimport monitors\nfrom images_capture import open_images_capture\nfrom openvino.model_zoo.model_api.performance_metrics import PerformanceMetrics\n\nlog.basicConfig(format='[ %(levelname)s ] %(message)s', level=log.DEBUG, stream=sys.stdout)\n\n\ndef build_arg():\n parser = ArgumentParser(add_help=False)\n in_args = parser.add_argument_group('Options')\n in_args.add_argument('-h', '--help', action='help', default=SUPPRESS, help='Help with the script.')\n in_args.add_argument(\"-m\", \"--model\", help=\"Required. Path to .xml file with pre-trained model.\",\n required=True, type=Path)\n in_args.add_argument(\"-d\", \"--device\",\n help=\"Optional. Specify target device for infer: CPU, GPU, HDDL or MYRIAD. \"\n \"Default: CPU\",\n default=\"CPU\", type=str)\n in_args.add_argument('-i', \"--input\", required=True,\n help='Required. An input to process. The input must be a single image, '\n 'a folder of images, video file or camera id.')\n in_args.add_argument('--loop', default=False, action='store_true',\n help='Optional. Enable reading the input in a loop.')\n in_args.add_argument('-o', '--output', required=False,\n help='Optional. Name of the output file(s) to save.')\n in_args.add_argument('-limit', '--output_limit', required=False, default=1000, type=int,\n help='Optional. Number of frames to store in output. '\n 'If 0 is set, all frames are stored.')\n in_args.add_argument(\"--no_show\", help=\"Optional. Don't show output.\",\n action='store_true', default=False)\n in_args.add_argument(\"-u\", \"--utilization_monitors\", default=\"\", type=str,\n help=\"Optional. List of monitors to show initially.\")\n return parser\n\ndef main(args):\n cap = open_images_capture(args.input, args.loop)\n\n log.info('OpenVINO Inference Engine')\n log.info('\\tbuild: {}'.format(get_version()))\n core = Core()\n\n log.info('Reading model {}'.format(args.model))\n model = core.read_model(args.model)\n\n input_tensor_name = 'data_l'\n input_shape = model.input(input_tensor_name).shape\n assert input_shape[1] == 1, \"Expected model input shape with 1 channel\"\n\n inputs = {}\n for input in model.inputs:\n inputs[input.get_any_name()] = np.zeros(input.shape)\n\n assert len(model.outputs) == 1, \"Expected number of outputs is equal 1\"\n\n compiled_model = core.compile_model(model, device_name=args.device)\n output_tensor = compiled_model.outputs[0]\n infer_request = compiled_model.create_infer_request()\n log.info('The model {} is loaded to {}'.format(args.model, args.device))\n\n _, _, h_in, w_in = input_shape\n\n frames_processed = 0\n imshow_size = (640, 480)\n graph_size = (imshow_size[0] // 2, imshow_size[1] // 4)\n presenter = monitors.Presenter(args.utilization_monitors, imshow_size[1] * 2 - graph_size[1], graph_size)\n metrics = PerformanceMetrics()\n\n video_writer = cv.VideoWriter()\n if args.output and not video_writer.open(args.output, cv.VideoWriter_fourcc(*'MJPG'),\n cap.fps(), (imshow_size[0] * 2, imshow_size[1] * 2)):\n raise RuntimeError(\"Can't open video writer\")\n\n start_time = perf_counter()\n original_frame = cap.read()\n if original_frame is None:\n raise RuntimeError(\"Can't read an image from the input\")\n\n while original_frame is not None:\n (h_orig, w_orig) = original_frame.shape[:2]\n\n if original_frame.shape[2] > 1:\n frame = cv.cvtColor(cv.cvtColor(original_frame, cv.COLOR_BGR2GRAY), cv.COLOR_GRAY2RGB)\n else:\n frame = cv.cvtColor(original_frame, cv.COLOR_GRAY2RGB)\n\n img_rgb = frame.astype(np.float32) / 255\n img_lab = cv.cvtColor(img_rgb, cv.COLOR_RGB2Lab)\n img_l_rs = cv.resize(img_lab.copy(), (w_in, h_in))[:, :, 0]\n\n inputs[input_tensor_name] = np.expand_dims(img_l_rs, axis=[0, 1])\n\n res = infer_request.infer(inputs)[output_tensor]\n\n update_res = np.squeeze(res)\n\n out = update_res.transpose((1, 2, 0))\n out = cv.resize(out, (w_orig, h_orig))\n img_lab_out = np.concatenate((img_lab[:, :, 0][:, :, np.newaxis], out), axis=2)\n img_bgr_out = np.clip(cv.cvtColor(img_lab_out, cv.COLOR_Lab2BGR), 0, 1)\n\n original_image = cv.resize(original_frame, imshow_size)\n grayscale_image = cv.resize(frame, imshow_size)\n colorize_image = (cv.resize(img_bgr_out, imshow_size) * 255).astype(np.uint8)\n lab_image = cv.resize(img_lab_out, imshow_size).astype(np.uint8)\n\n original_image = cv.putText(original_image, 'Original', (25, 50),\n cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv.LINE_AA)\n grayscale_image = cv.putText(grayscale_image, 'Grayscale', (25, 50),\n cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv.LINE_AA)\n colorize_image = cv.putText(colorize_image, 'Colorize', (25, 50),\n cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv.LINE_AA)\n lab_image = cv.putText(lab_image, 'LAB interpretation', (25, 50),\n cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv.LINE_AA)\n\n ir_image = [cv.hconcat([original_image, grayscale_image]),\n cv.hconcat([lab_image, colorize_image])]\n final_image = cv.vconcat(ir_image)\n\n metrics.update(start_time, final_image)\n\n frames_processed += 1\n if video_writer.isOpened() and (args.output_limit <= 0 or frames_processed <= args.output_limit):\n video_writer.write(final_image)\n\n presenter.drawGraphs(final_image)\n if not args.no_show:\n cv.imshow('Colorization Demo', final_image)\n key = cv.waitKey(1)\n if key in {ord(\"q\"), ord(\"Q\"), 27}:\n break\n presenter.handleKey(key)\n start_time = perf_counter()\n original_frame = cap.read()\n\n metrics.log_total()\n for rep in presenter.reportMeans():\n log.info(rep)\n\nif __name__ == \"__main__\":\n args = build_arg().parse_args()\n sys.exit(main(args) or 0)\n" ]
[ [ "numpy.expand_dims", "numpy.asarray", "numpy.concatenate", "numpy.argmax", "numpy.load", "scipy.special.softmax", "numpy.zeros" ], [ "numpy.concatenate", "numpy.squeeze", "numpy.expand_dims", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.10", "1.4", "1.9", "1.5", "1.2", "1.7", "1.3", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
eduardojdiniz/CompNeuro
[ "20269e66540dc4e802273735c97323020ee37406" ]
[ "CichyWanderers/dataloader.py" ]
[ "#!/usr/bin/env python\n# coding=utf-8\n\n# Imports\nimport h5py\nimport scipy.io as sio\nimport os\nimport requests\nimport zipfile\nimport numpy as np\nimport glob\nimport shutil\nimport pickle\n\n\ndef loadmat(matfile):\n \"\"\"Function to load .mat files.\n\n Parameters\n ----------\n matfile : str\n path to `matfile` containing fMRI data for a given trial.\n\n Returns\n -------\n dict\n dictionary containing data in key 'vol' for a given trial.\n\n \"\"\"\n try:\n f = h5py.File(matfile)\n except (IOError, OSError):\n return sio.loadmat(matfile)\n else:\n return {name: np.transpose(f.get(name)) for name in f.keys()}\n\n\ndef download_Cichy(**kwargs):\n \"\"\"Function to download data from Cichy et al, 2014.\n\n Parameters\n ----------\n kwargs: dict\n 'data_dirpath': str, data directory path. Default: ./data\n 'data_url' : str, data url. Default: https://osf.io/7vpyh/download'\n 'label_url' : str, visual stimuli labels url. Default:\n http://wednesday.csail.mit.edu/MEG1_MEG_Clear_Data/visual_stimuli.mat\n\n Returns\n -------\n path_dict: dict\n 'fMRI' : str, fMRI filepath\n 'MEG' : str, MEG filepath\n 'label': str, visual stimuli filepath\n 'image': str, jpeg images dirpath\n 'tmp' : str, temporary data dirpath\n\n \"\"\"\n cwd = os.getcwd()\n data_dirpath = kwargs.pop('data_dirpath', os.path.join(cwd, \"data\"))\n if not os.path.exists(data_dirpath):\n os.makedirs(data_dirpath)\n\n tmp_dirpath = os.path.join(cwd, \"tmp\")\n if not os.path.exists(tmp_dirpath):\n os.makedirs(tmp_dirpath)\n\n data_url = kwargs.pop('data_url', 'https://osf.io/7vpyh/download')\n label_url = kwargs.pop(\n 'label_url',\n 'http://wednesday.csail.mit.edu/MEG1_MEG_Clear_Data/visual_stimuli.mat')\n data_filepath = os.path.join(tmp_dirpath, 'data.zip')\n label_filepath = os.path.join(tmp_dirpath, 'visual_stimuli.mat')\n if not os.path.exists(tmp_dirpath):\n os.makedirs(tmp_dirpath)\n\n # Download MEG and fMRI RDMs\n r = requests.get(data_url)\n with open(data_filepath, 'wb') as f:\n f.write(r.content)\n\n # Download visual stimuli\n r = requests.get(label_url)\n with open(label_filepath, 'wb') as f:\n f.write(r.content)\n\n # Extract directory '92_Image_Set' and 'MEG_decoding_RDMs.mat'\n with zipfile.ZipFile(data_filepath, 'r') as zip_file:\n zip_file.extractall(tmp_dirpath)\n\n # Move image files to permanent directory\n tmp_image_dirpath = os.path.join(tmp_dirpath, '92_Image_Set', '92images')\n image_dirpath = os.path.join(cwd, 'data', 'images')\n if not os.path.exists(image_dirpath):\n os.makedirs(image_dirpath)\n\n for f in os.listdir(tmp_image_dirpath):\n shutil.move(tmp_image_dirpath + f, image_dirpath)\n\n path_dict = {}\n fMRI_filepath = os.path.join(\n data_dirpath,\n '92_Image_Set',\n 'target_fmri.mat')\n path_dict['fMRI'] = fMRI_filepath\n path_dict['MEG'] = os.path.join(data_dirpath, 'MEG_decoding_RDMs')\n path_dict['label'] = label_filepath\n path_dict['image'] = image_dirpath\n path_dict['tmp'] = tmp_dirpath\n\n return path_dict\n\n\ndef get_stim_dict(**kwargs):\n \"\"\"Get category names and binary features describing the Cichy dataset\n\n Parameters\n ----------\n kwargs: dict\n 'fMRI' : str, fMRI filepath\n 'MEG' : str, MEG filepath\n 'label': str, visual stimuli filepath\n 'image': str, jpeg images dirpath\n 'tmp' : str, temporary data dirpath\n\n Returns\n -------\n stim_dict: dict\n 'category' : list[str], indicating category\n 'human' : list[int], indicating membership (0=not a member, 1=member)\n 'face' : list[int], indicating membership (0=not a member, 1=member)\n 'animate' : list[int], indicating membership (0=not a member, 1=member)\n 'natural' : list[int], indicating membership (0=not a member, 1=member)\n 'imagepath' : list[str], jpeg image filepath\n\n \"\"\"\n stimuli_filepath = kwargs.pop('label', '')\n image_dirpath = kwargs.pop('image', '')\n\n stim_dat = loadmat(stimuli_filepath)['visual_stimuli']\n fields = ['category', 'human', 'face', 'animate', 'natural']\n\n stim_dict = {field: [] for field in fields}\n for ii in range(92):\n for jj, field in enumerate(fields):\n stim_dict[field].append(stim_dat[0, ii][jj][0])\n for field in fields[1:]:\n stim_dict[field] = np.array(stim_dict[field]).squeeze()\n stim_dict['imagepath'] = glob.glob(image_dirpath + '/*.jpg').sort()\n\n return stim_dict\n\n\ndef get_RDM_dict(**kwargs):\n \"\"\"Get MEG and fMRI RDMs from the Cichy dataset\n\n Parameters\n ----------\n kwargs: dict\n 'fMRI' : str, fMRI filepath\n 'MEG' : str, MEG filepath\n 'label': str, visual stimuli filepath\n 'image': str, jpeg images dirpath\n 'tmp' : str, temporary data dirpath\n\n Returns\n -------\n RDM_dict: dict\n 'MEG' : ndarray, (16, 2, 1301, 92, 92)\n 16 subjects, 2 sessions, 1301 time points (from -100 ms to 1200 ms\n wrt to stimulus onset at 0 ms), 92 conditions by 92 conditions.\n The last 2 dimensions form representational dissimilarity matrices of\n decoding accuracies, symmetric accross the diagonal, with the diagonal\n undefined (NaN).\n 'fMRI_EVC': ndarray, (15, 92, 92)\n 15 subjects, 92 conditions by 92 conditions.\n The last 2 dimensions form a representational dissimilarity matrix of\n spearman correlation for the EVC cortex, symmetric accross the diagonal,\n with the diagonal undefined (NaN).\n 'fMRI_IT' : ndarray, (15, 92, 92)\n 15 subjects, 92 conditions by 92 conditions.\n The last 2 dimensions form a representational dissimilarity matrix of\n spearman correlation for the IT cortex, symmetric accross the diagonal,\n with the diagonal undefined (NaN).\n\n \"\"\"\n fMRI_filepath = kwargs.pop('fMRI', '')\n MEG_filepath = kwargs.pop('MEG', '')\n\n RDM_dict = {}\n\n RDM_dict['MEG'] = loadmat(MEG_filepath)['MEG_decoding_RDMs']\n\n fMRI_RDMs = loadmat(fMRI_filepath)\n RDM_dict['fMRI_EVC'] = fMRI_RDMs['EVC_RDMs']\n RDM_dict['fMRI_IT'] = fMRI_RDMs['IT_RDMs']\n\n return RDM_dict\n\n\ndef main():\n \"\"\"Download and organize Cichy et al, 2014 dataset\n\n Parameters\n ----------\n None\n\n Returns\n -------\n data_dirpath: str, data directory containing an image directory with the 92\n visual stimuli and a pickle files containing the two dictionaries,\n stim_dict.pkl and RDM_dict.pkl. See help(get_stim_dict) and\n help(get_RDM_dict) for details.\n\n \"\"\"\n url_dict = {\n 'data_url': 'https://osf.io/7vpyh/download',\n 'label_url': 'http://wednesday.csail.mit.edu/MEG1_MEG_Clear_Data/visual_stimuli.mat'}\n\n # Download Cichy et al, 2014 dataset\n path_dict = download_Cichy(**url_dict)\n # Get stimuli dictionary\n stim_dict = get_stim_dict(**path_dict)\n # Get RDM dictionary\n RDM_dict = get_RDM_dict(**path_dict)\n\n data_dirpath = path_dict['data_dirpath']\n stim_dict_pickle = os.path.join(data_dirpath, 'stim_dict.pkl')\n RDM_dict_pickle = os.path.join(data_dirpath, 'RDM_dict.pkl')\n\n with open(stim_dict_pickle, 'wb') as pkl:\n pickle.dump(stim_dict, pkl)\n\n with open(RDM_dict_pickle, 'wb') as pkl:\n pickle.dump(RDM_dict, pkl)\n\n # Clean temporary directory\n shutil.rmtree(url_dict['tmp'])\n\n return data_dirpath\n\n\nif __name__ == \"__main__\":\n data_dirpath = main()\n" ]
[ [ "numpy.array", "scipy.io.loadmat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
gengkunling/tensorflow_poet
[ "5ef36da08ee0f50cdaa2d08753393c549c2e75b3" ]
[ "scripts/retrain.py" ]
[ "# Copyright 2015 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# ==============================================================================\nr\"\"\"Simple transfer learning with Inception v3 or Mobilenet models.\n\nWith support for TensorBoard.\n\nThis example shows how to take a Inception v3 or Mobilenet model trained on\nImageNet images, and train a new top layer that can recognize other classes of\nimages.\n\nThe top layer receives as input a 2048-dimensional vector (1001-dimensional for\nMobilenet) for each image. We train a softmax layer on top of this\nrepresentation. Assuming the softmax layer contains N labels, this corresponds\nto learning N + 2048*N (or 1001*N) model parameters corresponding to the\nlearned biases and weights.\n\nHere's an example, which assumes you have a folder containing class-named\nsubfolders, each full of images for each label. The example folder flower_photos\nshould have a structure like this:\n\n~/flower_photos/daisy/photo1.jpg\n~/flower_photos/daisy/photo2.jpg\n...\n~/flower_photos/rose/anotherphoto77.jpg\n...\n~/flower_photos/sunflower/somepicture.jpg\n\nThe subfolder names are important, since they define what label is applied to\neach image, but the filenames themselves don't matter. Once your images are\nprepared, you can run the training with a command like this:\n\n\n```bash\nbazel build tensorflow/examples/image_retraining:retrain && \\\nbazel-bin/tensorflow/examples/image_retraining/retrain \\\n --image_dir ~/flower_photos\n```\n\nOr, if you have a pip installation of tensorflow, `retrain.py` can be run\nwithout bazel:\n\n```bash\npython tensorflow/examples/image_retraining/retrain.py \\\n --image_dir ~/flower_photos\n```\n\nYou can replace the image_dir argument with any folder containing subfolders of\nimages. The label for each image is taken from the name of the subfolder it's\nin.\n\nThis produces a new model file that can be loaded and run by any TensorFlow\nprogram, for example the label_image sample code.\n\nBy default this script will use the high accuracy, but comparatively large and\nslow Inception v3 model architecture. It's recommended that you start with this\nto validate that you have gathered good training data, but if you want to deploy\non resource-limited platforms, you can try the `--architecture` flag with a\nMobilenet model. For example:\n\n```bash\npython tensorflow/examples/image_retraining/retrain.py \\\n --image_dir ~/flower_photos --architecture mobilenet_1.0_224\n```\n\nThere are 32 different Mobilenet models to choose from, with a variety of file\nsize and latency options. The first number can be '1.0', '0.75', '0.50', or\n'0.25' to control the size, and the second controls the input image size, either\n'224', '192', '160', or '128', with smaller sizes running faster. See\nhttps://research.googleblog.com/2017/06/mobilenets-open-source-models-for.html\nfor more information on Mobilenet.\n\nTo use with TensorBoard:\n\nBy default, this script will log summaries to /tmp/retrain_logs directory\n\nVisualize the summaries with this command:\n\ntensorboard --logdir /tmp/retrain_logs\n\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nfrom datetime import datetime\nimport hashlib\nimport os.path\nimport random\nimport re\nimport sys\nimport tarfile\n\nimport numpy as np\nfrom six.moves import urllib\nimport tensorflow as tf\n\nfrom tensorflow.python.framework import graph_util\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.util import compat\n\nFLAGS = None\n\n# These are all parameters that are tied to the particular model architecture\n# we're using for Inception v3. These include things like tensor names and their\n# sizes. If you want to adapt this script to work with another model, you will\n# need to update these to reflect the values in the network you're using.\nMAX_NUM_IMAGES_PER_CLASS = 2 ** 27 - 1 # ~134M\n\n\ndef create_image_lists(image_dir, testing_percentage, validation_percentage):\n \"\"\"Builds a list of training images from the file system.\n\n Analyzes the sub folders in the image directory, splits them into stable\n training, testing, and validation sets, and returns a data structure\n describing the lists of images for each label and their paths.\n\n Args:\n image_dir: String path to a folder containing subfolders of images.\n testing_percentage: Integer percentage of the images to reserve for tests.\n validation_percentage: Integer percentage of images reserved for validation.\n\n Returns:\n A dictionary containing an entry for each label subfolder, with images split\n into training, testing, and validation sets within each label.\n \"\"\"\n if not gfile.Exists(image_dir):\n tf.logging.error(\"Image directory '\" + image_dir + \"' not found.\")\n return None\n result = {}\n sub_dirs = [x[0] for x in gfile.Walk(image_dir)]\n # The root directory comes first, so skip it.\n is_root_dir = True\n for sub_dir in sub_dirs:\n if is_root_dir:\n is_root_dir = False\n continue\n extensions = ['jpg', 'jpeg', 'JPG', 'JPEG', 'png', 'PNG']\n file_list = []\n dir_name = os.path.basename(sub_dir)\n if dir_name == image_dir:\n continue\n tf.logging.info(\"Looking for images in '\" + dir_name + \"'\")\n for extension in extensions:\n file_glob = os.path.join(image_dir, dir_name, '*.' + extension)\n file_list.extend(gfile.Glob(file_glob))\n if not file_list:\n tf.logging.warning('No files found')\n continue\n if len(file_list) < 20:\n tf.logging.warning(\n 'WARNING: Folder has less than 20 images, which may cause issues.')\n elif len(file_list) > MAX_NUM_IMAGES_PER_CLASS:\n tf.logging.warning(\n 'WARNING: Folder {} has more than {} images. Some images will '\n 'never be selected.'.format(dir_name, MAX_NUM_IMAGES_PER_CLASS))\n label_name = re.sub(r'[^a-z0-9]+', ' ', dir_name.lower())\n training_images = []\n testing_images = []\n validation_images = []\n for file_name in file_list:\n base_name = os.path.basename(file_name)\n # We want to ignore anything after '_nohash_' in the file name when\n # deciding which set to put an image in, the data set creator has a way of\n # grouping photos that are close variations of each other. For example\n # this is used in the plant disease data set to group multiple pictures of\n # the same leaf.\n hash_name = re.sub(r'_nohash_.*$', '', file_name)\n # This looks a bit magical, but we need to decide whether this file should\n # go into the training, testing, or validation sets, and we want to keep\n # existing files in the same set even if more files are subsequently\n # added.\n # To do that, we need a stable way of deciding based on just the file name\n # itself, so we do a hash of that and then use that to generate a\n # probability value that we use to assign it.\n hash_name_hashed = hashlib.sha1(compat.as_bytes(hash_name)).hexdigest()\n percentage_hash = ((int(hash_name_hashed, 16) %\n (MAX_NUM_IMAGES_PER_CLASS + 1)) *\n (100.0 / MAX_NUM_IMAGES_PER_CLASS))\n if percentage_hash < validation_percentage:\n validation_images.append(base_name)\n elif percentage_hash < (testing_percentage + validation_percentage):\n testing_images.append(base_name)\n else:\n training_images.append(base_name)\n result[label_name] = {\n 'dir': dir_name,\n 'training': training_images,\n 'testing': testing_images,\n 'validation': validation_images,\n }\n return result\n\n\ndef get_image_path(image_lists, label_name, index, image_dir, category):\n \"\"\"\"Returns a path to an image for a label at the given index.\n\n Args:\n image_lists: Dictionary of training images for each label.\n label_name: Label string we want to get an image for.\n index: Int offset of the image we want. This will be moduloed by the\n available number of images for the label, so it can be arbitrarily large.\n image_dir: Root folder string of the subfolders containing the training\n images.\n category: Name string of set to pull images from - training, testing, or\n validation.\n\n Returns:\n File system path string to an image that meets the requested parameters.\n\n \"\"\"\n if label_name not in image_lists:\n tf.logging.fatal('Label does not exist %s.', label_name)\n label_lists = image_lists[label_name]\n if category not in label_lists:\n tf.logging.fatal('Category does not exist %s.', category)\n category_list = label_lists[category]\n if not category_list:\n tf.logging.fatal('Label %s has no images in the category %s.',\n label_name, category)\n mod_index = index % len(category_list)\n base_name = category_list[mod_index]\n sub_dir = label_lists['dir']\n full_path = os.path.join(image_dir, sub_dir, base_name)\n return full_path\n\n\ndef get_bottleneck_path(image_lists, label_name, index, bottleneck_dir,\n category, architecture):\n \"\"\"\"Returns a path to a bottleneck file for a label at the given index.\n\n Args:\n image_lists: Dictionary of training images for each label.\n label_name: Label string we want to get an image for.\n index: Integer offset of the image we want. This will be moduloed by the\n available number of images for the label, so it can be arbitrarily large.\n bottleneck_dir: Folder string holding cached files of bottleneck values.\n category: Name string of set to pull images from - training, testing, or\n validation.\n architecture: The name of the model architecture.\n\n Returns:\n File system path string to an image that meets the requested parameters.\n \"\"\"\n return get_image_path(image_lists, label_name, index, bottleneck_dir,\n category) + '_' + architecture + '.txt'\n\n\ndef create_model_graph(model_info):\n \"\"\"\"Creates a graph from saved GraphDef file and returns a Graph object.\n\n Args:\n model_info: Dictionary containing information about the model architecture.\n\n Returns:\n Graph holding the trained Inception network, and various tensors we'll be\n manipulating.\n \"\"\"\n with tf.Graph().as_default() as graph:\n model_path = os.path.join(FLAGS.model_dir, model_info['model_file_name'])\n with gfile.FastGFile(model_path, 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n bottleneck_tensor, resized_input_tensor = (tf.import_graph_def(\n graph_def,\n name='',\n return_elements=[\n model_info['bottleneck_tensor_name'],\n model_info['resized_input_tensor_name'],\n ]))\n return graph, bottleneck_tensor, resized_input_tensor\n\n\ndef run_bottleneck_on_image(sess, image_data, image_data_tensor,\n decoded_image_tensor, resized_input_tensor,\n bottleneck_tensor):\n \"\"\"Runs inference on an image to extract the 'bottleneck' summary layer.\n\n Args:\n sess: Current active TensorFlow Session.\n image_data: String of raw JPEG data.\n image_data_tensor: Input data layer in the graph.\n decoded_image_tensor: Output of initial image resizing and preprocessing.\n resized_input_tensor: The input node of the recognition graph.\n bottleneck_tensor: Layer before the final softmax.\n\n Returns:\n Numpy array of bottleneck values.\n \"\"\"\n # First decode the JPEG image, resize it, and rescale the pixel values.\n resized_input_values = sess.run(decoded_image_tensor,\n {image_data_tensor: image_data})\n # Then run it through the recognition network.\n bottleneck_values = sess.run(bottleneck_tensor,\n {resized_input_tensor: resized_input_values})\n bottleneck_values = np.squeeze(bottleneck_values)\n return bottleneck_values\n\n\ndef maybe_download_and_extract(data_url):\n \"\"\"Download and extract model tar file.\n\n If the pretrained model we're using doesn't already exist, this function\n downloads it from the TensorFlow.org website and unpacks it into a directory.\n\n Args:\n data_url: Web location of the tar file containing the pretrained model.\n \"\"\"\n dest_directory = FLAGS.model_dir\n if not os.path.exists(dest_directory):\n os.makedirs(dest_directory)\n filename = data_url.split('/')[-1]\n filepath = os.path.join(dest_directory, filename)\n if not os.path.exists(filepath):\n\n def _progress(count, block_size, total_size):\n sys.stdout.write('\\r>> Downloading %s %.1f%%' %\n (filename,\n float(count * block_size) / float(total_size) * 100.0))\n sys.stdout.flush()\n\n filepath, _ = urllib.request.urlretrieve(data_url, filepath, _progress)\n print()\n statinfo = os.stat(filepath)\n tf.logging.info('Successfully downloaded', filename, statinfo.st_size,\n 'bytes.')\n tarfile.open(filepath, 'r:gz').extractall(dest_directory)\n\n\ndef ensure_dir_exists(dir_name):\n \"\"\"Makes sure the folder exists on disk.\n\n Args:\n dir_name: Path string to the folder we want to create.\n \"\"\"\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n\n\nbottleneck_path_2_bottleneck_values = {}\n\n\ndef create_bottleneck_file(bottleneck_path, image_lists, label_name, index,\n image_dir, category, sess, jpeg_data_tensor,\n decoded_image_tensor, resized_input_tensor,\n bottleneck_tensor):\n \"\"\"Create a single bottleneck file.\"\"\"\n tf.logging.info('Creating bottleneck at ' + bottleneck_path)\n image_path = get_image_path(image_lists, label_name, index,\n image_dir, category)\n if not gfile.Exists(image_path):\n tf.logging.fatal('File does not exist %s', image_path)\n image_data = gfile.FastGFile(image_path, 'rb').read()\n try:\n bottleneck_values = run_bottleneck_on_image(\n sess, image_data, jpeg_data_tensor, decoded_image_tensor,\n resized_input_tensor, bottleneck_tensor)\n except Exception as e:\n raise RuntimeError('Error during processing file %s (%s)' % (image_path,\n str(e)))\n bottleneck_string = ','.join(str(x) for x in bottleneck_values)\n with open(bottleneck_path, 'w') as bottleneck_file:\n bottleneck_file.write(bottleneck_string)\n\n\ndef get_or_create_bottleneck(sess, image_lists, label_name, index, image_dir,\n category, bottleneck_dir, jpeg_data_tensor,\n decoded_image_tensor, resized_input_tensor,\n bottleneck_tensor, architecture):\n \"\"\"Retrieves or calculates bottleneck values for an image.\n\n If a cached version of the bottleneck data exists on-disk, return that,\n otherwise calculate the data and save it to disk for future use.\n\n Args:\n sess: The current active TensorFlow Session.\n image_lists: Dictionary of training images for each label.\n label_name: Label string we want to get an image for.\n index: Integer offset of the image we want. This will be modulo-ed by the\n available number of images for the label, so it can be arbitrarily large.\n image_dir: Root folder string of the subfolders containing the training\n images.\n category: Name string of which set to pull images from - training, testing,\n or validation.\n bottleneck_dir: Folder string holding cached files of bottleneck values.\n jpeg_data_tensor: The tensor to feed loaded jpeg data into.\n decoded_image_tensor: The output of decoding and resizing the image.\n resized_input_tensor: The input node of the recognition graph.\n bottleneck_tensor: The output tensor for the bottleneck values.\n architecture: The name of the model architecture.\n\n Returns:\n Numpy array of values produced by the bottleneck layer for the image.\n \"\"\"\n label_lists = image_lists[label_name]\n sub_dir = label_lists['dir']\n sub_dir_path = os.path.join(bottleneck_dir, sub_dir)\n ensure_dir_exists(sub_dir_path)\n bottleneck_path = get_bottleneck_path(image_lists, label_name, index,\n bottleneck_dir, category, architecture)\n if not os.path.exists(bottleneck_path):\n create_bottleneck_file(bottleneck_path, image_lists, label_name, index,\n image_dir, category, sess, jpeg_data_tensor,\n decoded_image_tensor, resized_input_tensor,\n bottleneck_tensor)\n with open(bottleneck_path, 'r') as bottleneck_file:\n bottleneck_string = bottleneck_file.read()\n did_hit_error = False\n try:\n bottleneck_values = [float(x) for x in bottleneck_string.split(',')]\n except ValueError:\n tf.logging.warning('Invalid float found, recreating bottleneck')\n did_hit_error = True\n if did_hit_error:\n create_bottleneck_file(bottleneck_path, image_lists, label_name, index,\n image_dir, category, sess, jpeg_data_tensor,\n decoded_image_tensor, resized_input_tensor,\n bottleneck_tensor)\n with open(bottleneck_path, 'r') as bottleneck_file:\n bottleneck_string = bottleneck_file.read()\n # Allow exceptions to propagate here, since they shouldn't happen after a\n # fresh creation\n bottleneck_values = [float(x) for x in bottleneck_string.split(',')]\n return bottleneck_values\n\n\ndef cache_bottlenecks(sess, image_lists, image_dir, bottleneck_dir,\n jpeg_data_tensor, decoded_image_tensor,\n resized_input_tensor, bottleneck_tensor, architecture):\n \"\"\"Ensures all the training, testing, and validation bottlenecks are cached.\n\n Because we're likely to read the same image multiple times (if there are no\n distortions applied during training) it can speed things up a lot if we\n calculate the bottleneck layer values once for each image during\n preprocessing, and then just read those cached values repeatedly during\n training. Here we go through all the images we've found, calculate those\n values, and save them off.\n\n Args:\n sess: The current active TensorFlow Session.\n image_lists: Dictionary of training images for each label.\n image_dir: Root folder string of the subfolders containing the training\n images.\n bottleneck_dir: Folder string holding cached files of bottleneck values.\n jpeg_data_tensor: Input tensor for jpeg data from file.\n decoded_image_tensor: The output of decoding and resizing the image.\n resized_input_tensor: The input node of the recognition graph.\n bottleneck_tensor: The penultimate output layer of the graph.\n architecture: The name of the model architecture.\n\n Returns:\n Nothing.\n \"\"\"\n how_many_bottlenecks = 0\n ensure_dir_exists(bottleneck_dir)\n for label_name, label_lists in image_lists.items():\n for category in ['training', 'testing', 'validation']:\n category_list = label_lists[category]\n for index, unused_base_name in enumerate(category_list):\n get_or_create_bottleneck(\n sess, image_lists, label_name, index, image_dir, category,\n bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,\n resized_input_tensor, bottleneck_tensor, architecture)\n\n how_many_bottlenecks += 1\n if how_many_bottlenecks % 100 == 0:\n tf.logging.info(\n str(how_many_bottlenecks) + ' bottleneck files created.')\n\n\ndef get_random_cached_bottlenecks(sess, image_lists, how_many, category,\n bottleneck_dir, image_dir, jpeg_data_tensor,\n decoded_image_tensor, resized_input_tensor,\n bottleneck_tensor, architecture):\n \"\"\"Retrieves bottleneck values for cached images.\n\n If no distortions are being applied, this function can retrieve the cached\n bottleneck values directly from disk for images. It picks a random set of\n images from the specified category.\n\n Args:\n sess: Current TensorFlow Session.\n image_lists: Dictionary of training images for each label.\n how_many: If positive, a random sample of this size will be chosen.\n If negative, all bottlenecks will be retrieved.\n category: Name string of which set to pull from - training, testing, or\n validation.\n bottleneck_dir: Folder string holding cached files of bottleneck values.\n image_dir: Root folder string of the subfolders containing the training\n images.\n jpeg_data_tensor: The layer to feed jpeg image data into.\n decoded_image_tensor: The output of decoding and resizing the image.\n resized_input_tensor: The input node of the recognition graph.\n bottleneck_tensor: The bottleneck output layer of the CNN graph.\n architecture: The name of the model architecture.\n\n Returns:\n List of bottleneck arrays, their corresponding ground truths, and the\n relevant filenames.\n \"\"\"\n class_count = len(image_lists.keys())\n bottlenecks = []\n ground_truths = []\n filenames = []\n if how_many >= 0:\n # Retrieve a random sample of bottlenecks.\n for unused_i in range(how_many):\n label_index = random.randrange(class_count)\n label_name = list(image_lists.keys())[label_index]\n image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1)\n image_name = get_image_path(image_lists, label_name, image_index,\n image_dir, category)\n bottleneck = get_or_create_bottleneck(\n sess, image_lists, label_name, image_index, image_dir, category,\n bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,\n resized_input_tensor, bottleneck_tensor, architecture)\n ground_truth = np.zeros(class_count, dtype=np.float32)\n ground_truth[label_index] = 1.0\n bottlenecks.append(bottleneck)\n ground_truths.append(ground_truth)\n filenames.append(image_name)\n else:\n # Retrieve all bottlenecks.\n for label_index, label_name in enumerate(image_lists.keys()):\n for image_index, image_name in enumerate(\n image_lists[label_name][category]):\n image_name = get_image_path(image_lists, label_name, image_index,\n image_dir, category)\n bottleneck = get_or_create_bottleneck(\n sess, image_lists, label_name, image_index, image_dir, category,\n bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,\n resized_input_tensor, bottleneck_tensor, architecture)\n ground_truth = np.zeros(class_count, dtype=np.float32)\n ground_truth[label_index] = 1.0\n bottlenecks.append(bottleneck)\n ground_truths.append(ground_truth)\n filenames.append(image_name)\n return bottlenecks, ground_truths, filenames\n\n\ndef get_random_distorted_bottlenecks(\n sess, image_lists, how_many, category, image_dir, input_jpeg_tensor,\n distorted_image, resized_input_tensor, bottleneck_tensor):\n \"\"\"Retrieves bottleneck values for training images, after distortions.\n\n If we're training with distortions like crops, scales, or flips, we have to\n recalculate the full model for every image, and so we can't use cached\n bottleneck values. Instead we find random images for the requested category,\n run them through the distortion graph, and then the full graph to get the\n bottleneck results for each.\n\n Args:\n sess: Current TensorFlow Session.\n image_lists: Dictionary of training images for each label.\n how_many: The integer number of bottleneck values to return.\n category: Name string of which set of images to fetch - training, testing,\n or validation.\n image_dir: Root folder string of the subfolders containing the training\n images.\n input_jpeg_tensor: The input layer we feed the image data to.\n distorted_image: The output node of the distortion graph.\n resized_input_tensor: The input node of the recognition graph.\n bottleneck_tensor: The bottleneck output layer of the CNN graph.\n\n Returns:\n List of bottleneck arrays and their corresponding ground truths.\n \"\"\"\n class_count = len(image_lists.keys())\n bottlenecks = []\n ground_truths = []\n for unused_i in range(how_many):\n label_index = random.randrange(class_count)\n label_name = list(image_lists.keys())[label_index]\n image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1)\n image_path = get_image_path(image_lists, label_name, image_index, image_dir,\n category)\n if not gfile.Exists(image_path):\n tf.logging.fatal('File does not exist %s', image_path)\n jpeg_data = gfile.FastGFile(image_path, 'rb').read()\n # Note that we materialize the distorted_image_data as a numpy array before\n # sending running inference on the image. This involves 2 memory copies and\n # might be optimized in other implementations.\n distorted_image_data = sess.run(distorted_image,\n {input_jpeg_tensor: jpeg_data})\n bottleneck_values = sess.run(bottleneck_tensor,\n {resized_input_tensor: distorted_image_data})\n bottleneck_values = np.squeeze(bottleneck_values)\n ground_truth = np.zeros(class_count, dtype=np.float32)\n ground_truth[label_index] = 1.0\n bottlenecks.append(bottleneck_values)\n ground_truths.append(ground_truth)\n return bottlenecks, ground_truths\n\n\ndef should_distort_images(flip_left_right, random_crop, random_scale,\n random_brightness):\n \"\"\"Whether any distortions are enabled, from the input flags.\n\n Args:\n flip_left_right: Boolean whether to randomly mirror images horizontally.\n random_crop: Integer percentage setting the total margin used around the\n crop box.\n random_scale: Integer percentage of how much to vary the scale by.\n random_brightness: Integer range to randomly multiply the pixel values by.\n\n Returns:\n Boolean value indicating whether any distortions should be applied.\n \"\"\"\n return (flip_left_right or (random_crop != 0) or (random_scale != 0) or\n (random_brightness != 0))\n\n\ndef add_input_distortions(flip_left_right, random_crop, random_scale,\n random_brightness, input_width, input_height,\n input_depth, input_mean, input_std):\n \"\"\"Creates the operations to apply the specified distortions.\n\n During training it can help to improve the results if we run the images\n through simple distortions like crops, scales, and flips. These reflect the\n kind of variations we expect in the real world, and so can help train the\n model to cope with natural data more effectively. Here we take the supplied\n parameters and construct a network of operations to apply them to an image.\n\n Cropping\n ~~~~~~~~\n\n Cropping is done by placing a bounding box at a random position in the full\n image. The cropping parameter controls the size of that box relative to the\n input image. If it's zero, then the box is the same size as the input and no\n cropping is performed. If the value is 50%, then the crop box will be half the\n width and height of the input. In a diagram it looks like this:\n\n < width >\n +---------------------+\n | |\n | width - crop% |\n | < > |\n | +------+ |\n | | | |\n | | | |\n | | | |\n | +------+ |\n | |\n | |\n +---------------------+\n\n Scaling\n ~~~~~~~\n\n Scaling is a lot like cropping, except that the bounding box is always\n centered and its size varies randomly within the given range. For example if\n the scale percentage is zero, then the bounding box is the same size as the\n input and no scaling is applied. If it's 50%, then the bounding box will be in\n a random range between half the width and height and full size.\n\n Args:\n flip_left_right: Boolean whether to randomly mirror images horizontally.\n random_crop: Integer percentage setting the total margin used around the\n crop box.\n random_scale: Integer percentage of how much to vary the scale by.\n random_brightness: Integer range to randomly multiply the pixel values by.\n graph.\n input_width: Horizontal size of expected input image to model.\n input_height: Vertical size of expected input image to model.\n input_depth: How many channels the expected input image should have.\n input_mean: Pixel value that should be zero in the image for the graph.\n input_std: How much to divide the pixel values by before recognition.\n\n Returns:\n The jpeg input layer and the distorted result tensor.\n \"\"\"\n\n jpeg_data = tf.placeholder(tf.string, name='DistortJPGInput')\n decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth)\n decoded_image_as_float = tf.cast(decoded_image, dtype=tf.float32)\n decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0)\n margin_scale = 1.0 + (random_crop / 100.0)\n resize_scale = 1.0 + (random_scale / 100.0)\n margin_scale_value = tf.constant(margin_scale)\n resize_scale_value = tf.random_uniform(tensor_shape.scalar(),\n minval=1.0,\n maxval=resize_scale)\n scale_value = tf.multiply(margin_scale_value, resize_scale_value)\n precrop_width = tf.multiply(scale_value, input_width)\n precrop_height = tf.multiply(scale_value, input_height)\n precrop_shape = tf.stack([precrop_height, precrop_width])\n precrop_shape_as_int = tf.cast(precrop_shape, dtype=tf.int32)\n precropped_image = tf.image.resize_bilinear(decoded_image_4d,\n precrop_shape_as_int)\n precropped_image_3d = tf.squeeze(precropped_image, squeeze_dims=[0])\n cropped_image = tf.random_crop(precropped_image_3d,\n [input_height, input_width, input_depth])\n if flip_left_right:\n flipped_image = tf.image.random_flip_left_right(cropped_image)\n else:\n flipped_image = cropped_image\n brightness_min = 1.0 - (random_brightness / 100.0)\n brightness_max = 1.0 + (random_brightness / 100.0)\n brightness_value = tf.random_uniform(tensor_shape.scalar(),\n minval=brightness_min,\n maxval=brightness_max)\n brightened_image = tf.multiply(flipped_image, brightness_value)\n offset_image = tf.subtract(brightened_image, input_mean)\n mul_image = tf.multiply(offset_image, 1.0 / input_std)\n distort_result = tf.expand_dims(mul_image, 0, name='DistortResult')\n return jpeg_data, distort_result\n\n\ndef variable_summaries(var):\n \"\"\"Attach a lot of summaries to a Tensor (for TensorBoard visualization).\"\"\"\n with tf.name_scope('summaries'):\n mean = tf.reduce_mean(var)\n tf.summary.scalar('mean', mean)\n with tf.name_scope('stddev'):\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n tf.summary.scalar('stddev', stddev)\n tf.summary.scalar('max', tf.reduce_max(var))\n tf.summary.scalar('min', tf.reduce_min(var))\n tf.summary.histogram('histogram', var)\n\n\ndef add_final_training_ops(class_count, final_tensor_name, bottleneck_tensor,\n bottleneck_tensor_size):\n \"\"\"Adds a new softmax and fully-connected layer for training.\n\n We need to retrain the top layer to identify our new classes, so this function\n adds the right operations to the graph, along with some variables to hold the\n weights, and then sets up all the gradients for the backward pass.\n\n The set up for the softmax and fully-connected layers is based on:\n https://www.tensorflow.org/versions/master/tutorials/mnist/beginners/index.html\n\n Args:\n class_count: Integer of how many categories of things we're trying to\n recognize.\n final_tensor_name: Name string for the new final node that produces results.\n bottleneck_tensor: The output of the main CNN graph.\n bottleneck_tensor_size: How many entries in the bottleneck vector.\n\n Returns:\n The tensors for the training and cross entropy results, and tensors for the\n bottleneck input and ground truth input.\n \"\"\"\n with tf.name_scope('input'):\n bottleneck_input = tf.placeholder_with_default(\n bottleneck_tensor,\n shape=[None, bottleneck_tensor_size],\n name='BottleneckInputPlaceholder')\n\n ground_truth_input = tf.placeholder(tf.float32,\n [None, class_count],\n name='GroundTruthInput')\n\n # Organizing the following ops as `final_training_ops` so they're easier\n # to see in TensorBoard\n layer_name = 'final_training_ops'\n with tf.name_scope(layer_name):\n with tf.name_scope('weights'):\n initial_value = tf.truncated_normal(\n [bottleneck_tensor_size, class_count], stddev=0.001)\n\n layer_weights = tf.Variable(initial_value, name='final_weights')\n\n variable_summaries(layer_weights)\n with tf.name_scope('biases'):\n layer_biases = tf.Variable(tf.zeros([class_count]), name='final_biases')\n variable_summaries(layer_biases)\n with tf.name_scope('Wx_plus_b'):\n logits = tf.matmul(bottleneck_input, layer_weights) + layer_biases\n tf.summary.histogram('pre_activations', logits)\n\n final_tensor = tf.nn.softmax(logits, name=final_tensor_name)\n tf.summary.histogram('activations', final_tensor)\n\n with tf.name_scope('cross_entropy'):\n #cross_entropy = tf.nn.softmax_cross_entropy_with_logits(\n # labels=ground_truth_input, logits=logits)\n cross_entropy = tf.nn.weighted_cross_entropy_with_logits(targets=ground_truth_input, logits=logits, pos_weight=4)\n with tf.name_scope('total'):\n cross_entropy_mean = tf.reduce_mean(cross_entropy)\n tf.summary.scalar('cross_entropy', cross_entropy_mean)\n\n with tf.name_scope('train'):\n optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate)\n train_step = optimizer.minimize(cross_entropy_mean)\n\n return (train_step, cross_entropy_mean, bottleneck_input, ground_truth_input,\n final_tensor)\n\n\ndef add_evaluation_step(result_tensor, ground_truth_tensor):\n \"\"\"Inserts the operations we need to evaluate the accuracy of our results.\n\n Args:\n result_tensor: The new final node that produces results.\n ground_truth_tensor: The node we feed ground truth data\n into.\n\n Returns:\n Tuple of (evaluation step, prediction).\n \"\"\"\n with tf.name_scope('accuracy'):\n with tf.name_scope('correct_prediction'):\n prediction = tf.argmax(result_tensor, 1)\n correct_prediction = tf.equal(\n prediction, tf.argmax(ground_truth_tensor, 1))\n with tf.name_scope('accuracy'):\n evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n tf.summary.scalar('accuracy', evaluation_step)\n return evaluation_step, prediction\n\n\ndef save_graph_to_file(sess, graph, graph_file_name):\n output_graph_def = graph_util.convert_variables_to_constants(\n sess, graph.as_graph_def(), [FLAGS.final_tensor_name])\n with gfile.FastGFile(graph_file_name, 'wb') as f:\n f.write(output_graph_def.SerializeToString())\n return\n\n\ndef prepare_file_system():\n # Setup the directory we'll write summaries to for TensorBoard\n if tf.gfile.Exists(FLAGS.summaries_dir):\n tf.gfile.DeleteRecursively(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(FLAGS.summaries_dir)\n if FLAGS.intermediate_store_frequency > 0:\n ensure_dir_exists(FLAGS.intermediate_output_graphs_dir)\n return\n\n\ndef create_model_info(architecture):\n \"\"\"Given the name of a model architecture, returns information about it.\n\n There are different base image recognition pretrained models that can be\n retrained using transfer learning, and this function translates from the name\n of a model to the attributes that are needed to download and train with it.\n\n Args:\n architecture: Name of a model architecture.\n\n Returns:\n Dictionary of information about the model, or None if the name isn't\n recognized\n\n Raises:\n ValueError: If architecture name is unknown.\n \"\"\"\n architecture = architecture.lower()\n if architecture == 'inception_v3':\n # pylint: disable=line-too-long\n data_url = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'\n # pylint: enable=line-too-long\n bottleneck_tensor_name = 'pool_3/_reshape:0'\n bottleneck_tensor_size = 2048\n input_width = 299\n input_height = 299\n input_depth = 3\n resized_input_tensor_name = 'Mul:0'\n model_file_name = 'classify_image_graph_def.pb'\n input_mean = 128\n input_std = 128\n elif architecture.startswith('mobilenet_'):\n parts = architecture.split('_')\n if len(parts) != 3 and len(parts) != 4:\n tf.logging.error(\"Couldn't understand architecture name '%s'\",\n architecture)\n return None\n version_string = parts[1]\n if (version_string != '1.0' and version_string != '0.75' and\n version_string != '0.50' and version_string != '0.25'):\n tf.logging.error(\n \"\"\"\"The Mobilenet version should be '1.0', '0.75', '0.50', or '0.25',\n but found '%s' for architecture '%s'\"\"\",\n version_string, architecture)\n return None\n size_string = parts[2]\n if (size_string != '224' and size_string != '192' and\n size_string != '160' and size_string != '128'):\n tf.logging.error(\n \"\"\"The Mobilenet input size should be '224', '192', '160', or '128',\n but found '%s' for architecture '%s'\"\"\",\n size_string, architecture)\n return None\n if len(parts) == 3:\n is_quantized = False\n else:\n if parts[3] != 'quantized':\n tf.logging.error(\n \"Couldn't understand architecture suffix '%s' for '%s'\", parts[3],\n architecture)\n return None\n is_quantized = True\n data_url = 'http://download.tensorflow.org/models/mobilenet_v1_'\n data_url += version_string + '_' + size_string + '_frozen.tgz'\n bottleneck_tensor_name = 'MobilenetV1/Predictions/Reshape:0'\n bottleneck_tensor_size = 1001\n input_width = int(size_string)\n input_height = int(size_string)\n input_depth = 3\n resized_input_tensor_name = 'input:0'\n if is_quantized:\n model_base_name = 'quantized_graph.pb'\n else:\n model_base_name = 'frozen_graph.pb'\n model_dir_name = 'mobilenet_v1_' + version_string + '_' + size_string\n model_file_name = os.path.join(model_dir_name, model_base_name)\n input_mean = 127.5\n input_std = 127.5\n else:\n tf.logging.error(\"Couldn't understand architecture name '%s'\", architecture)\n raise ValueError('Unknown architecture', architecture)\n\n return {\n 'data_url': data_url,\n 'bottleneck_tensor_name': bottleneck_tensor_name,\n 'bottleneck_tensor_size': bottleneck_tensor_size,\n 'input_width': input_width,\n 'input_height': input_height,\n 'input_depth': input_depth,\n 'resized_input_tensor_name': resized_input_tensor_name,\n 'model_file_name': model_file_name,\n 'input_mean': input_mean,\n 'input_std': input_std,\n }\n\n\ndef add_jpeg_decoding(input_width, input_height, input_depth, input_mean,\n input_std):\n \"\"\"Adds operations that perform JPEG decoding and resizing to the graph..\n\n Args:\n input_width: Desired width of the image fed into the recognizer graph.\n input_height: Desired width of the image fed into the recognizer graph.\n input_depth: Desired channels of the image fed into the recognizer graph.\n input_mean: Pixel value that should be zero in the image for the graph.\n input_std: How much to divide the pixel values by before recognition.\n\n Returns:\n Tensors for the node to feed JPEG data into, and the output of the\n preprocessing steps.\n \"\"\"\n jpeg_data = tf.placeholder(tf.string, name='DecodeJPGInput')\n decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth)\n decoded_image_as_float = tf.cast(decoded_image, dtype=tf.float32)\n decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0)\n resize_shape = tf.stack([input_height, input_width])\n resize_shape_as_int = tf.cast(resize_shape, dtype=tf.int32)\n resized_image = tf.image.resize_bilinear(decoded_image_4d,\n resize_shape_as_int)\n offset_image = tf.subtract(resized_image, input_mean)\n mul_image = tf.multiply(offset_image, 1.0 / input_std)\n return jpeg_data, mul_image\n\n\ndef main(_):\n # Needed to make sure the logging output is visible.\n # See https://github.com/tensorflow/tensorflow/issues/3047\n tf.logging.set_verbosity(tf.logging.INFO)\n\n # Prepare necessary directories that can be used during training\n prepare_file_system()\n\n # Gather information about the model architecture we'll be using.\n model_info = create_model_info(FLAGS.architecture)\n if not model_info:\n tf.logging.error('Did not recognize architecture flag')\n return -1\n\n # Set up the pre-trained graph.\n maybe_download_and_extract(model_info['data_url'])\n graph, bottleneck_tensor, resized_image_tensor = (\n create_model_graph(model_info))\n\n # Look at the folder structure, and create lists of all the images.\n image_lists = create_image_lists(FLAGS.image_dir, FLAGS.testing_percentage,\n FLAGS.validation_percentage)\n class_count = len(image_lists.keys())\n if class_count == 0:\n tf.logging.error('No valid folders of images found at ' + FLAGS.image_dir)\n return -1\n if class_count == 1:\n tf.logging.error('Only one valid folder of images found at ' +\n FLAGS.image_dir +\n ' - multiple classes are needed for classification.')\n return -1\n\n # See if the command-line flags mean we're applying any distortions.\n do_distort_images = should_distort_images(\n FLAGS.flip_left_right, FLAGS.random_crop, FLAGS.random_scale,\n FLAGS.random_brightness)\n\n with tf.Session(graph=graph) as sess:\n # Set up the image decoding sub-graph.\n jpeg_data_tensor, decoded_image_tensor = add_jpeg_decoding(\n model_info['input_width'], model_info['input_height'],\n model_info['input_depth'], model_info['input_mean'],\n model_info['input_std'])\n\n if do_distort_images:\n # We will be applying distortions, so setup the operations we'll need.\n (distorted_jpeg_data_tensor,\n distorted_image_tensor) = add_input_distortions(\n FLAGS.flip_left_right, FLAGS.random_crop, FLAGS.random_scale,\n FLAGS.random_brightness, model_info['input_width'],\n model_info['input_height'], model_info['input_depth'],\n model_info['input_mean'], model_info['input_std'])\n else:\n # We'll make sure we've calculated the 'bottleneck' image summaries and\n # cached them on disk.\n cache_bottlenecks(sess, image_lists, FLAGS.image_dir,\n FLAGS.bottleneck_dir, jpeg_data_tensor,\n decoded_image_tensor, resized_image_tensor,\n bottleneck_tensor, FLAGS.architecture)\n\n # Add the new layer that we'll be training.\n (train_step, cross_entropy, bottleneck_input, ground_truth_input,\n final_tensor) = add_final_training_ops(\n len(image_lists.keys()), FLAGS.final_tensor_name, bottleneck_tensor,\n model_info['bottleneck_tensor_size'])\n\n # Create the operations we need to evaluate the accuracy of our new layer.\n evaluation_step, prediction = add_evaluation_step(\n final_tensor, ground_truth_input)\n\n # Merge all the summaries and write them out to the summaries_dir\n merged = tf.summary.merge_all()\n train_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/train',\n sess.graph)\n\n validation_writer = tf.summary.FileWriter(\n FLAGS.summaries_dir + '/validation')\n\n # Set up all our weights to their initial default values.\n init = tf.global_variables_initializer()\n sess.run(init)\n\n # Run the training for as many cycles as requested on the command line.\n for i in range(FLAGS.how_many_training_steps):\n # Get a batch of input bottleneck values, either calculated fresh every\n # time with distortions applied, or from the cache stored on disk.\n if do_distort_images:\n (train_bottlenecks,\n train_ground_truth) = get_random_distorted_bottlenecks(\n sess, image_lists, FLAGS.train_batch_size, 'training',\n FLAGS.image_dir, distorted_jpeg_data_tensor,\n distorted_image_tensor, resized_image_tensor, bottleneck_tensor)\n else:\n (train_bottlenecks,\n train_ground_truth, _) = get_random_cached_bottlenecks(\n sess, image_lists, FLAGS.train_batch_size, 'training',\n FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor,\n decoded_image_tensor, resized_image_tensor, bottleneck_tensor,\n FLAGS.architecture)\n # Feed the bottlenecks and ground truth into the graph, and run a training\n # step. Capture training summaries for TensorBoard with the `merged` op.\n train_summary, _ = sess.run(\n [merged, train_step],\n feed_dict={bottleneck_input: train_bottlenecks,\n ground_truth_input: train_ground_truth})\n train_writer.add_summary(train_summary, i)\n\n # Every so often, print out how well the graph is training.\n is_last_step = (i + 1 == FLAGS.how_many_training_steps)\n if (i % FLAGS.eval_step_interval) == 0 or is_last_step:\n train_accuracy, cross_entropy_value = sess.run(\n [evaluation_step, cross_entropy],\n feed_dict={bottleneck_input: train_bottlenecks,\n ground_truth_input: train_ground_truth})\n tf.logging.info('%s: Step %d: Train accuracy = %.1f%%' %\n (datetime.now(), i, train_accuracy * 100))\n tf.logging.info('%s: Step %d: Cross entropy = %f' %\n (datetime.now(), i, cross_entropy_value))\n validation_bottlenecks, validation_ground_truth, _ = (\n get_random_cached_bottlenecks(\n sess, image_lists, FLAGS.validation_batch_size, 'validation',\n FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor,\n decoded_image_tensor, resized_image_tensor, bottleneck_tensor,\n FLAGS.architecture))\n # Run a validation step and capture training summaries for TensorBoard\n # with the `merged` op.\n validation_summary, validation_accuracy = sess.run(\n [merged, evaluation_step],\n feed_dict={bottleneck_input: validation_bottlenecks,\n ground_truth_input: validation_ground_truth})\n validation_writer.add_summary(validation_summary, i)\n tf.logging.info('%s: Step %d: Validation accuracy = %.1f%% (N=%d)' %\n (datetime.now(), i, validation_accuracy * 100,\n len(validation_bottlenecks)))\n\n # Store intermediate results\n intermediate_frequency = FLAGS.intermediate_store_frequency\n\n if (intermediate_frequency > 0 and (i % intermediate_frequency == 0)\n and i > 0):\n intermediate_file_name = (FLAGS.intermediate_output_graphs_dir +\n 'intermediate_' + str(i) + '.pb')\n tf.logging.info('Save intermediate result to : ' +\n intermediate_file_name)\n save_graph_to_file(sess, graph, intermediate_file_name)\n\n # We've completed all our training, so run a final test evaluation on\n # some new images we haven't used before.\n test_bottlenecks, test_ground_truth, test_filenames = (\n get_random_cached_bottlenecks(\n sess, image_lists, FLAGS.test_batch_size, 'testing',\n FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor,\n decoded_image_tensor, resized_image_tensor, bottleneck_tensor,\n FLAGS.architecture))\n test_accuracy, predictions = sess.run(\n [evaluation_step, prediction],\n feed_dict={bottleneck_input: test_bottlenecks,\n ground_truth_input: test_ground_truth})\n tf.logging.info('Final test accuracy = %.1f%% (N=%d)' %\n (test_accuracy * 100, len(test_bottlenecks)))\n\n if FLAGS.print_misclassified_test_images:\n tf.logging.info('=== MISCLASSIFIED TEST IMAGES ===')\n for i, test_filename in enumerate(test_filenames):\n if predictions[i] != test_ground_truth[i].argmax():\n tf.logging.info('%70s %s' %\n (test_filename,\n list(image_lists.keys())[predictions[i]]))\n\n # Write out the trained graph and labels with the weights stored as\n # constants.\n save_graph_to_file(sess, graph, FLAGS.output_graph)\n with gfile.FastGFile(FLAGS.output_labels, 'w') as f:\n f.write('\\n'.join(image_lists.keys()) + '\\n')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--image_dir',\n type=str,\n default='',\n help='Path to folders of labeled images.'\n )\n parser.add_argument(\n '--output_graph',\n type=str,\n default='/tmp/output_graph.pb',\n help='Where to save the trained graph.'\n )\n parser.add_argument(\n '--intermediate_output_graphs_dir',\n type=str,\n default='/tmp/intermediate_graph/',\n help='Where to save the intermediate graphs.'\n )\n parser.add_argument(\n '--intermediate_store_frequency',\n type=int,\n default=0,\n help=\"\"\"\\\n How many steps to store intermediate graph. If \"0\" then will not\n store.\\\n \"\"\"\n )\n parser.add_argument(\n '--output_labels',\n type=str,\n default='/tmp/output_labels.txt',\n help='Where to save the trained graph\\'s labels.'\n )\n parser.add_argument(\n '--summaries_dir',\n type=str,\n default='/tmp/retrain_logs',\n help='Where to save summary logs for TensorBoard.'\n )\n parser.add_argument(\n '--how_many_training_steps',\n type=int,\n default=4000,\n help='How many training steps to run before ending.'\n )\n parser.add_argument(\n '--learning_rate',\n type=float,\n default=0.01,\n help='How large a learning rate to use when training.'\n )\n parser.add_argument(\n '--testing_percentage',\n type=int,\n default=10,\n help='What percentage of images to use as a test set.'\n )\n parser.add_argument(\n '--validation_percentage',\n type=int,\n default=10,\n help='What percentage of images to use as a validation set.'\n )\n parser.add_argument(\n '--eval_step_interval',\n type=int,\n default=10,\n help='How often to evaluate the training results.'\n )\n parser.add_argument(\n '--train_batch_size',\n type=int,\n default=100,\n help='How many images to train on at a time.'\n )\n parser.add_argument(\n '--test_batch_size',\n type=int,\n default=-1,\n help=\"\"\"\\\n How many images to test on. This test set is only used once, to evaluate\n the final accuracy of the model after training completes.\n A value of -1 causes the entire test set to be used, which leads to more\n stable results across runs.\\\n \"\"\"\n )\n parser.add_argument(\n '--validation_batch_size',\n type=int,\n default=100,\n help=\"\"\"\\\n How many images to use in an evaluation batch. This validation set is\n used much more often than the test set, and is an early indicator of how\n accurate the model is during training.\n A value of -1 causes the entire validation set to be used, which leads to\n more stable results across training iterations, but may be slower on large\n training sets.\\\n \"\"\"\n )\n parser.add_argument(\n '--print_misclassified_test_images',\n default=False,\n help=\"\"\"\\\n Whether to print out a list of all misclassified test images.\\\n \"\"\",\n action='store_true'\n )\n parser.add_argument(\n '--model_dir',\n type=str,\n default='/tmp/imagenet',\n help=\"\"\"\\\n Path to classify_image_graph_def.pb,\n imagenet_synset_to_human_label_map.txt, and\n imagenet_2012_challenge_label_map_proto.pbtxt.\\\n \"\"\"\n )\n parser.add_argument(\n '--bottleneck_dir',\n type=str,\n default='/tmp/bottleneck',\n help='Path to cache bottleneck layer values as files.'\n )\n parser.add_argument(\n '--final_tensor_name',\n type=str,\n default='final_result',\n help=\"\"\"\\\n The name of the output classification layer in the retrained graph.\\\n \"\"\"\n )\n parser.add_argument(\n '--flip_left_right',\n default=False,\n help=\"\"\"\\\n Whether to randomly flip half of the training images horizontally.\\\n \"\"\",\n action='store_true'\n )\n parser.add_argument(\n '--random_crop',\n type=int,\n default=0,\n help=\"\"\"\\\n A percentage determining how much of a margin to randomly crop off the\n training images.\\\n \"\"\"\n )\n parser.add_argument(\n '--random_scale',\n type=int,\n default=0,\n help=\"\"\"\\\n A percentage determining how much to randomly scale up the size of the\n training images by.\\\n \"\"\"\n )\n parser.add_argument(\n '--random_brightness',\n type=int,\n default=0,\n help=\"\"\"\\\n A percentage determining how much to randomly multiply the training image\n input pixels up or down by.\\\n \"\"\"\n )\n parser.add_argument(\n '--architecture',\n type=str,\n default='inception_v3',\n help=\"\"\"\\\n Which model architecture to use. 'inception_v3' is the most accurate, but\n also the slowest. For faster or smaller models, chose a MobileNet with the\n form 'mobilenet_<parameter size>_<input_size>[_quantized]'. For example,\n 'mobilenet_1.0_224' will pick a model that is 17 MB in size and takes 224\n pixel input images, while 'mobilenet_0.25_128_quantized' will choose a much\n less accurate, but smaller and faster network that's 920 KB on disk and\n takes 128x128 images. See https://research.googleblog.com/2017/06/mobilenets-open-source-models-for.html\n for more information on Mobilenet.\\\n \"\"\")\n FLAGS, unparsed = parser.parse_known_args()\n tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)\n" ]
[ [ "tensorflow.python.framework.tensor_shape.scalar", "tensorflow.logging.warning", "tensorflow.python.platform.gfile.Walk", "tensorflow.gfile.DeleteRecursively", "tensorflow.zeros", "tensorflow.gfile.Exists", "tensorflow.stack", "numpy.squeeze", "tensorflow.cast", "tensorflow.python.platform.gfile.Exists", "tensorflow.gfile.MakeDirs", "tensorflow.summary.scalar", "tensorflow.Graph", "tensorflow.import_graph_def", "tensorflow.image.random_flip_left_right", "tensorflow.Variable", "tensorflow.placeholder_with_default", "tensorflow.squeeze", "tensorflow.subtract", "tensorflow.logging.set_verbosity", "tensorflow.name_scope", "tensorflow.Session", "tensorflow.square", "tensorflow.argmax", "numpy.zeros", "tensorflow.logging.fatal", "tensorflow.image.decode_jpeg", "tensorflow.app.run", "tensorflow.image.resize_bilinear", "tensorflow.matmul", "tensorflow.truncated_normal", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.train.GradientDescentOptimizer", "tensorflow.logging.info", "tensorflow.summary.merge_all", "tensorflow.python.platform.gfile.FastGFile", "tensorflow.summary.histogram", "tensorflow.reduce_max", "tensorflow.multiply", "tensorflow.constant", "tensorflow.nn.softmax", "tensorflow.summary.FileWriter", "tensorflow.reduce_mean", "tensorflow.python.platform.gfile.Glob", "tensorflow.expand_dims", "tensorflow.random_crop", "tensorflow.python.util.compat.as_bytes", "tensorflow.logging.error", "tensorflow.reduce_min", "tensorflow.GraphDef", "tensorflow.nn.weighted_cross_entropy_with_logits" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
iriszero/DepthAwareCNNplus
[ "5dcc0a9279d53a2826d76631f097959d52982f8b" ]
[ "models/Deeplab.py" ]
[ "import torch.nn as nn\nimport math\nimport torch.utils.model_zoo as model_zoo\nimport torch\nfrom .base_model import BaseModel\nimport numpy as np\nfrom . import losses\nimport shutil\nfrom utils.util import *\nfrom torch.autograd import Variable\nfrom collections import OrderedDict\nfrom tensorboardX import SummaryWriter\nimport os\nfrom . import VGG_Deeplab\n\n\nclass Deeplab_VGG(nn.Module):\n def __init__(self, num_classes, depthconv=False):\n super(Deeplab_VGG,self).__init__()\n self.Scale = VGG_Deeplab.vgg16(num_classes=num_classes,depthconv=depthconv)\n\n def forward(self,x, depth=None):\n output = self.Scale(x,depth) # for original scale\n return output\n\n#------------------------------------------------------#\n\nclass Deeplab_Solver(BaseModel):\n def __init__(self, opt, dataset=None, encoder='VGG'):\n BaseModel.initialize(self, opt)\n self.encoder = encoder\n if encoder == 'VGG':\n self.model = Deeplab_VGG(self.opt.label_nc, self.opt.depthconv)\n\n if self.opt.isTrain:\n self.criterionSeg = torch.nn.CrossEntropyLoss(ignore_index=255).cuda()\n # self.criterionSeg = torch.nn.CrossEntropyLoss(ignore_index=255).cuda()\n # self.criterionSeg = nn.NLLLoss2d(ignore_index=255)#.cuda()\n\n if encoder == 'VGG':\n self.optimizer = torch.optim.SGD([{'params': self.model.Scale.get_1x_lr_params_NOscale(), 'lr': self.opt.lr},\n {'params': self.model.Scale.get_10x_lr_params(), 'lr': self.opt.lr},\n {'params': self.model.Scale.get_2x_lr_params_NOscale(), 'lr': self.opt.lr, 'weight_decay': 0.},\n {'params': self.model.Scale.get_20x_lr_params(), 'lr': self.opt.lr, 'weight_decay': 0.}\n ],\n lr=self.opt.lr, momentum=self.opt.momentum, weight_decay=self.opt.wd)\n\n # self.optimizer = torch.optim.SGD(self.model.parameters(), lr=self.opt.lr, momentum=self.opt.momentum, weight_decay=self.opt.wd)\n\n self.old_lr = self.opt.lr\n self.averageloss = []\n # copy scripts\n self.model_path = './models' #os.path.dirname(os.path.realpath(__file__))\n self.data_path = './data' #os.path.dirname(os.path.realpath(__file__))\n shutil.copyfile(os.path.join(self.model_path, 'Deeplab.py'), os.path.join(self.model_dir, 'Deeplab.py'))\n\n if encoder == 'VGG':\n shutil.copyfile(os.path.join(self.model_path, 'VGG_Deeplab.py'), os.path.join(self.model_dir, 'VGG_Deeplab.py'))\n shutil.copyfile(os.path.join(self.model_path, 'model_utils.py'), os.path.join(self.model_dir, 'model_utils.py'))\n shutil.copyfile(os.path.join(self.data_path, dataset.datafile), os.path.join(self.model_dir, dataset.datafile))\n shutil.copyfile(os.path.join(self.data_path, 'base_dataset.py'), os.path.join(self.model_dir, 'base_dataset.py'))\n\n self.writer = SummaryWriter(self.tensorborad_dir)\n self.counter = 0\n\n if not self.isTrain or self.opt.continue_train:\n if self.opt.pretrained_model!='':\n self.load_pretrained_network(self.model, self.opt.pretrained_model, self.opt.which_epoch, strict=False)\n print(\"Successfully loaded from pretrained model with given path!\")\n else:\n self.load()\n print(\"Successfully loaded model, continue training....!\")\n\n self.model.cuda()\n self.normweightgrad=0.\n # if len(opt.gpu_ids):#opt.isTrain and\n # self.model = torch.nn.DataParallel(self.model, device_ids=opt.gpu_ids)\n\n def forward(self, data, isTrain=True):\n self.model.zero_grad()\n\n self.image = Variable(data['image'], volatile=not isTrain).cuda()\n if 'depth' in data.keys():\n self.depth = Variable(data['depth'], volatile=not isTrain).cuda()\n else:\n self.depth = None\n if data['seg'] is not None:\n self.seggt = Variable(data['seg'], volatile=not isTrain).cuda()\n else:\n self.seggt = None\n\n input_size = self.image.size()\n self.segpred = self.model(self.image,self.depth)\n self.segpred = nn.functional.upsample(self.segpred, size=(input_size[2], input_size[3]), mode='bilinear')\n # self.segpred = nn.functional.log_softmax(nn.functional.upsample(self.segpred, size=(input_size[2], input_size[3]), mode='bilinear'))\n\n if self.opt.isTrain:\n self.loss = self.criterionSeg(self.segpred, torch.squeeze(self.seggt,1).long())\n self.averageloss += [self.loss.data[0]]\n# self.averageloss += [self.loss.item()]\n \n segpred = self.segpred.max(1, keepdim=True)[1]\n return self.seggt, segpred\n\n\n def backward(self, step, total_step):\n self.loss.backward()\n self.optimizer.step()\n # print self.model.Scale.classifier.fc6_2.weight.grad.mean().data.cpu().numpy()\n # self.normweightgrad +=self.model.Scale.classifier.norm.scale.grad.mean().data.cpu().numpy()\n # print self.normweightgrad#self.model.Scale.classifier.norm.scale.grad.mean().data.cpu().numpy()\n if step % self.opt.iterSize == 0:\n self.update_learning_rate(step, total_step)\n trainingavgloss = np.mean(self.averageloss)\n if self.opt.verbose:\n print (' Iter: %d, Loss: %f' % (step, trainingavgloss) )\n\n def get_visuals(self, step):\n ############## Display results and errors ############\n if self.opt.isTrain:\n self.trainingavgloss = np.mean(self.averageloss)\n if self.opt.verbose:\n print (' Iter: %d, Loss: %f' % (step, self.trainingavgloss) )\n self.writer.add_scalar(self.opt.name+'/trainingloss/', self.trainingavgloss, step)\n self.averageloss = []\n\n if self.depth is not None:\n return OrderedDict([('image', tensor2im(self.image.data[0], inputmode=self.opt.inputmode)),\n ('depth', tensor2im(self.depth.data[0], inputmode='divstd-mean')),\n ('segpred', tensor2label(self.segpred.data[0], self.opt.label_nc)),\n ('seggt', tensor2label(self.seggt.data[0], self.opt.label_nc))])\n else:\n return OrderedDict([('image', tensor2im(self.image.data[0], inputmode=self.opt.inputmode)),\n ('segpred', tensor2label(self.segpred.data[0], self.opt.label_nc)),\n ('seggt', tensor2label(self.seggt.data[0], self.opt.label_nc))])\n\n def update_tensorboard(self, data, step):\n if self.opt.isTrain:\n self.writer.add_scalar(self.opt.name+'/Accuracy/', data[0], step)\n self.writer.add_scalar(self.opt.name+'/Accuracy_Class/', data[1], step)\n self.writer.add_scalar(self.opt.name+'/Mean_IoU/', data[2], step)\n self.writer.add_scalar(self.opt.name+'/FWAV_Accuracy/', data[3], step)\n\n self.trainingavgloss = np.mean(self.averageloss)\n self.writer.add_scalars(self.opt.name+'/loss', {\"train\": self.trainingavgloss,\n \"val\": np.mean(self.averageloss)}, step)\n\n self.writer.add_scalars('trainingavgloss/', {self.opt.name: self.trainingavgloss}, step)\n self.writer.add_scalars('valloss/', {self.opt.name: np.mean(self.averageloss)}, step)\n self.writer.add_scalars('val_MeanIoU/', {self.opt.name: data[2]}, step)\n\n file_name = os.path.join(self.save_dir, 'MIoU.txt')\n with open(file_name, 'wt') as opt_file:\n opt_file.write('%f\\n' % (data[2]))\n # self.writer.add_scalars('losses/'+self.opt.name, {\"train\": self.trainingavgloss,\n # \"val\": np.mean(self.averageloss)}, step)\n self.averageloss = []\n\n def save(self, which_epoch):\n # self.save_network(self.netG, 'G', which_epoch, self.gpu_ids)\n self.save_network(self.model, 'net', which_epoch, self.gpu_ids)\n\n def load(self):\n self.load_network(self.model, 'net',self.opt.which_epoch)\n\n def update_learning_rate(self, step, total_step):\n\n lr = max(self.opt.lr * ((1 - float(step) / total_step) ** (self.opt.lr_power)), 1e-6)\n\n # drop_ratio = (1. * float(total_step - step) / (total_step - step + 1)) ** self.opt.lr_power\n # lr = self.old_lr * drop_ratio\n\n self.writer.add_scalar(self.opt.name+'/Learning_Rate/', lr, step)\n \n self.optimizer.param_groups[0]['lr'] = lr\n self.optimizer.param_groups[1]['lr'] = lr\n self.optimizer.param_groups[2]['lr'] = lr\n self.optimizer.param_groups[3]['lr'] = lr\n\t# self.optimizer.param_groups[0]['lr'] = lr\n\t# self.optimizer.param_groups[1]['lr'] = lr*10\n\t# self.optimizer.param_groups[2]['lr'] = lr*2 #* 100\n\t# self.optimizer.param_groups[3]['lr'] = lr*20\n\t# self.optimizer.param_groups[4]['lr'] = lr*100\n\n\n # torch.nn.utils.clip_grad_norm(self.model.Scale.get_1x_lr_params_NOscale(), 1.)\n # torch.nn.utils.clip_grad_norm(self.model.Scale.get_10x_lr_params(), 1.)\n if self.opt.verbose:\n print(' update learning rate: %f -> %f' % (self.old_lr, lr))\n\n self.old_lr = lr\n" ]
[ [ "torch.nn.functional.upsample", "torch.nn.CrossEntropyLoss", "numpy.mean", "torch.squeeze", "torch.autograd.Variable" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
laipaang/Paddle
[ "0ec3a42e9740a5f5066053bb49a923d538eba24a", "0ec3a42e9740a5f5066053bb49a923d538eba24a", "0ec3a42e9740a5f5066053bb49a923d538eba24a", "0ec3a42e9740a5f5066053bb49a923d538eba24a", "0ec3a42e9740a5f5066053bb49a923d538eba24a" ]
[ "python/paddle/incubate/hapi/tests/test_loss.py", "python/paddle/fluid/tests/unittests/dygraph_to_static/test_ptb_lm.py", "python/paddle/fluid/tests/unittests/test_logsumexp.py", "python/paddle/incubate/hapi/tests/test_progressbar.py", "python/paddle/fluid/tests/unittests/test_cast_op.py" ]
[ "# Copyright (c) 2020 PaddlePaddle 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\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport unittest\nimport os\nimport six\nimport numpy as np\nimport shutil\nimport copy\n\nimport paddle\nfrom paddle import fluid\n\nfrom paddle.incubate.hapi.model import Model, Input\nfrom paddle.incubate.hapi.loss import CrossEntropy, SoftmaxWithCrossEntropy\n\n\ndef stable_softmax(x):\n \"\"\"Compute the softmax of vector x in a numerically stable way.\"\"\"\n # clip to shiftx, otherwise, when calc loss with\n # log(exp(shiftx)), may get log(0)=INF\n shiftx = (x - np.max(x)).clip(-64.)\n exps = np.exp(shiftx)\n return exps / np.sum(exps)\n\n\ndef randomize_probability(batch_size, class_num, dtype='float32'):\n prob = np.random.uniform(\n 0.1, 1.0, size=(batch_size, class_num)).astype(dtype)\n prob_sum = prob.sum(axis=1)\n for i in six.moves.xrange(len(prob)):\n prob[i] /= prob_sum[i]\n return prob\n\n\ndef numpy_ce(x, label):\n return np.asmatrix(\n [[-np.log(x[i][label[i][0]])] for i in range(x.shape[0])],\n dtype=\"float32\").mean()\n\n\nclass TestLoss(unittest.TestCase):\n def test_cross_entropy(self):\n class_num = 100\n batch_size = 128\n inputs = [randomize_probability(128, class_num) for _ in range(2)]\n\n labels = [\n np.random.randint(\n 0, class_num, (batch_size, 1), dtype=\"int64\") for _ in range(2)\n ]\n\n gt_out = [numpy_ce(inputs[i], labels[i]) for i in range(2)]\n\n fluid.enable_dygraph()\n cross_entropy = CrossEntropy()\n out = cross_entropy(\n [fluid.dygraph.to_variable(x) for x in inputs],\n [fluid.dygraph.to_variable(label) for label in labels])\n out = [o.numpy() for o in out]\n\n for o, g in zip(out, gt_out):\n np.testing.assert_allclose(o, g, atol=1e-5)\n\n def test_soft_cross_entronpy(self):\n class_num = 100\n batch_size = 128\n\n inputs = [randomize_probability(128, class_num) for _ in range(2)]\n\n labels = [\n np.random.randint(\n 0, class_num, (batch_size, 1), dtype=\"int64\") for _ in range(2)\n ]\n\n fluid.enable_dygraph()\n softmax_cross_entropy = SoftmaxWithCrossEntropy()\n\n softmax_cross_entropy(\n [fluid.dygraph.to_variable(x) for x in inputs],\n [fluid.dygraph.to_variable(label) for label in labels])\n\n softmax_cross_entropy = SoftmaxWithCrossEntropy(average=False)\n\n inputs = [randomize_probability(128, class_num)]\n\n labels = [\n np.random.randint(\n 0, class_num, (batch_size, 1), dtype=\"int64\")\n ]\n\n softmax_cross_entropy([fluid.dygraph.to_variable(x) for x in inputs],\n fluid.dygraph.to_variable(labels[0]))\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2018 PaddlePaddle 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\nfrom __future__ import absolute_import, division, print_function\n\nimport logging\nimport time\nimport unittest\n\nimport numpy as np\n\nimport paddle.fluid as fluid\nfrom paddle.fluid.dygraph.dygraph_to_static import ProgramTranslator\nfrom paddle.fluid.dygraph.base import to_variable\nfrom paddle.fluid.dygraph.jit import declarative\nfrom paddle.fluid.dygraph.nn import Embedding\nfrom paddle.fluid.optimizer import SGDOptimizer\n\nPRINT_STEP = 20\nSEED = 2020\n\nprogram_translator = ProgramTranslator()\n\n\nclass SimpleLSTMRNN(fluid.Layer):\n def __init__(self,\n hidden_size,\n num_steps,\n num_layers=2,\n init_scale=0.1,\n dropout=None):\n super(SimpleLSTMRNN, self).__init__()\n self._hidden_size = hidden_size\n self._num_layers = num_layers\n self._init_scale = init_scale\n self._dropout = dropout\n self._num_steps = num_steps\n self.cell_array = []\n self.hidden_array = []\n\n self.weight_1_arr = []\n self.weight_2_arr = []\n self.bias_arr = []\n self.mask_array = []\n\n for i in range(self._num_layers):\n weight_1 = self.create_parameter(\n attr=fluid.ParamAttr(\n initializer=fluid.initializer.UniformInitializer(\n low=-self._init_scale, high=self._init_scale)),\n shape=[self._hidden_size * 2, self._hidden_size * 4],\n dtype=\"float32\",\n default_initializer=fluid.initializer.UniformInitializer(\n low=-self._init_scale, high=self._init_scale))\n self.weight_1_arr.append(self.add_parameter('w_%d' % i, weight_1))\n bias_1 = self.create_parameter(\n attr=fluid.ParamAttr(\n initializer=fluid.initializer.UniformInitializer(\n low=-self._init_scale, high=self._init_scale)),\n shape=[self._hidden_size * 4],\n dtype=\"float32\",\n default_initializer=fluid.initializer.Constant(0.0))\n self.bias_arr.append(self.add_parameter('b_%d' % i, bias_1))\n\n def forward(self, input_embedding, init_hidden=None, init_cell=None):\n cell_array = []\n hidden_array = []\n\n for i in range(self._num_layers):\n hidden_array.append(init_hidden[i])\n cell_array.append(init_cell[i])\n\n res = []\n for index in range(self._num_steps):\n step_input = input_embedding[:, index, :]\n for k in range(self._num_layers):\n pre_hidden = hidden_array[k]\n pre_cell = cell_array[k]\n weight_1 = self.weight_1_arr[k]\n bias = self.bias_arr[k]\n\n nn = fluid.layers.concat([step_input, pre_hidden], 1)\n gate_input = fluid.layers.matmul(x=nn, y=weight_1)\n\n gate_input = fluid.layers.elementwise_add(gate_input, bias)\n i, j, f, o = fluid.layers.split(\n gate_input, num_or_sections=4, dim=-1)\n c = pre_cell * fluid.layers.sigmoid(f) + fluid.layers.sigmoid(\n i) * fluid.layers.tanh(j)\n m = fluid.layers.tanh(c) * fluid.layers.sigmoid(o)\n hidden_array[k] = m\n cell_array[k] = c\n step_input = m\n\n if self._dropout is not None and self._dropout > 0.0:\n step_input = fluid.layers.dropout(\n step_input,\n dropout_prob=self._dropout,\n dropout_implementation='upscale_in_train')\n res.append(step_input)\n real_res = fluid.layers.concat(res, 1)\n real_res = fluid.layers.reshape(\n real_res, [-1, self._num_steps, self._hidden_size])\n last_hidden = fluid.layers.concat(hidden_array, 1)\n last_hidden = fluid.layers.reshape(\n last_hidden, shape=[-1, self._num_layers, self._hidden_size])\n last_hidden = fluid.layers.transpose(x=last_hidden, perm=[1, 0, 2])\n last_cell = fluid.layers.concat(cell_array, 1)\n last_cell = fluid.layers.reshape(\n last_cell, shape=[-1, self._num_layers, self._hidden_size])\n last_cell = fluid.layers.transpose(x=last_cell, perm=[1, 0, 2])\n return real_res, last_hidden, last_cell\n\n\nclass PtbModel(fluid.Layer):\n def __init__(self,\n hidden_size,\n vocab_size,\n num_layers=2,\n num_steps=20,\n init_scale=0.1,\n dropout=None):\n super(PtbModel, self).__init__()\n self.hidden_size = hidden_size\n self.vocab_size = vocab_size\n self.init_scale = init_scale\n self.num_layers = num_layers\n self.num_steps = num_steps\n self.dropout = dropout\n self.simple_lstm_rnn = SimpleLSTMRNN(\n hidden_size,\n num_steps,\n num_layers=num_layers,\n init_scale=init_scale,\n dropout=dropout)\n self.embedding = Embedding(\n size=[vocab_size, hidden_size],\n dtype='float32',\n is_sparse=False,\n param_attr=fluid.ParamAttr(\n name='embedding_para',\n initializer=fluid.initializer.UniformInitializer(\n low=-init_scale, high=init_scale)))\n self.softmax_weight = self.create_parameter(\n attr=fluid.ParamAttr(),\n shape=[self.hidden_size, self.vocab_size],\n dtype=\"float32\",\n default_initializer=fluid.initializer.UniformInitializer(\n low=-self.init_scale, high=self.init_scale))\n self.softmax_bias = self.create_parameter(\n attr=fluid.ParamAttr(),\n shape=[self.vocab_size],\n dtype=\"float32\",\n default_initializer=fluid.initializer.UniformInitializer(\n low=-self.init_scale, high=self.init_scale))\n\n def build_once(self, input, label, init_hidden, init_cell):\n pass\n\n @declarative\n def forward(self, input, label, init_hidden, init_cell):\n\n init_h = fluid.layers.reshape(\n init_hidden, shape=[self.num_layers, -1, self.hidden_size])\n\n init_c = fluid.layers.reshape(\n init_cell, shape=[self.num_layers, -1, self.hidden_size])\n\n x_emb = self.embedding(input)\n\n x_emb = fluid.layers.reshape(\n x_emb, shape=[-1, self.num_steps, self.hidden_size])\n if self.dropout is not None and self.dropout > 0.0:\n x_emb = fluid.layers.dropout(\n x_emb,\n dropout_prob=self.dropout,\n dropout_implementation='upscale_in_train')\n rnn_out, last_hidden, last_cell = self.simple_lstm_rnn(x_emb, init_h,\n init_c)\n\n projection = fluid.layers.matmul(rnn_out, self.softmax_weight)\n projection = fluid.layers.elementwise_add(projection, self.softmax_bias)\n\n loss = fluid.layers.softmax_with_cross_entropy(\n logits=projection, label=label, soft_label=False)\n loss = fluid.layers.reshape(loss, shape=[-1, self.num_steps])\n loss = fluid.layers.reduce_mean(loss, dim=[0])\n loss = fluid.layers.reduce_sum(loss)\n\n return loss, last_hidden, last_cell\n\n def debug_emb(self):\n\n np.save(\"emb_grad\", self.x_emb.gradient())\n\n\ndef train(place):\n\n num_layers = 1\n batch_size = 4\n hidden_size = 10\n num_steps = 3\n init_scale = 0.1\n max_epoch = 1\n dropout = 0.0\n vocab_size = 1000\n batch_num = 200\n\n with fluid.dygraph.guard(place):\n fluid.default_startup_program().random_seed = SEED\n fluid.default_main_program().random_seed = SEED\n ptb_model = PtbModel(\n hidden_size=hidden_size,\n vocab_size=vocab_size,\n num_layers=num_layers,\n num_steps=num_steps,\n init_scale=init_scale,\n dropout=dropout)\n\n sgd = SGDOptimizer(\n learning_rate=1e-3, parameter_list=ptb_model.parameters())\n\n for epoch_id in range(max_epoch):\n\n total_loss = 0.0\n iters = 0.0\n total_sample = 0\n\n init_hidden_data = np.zeros(\n (num_layers, batch_size, hidden_size), dtype='float32')\n init_cell_data = np.zeros(\n (num_layers, batch_size, hidden_size), dtype='float32')\n\n init_hidden = to_variable(init_hidden_data)\n init_cell = to_variable(init_cell_data)\n for step_id in range(batch_num):\n x_data = np.arange(12).reshape(4, 3).astype('int64')\n y_data = np.arange(1, 13).reshape(4, 3).astype('int64')\n y_data = y_data.reshape((-1, 1))\n\n x_data = x_data.reshape((-1, num_steps, 1))\n y_data = y_data.reshape((-1, num_steps, 1))\n\n x = to_variable(x_data)\n y = to_variable(y_data)\n\n dy_loss, last_hidden, last_cell = ptb_model(x, y, init_hidden,\n init_cell)\n out_loss = dy_loss.numpy()\n\n dy_loss.backward()\n sgd.minimize(dy_loss)\n ptb_model.clear_gradients()\n\n total_loss += out_loss\n iters += num_steps\n total_sample += 1\n if step_id % PRINT_STEP == 0:\n if step_id == 0:\n logging.info(\"epoch %d | step %d, loss %0.3f\" % (\n epoch_id, step_id, total_loss / total_sample))\n avg_batch_time = time.time()\n else:\n speed = PRINT_STEP / (time.time() - avg_batch_time)\n logging.info(\n \"epoch %d | step %d, loss %0.3f, speed %.3f steps/s\"\n % (epoch_id, step_id, total_loss / total_sample,\n speed))\n avg_batch_time = time.time()\n\n return out_loss, last_hidden.numpy(), last_cell.numpy()\n\n\ndef train_dygraph(place):\n program_translator.enable(False)\n return train(place)\n\n\ndef train_static(place):\n program_translator.enable(True)\n return train(place)\n\n\nclass TestPtb(unittest.TestCase):\n def setUp(self):\n self.place = fluid.CUDAPlace(0) if fluid.is_compiled_with_cuda() \\\n else fluid.CPUPlace()\n\n def test_check_result(self):\n loss_1, hidden_1, cell_1 = train_static(self.place)\n loss_2, hidden_2, cell_2 = train_dygraph(self.place)\n\n self.assertTrue(\n np.allclose(loss_1, loss_2),\n msg=\"static loss: {} \\ndygraph loss: {}\".format(loss_1, loss_2))\n self.assertTrue(\n np.allclose(hidden_1, hidden_2),\n msg=\"static hidden: {} \\ndygraph acc1: {}\".format(hidden_1,\n hidden_2))\n self.assertTrue(\n np.allclose(cell_1, cell_2),\n msg=\"static cell: {} \\ndygraph cell: {}\".format(cell_1, cell_2))\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2020 PaddlePaddle 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\nfrom __future__ import print_function\nimport paddle\nimport paddle.fluid as fluid\nimport unittest\nimport numpy as np\nfrom op_test import OpTest\nfrom paddle.fluid import Program, program_guard\nfrom paddle.fluid.layer_helper import LayerHelper\n\n\nclass TestLogSumOpError(unittest.TestCase):\n def test_errors(self):\n with program_guard(Program(), Program()):\n\n x1 = fluid.layers.data(name='x1', shape=[120], dtype=\"uint8\")\n self.assertRaises(Exception, paddle.logsumexp, x1)\n\n x2 = fluid.layers.data(name='x2', shape=[2, 3], dtype=\"int\")\n self.assertRaises(Exception, paddle.logsumexp, x2)\n\n x3 = fluid.layers.data(name='x3', shape=[3], dtype=\"float16\")\n self.assertRaises(Exception, paddle.logsumexp, x3)\n\n self.assertRaises(AssertionError, paddle.logsumexp, None)\n\n\nclass TestLogSumExpOp(unittest.TestCase):\n def test_dygraph(self):\n with fluid.dygraph.guard():\n np_x = np.random.uniform(0.1, 1, [123]).astype(np.float32)\n x = fluid.dygraph.to_variable(np_x)\n self.assertTrue(\n np.allclose(\n paddle.logsumexp(x).numpy(), np.log(np.sum(np.exp(np_x)))))\n\n np_x = np.random.uniform(0.1, 1, [2, 3, 4]).astype(np.float32)\n x = fluid.dygraph.to_variable(np_x)\n self.assertTrue(\n np.allclose(\n paddle.logsumexp(\n x, dim=[1, 2]).numpy(),\n np.log(np.sum(np.exp(np_x), axis=(1, 2)))))\n\n np_x = np.random.uniform(0.1, 1, [2, 3, 4]).astype(np.float32)\n x = fluid.dygraph.to_variable(np_x)\n self.assertTrue(\n np.allclose(\n paddle.logsumexp(\n x, dim=[2]).numpy(),\n np.log(np.sum(np.exp(np_x), axis=(2)))))\n\n np_x = np.random.uniform(0.1, 1, [2, 3, 4]).astype(np.float32)\n x = fluid.dygraph.to_variable(np_x)\n self.assertTrue(\n np.allclose(\n paddle.logsumexp(\n x, keepdim=True).numpy(),\n np.log(np.sum(np.exp(np_x), keepdims=True))))\n\n np_x = np.random.uniform(0.1, 1, [2, 3, 4]).astype(np.float32)\n x = fluid.dygraph.to_variable(np_x)\n helper = LayerHelper(\"test_logsumexp\")\n out = helper.create_variable(\n type=x.type, name='out', dtype=x.dtype, persistable=False)\n paddle.logsumexp(x, out=out)\n self.assertTrue(\n np.allclose(out.numpy(), np.log(np.sum(np.exp(np_x)))))\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2020 PaddlePaddle 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\nimport numpy as np\nimport unittest\nimport random\nimport time\n\nfrom paddle.incubate.hapi.progressbar import ProgressBar\n\n\nclass TestProgressBar(unittest.TestCase):\n def prog_bar(self, num, epoch, width, verbose=1):\n for epoch in range(epoch):\n progbar = ProgressBar(num, verbose=verbose)\n values = [\n ['loss', 50.341673],\n ['acc', 0.00256],\n ]\n for step in range(1, num + 1):\n values[0][1] -= random.random() * 0.1\n values[1][1] += random.random() * 0.1\n if step % 10 == 0:\n progbar.update(step, values)\n time.sleep(0.002)\n progbar.update(step, values)\n\n progbar.update(1, [['loss', int(1)]])\n progbar.update(1, [['loss', 'INF']])\n progbar.update(1, [['loss', 1e-4]])\n progbar.update(1, [['loss', np.array([1.])]])\n progbar.update(1, [['loss', np.array([1e-4])]])\n progbar.start()\n\n progbar.update(0, values)\n progbar._dynamic_display = False\n progbar.update(1e4, values)\n\n progbar._num = None\n progbar.update(0, values)\n progbar._num = 1\n progbar.update(1 + 1e-4, values)\n\n def test1(self):\n self.prog_bar(50, 1, 30)\n\n def test2(self):\n self.prog_bar(50, 2, 30)\n\n def test4(self):\n self.prog_bar(50, 2, 30, verbose=2)\n\n def test_errors(self):\n with self.assertRaises(TypeError):\n ProgressBar(-1)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2018 PaddlePaddle 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\nfrom __future__ import print_function\n\nimport op_test\nimport unittest\nimport numpy as np\nimport paddle.fluid.core as core\nimport paddle.fluid as fluid\nfrom paddle.fluid import compiler, Program, program_guard\n\n\nclass TestCastOp1(op_test.OpTest):\n def setUp(self):\n ipt = np.random.random(size=[10, 10])\n self.inputs = {'X': ipt.astype('float32')}\n self.outputs = {'Out': ipt.astype('float64')}\n self.attrs = {\n 'in_dtype': int(core.VarDesc.VarType.FP32),\n 'out_dtype': int(core.VarDesc.VarType.FP64)\n }\n self.op_type = 'cast'\n\n def test_check_output(self):\n self.check_output()\n\n def test_grad(self):\n self.check_grad(['X'], ['Out'])\n\n\nclass TestCastOp2(op_test.OpTest):\n def setUp(self):\n ipt = np.random.random(size=[10, 10])\n self.inputs = {'X': ipt.astype('float16')}\n self.outputs = {'Out': ipt.astype('float32')}\n self.attrs = {\n 'in_dtype': int(core.VarDesc.VarType.FP16),\n 'out_dtype': int(core.VarDesc.VarType.FP32)\n }\n self.op_type = 'cast'\n\n def test_check_output(self):\n self.check_output(atol=1e-3)\n\n\nclass TestCastOp3(op_test.OpTest):\n def setUp(self):\n ipt = np.random.random(size=[10, 10])\n self.inputs = {'X': ipt.astype('float32')}\n self.outputs = {'Out': ipt.astype('float16')}\n self.attrs = {\n 'in_dtype': int(core.VarDesc.VarType.FP32),\n 'out_dtype': int(core.VarDesc.VarType.FP16)\n }\n self.op_type = 'cast'\n\n def test_check_output(self):\n self.check_output(atol=1e-3)\n\n\nclass TestCastOpError(unittest.TestCase):\n def test_errors(self):\n with program_guard(Program(), Program()):\n # The input type of cast_op must be Variable.\n x1 = fluid.create_lod_tensor(\n np.array([[-1]]), [[1]], fluid.CPUPlace())\n self.assertRaises(TypeError, fluid.layers.cast, x1, 'int32')\n # The input dtype of cast_op must be bool, float16, float32, float64, int32, int64, uint8.\n x2 = fluid.layers.data(name='x2', shape=[4], dtype='int16')\n self.assertRaises(TypeError, fluid.layers.cast, x2, 'int32')\n\n def test_dtype_type():\n x4 = fluid.layers.data(name='x4', shape=[4], dtype='int32')\n output = fluid.layers.cast(x=x4, dtype='int16')\n\n self.assertRaises(TypeError, test_dtype_type)\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.log", "numpy.max", "numpy.testing.assert_allclose", "numpy.random.uniform", "numpy.exp", "numpy.sum", "numpy.random.randint" ], [ "numpy.arange", "numpy.zeros", "numpy.allclose" ], [ "numpy.random.uniform", "numpy.exp" ], [ "numpy.array" ], [ "numpy.array", "numpy.random.random" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
YexuZhou/TimeSeriesClassification_Transformer
[ "c20e00cfac4cfdb849e57e14c184f7d424257409" ]
[ "models/embedding.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nimport seaborn as sns\nimport matplotlib.pylab as plt\nimport numpy as np\n\n# TODO 所有循环结构应该呈现灵活性,每一层都不能一样!\nactivation_dict = {\"relu\" : nn.ReLU,\n \"leakyrelu\" : nn.LeakyReLU,\n \"prelu\" : nn.PReLU,\n \"rrelu\" : nn.RReLU,\n \"elu\" : nn.ELU,\n \"gelu\" : nn.GELU,\n \"hardswish\" : nn.Hardswish,\n \"mish\" : nn.Mish}\nNorm_dict = {\"layer\" : nn.LayerNorm,\n \"batch\" : nn.BatchNorm1d}\n\n\nclass DW_PW_projection(nn.Module):\n def __init__(self, c_in, c_out, kernel_size, stride=1, bias = False, padding_mode = \"replicate\"):\n super(DW_PW_projection, self).__init__()\n\n self.dw_conv1d = nn.Conv1d(in_channels = c_in,\n out_channels = c_in,\n kernel_size = kernel_size,\n padding = int(kernel_size/2),\n groups = c_in,\n stride = stride,\n bias = bias, \n padding_mode = padding_mode)\n\n self.pw_conv1d = nn.Conv1d(in_channels = c_in,\n out_channels = c_out,\n kernel_size = 1,\n padding = 0,\n groups = 1,\n bias = bias, \n padding_mode = padding_mode)\n def forward(self, x):\n\n\n x = self.dw_conv1d(x)\n x = self.pw_conv1d(x)\n\n return x\n\nclass Forward_block(nn.Module):\n def __init__(self,\n c_in,\n c_out,\n kernel_size,\n stride = 1, \n conv_bias = False,\n activation = \"relu\",\n norm_type = \"batch\",\n max_pool = False,\n pooling_kernel_size = 3, \n pooling_stride = 2,\n pooling_padding = 1,\n padding_mode = 'replicate',\n light_weight = False):\n \"\"\"\n embedding的block 由 conv --> norm --> activation --> maxpooling组成\n \"\"\"\n super(Forward_block, self).__init__() \n if light_weight:\n self.conv = DW_PW_projection(c_in = c_in, \n c_out = c_out,\n kernel_size = kernel_size,\n stride = stride,\n bias = conv_bias, \n padding_mode = padding_mode)\n else:\n self.conv = nn.Conv1d(in_channels = c_in, \n out_channels = c_out,\n kernel_size = kernel_size,\n padding = int(kernel_size/2),\n stride = stride,\n bias = conv_bias,\n padding_mode = padding_mode)\n self.norm_type = norm_type\n self.norm = Norm_dict[norm_type](c_out)\n self.activation = activation_dict[activation]()\n self.max_pool = max_pool\n if max_pool:\n self.maxpooling = nn.MaxPool1d(kernel_size = pooling_kernel_size,\n stride = pooling_stride,\n padding = pooling_padding)\n def forward(self, x):\n\n x = self.conv(x.permute(0, 2, 1)).permute(0, 2, 1)\n\n if self.norm_type == \"layer\":\n x = self.activation(self.norm(x))\n else :\n x = self.activation(self.norm(x.permute(0, 2, 1)).permute(0, 2, 1))\n\n if self.max_pool:\n x = self.maxpooling(x.permute(0, 2, 1)).permute(0, 2, 1)\n return x\n\n\nclass Freq_Forward_block(nn.Module):\n def __init__(self, \n c_in, \n c_out, # 主要是把channel的dim压平\n kernel_size, \n stride=1, \n bias = False, \n padding_mode = \"replicate\"):\n \n super(Freq_Forward_block, self).__init__()\n \n # depthwise\n self.dw_conv = nn.Conv2d(in_channels = c_in,\n out_channels = c_in,\n kernel_size = [kernel_size,kernel_size],\n padding = [int(kernel_size/2),int(kernel_size/2)],\n groups = c_in,\n stride = [1,stride], #缩短长度\n bias = bias, \n padding_mode = padding_mode)\n self.batch_norm_1 = nn.BatchNorm2d(c_in)\n self.act_1 = nn.ReLU()\n # pointwise\n self.pw_conv = nn.Conv2d(in_channels = c_in,\n out_channels = c_out, # 压平\n kernel_size = 1,\n padding = 0,\n stride = 1,\n bias = bias, \n padding_mode = padding_mode)\n self.batch_norm_2 = nn.BatchNorm2d(c_out)\n self.act_2 = nn.ReLU()\n \n def forward(self, x):\n\n x = self.dw_conv(x)\n x = self.batch_norm_1(x)\n x = self.act_1(x)\n\n x = self.pw_conv(x)\n x = self.batch_norm_2(x)\n x = self.act_2(x)\n\n return x\n\n\nclass TokenEmbedding(nn.Module):\n def __init__(self,\n c_in, \n token_d_model,\n kernel_size = 3, \n stride = 1, \n conv_bias = False,\n activation = \"relu\",\n norm_type = \"batch\",\n n_conv_layers = 1,\n in_planes = None,\n max_pool = False,\n pooling_kernel_size = 3, \n pooling_stride = 2,\n pooling_padding = 1,\n padding_mode = 'replicate',\n light_weight = False):\n \"\"\"\n c_in : 模型输入的维度\n token_d_model : embedding的维度 TODO看看后面是需要被相加还是被cat\n kernel_size : 每一层conv的kernel大小\n \n \"\"\"\n super(TokenEmbedding, self).__init__()\n in_planes = in_planes or int(token_d_model/2)\n n_filter_list = [c_in] + [in_planes for _ in range(n_conv_layers - 1)] + [token_d_model]\n padding = int(kernel_size/2)\n\n\n self.conv_layers = []\n for i in range(n_conv_layers):\n self.conv_layers.append(Forward_block(c_in = n_filter_list[i],\n c_out = n_filter_list[i + 1], \n kernel_size = kernel_size,\n stride = stride, \n conv_bias = conv_bias,\n activation = activation,\n norm_type = norm_type,\n max_pool = max_pool,\n pooling_kernel_size = pooling_kernel_size, \n pooling_stride = pooling_stride,\n pooling_padding = pooling_padding,\n padding_mode = padding_mode,\n light_weight = light_weight))\n\n self.conv_layers = nn.ModuleList(self.conv_layers)\n\n #for m in self.modules():\n # if isinstance(m, nn.Conv1d):\n # nn.init.kaiming_normal_(m.weight)\n\n\n\n def forward(self, x):\n\n\n for layer in self.conv_layers:\n x = layer(x)\n return x\n\n def sequence_length(self, length=100, n_channels=3):\n return self.forward(torch.zeros((1, length,n_channels))).shape[1]\n\n\n\nclass Freq_TokenEmbedding(nn.Module):\n def __init__(self,\n c_in, \n token_d_model,\n kernel_size = 3, \n stride = 1, #横向方向缩短距离\n conv_bias = False,\n n_conv_layers = 1,\n f_max = 100,\n padding_mode = 'replicate',\n light_weight = False):\n \"\"\"\n c_in : 模型输入的维度\n token_d_model : embedding的维度 TODO看看后面是需要被相加还是被cat\n kernel_size : 每一层conv的kernel大小\n \n \"\"\"\n super(Freq_TokenEmbedding, self).__init__()\n\n n_filter_list = [c_in] + [max(1,int(c_in/2**(i+1))) for i in range(n_conv_layers - 1)] + [1]\n print(n_filter_list)\n self.conv_layers = []\n for i in range(n_conv_layers):\n self.conv_layers.append(Freq_Forward_block(c_in = n_filter_list[i], \n c_out = n_filter_list[i + 1], # 主要是把channel的dim压平\n kernel_size = kernel_size, \n stride = stride, \n bias = conv_bias,\n padding_mode = padding_mode))\n\n self.conv_layers = nn.ModuleList(self.conv_layers)\n\n self.conv = nn.Conv1d(in_channels = self.channel(c_in = c_in, freq = int(f_max/2), length=100), \n out_channels = token_d_model,\n kernel_size = kernel_size,\n padding = int(kernel_size/2),\n stride = 1,\n bias = conv_bias,\n padding_mode = padding_mode)\n self.norm = nn.LayerNorm(token_d_model)\n self.activation = nn.ReLU()\n def forward(self, x):\n\n\n for layer in self.conv_layers:\n x = layer(x)\n\n x = torch.squeeze(x, 1)\n\n x = self.conv(x) # B C L\n x = self.activation(self.norm(x.permute(0, 2, 1)))\n\n return x\n \n def sequence_length(self, c_in = 100, freq = 50, length=100):\n x = torch.rand(1,c_in,freq,length).float()\n for layer in self.conv_layers:\n x = layer(x)\n return x.shape[3]\n\n def channel(self, c_in = 100, freq = 50, length=100):\n x = torch.rand(1,c_in,freq,length).float()\n for layer in self.conv_layers:\n x = layer(x)\n print(\"channel ,\", x.shape[2])\n return x.shape[2]\n\nclass PositionalEmbedding(nn.Module):\n \"\"\"\n input shape should be (batch, seq_length, feature_channel)\n \n \"\"\"\n def __init__(self, pos_d_model, max_len=5000):\n super(PositionalEmbedding, self).__init__()\n # Compute the positional encodings once in log space.\n \n \n pe = torch.zeros(max_len, pos_d_model).float()\n pe.require_grad = False\n\n position = torch.arange(0, max_len).float().unsqueeze(1)\n div_term = (torch.arange(0, pos_d_model, 2).float() * -(math.log(10000.0) / pos_d_model)).exp()\n\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n\n pe = pe.unsqueeze(0)# [1, max_len, pos_d_model]\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n return self.pe[:, :x.size(1)] # select the the length same as input\n\n\n def vis_pos_heat(self, length):\n heat = self.pe[:, :length]\n plt.figure(figsize=(15,5))\n sns.heatmap(heat.detach().numpy()[0], linewidth=0)\n plt.ylabel(\"length\")\n plt.xlabel(\"embedding\")\n\n" ]
[ [ "torch.cos", "torch.sin", "torch.zeros", "torch.nn.ModuleList", "torch.nn.Conv2d", "torch.arange", "torch.nn.LayerNorm", "torch.nn.MaxPool1d", "torch.nn.Conv1d", "matplotlib.pylab.figure", "matplotlib.pylab.ylabel", "torch.rand", "torch.nn.BatchNorm2d", "torch.nn.ReLU", "matplotlib.pylab.xlabel", "torch.squeeze" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
techshot25/gpytorch
[ "092d523027a844939ba85d7ea8c8c7b7511843d5", "b4aee6f81a3428172d4914e7e0fef0e71cd1f519", "092d523027a844939ba85d7ea8c8c7b7511843d5", "092d523027a844939ba85d7ea8c8c7b7511843d5", "092d523027a844939ba85d7ea8c8c7b7511843d5", "092d523027a844939ba85d7ea8c8c7b7511843d5" ]
[ "test/kernels/test_rbf_kernel_grad.py", "gpytorch/utils/cholesky.py", "test/kernels/test_polynomial_kernel.py", "gpytorch/kernels/linear_kernel.py", "gpytorch/likelihoods/gaussian_likelihood.py", "gpytorch/module.py" ]
[ "#!/usr/bin/env python3\n\nimport torch\nimport unittest\nfrom gpytorch.kernels import RBFKernelGrad\nfrom gpytorch.test.base_kernel_test_case import BaseKernelTestCase\n\n\nclass TestRBFKernelGrad(unittest.TestCase, BaseKernelTestCase):\n def create_kernel_no_ard(self, **kwargs):\n return RBFKernelGrad(**kwargs)\n\n def create_kernel_ard(self, num_dims, **kwargs):\n return RBFKernelGrad(ard_num_dims=num_dims, **kwargs)\n\n def test_kernel(self, cuda=False):\n a = torch.tensor([[[1, 2], [2, 4]]], dtype=torch.float)\n b = torch.tensor([[[1, 3], [0, 4]]], dtype=torch.float)\n\n actual = torch.tensor(\n [\n [0.35321, 0, -0.73517, 0.0054977, 0.011443, -0.022886],\n [0, 0.73517, 0, -0.011443, -0.012374, 0.047633],\n [0.73517, 0, -0.79499, 0.022886, 0.047633, -0.083824],\n [0.12476, 0.25967, 0.25967, 0.015565, 0.064793, 0],\n [-0.25967, -0.2808, -0.54047, -0.064793, -0.23732, 0],\n [-0.25967, -0.54047, -0.2808, 0, 0, 0.032396],\n ]\n )\n\n kernel = RBFKernelGrad()\n\n if cuda:\n a = a.cuda()\n b = b.cuda()\n actual = actual.cuda()\n kernel = kernel.cuda()\n\n res = kernel(a, b).evaluate()\n\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n def test_kernel_cuda(self):\n if torch.cuda.is_available():\n self.test_kernel(cuda=True)\n\n def test_kernel_batch(self):\n a = torch.tensor([[[1, 2, 3], [2, 4, 0]], [[-1, 1, 2], [2, 1, 4]]], dtype=torch.float)\n b = torch.tensor([[[1, 3, 1]], [[2, -1, 0]]], dtype=torch.float).repeat(1, 2, 1)\n\n kernel = RBFKernelGrad()\n res = kernel(a, b).evaluate()\n\n # Compute each batch separately\n actual = torch.zeros(2, 8, 8)\n actual[0, :, :] = kernel(a[0, :, :].squeeze(), b[0, :, :].squeeze()).evaluate()\n actual[1, :, :] = kernel(a[1, :, :].squeeze(), b[1, :, :].squeeze()).evaluate()\n\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n def test_initialize_lengthscale(self):\n kernel = RBFKernelGrad()\n kernel.initialize(lengthscale=3.14)\n actual_value = torch.tensor(3.14).view_as(kernel.lengthscale)\n self.assertLess(torch.norm(kernel.lengthscale - actual_value), 1e-5)\n\n def test_initialize_lengthscale_batch(self):\n kernel = RBFKernelGrad(batch_shape=torch.Size([2]))\n ls_init = torch.tensor([3.14, 4.13])\n kernel.initialize(lengthscale=ls_init)\n actual_value = ls_init.view_as(kernel.lengthscale)\n self.assertLess(torch.norm(kernel.lengthscale - actual_value), 1e-5)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "#!/usr/bin/env python3\n\nimport warnings\nimport torch\n\n\ndef psd_safe_cholesky(A, upper=False, out=None, jitter=None):\n \"\"\"Compute the Cholesky decomposition of A. If A is only p.s.d, add a small jitter to the diagonal.\n Args:\n :attr:`A` (Tensor):\n The tensor to compute the Cholesky decomposition of\n :attr:`upper` (bool, optional):\n See torch.cholesky\n :attr:`out` (Tensor, optional):\n See torch.cholesky\n :attr:`jitter` (float, optional):\n The jitter to add to the diagonal of A in case A is only p.s.d. If omitted, chosen\n as 1e-6 (float) or 1e-8 (double)\n \"\"\"\n try:\n L = torch.cholesky(A, upper=upper, out=out)\n # TODO: Remove once fixed in pytorch (#16780)\n if A.dim() > 2 and A.is_cuda:\n if torch.isnan(L if out is None else out).any():\n raise RuntimeError(\"cholesky_cuda: singular U.\")\n return L\n except RuntimeError as e:\n if jitter is None:\n jitter = 1e-6 if A.dtype == torch.float32 else 1e-8\n Aprime = A.clone()\n jitter_prev = 0\n for i in range(3):\n jitter_new = jitter * (10 ** i)\n Aprime.diagonal(dim1=-2, dim2=-1).add_(jitter_new - jitter_prev)\n jitter_prev = jitter_new\n try:\n L = torch.cholesky(Aprime, upper=upper, out=out)\n # TODO: Remove once fixed in pytorch (#16780)\n if A.dim() > 2 and A.is_cuda:\n if torch.isnan(L if out is None else out).any():\n raise RuntimeError(\"cholesky_cuda: singular U.\")\n warnings.warn(f\"A not p.d., added jitter of {jitter_new} to the diagonal\", RuntimeWarning)\n return L\n except RuntimeError:\n continue\n raise e\n", "#!/usr/bin/env python3\n\nimport torch\nimport unittest\nfrom gpytorch.kernels import PolynomialKernel\nfrom gpytorch.test.base_kernel_test_case import BaseKernelTestCase\n\n\nclass TestPolynomialKernel(unittest.TestCase, BaseKernelTestCase):\n def create_kernel_no_ard(self, **kwargs):\n return PolynomialKernel(power=2, **kwargs)\n\n def test_computes_quadratic_kernel(self):\n a = torch.tensor([[4, 1], [2, 2], [8, 0]], dtype=torch.float)\n b = torch.tensor([[0, 0], [2, 1], [1, 0]], dtype=torch.float)\n kernel = PolynomialKernel(power=2)\n kernel.eval()\n\n actual = torch.zeros(3, 3)\n for i in range(3):\n for j in range(3):\n actual[i, j] = (a[i].matmul(b[j]) + kernel.offset).pow(kernel.power)\n\n res = kernel(a, b).evaluate()\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n # diag\n res = kernel(a, b).diag()\n actual = actual.diag()\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n # batch_dims\n actual = torch.zeros(2, 3, 3)\n for l in range(2):\n actual[l] = kernel(a[:, l].unsqueeze(-1), b[:, l].unsqueeze(-1)).evaluate()\n\n res = kernel(a, b, last_dim_is_batch=True).evaluate()\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n # batch_dims + diag\n res = kernel(a, b, last_dim_is_batch=True).diag()\n actual = torch.cat([actual[i].diag().unsqueeze(0) for i in range(actual.size(0))])\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n def test_computes_cubic_kernel(self):\n a = torch.tensor([[4, 1], [2, 2], [8, 0]], dtype=torch.float)\n b = torch.tensor([[0, 0], [2, 1], [1, 0]], dtype=torch.float)\n kernel = PolynomialKernel(power=3)\n kernel.eval()\n\n actual = torch.zeros(3, 3)\n for i in range(3):\n for j in range(3):\n actual[i, j] = (a[i].matmul(b[j]) + kernel.offset).pow(kernel.power)\n\n res = kernel(a, b).evaluate()\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n # diag\n res = kernel(a, b).diag()\n actual = actual.diag()\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n # batch_dims\n actual = torch.zeros(2, 3, 3)\n for l in range(2):\n actual[l] = kernel(a[:, l].unsqueeze(-1), b[:, l].unsqueeze(-1)).evaluate()\n\n res = kernel(a, b, last_dim_is_batch=True).evaluate()\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n # batch_dims + diag\n res = kernel(a, b, last_dim_is_batch=True).diag()\n actual = torch.cat([actual[i].diag().unsqueeze(0) for i in range(actual.size(0))])\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n def test_quadratic_kernel_batch(self):\n a = torch.tensor([[4, 2, 8], [1, 2, 3]], dtype=torch.float).view(2, 3, 1)\n b = torch.tensor([[0, 2, 1], [-1, 2, 0]], dtype=torch.float).view(2, 3, 1)\n kernel = PolynomialKernel(power=2, batch_shape=torch.Size([2])).initialize(offset=torch.rand(2, 1))\n kernel.eval()\n\n actual = torch.zeros(2, 3, 3)\n for k in range(2):\n for i in range(3):\n for j in range(3):\n actual[k, i, j] = (a[k, i].matmul(b[k, j]) + kernel.offset[k]).pow(kernel.power)\n\n res = kernel(a, b).evaluate()\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n def test_cubic_kernel_batch(self):\n a = torch.tensor([[4, 2, 8], [1, 2, 3]], dtype=torch.float).view(2, 3, 1)\n b = torch.tensor([[0, 2, 1], [-1, 2, 0]], dtype=torch.float).view(2, 3, 1)\n kernel = PolynomialKernel(power=3, batch_shape=torch.Size([2])).initialize(offset=torch.rand(2, 1))\n kernel.eval()\n\n actual = torch.zeros(2, 3, 3)\n for k in range(2):\n for i in range(3):\n for j in range(3):\n actual[k, i, j] = (a[k, i].matmul(b[k, j]) + kernel.offset[k]).pow(kernel.power)\n\n res = kernel(a, b).evaluate()\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "#!/usr/bin/env python3\n\nimport torch\nimport warnings\nfrom .kernel import Kernel\nfrom ..lazy import MatmulLazyTensor, RootLazyTensor\nfrom ..constraints import Positive\n\n\nclass LinearKernel(Kernel):\n r\"\"\"\n Computes a covariance matrix based on the Linear kernel\n between inputs :math:`\\mathbf{x_1}` and :math:`\\mathbf{x_2}`:\n\n .. math::\n \\begin{equation*}\n k_\\text{Linear}(\\mathbf{x_1}, \\mathbf{x_2}) = v\\mathbf{x_1}^\\top\n \\mathbf{x_2}.\n \\end{equation*}\n\n where\n\n * :math:`v` is a :attr:`variance` parameter.\n\n\n .. note::\n\n To implement this efficiently, we use a :obj:`gpytorch.lazy.RootLazyTensor` during training and a\n :class:`gpytorch.lazy.MatmulLazyTensor` during test. These lazy tensors represent matrices of the form\n :math:`K = XX^{\\top}` and :math:`K = XZ^{\\top}`. This makes inference\n efficient because a matrix-vector product :math:`Kv` can be computed as\n :math:`Kv=X(X^{\\top}v)`, where the base multiply :math:`Xv` takes only\n :math:`O(nd)` time and space.\n\n Args:\n :attr:`variance_prior` (:class:`gpytorch.priors.Prior`):\n Prior over the variance parameter (default `None`).\n :attr:`variance_constraint` (Constraint, optional):\n Constraint to place on variance parameter. Default: `Positive`.\n :attr:`active_dims` (list):\n List of data dimensions to operate on.\n `len(active_dims)` should equal `num_dimensions`.\n \"\"\"\n\n def __init__(\n self,\n num_dimensions=None,\n offset_prior=None,\n variance_prior=None,\n variance_constraint=None,\n **kwargs\n ):\n super(LinearKernel, self).__init__(**kwargs)\n if variance_constraint is None:\n variance_constraint = Positive()\n\n if num_dimensions is not None:\n warnings.warn(\n \"The `num_dimensions` argument is deprecated and no longer used.\",\n DeprecationWarning\n )\n self.register_parameter(\n name=\"offset\",\n parameter=torch.nn.Parameter(torch.zeros(1, 1, num_dimensions))\n )\n if offset_prior is not None:\n warnings.warn(\n \"The `offset_prior` argument is deprecated and no longer used.\",\n DeprecationWarning\n )\n self.register_parameter(\n name=\"raw_variance\", parameter=torch.nn.Parameter(torch.zeros(*self.batch_shape, 1, 1))\n )\n if variance_prior is not None:\n self.register_prior(\n \"variance_prior\",\n variance_prior,\n lambda: self.variance,\n lambda v: self._set_variance(v)\n )\n\n self.register_constraint(\"raw_variance\", variance_constraint)\n\n @property\n def variance(self):\n return self.raw_variance_constraint.transform(self.raw_variance)\n\n @variance.setter\n def variance(self, value):\n self._set_variance(value)\n\n def _set_variance(self, value):\n if not torch.is_tensor(value):\n value = torch.as_tensor(value).to(self.raw_variance)\n self.initialize(raw_variance=self.raw_variance_constraint.inverse_transform(value))\n\n def forward(self, x1, x2, diag=False, last_dim_is_batch=False, **params):\n x1_ = x1 * self.variance.sqrt()\n if last_dim_is_batch:\n x1_ = x1_.transpose(-1, -2).unsqueeze(-1)\n\n if x1.size() == x2.size() and torch.equal(x1, x2):\n # Use RootLazyTensor when x1 == x2 for efficiency when composing\n # with other kernels\n prod = RootLazyTensor(x1_)\n\n else:\n x2_ = x2 * self.variance.sqrt()\n if last_dim_is_batch:\n x2_ = x2_.transpose(-1, -2).unsqueeze(-1)\n\n prod = MatmulLazyTensor(x1_, x2_.transpose(-2, -1))\n\n if diag:\n return prod.diag()\n else:\n return prod\n", "#!/usr/bin/env python3\n\nfrom copy import deepcopy\n\nimport math\nimport warnings\nfrom typing import Any, Optional\n\nimport torch\nfrom torch import Tensor\n\nfrom ..distributions import MultivariateNormal, base_distributions\nfrom ..likelihoods import Likelihood\nfrom ..lazy import ZeroLazyTensor\nfrom ..utils.deprecation import _deprecate_kwarg_with_transform\nfrom .noise_models import FixedGaussianNoise, HomoskedasticNoise, Noise\n\n\nclass _GaussianLikelihoodBase(Likelihood):\n \"\"\"Base class for Gaussian Likelihoods, supporting general heteroskedastic noise models.\"\"\"\n\n def __init__(self, noise_covar: Noise, **kwargs: Any) -> None:\n\n super().__init__()\n param_transform = kwargs.get(\"param_transform\")\n if param_transform is not None:\n warnings.warn(\"The 'param_transform' argument is now deprecated. If you want to use a different \"\n \"transformaton, specify a different 'noise_constraint' instead.\")\n\n self.noise_covar = noise_covar\n\n def _shaped_noise_covar(self, base_shape: torch.Size, *params: Any, **kwargs: Any):\n if len(params) > 0:\n # we can infer the shape from the params\n shape = None\n else:\n # here shape[:-1] is the batch shape requested, and shape[-1] is `n`, the number of points\n shape = base_shape\n return self.noise_covar(*params, shape=shape, **kwargs)\n\n def forward(self, function_samples: Tensor, *params: Any, **kwargs: Any) -> base_distributions.Normal:\n noise = self._shaped_noise_covar(function_samples.shape, *params, **kwargs).diag()\n return base_distributions.Normal(function_samples, noise.sqrt())\n\n def marginal(self, function_dist: MultivariateNormal, *params: Any, **kwargs: Any) -> MultivariateNormal:\n mean, covar = function_dist.mean, function_dist.lazy_covariance_matrix\n noise_covar = self._shaped_noise_covar(mean.shape, *params, **kwargs)\n full_covar = covar + noise_covar\n return function_dist.__class__(mean, full_covar)\n\n\nclass GaussianLikelihood(_GaussianLikelihoodBase):\n def __init__(self, noise_prior=None, noise_constraint=None, batch_shape=torch.Size(), **kwargs):\n batch_shape = _deprecate_kwarg_with_transform(\n kwargs, \"batch_size\", \"batch_shape\", batch_shape, lambda n: torch.Size([n])\n )\n noise_covar = HomoskedasticNoise(\n noise_prior=noise_prior,\n noise_constraint=noise_constraint,\n batch_shape=batch_shape,\n )\n super().__init__(noise_covar=noise_covar)\n\n @property\n def noise(self) -> Tensor:\n return self.noise_covar.noise\n\n @noise.setter\n def noise(self, value: Tensor) -> None:\n self.noise_covar.initialize(noise=value)\n\n @property\n def raw_noise(self) -> Tensor:\n return self.noise_covar.raw_noise\n\n @raw_noise.setter\n def raw_noise(self, value: Tensor) -> None:\n self.noise_covar.initialize(raw_noise=value)\n\n def expected_log_prob(self, target: Tensor, input: MultivariateNormal, *params: Any, **kwargs: Any) -> Tensor:\n mean, variance = input.mean, input.variance\n noise = self.noise_covar.noise\n\n res = ((target - mean) ** 2 + variance) / noise + noise.log() + math.log(2 * math.pi)\n return res.mul(-0.5).sum(-1)\n\n\nclass FixedNoiseGaussianLikelihood(_GaussianLikelihoodBase):\n \"\"\"\n A Likelihood that assumes fixed heteroscedastic noise. This is useful when you have fixed, known observation\n noise for each training example.\n\n Args:\n :attr:`noise` (Tensor):\n Known observation noise (variance) for each training example.\n :attr:`learn_additional_noise` (bool, optional):\n Set to true if you additionally want to learn added diagonal noise, similar to GaussianLikelihood.\n\n Note that this likelihood takes an additional argument when you call it, `noise`, that adds a specified amount\n of noise to the passed MultivariateNormal. This allows for adding known observational noise to test data.\n\n Example:\n >>> train_x = torch.randn(55, 2)\n >>> noises = torch.ones(55) * 0.01\n >>> likelihood = FixedNoiseGaussianLikelihood(noise=noises, learn_additional_noise=True)\n >>> pred_y = likelihood(gp_model(train_x))\n >>>\n >>> test_x = torch.randn(21, 2)\n >>> test_noises = torch.ones(21) * 0.02\n >>> pred_y = likelihood(gp_model(test_x), noise=test_noises)\n \"\"\"\n def __init__(\n self,\n noise: Tensor,\n learn_additional_noise: Optional[bool] = False,\n batch_shape: Optional[torch.Size] = torch.Size(),\n **kwargs: Any\n ) -> None:\n super().__init__(noise_covar=FixedGaussianNoise(noise=noise))\n\n batch_shape = _deprecate_kwarg_with_transform(\n kwargs, \"batch_size\", \"batch_shape\", batch_shape, lambda n: torch.Size([n])\n )\n if learn_additional_noise:\n noise_prior = kwargs.get(\"noise_prior\", None)\n noise_constraint = kwargs.get(\"noise_constraint\", None)\n self.second_noise_covar = HomoskedasticNoise(\n noise_prior=noise_prior,\n noise_constraint=noise_constraint,\n batch_shape=batch_shape,\n )\n else:\n self.second_noise_covar = None\n\n @property\n def noise(self) -> Tensor:\n return self.noise_covar.noise + self.second_noise\n\n @noise.setter\n def noise(self, value: Tensor) -> None:\n self.noise_covar.initialize(noise=value)\n\n @property\n def second_noise(self) -> Tensor:\n if self.second_noise_covar is None:\n return 0\n else:\n return self.second_noise_covar.noise\n\n @second_noise.setter\n def second_noise(self, value: Tensor) -> None:\n if self.second_noise_covar is None:\n raise RuntimeError(\n \"Attempting to set secondary learned noise for FixedNoiseGaussianLikelihood, \"\n \"but learn_additional_noise must have been False!\"\n )\n self.second_noise_covar.initialize(noise=value)\n\n def get_fantasy_likelihood(self, **kwargs):\n if \"noise\" not in kwargs:\n raise RuntimeError(\"FixedNoiseGaussianLikelihood.fantasize requires a `noise` kwarg\")\n old_noise_covar = self.noise_covar\n self.noise_covar = None\n fantasy_liklihood = deepcopy(self)\n self.noise_covar = old_noise_covar\n\n old_noise = old_noise_covar.noise\n new_noise = kwargs.get(\"noise\")\n if old_noise.dim() != new_noise.dim():\n old_noise = old_noise.expand(*new_noise.shape[:-1], old_noise.shape[-1])\n fantasy_liklihood.noise_covar = FixedGaussianNoise(noise=torch.cat([old_noise, new_noise], -1))\n return fantasy_liklihood\n\n def _shaped_noise_covar(self, base_shape: torch.Size, *params: Any, **kwargs: Any):\n if len(params) > 0:\n # we can infer the shape from the params\n shape = None\n else:\n # here shape[:-1] is the batch shape requested, and shape[-1] is `n`, the number of points\n shape = base_shape\n\n res = self.noise_covar(*params, shape=shape, **kwargs)\n\n if self.second_noise_covar is not None:\n res = res + self.second_noise_covar(*params, shape=shape, **kwargs)\n elif isinstance(res, ZeroLazyTensor):\n warnings.warn(\n \"You have passed data through a FixedNoiseGaussianLikelihood that did not match the size \"\n \"of the fixed noise, *and* you did not specify noise. This is treated as a no-op.\"\n )\n\n return res\n", "#!/usr/bin/env python3\n\nfrom collections import OrderedDict\n\nimport torch\nfrom torch import nn\nfrom torch.distributions import Distribution\n\nfrom .lazy import LazyTensor\nfrom .utils.deprecation import DeprecationError\nfrom .constraints import Interval\n\n\nclass Module(nn.Module):\n def __init__(self):\n super().__init__()\n self._added_loss_terms = OrderedDict()\n self._priors = OrderedDict()\n self._constraints = OrderedDict()\n\n def __call__(self, *inputs, **kwargs):\n outputs = self.forward(*inputs, **kwargs)\n if isinstance(outputs, list):\n return [_validate_module_outputs(output) for output in outputs]\n return _validate_module_outputs(outputs)\n\n def _get_module_and_name(self, parameter_name):\n \"\"\"Get module and name from full parameter name.\"\"\"\n module, name = parameter_name.split(\".\", 1)\n if module in self._modules:\n return self.__getattr__(module), name\n else:\n raise AttributeError(\n \"Invalid parameter name {}. {} has no module {}\".format(parameter_name, type(self).__name__, module)\n )\n\n def added_loss_terms(self):\n for _, strategy in self.named_added_loss_terms():\n yield strategy\n\n def forward(self, *inputs, **kwargs):\n raise NotImplementedError\n\n def constraints(self):\n for _, constraint in self.named_constraints():\n yield constraint\n\n def hyperparameters(self):\n for _, param in self.named_hyperparameters():\n yield param\n\n def initialize(self, **kwargs):\n \"\"\"\n Set a value for a parameter\n\n kwargs: (param_name, value) - parameter to initialize.\n Can also initialize recursively by passing in the full name of a\n parameter. For example if model has attribute model.likelihood,\n we can initialize the noise with either\n `model.initialize(**{'likelihood.noise': 0.1})`\n or\n `model.likelihood.initialize(noise=0.1)`.\n The former method would allow users to more easily store the\n initialization values as one object.\n\n Value can take the form of a tensor, a float, or an int\n \"\"\"\n\n for name, val in kwargs.items():\n if isinstance(val, int):\n val = float(val)\n if '.' in name:\n module, name = self._get_module_and_name(name)\n module.initialize(**{name: val})\n elif not hasattr(self, name):\n raise AttributeError(\"Unknown parameter {p} for {c}\".format(p=name, c=self.__class__.__name__))\n elif name not in self._parameters and name not in self._buffers:\n setattr(self, name, val)\n elif torch.is_tensor(val):\n constraint = self.constraint_for_parameter_name(name)\n if constraint is not None and not constraint.check_raw(val):\n raise RuntimeError(\n \"Attempting to manually set a parameter value that is out of bounds of \"\n f\"its current constraints, {constraint}. \"\n \"Most likely, you want to do the following:\\n likelihood = GaussianLikelihood\"\n \"(noise_constraint=gpytorch.constraints.GreaterThan(better_lower_bound))\"\n )\n try:\n self.__getattr__(name).data.copy_(val.expand_as(self.__getattr__(name)))\n except RuntimeError:\n self.__getattr__(name).data.copy_(val.view_as(self.__getattr__(name)))\n\n elif isinstance(val, float):\n constraint = self.constraint_for_parameter_name(name)\n if constraint is not None and not constraint.check_raw(val):\n raise RuntimeError(\n \"Attempting to manually set a parameter value that is out of bounds of \"\n f\"its current constraints, {constraint}. \"\n \"Most likely, you want to do the following:\\n likelihood = GaussianLikelihood\"\n \"(noise_constraint=gpytorch.constraints.GreaterThan(better_lower_bound))\"\n )\n self.__getattr__(name).data.fill_(val)\n else:\n raise AttributeError(\"Type {t} not valid for initializing parameter {p}\".format(t=type(val), p=name))\n\n # Ensure value is contained in support of prior (if present)\n prior_name = \"_\".join([name, \"prior\"])\n if prior_name in self._priors:\n prior, closure, _ = self._priors[prior_name]\n try:\n prior._validate_sample(closure())\n except ValueError as e:\n raise ValueError(\"Invalid input value for prior {}. Error:\\n{}\".format(prior_name, e))\n\n return self\n\n def named_added_loss_terms(self):\n \"\"\"Returns an iterator over module variational strategies, yielding both\n the name of the variational strategy as well as the strategy itself.\n\n Yields:\n (string, VariationalStrategy): Tuple containing the name of the\n strategy and the strategy\n\n \"\"\"\n return _extract_named_added_loss_terms(module=self, memo=None, prefix=\"\")\n\n def named_hyperparameters(self):\n for name, param in self.named_parameters():\n if \"variational_\" not in name:\n yield name, param\n\n def named_priors(self, memo=None, prefix=\"\"):\n \"\"\"Returns an iterator over the module's priors, yielding the name of the prior,\n the prior, the associated parameter names, and the transformation callable.\n\n Yields:\n (string, Prior, tuple((Parameter, callable)), callable): Tuple containing:\n - the name of the prior\n - the prior\n - a tuple of tuples (param, transform), one for each of the parameters associated with the prior\n - the prior's transform to be called on the parameters\n \"\"\"\n return _extract_named_priors(module=self, memo=None, prefix=\"\")\n\n def named_constraints(self, memo=None, prefix=\"\"):\n return _extract_named_constraints(module=self, memo=None, prefix=\"\")\n\n def named_variational_parameters(self):\n for name, param in self.named_parameters():\n if \"variational_\" in name:\n yield name, param\n\n def register_added_loss_term(self, name):\n self._added_loss_terms[name] = None\n\n def register_parameter(self, name, parameter, prior=None):\n r\"\"\"\n Adds a parameter to the module. The parameter can be accessed as an attribute using the given name.\n\n Args:\n :attr:`name` (str):\n The name of the parameter\n :attr:`parameter` (torch.nn.Parameter):\n The parameter\n \"\"\"\n if prior is not None:\n raise DeprecationError(\n \"Setting a prior upon registering a parameter is deprecated. Please use \"\n \".register_prior('{name}_prior', prior, '{name}') instead.\".format(name=name)\n )\n if \"_parameters\" not in self.__dict__:\n raise AttributeError(\"Cannot assign parameter before Module.__init__() call\")\n super().register_parameter(name, parameter)\n\n def register_prior(self, name, prior, param_or_closure, setting_closure=None):\n \"\"\"\n Adds a prior to the module. The prior can be accessed as an attribute using the given name.\n\n Args:\n :attr:`name` (str):\n The name of the prior\n :attr:`prior` (Prior):\n The prior to be registered`\n :attr:`param_or_closure` (string or callable):\n Either the name of the parameter, or a closure (which upon calling evalutes a function on\n one or more parameters):\n single parameter without a transform: `.register_prior(\"foo_prior\", foo_prior, \"foo_param\")`\n transform a single parameter (e.g. put a log-Normal prior on it):\n `.register_prior(\"foo_prior\", NormalPrior(0, 1), lambda: torch.log(self.foo_param))`\n function of multiple parameters:\n `.register_prior(\"foo2_prior\", foo2_prior, lambda: f(self.param1, self.param2)))`\n :attr:`setting_closure` (callable, optional):\n A function taking in a tensor in (transformed) parameter space and initializing the\n internal parameter representation to the proper value by applying the inverse transform.\n Enables setting parametres directly in the transformed space, as well as sampling\n parameter values from priors (see `sample_from_prior`)\n\n \"\"\"\n if isinstance(param_or_closure, str):\n if param_or_closure not in self._parameters:\n raise AttributeError(\n \"Unknown parameter {name} for {module}\".format(\n name=param_or_closure, module=self.__class__.__name__\n )\n + \"Make sure the parameter is registered before registering a prior.\"\n )\n\n def closure():\n return self._parameters[param_or_closure]\n\n if setting_closure is not None:\n raise RuntimeError(\"Must specify a closure instead of a parameter name when providing setting_closure\")\n\n def setting_closure(val):\n return self.initialize(**{param_or_closure: val})\n\n else:\n closure = param_or_closure\n self.add_module(name, prior)\n self._priors[name] = (prior, closure, setting_closure)\n\n def register_constraint(self, param_name, constraint, replace=True):\n if param_name not in self._parameters:\n raise RuntimeError(\"Attempting to register constraint for nonexistent parameter.\")\n\n constraint_name = param_name + \"_constraint\"\n if constraint_name in self._constraints:\n current_constraint = self._constraints[constraint_name]\n else:\n current_constraint = None\n\n if isinstance(current_constraint, Interval) and not replace:\n new_constraint = constraint.intersect(current_constraint)\n else:\n new_constraint = constraint\n\n self.add_module(constraint_name, new_constraint)\n self._constraints[constraint_name] = new_constraint\n\n # re-initialize the parameter if the constraint specifies an initial value\n if new_constraint.initial_value is not None:\n self.initialize(**{param_name: new_constraint.initial_value})\n\n def constraint_for_parameter_name(self, param_name):\n base_module = self\n base_name = param_name\n\n while \".\" in base_name:\n components = base_name.split(\".\")\n submodule_name = components[0]\n submodule = getattr(base_module, submodule_name)\n\n base_module = submodule\n base_name = \".\".join(components[1:])\n\n constraint_name = base_name + \"_constraint\"\n return base_module._constraints.get(constraint_name)\n\n def named_parameters_and_constraints(self):\n for name, param in self.named_parameters():\n yield name, param, self.constraint_for_parameter_name(name)\n\n def sample_from_prior(self, prior_name):\n \"\"\"Sample parameter values from prior. Modifies the module's parameters in-place.\"\"\"\n if prior_name not in self._priors:\n raise RuntimeError(\"Unknown prior name '{}'\".format(prior_name))\n prior, _, setting_closure = self._priors[prior_name]\n if setting_closure is None:\n raise RuntimeError(\"Must provide inverse transform to be able to sample from prior.\")\n setting_closure(prior.sample())\n\n def update_added_loss_term(self, name, added_loss_term):\n from .mlls import AddedLossTerm\n\n if not isinstance(added_loss_term, AddedLossTerm):\n raise RuntimeError(\"added_loss_term must be a AddedLossTerm\")\n if name not in self._added_loss_terms.keys():\n raise RuntimeError(\"added_loss_term {} not registered\".format(name))\n self._added_loss_terms[name] = added_loss_term\n\n def variational_parameters(self):\n for _, param in self.named_variational_parameters():\n yield param\n\n def __getattr__(self, name):\n try:\n return super().__getattr__(name)\n except AttributeError as e:\n try:\n return super().__getattribute__(name)\n except AttributeError:\n raise e\n\n\ndef _validate_module_outputs(outputs):\n if isinstance(outputs, tuple):\n if not all(\n torch.is_tensor(output) or isinstance(output, Distribution) or isinstance(output, LazyTensor)\n for output in outputs\n ):\n raise RuntimeError(\n \"All outputs must be a Distribution, torch.Tensor, or LazyTensor. \"\n \"Got {}\".format([output.__class__.__name__ for output in outputs])\n )\n if len(outputs) == 1:\n outputs = outputs[0]\n return outputs\n elif torch.is_tensor(outputs) or isinstance(outputs, Distribution) or isinstance(outputs, LazyTensor):\n return outputs\n else:\n raise RuntimeError(\n \"Output must be a Distribution, torch.Tensor, or LazyTensor. Got {}\".format(outputs.__class__.__name__)\n )\n\n\ndef _extract_named_added_loss_terms(module, memo=None, prefix=\"\"):\n if memo is None:\n memo = set()\n if hasattr(module, \"_added_loss_terms\"):\n for name, strategy in module._added_loss_terms.items():\n if strategy is not None and strategy not in memo:\n memo.add(strategy)\n yield prefix + (\".\" if prefix else \"\") + name, strategy\n for mname, module_ in module.named_children():\n submodule_prefix = prefix + (\".\" if prefix else \"\") + mname\n for name, strategy in _extract_named_added_loss_terms(module=module_, memo=memo, prefix=submodule_prefix):\n yield name, strategy\n\n\ndef _extract_named_priors(module, memo=None, prefix=\"\"):\n if memo is None:\n memo = set()\n if hasattr(module, \"_priors\"):\n for name, (prior, closure, inv_closure) in module._priors.items():\n if prior is not None and prior not in memo:\n memo.add(prior)\n full_name = (\".\" if prefix else \"\").join([prefix, name])\n yield full_name, prior, closure, inv_closure\n for mname, module_ in module.named_children():\n submodule_prefix = prefix + (\".\" if prefix else \"\") + mname\n for name, prior, closure, inv_closure in _extract_named_priors(module_, memo=memo, prefix=submodule_prefix):\n yield name, prior, closure, inv_closure\n\n\ndef _extract_named_constraints(module, memo=None, prefix=\"\"):\n if memo is None:\n memo = set()\n if hasattr(module, \"_constraints\"):\n for name, constraint in module._constraints.items():\n if constraint is not None and constraint not in memo:\n memo.add(constraint)\n full_name = (\".\" if prefix else \"\").join([prefix, name])\n yield full_name, constraint\n for mname, module_ in module.named_children():\n submodule_prefix = prefix + (\".\" if prefix else \"\") + mname\n for name, constraint in _extract_named_constraints(module_, memo=memo, prefix=submodule_prefix):\n yield name, constraint\n" ]
[ [ "torch.Size", "torch.norm", "torch.zeros", "torch.tensor", "torch.cuda.is_available" ], [ "torch.cholesky", "torch.isnan" ], [ "torch.Size", "torch.norm", "torch.zeros", "torch.tensor", "torch.rand" ], [ "torch.as_tensor", "torch.is_tensor", "torch.equal", "torch.zeros" ], [ "torch.Size", "torch.cat" ], [ "torch.is_tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JamesFengi/handPose_Eric
[ "3e329181930ebc7ef0fed2abb9a9d092a8541f9c" ]
[ "lib/wyw2s_lib/make_facebank_tools/make_facebank.py" ]
[ "# make facebank\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport os\nimport torch\nfrom model import Backbone\nimport argparse\nfrom pathlib import Path\nfrom torchvision import transforms as trans\nfrom PIL import Image\nimport numpy as np\ndef prepare_facebank(path_images,facebank_path, model, mtcnn, device , tta = True):\n #\n test_transform_ = trans.Compose([\n trans.ToTensor(),\n trans.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n ])\n #\n model.eval()\n embeddings = []\n names = ['Unknown']\n idx = 0\n for path in path_images.iterdir():\n if path.is_file():\n continue\n else:\n idx += 1\n print(\"idx {} : {}\".format(idx,path))\n embs = []\n for file in path.iterdir():\n # print(file)\n if not file.is_file():\n continue\n else:\n\n try:\n # print(\"---------------------------\")\n img = Image.open(file)\n print(\" {}) {}\".format(idx,file))\n except:\n continue\n\n with torch.no_grad():\n if tta:\n mirror = trans.functional.hflip(img)\n emb = model(test_transform_(img).to(device).unsqueeze(0))\n emb_mirror = model(test_transform_(mirror).to(device).unsqueeze(0))\n embs.append(l2_norm(emb + emb_mirror))\n else:\n embs.append(model(test_transform_(img).to(device).unsqueeze(0)))\n if len(embs) == 0:\n continue\n embedding = torch.cat(embs).mean(0,keepdim=True)\n embeddings.append(embedding)\n names.append(path.name)\n embeddings = torch.cat(embeddings)\n names = np.array(names)\n torch.save(embeddings, facebank_path+'/facebank.pth')\n np.save(facebank_path + '/names', names)\n return embeddings, names\n\nif __name__ == '__main__':\n # 需要制作人脸库对应的 图片地址\n path_images = \"./images/\"\n\n\n # 定义模型\n device_ = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n model_ = Backbone(50, 1., \"ir_se\").to(device_)\n # 加载模型\n if os.access(\"./model_ir_se50.pth\",os.F_OK):\n model_.load_state_dict(torch.load(\"./model_ir_se50.pth\"))\n\n model_.eval()\n facebank_path = \"./facebank/\" # 人脸库对应地址\n targets, names = prepare_facebank(Path(path_images), facebank_path,model_, \"\" ,device_, tta = False) # 构建 人脸 底库\n" ]
[ [ "torch.cat", "torch.load", "numpy.save", "torch.no_grad", "torch.cuda.is_available", "numpy.array", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
firmai/universal-portfolios
[ "b1d99d6dbcf553582d399cf3851ac4ba35a93d3e" ]
[ "universal/algo.py" ]
[ "import sys\nimport numpy as np\nimport pandas as pd\nimport itertools\nimport logging\nimport inspect\nimport copy\nfrom .result import AlgoResult, ListResult\nfrom scipy.misc import comb\nfrom . import tools\n\n\nclass Algo(object):\n \"\"\" Base class for algorithm calculating weights for online portfolio.\n You have to subclass either step method to calculate weights sequentially\n or weights method, which does it at once. weights method might be useful\n for better performance when using matrix calculation, but be careful about\n look-ahead bias.\n\n Upper case letters stand for matrix and lower case for vectors (such as\n B and b for weights).\n \"\"\"\n\n # if true, replace missing values by last values\n REPLACE_MISSING = False\n\n # type of prices going into weights or step function\n # ratio: pt / pt-1\n # log: log(pt / pt-1)\n # raw: pt\n PRICE_TYPE = 'ratio'\n\n def __init__(self, min_history=None, frequency=1):\n \"\"\" Subclass to define algo specific parameters here.\n :param min_history: If not None, use initial weights for first min_window days. Use\n this if the algo needs some history for proper parameter estimation.\n :param frequency: algorithm should trade every `frequency` periods\n \"\"\"\n self.min_history = min_history or 0\n self.frequency = frequency\n\n def init_weights(self, m):\n \"\"\" Set initial weights.\n :param m: Number of assets.\n \"\"\"\n return np.zeros(m)\n\n def init_step(self, X):\n \"\"\" Called before step method. Use to initialize persistent variables.\n :param X: Entire stock returns history.\n \"\"\"\n pass\n\n def step(self, x, last_b, history):\n \"\"\" Calculate new portfolio weights. If history parameter is omited, step\n method gets passed just parameters `x` and `last_b`. This significantly\n increases performance.\n :param x: Last returns.\n :param last_b: Last weights.\n :param history: All returns up to now. You can omit this parameter to increase\n performance.\n \"\"\"\n raise NotImplementedError('Subclass must implement this!')\n\n def _use_history_step(self):\n \"\"\" Use history parameter in step method? \"\"\"\n step_args = inspect.getargspec(self.step)[0]\n return len(step_args) >= 4\n\n def weights(self, X, min_history=None, log_progress=True):\n \"\"\" Return weights. Call step method to update portfolio sequentially. Subclass\n this method only at your own risk. \"\"\"\n min_history = self.min_history if min_history is None else min_history\n\n # init\n B = X.copy() * 0.\n last_b = self.init_weights(X.shape[1])\n if isinstance(last_b, np.ndarray):\n last_b = pd.Series(last_b, X.columns)\n\n # use history in step method?\n use_history = self._use_history_step()\n\n # run algo\n self.init_step(X)\n for t, (_, x) in enumerate(X.iterrows()):\n # save weights\n B.ix[t] = last_b\n\n # keep initial weights for min_history\n if t < min_history:\n continue\n\n # trade each `frequency` periods\n if (t + 1) % self.frequency != 0:\n continue\n\n # predict for t+1\n if use_history:\n history = X.iloc[:t+1]\n last_b = self.step(x, last_b, history)\n else:\n last_b = self.step(x, last_b)\n\n # convert last_b to suitable format if needed\n if type(last_b) == np.matrix:\n # remove dimension\n last_b = np.squeeze(np.array(last_b))\n\n # show progress by 10 pcts\n if log_progress:\n tools.log_progress(t, len(X), by=10)\n\n return B\n\n def _split_index(self, ix, nr_chunks, freq):\n \"\"\" Split index into chunks so that each chunk except of the last has length\n divisible by freq. \"\"\"\n chunksize = int(len(ix) / freq / nr_chunks + 1) * freq\n return [ix[i*chunksize:(i+1)*chunksize] for i in range(len(ix) / chunksize + 1)]\n\n def run(self, S, n_jobs=1, log_progress=True):\n \"\"\" Run algorithm and get weights.\n :params S: Absolute stock prices. DataFrame with stocks in columns.\n :param show_progress: Log computation progress. Works only for algos with\n defined step method.\n :param n_jobs: run step method in parallel (step method can't depend on last weights)\n \"\"\"\n if log_progress:\n logging.debug('Running {}...'.format(self.__class__.__name__))\n\n if isinstance(S, ListResult):\n P = S.to_dataframe()\n else:\n P = S\n\n # convert prices to proper format\n X = self._convert_prices(P, self.PRICE_TYPE, self.REPLACE_MISSING)\n\n # get weights\n if n_jobs == 1:\n try:\n B = self.weights(X, log_progress=log_progress)\n except TypeError: # weights are missing log_progress parameter\n B = self.weights(X)\n else:\n with tools.mp_pool(n_jobs) as pool:\n ix_blocks = self._split_index(X.index, pool._processes * 2, self.frequency)\n min_histories = np.maximum(np.cumsum([0] + map(len, ix_blocks[:-1])) - 1, self.min_history)\n\n B_blocks = pool.map(_parallel_weights, [(self, X.ix[:ix_block[-1]], min_history, log_progress)\n for ix_block, min_history in zip(ix_blocks, min_histories)])\n\n # join weights to one dataframe\n B = pd.concat([B_blocks[i].ix[ix] for i, ix in enumerate(ix_blocks)])\n\n # cast to dataframe if weights return numpy array\n if not isinstance(B, pd.DataFrame):\n B = pd.DataFrame(B, index=P.index, columns=P.columns)\n\n if log_progress:\n logging.debug('{} finished successfully.'.format(self.__class__.__name__))\n\n # if we are aggregating strategies, combine weights from strategies\n # and use original assets\n if isinstance(S, ListResult):\n B = sum(result.B.mul(B[col], axis=0) for result, col in zip(S, B.columns))\n return AlgoResult(S[0].X, B)\n else:\n return AlgoResult(self._convert_prices(S, 'ratio'), B)\n\n def next_weights(self, S, last_b, **kwargs):\n \"\"\" Calculate weights for next day. \"\"\"\n # use history in step method?\n use_history = self._use_history_step()\n history = self._convert_prices(S, self.PRICE_TYPE, self.REPLACE_MISSING)\n x = history.iloc[-1]\n\n if use_history:\n b = self.step(x, last_b, history, **kwargs)\n else:\n b = self.step(x, last_b, **kwargs)\n return pd.Series(b, index=S.columns)\n\n def run_subsets(self, S, r, generator=False):\n \"\"\" Run algorithm on all stock subsets of length r. Note that number of such tests can be\n very large.\n :param S: stock prices\n :param r: number of stocks in a subset\n :param generator: yield results\n \"\"\"\n def subset_generator():\n total_subsets = comb(S.shape[1], r)\n\n for i, S_sub in enumerate(tools.combinations(S, r)):\n # run algorithm on given subset\n result = self.run(S_sub, log_progress=False)\n name = ', '.join(S_sub.columns.astype(str))\n\n # log progress by 1 pcts\n tools.log_progress(i, total_subsets, by=1)\n\n yield result, name\n raise StopIteration\n\n if generator:\n return subset_generator()\n else:\n results = []\n names = []\n for result, name in subset_generator():\n results.append(result)\n names.append(name)\n return ListResult(results, names)\n\n @classmethod\n def _convert_prices(self, S, method, replace_missing=False):\n \"\"\" Convert prices to format suitable for weight or step function.\n Available price types are:\n ratio: pt / pt_1\n log: log(pt / pt_1)\n raw: pt (normalized to start with 1)\n \"\"\"\n if method == 'raw':\n # normalize prices so that they start with 1.\n r = {}\n for name, s in S.iteritems():\n init_val = s.ix[s.first_valid_index()]\n r[name] = s / init_val\n X = pd.DataFrame(r)\n\n if replace_missing:\n X.ix[0] = 1.\n X = X.fillna(method='ffill')\n\n return X\n\n elif method == 'absolute':\n return S\n\n elif method in ('ratio', 'log'):\n # be careful about NaN values\n X = S / S.shift(1).fillna(method='ffill')\n for name, s in X.iteritems():\n X[name].iloc[s.index.get_loc(s.first_valid_index()) - 1] = 1.\n\n if replace_missing:\n X = X.fillna(1.)\n\n return np.log(X) if method == 'log' else X\n\n else:\n raise ValueError('invalid price conversion method')\n\n @classmethod\n def run_combination(cls, S, **kwargs):\n \"\"\" Get equity of algo using all combinations of parameters. All\n values in lists specified in kwargs will be optimized. Other types\n will be passed as they are to algo __init__ (like numbers, strings,\n tuples).\n Return ListResult object, which is basically a wrapper of list of AlgoResult objects.\n It is possible to pass ListResult to Algo or run_combination again\n to get AlgoResult. This is useful for chaining of Algos.\n\n Example:\n S = ...load data...\n list_results = Anticor.run_combination(S, alpha=[0.01, 0.1, 1.])\n result = CRP().run(list_results)\n\n :param S: Stock prices.\n :param kwargs: Additional arguments to algo.\n :param n_jobs: Use multiprocessing (-1 = use all cores). Use all cores by default.\n \"\"\"\n if isinstance(S, ListResult):\n S = S.to_dataframe()\n\n n_jobs = kwargs.pop('n_jobs', -1)\n\n # extract simple parameters\n simple_params = {k: kwargs.pop(k) for k, v in kwargs.items()\n if not isinstance(v, list)}\n\n # iterate over all combinations\n names = []\n params_to_try = []\n for seq in itertools.product(*kwargs.values()):\n params = dict(zip(kwargs.keys(), seq))\n\n # run algo\n all_params = dict(params.items() + simple_params.items())\n params_to_try.append(all_params)\n\n # create name with format param:value\n name = ','.join([str(k) + '=' + str(v) for k, v in params.items()])\n names.append(name)\n\n # try all combinations in parallel\n with tools.mp_pool(n_jobs) as pool:\n results = pool.map(_run_algo_params, [(S, cls, all_params) for all_params in params_to_try])\n results = map(_run_algo_params, [(S, cls, all_params) for all_params in params_to_try])\n\n return ListResult(results, names)\n\n def copy(self):\n return copy.deepcopy(self)\n\n\ndef _parallel_weights(tuple_args):\n self, X, min_history, log_progress = tuple_args\n try:\n return self.weights(X, min_history=min_history, log_progress=log_progress)\n except TypeError: # weights are missing log_progress parameter\n return self.weights(X, min_history=min_history)\n\n\ndef _run_algo_params(tuple_args):\n S, cls, params = tuple_args\n logging.debug('Run combination of parameters: {}'.format(params))\n return cls(**params).run(S)\n" ]
[ [ "numpy.log", "pandas.Series", "pandas.DataFrame", "numpy.array", "numpy.zeros", "scipy.misc.comb" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [ "0.13", "0.14", "0.15", "0.19", "0.18", "1.2", "0.12", "1.0", "0.17", "0.16" ], "tensorflow": [] } ]
Pandinosaurus/RandPerson
[ "1c6e935d64d8210ee4cddbf803da054016090675" ]
[ "trainCode/Source/reid/models/resmap.py" ]
[ "from __future__ import absolute_import\n\nfrom torch import nn\nimport torchvision\n\nfea_dims_small = {'layer2': 128, 'layer3': 256, 'layer4': 512}\nfea_dims = {'layer2': 512, 'layer3': 1024, 'layer4': 2048}\n\n\nclass ResNet(nn.Module):\n __factory = {\n 18: torchvision.models.resnet18,\n 34: torchvision.models.resnet34,\n 50: torchvision.models.resnet50,\n 101: torchvision.models.resnet101,\n 152: torchvision.models.resnet152,\n }\n\n def __init__(self, depth, final_layer='layer3', neck=128, pretrained=True):\n super(ResNet, self).__init__()\n\n self.depth = depth\n self.final_layer = final_layer\n self.neck = neck\n self.pretrained = pretrained\n\n # Construct base (pretrained) resnet\n if depth not in ResNet.__factory:\n raise KeyError(\"Unsupported depth:\", depth)\n self.base = ResNet.__factory[depth](pretrained=pretrained)\n\n if depth < 50:\n out_planes = fea_dims_small[final_layer]\n else:\n out_planes = fea_dims[final_layer]\n\n if neck > 0:\n self.neck_conv = nn.Conv2d(out_planes, neck, kernel_size=3, padding=1, bias=False)\n out_planes = neck\n self.neck_bn = nn.BatchNorm2d(out_planes)\n\n self.num_features = out_planes\n\n def forward(self, inputs):\n x = inputs\n for name, module in self.base._modules.items():\n x = module(x)\n if name == self.final_layer:\n break\n\n if self.neck > 0:\n x = self.neck_conv(x)\n x = self.neck_bn(x)\n\n return x\n\n\ndef resnet18(**kwargs):\n return ResNet(18, **kwargs)\n\n\ndef resnet34(**kwargs):\n return ResNet(34, **kwargs)\n\n\ndef resnet50(**kwargs):\n return ResNet(50, **kwargs)\n\n\ndef resnet101(**kwargs):\n return ResNet(101, **kwargs)\n\n\ndef resnet152(**kwargs):\n return ResNet(152, **kwargs)\n\n\n__factory = {\n 'resnet18': resnet18,\n 'resnet34': resnet34,\n 'resnet50': resnet50,\n 'resnet101': resnet101,\n 'resnet152': resnet152,\n}\n\n\ndef names():\n return sorted(__factory.keys())\n\n\ndef create(name, *args, **kwargs):\n \"\"\"\n Create a model instance.\n\n Parameters\n ----------\n name : str\n Model name. Can be one of 'inception', 'resnet18', 'resnet34',\n 'resnet50', 'resnet101', and 'resnet152'.\n pretrained : bool, optional\n Only applied for 'resnet*' models. If True, will use ImageNet pretrained\n model. Default: True\n cut_at_pooling : bool, optional\n If True, will cut the model before the last global pooling layer and\n ignore the remaining kwargs. Default: False\n num_features : int, optional\n If positive, will append a Linear layer after the global pooling layer,\n with this number of output units, followed by a BatchNorm layer.\n Otherwise these layers will not be appended. Default: 256 for\n 'inception', 0 for 'resnet*'\n norm : bool, optional\n If True, will normalize the feature to be unit L2-norm for each sample.\n Otherwise will append a ReLU layer after the above Linear layer if\n num_features > 0. Default: False\n dropout : float, optional\n If positive, will append a Dropout layer with this dropout rate.\n Default: 0\n num_classes : int, optional\n If positive, will append a Linear layer at the end as the classifier\n with this number of output units. Default: 0\n \"\"\"\n if name not in __factory:\n raise KeyError(\"Unknown model:\", name)\n return __factory[name](*args, **kwargs)\n" ]
[ [ "torch.nn.Conv2d", "torch.nn.BatchNorm2d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wanirepo/Neurosynth
[ "5b770ec31c5095c16e27ebe664fa5d515c662298" ]
[ "neurosynth/analysis/reduce.py" ]
[ "import numpy as np\n\n\"\"\" Dimensional/data reduction methods. \"\"\"\n\ndef average_within_regions(dataset, img, threshold=None, remove_zero=True):\n \"\"\" Averages over all voxels within each ROI in the input image.\n\n Takes a Dataset and a Nifti image that defines distinct regions, and \n returns a numpy matrix of ROIs x mappables, where the value at each ROI is \n the proportion of active voxels in that ROI. Each distinct ROI must have a \n unique value in the image; non-contiguous voxels with the same value will \n be assigned to the same ROI.\n\n Args:\n dataset: A Dataset instance\n img: A NIFTI or Analyze-format image that provides the ROI definitions\n threshold: An optional float in the range of 0 - 1. If passed, the array \n will be binarized, with ROI values above the threshold assigned to True \n and values below the threshold assigned to False. (E.g., if threshold = \n 0.05, only ROIs in which more than 5% of voxels are active will be \n considered active.).\n remove_zero: An optional boolean; when True, assume that voxels with value \n of 0 should not be considered as a separate ROI, and will be ignored. \n\n Returns:\n If replace == True, nothing is returned (the Dataset is modified in-place).\n Otherwise, returns a 2D numpy array with ROIs in rows and mappables in columns.\n \"\"\"\n regions = dataset.volume.mask(img)\n labels = np.unique(regions)\n if remove_zero: labels = labels[np.nonzero(labels)]\n n_regions = labels.size\n m = np.zeros((regions.size, n_regions))\n for i in range(n_regions):\n m[regions==labels[i],i] = 1.0/np.sum(regions==labels[i])\n # produces roi x study matrix\n result = np.transpose(m) * dataset.get_image_data(ids=None, dense=False)\n if threshold is not None:\n result[result < threshold] = 0.0\n result = result.astype(bool)\n return result\n\ndef get_random_voxels(dataset, n_voxels):\n \"\"\" Returns mappable data for a random subset of voxels.\n\n May be useful as a baseline in predictive analyses--e.g., to compare performance \n of a more principled feature selection method with simple random selection.\n\n Args:\n dataset: A Dataset instance\n n_voxels: An integer specifying the number of random voxels to select.\n\n Returns:\n A 2D numpy array with (randomly-selected) voxels in rows and mappables in columns.\n \"\"\"\n voxels = np.range(dataset.volume.num_vox_in_mask)\n selected = np.random.shuffle(voxels)[0:n_voxels]\n return dataset.get_image_data(voxels=selected)\n" ]
[ [ "numpy.range", "numpy.nonzero", "numpy.unique", "numpy.random.shuffle", "numpy.transpose", "numpy.zeros", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jdey4/progressive-learning
[ "410b3525ab63e1f7c32e9838460b2c9af7b9d256", "410b3525ab63e1f7c32e9838460b2c9af7b9d256", "410b3525ab63e1f7c32e9838460b2c9af7b9d256", "410b3525ab63e1f7c32e9838460b2c9af7b9d256" ]
[ "replaying/test.py", "src/lifelong_dnn.py", "replaying/plot_parity.py", "experiments/xor_rxor_spiral_exp/main_fig_plot.py" ]
[ "#%%\nimport random\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport tensorflow.keras as keras\nimport seaborn as sns \n\nimport numpy as np\nimport pickle\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom math import log2, ceil \n\nimport sys\n#sys.path.append(\"../src/\")\nsys.path.append(\"../src_sampling/\")\nfrom lifelong_dnn import LifeLongDNN\nfrom joblib import Parallel, delayed\n\n#%%\ndef unpickle(file):\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\ndef get_colors(colors, inds):\n c = [colors[i] for i in inds]\n return c\n\ndef generate_2d_rotation(theta=0, acorn=None):\n if acorn is not None:\n np.random.seed(acorn)\n \n R = np.array([\n [np.cos(theta), np.sin(theta)],\n [-np.sin(theta), np.cos(theta)]\n ])\n \n return R\n\n\ndef generate_gaussian_parity(n, mean=np.array([-1, -1]), cov_scale=1, angle_params=None, k=1, acorn=None):\n if acorn is not None:\n np.random.seed(acorn)\n \n d = len(mean)\n \n if mean[0] == -1 and mean[1] == -1:\n mean = mean + 1 / 2**k\n \n mnt = np.random.multinomial(n, 1/(4**k) * np.ones(4**k))\n cumsum = np.cumsum(mnt)\n cumsum = np.concatenate(([0], cumsum))\n \n Y = np.zeros(n)\n X = np.zeros((n, d))\n \n for i in range(2**k):\n for j in range(2**k):\n temp = np.random.multivariate_normal(mean, cov_scale * np.eye(d), \n size=mnt[i*(2**k) + j])\n temp[:, 0] += i*(1/2**(k-1))\n temp[:, 1] += j*(1/2**(k-1))\n \n X[cumsum[i*(2**k) + j]:cumsum[i*(2**k) + j + 1]] = temp\n \n if i % 2 == j % 2:\n Y[cumsum[i*(2**k) + j]:cumsum[i*(2**k) + j + 1]] = 0\n else:\n Y[cumsum[i*(2**k) + j]:cumsum[i*(2**k) + j + 1]] = 1\n \n if d == 2:\n if angle_params is None:\n angle_params = np.random.uniform(0, 2*np.pi)\n \n R = generate_2d_rotation(angle_params)\n X = X @ R\n \n else:\n raise ValueError('d=%i not implemented!'%(d))\n \n return X, Y.astype(int)\n\n\n#%%\ndef experiment(n_xor, n_nxor, n_test, reps, n_trees, max_depth, acorn=None):\n #print(1)\n if n_xor==0 and n_nxor==0:\n raise ValueError('Wake up and provide samples to train!!!')\n \n if acorn != None:\n np.random.seed(acorn)\n \n errors = np.zeros((reps,4),dtype=float)\n \n for i in range(reps):\n l2f = LifeLongDNN(parallel=False)\n uf1 = LifeLongDNN(parallel=False)\n uf2 = LifeLongDNN(parallel=False)\n #source data\n xor, label_xor = generate_gaussian_parity(n_xor,cov_scale=0.1,angle_params=0)\n test_xor, test_label_xor = generate_gaussian_parity(n_test,cov_scale=0.1,angle_params=0)\n\n '''min_xor = np.min(xor)\n xor = (xor - min_xor)\n max_xor = np.max(xor)\n xor = xor/max_xor\n test_xor = (test_xor-min_xor)/max_xor'''\n #target data\n if n_nxor!=0:\n nxor, label_nxor = generate_gaussian_parity(n_nxor,cov_scale=0.1,angle_params=np.pi/2)\n test_nxor, test_label_nxor = generate_gaussian_parity(n_test,cov_scale=0.1,angle_params=np.pi/2)\n\n '''min_nxor = np.min(nxor)\n nxor = (nxor - min_nxor)\n max_nxor = np.max(nxor)\n nxor = nxor/max_nxor\n test_nxor = (test_nxor-min_nxor)/max_nxor'''\n\n if n_xor == 0:\n l2f.new_forest(nxor, label_nxor, n_estimators=n_trees,max_depth=max_depth)\n \n errors[i,0] = 0.5\n errors[i,1] = 0.5\n \n uf_task2=l2f.predict(test_nxor, representation=0, decider=0)\n l2f_task2=l2f.predict(test_nxor, representation='all', decider=0)\n \n errors[i,2] = 1 - np.sum(uf_task2 == test_label_nxor)/n_test\n errors[i,3] = 1 - np.sum(l2f_task2 == test_label_nxor)/n_test\n elif n_nxor == 0:\n l2f.new_forest(xor, label_xor, n_estimators=n_trees,max_depth=max_depth)\n \n uf_task1=l2f.predict(test_xor, representation=0, decider=0)\n l2f_task1=l2f.predict(test_xor, representation='all', decider=0)\n \n errors[i,0] = 1 - np.sum(uf_task1 == test_label_xor)/n_test\n errors[i,1] = 1 - np.sum(l2f_task1 == test_label_xor)/n_test\n errors[i,2] = 0.5\n errors[i,3] = 0.5\n else:\n l2f.new_forest(xor, label_xor, n_estimators=n_trees,max_depth=max_depth)\n\n delta = .001\n #sample the grid\n x = np.arange(-1,1,step=delta)\n y = np.arange(-1,1,step=delta)\n x,y = np.meshgrid(x,y)\n sample = np.concatenate(\n (\n x.reshape(-1,1),\n y.reshape(-1,1)\n ),\n axis=1\n )\n #sample_label = l2f.predict(sample, representation=0,decider=0)\n sample_label = l2f._estimate_posteriors(sample, representation='all', decider=0)\n l2f.X_across_tasks[0] = sample\n l2f.y_across_tasks[0] = sample_label\n ############################\n\n l2f.new_forest(nxor, label_nxor, n_estimators=n_trees,max_depth=max_depth)\n \n uf1.new_forest(xor, label_xor, n_estimators=n_trees,max_depth=max_depth)\n uf2.new_forest(nxor, label_nxor, n_estimators=n_trees,max_depth=max_depth)\n\n uf_task1=uf1.predict(test_xor, representation=0, decider=0)\n l2f_task1=l2f.predict(test_xor, representation='all', decider=0)\n uf_task2=uf2.predict(test_nxor, representation=0, decider=0)\n l2f_task2=l2f.predict(test_nxor, representation='all', decider=1)\n \n errors[i,0] = 1 - np.sum(uf_task1 == test_label_xor)/n_test\n errors[i,1] = 1 - np.sum(l2f_task1 == test_label_xor)/n_test\n errors[i,2] = 1 - np.sum(uf_task2 == test_label_nxor)/n_test\n errors[i,3] = 1 - np.sum(l2f_task2 == test_label_nxor)/n_test\n\n return np.mean(errors,axis=0)\n\n#%%\nmc_rep = 1000\nn_test = 1000\nn_trees = 10\nn_xor = (100*np.arange(0.5, 7.25, step=0.25)).astype(int)\nn_nxor = (100*np.arange(0.5, 7.5, step=0.25)).astype(int)\n\nmean_error = np.zeros((4, len(n_xor)+len(n_nxor)))\nstd_error = np.zeros((4, len(n_xor)+len(n_nxor)))\n\nmean_te = np.zeros((2, len(n_xor)+len(n_nxor)))\nstd_te = np.zeros((2, len(n_xor)+len(n_nxor)))\n\nfor i,n1 in enumerate(n_xor):\n print('starting to compute %s xor\\n'%n1)\n error = np.array(\n Parallel(n_jobs=-1,verbose=1)(\n delayed(experiment)(n1,0,n_test,1,n_trees=n_trees,max_depth=200) for _ in range(mc_rep)\n )\n )\n mean_error[:,i] = np.mean(error,axis=0)\n std_error[:,i] = np.std(error,ddof=1,axis=0)\n mean_te[0,i] = np.mean(error[:,0]/error[:,1])\n mean_te[1,i] = np.mean(error[:,2]/error[:,3])\n std_te[0,i] = np.std(error[:,0]/error[:,1],ddof=1)\n std_te[1,i] = np.std(error[:,2]/error[:,3],ddof=1)\n \n if n1==n_xor[-1]:\n for j,n2 in enumerate(n_nxor):\n print('starting to compute %s nxor\\n'%n2)\n \n error = np.array(\n Parallel(n_jobs=-1,verbose=1)(\n delayed(experiment)(n1,n2,n_test,1,n_trees=n_trees,max_depth=200) for _ in range(mc_rep)\n )\n )\n mean_error[:,i+j+1] = np.mean(error,axis=0)\n std_error[:,i+j+1] = np.std(error,ddof=1,axis=0)\n mean_te[0,i+j+1] = np.mean(error[:,0]/error[:,1])\n mean_te[1,i+j+1] = np.mean(error[:,2]/error[:,3])\n std_te[0,i+j+1] = np.std(error[:,0]/error[:,1],ddof=1)\n std_te[1,i+j+1] = np.std(error[:,2]/error[:,3],ddof=1)\n \nwith open('./result/mean_xor_nxor.pickle','wb') as f:\n pickle.dump(mean_error,f)\n \nwith open('./result/std_xor_nxor.pickle','wb') as f:\n pickle.dump(std_error,f)\n \nwith open('./result/mean_te_xor_nxor.pickle','wb') as f:\n pickle.dump(mean_te,f)\n \nwith open('./result/std_te_xor_nxor.pickle','wb') as f:\n pickle.dump(std_te,f)\n\n#%% Plotting the result\n#mc_rep = 50\nmean_error = unpickle('result/mean_xor_nxor.pickle')\nstd_error = unpickle('result/std_xor_nxor.pickle')\n\nn_xor = (100*np.arange(0.5, 7.25, step=0.25)).astype(int)\nn_nxor = (100*np.arange(0.5, 7.5, step=0.25)).astype(int)\n\nn1s = n_xor\nn2s = n_nxor\n\nns = np.concatenate((n1s, n2s + n1s[-1]))\nls=['-', '--']\nalgorithms = ['Uncertainty Forest', 'Lifelong Forest']\n\n\nTASK1='XOR'\nTASK2='N-XOR'\n\nfontsize=30\nlabelsize=28\n\ncolors = sns.color_palette(\"Set1\", n_colors = 2)\n\nfig = plt.figure(constrained_layout=True,figsize=(21,14))\ngs = fig.add_gridspec(14, 21)\nax1 = fig.add_subplot(gs[7:,:6])\n# for i, algo in enumerate(algorithms):\nax1.plot(ns, mean_error[0], label=algorithms[0], c=colors[1], ls=ls[np.sum(0 > 1).astype(int)], lw=3)\n#ax1.fill_between(ns, \n# mean_error[0] + 1.96*std_error[0], \n# mean_error[0] - 1.96*std_error[0], \n# where=mean_error[0] + 1.96*std_error[0] >= mean_error[0] - 1.96*std_error[0], \n# facecolor=colors[1], \n# alpha=0.15,\n# interpolate=True)\n\nax1.plot(ns, mean_error[1], label=algorithms[1], c=colors[0], ls=ls[np.sum(1 > 1).astype(int)], lw=3)\n#ax1.fill_between(ns, \n# mean_error[1] + 1.96*std_error[1, ], \n# mean_error[1] - 1.96*std_error[1, ], \n# where=mean_error[1] + 1.96*std_error[1] >= mean_error[1] - 1.96*std_error[1], \n# facecolor=colors[0], \n# alpha=0.15,\n# interpolate=True)\n\nax1.set_ylabel('Generalization Error (%s)'%(TASK1), fontsize=fontsize)\nax1.legend(loc='upper right', fontsize=20, frameon=False)\nax1.set_ylim(0.1, 0.21)\nax1.set_xlabel('Total Sample Size', fontsize=fontsize)\nax1.tick_params(labelsize=labelsize)\nax1.set_yticks([0.15, 0.2])\nax1.set_xticks([250,750, 1500])\nax1.axvline(x=750, c='gray', linewidth=1.5, linestyle=\"dashed\")\nax1.set_title('XOR', fontsize=30)\n\nright_side = ax1.spines[\"right\"]\nright_side.set_visible(False)\ntop_side = ax1.spines[\"top\"]\ntop_side.set_visible(False)\n\nax1.text(250, np.mean(ax1.get_ylim()), \"%s\"%(TASK1), fontsize=26)\nax1.text(900, np.mean(ax1.get_ylim()), \"%s\"%(TASK2), fontsize=26)\n\n#plt.tight_layout()\n\n#plt.savefig('./result/figs/generalization_error_xor.pdf',dpi=500)\n\n#####\nmean_error = unpickle('result/mean_xor_nxor.pickle')\nstd_error = unpickle('result/std_xor_nxor.pickle')\n\nalgorithms = ['Uncertainty Forest', 'Lifelong Forest']\n\nTASK1='XOR'\nTASK2='N-XOR'\n\nax1 = fig.add_subplot(gs[7:,7:13])\n# for i, algo in enumerate(algorithms):\nax1.plot(ns[len(n1s):], mean_error[2, len(n1s):], label=algorithms[0], c=colors[1], ls=ls[1], lw=3)\n#ax1.fill_between(ns[len(n1s):], \n# mean_error[2, len(n1s):] + 1.96*std_error[2, len(n1s):], \n# mean_error[2, len(n1s):] - 1.96*std_error[2, len(n1s):], \n# where=mean_error[2, len(n1s):] + 1.96*std_error[2, len(n1s):] >= mean_error[2, len(n1s):] - 1.96*std_error[2, len(n1s):], \n# facecolor=colors[1], \n# alpha=0.15,\n# interpolate=True)\n\nax1.plot(ns[len(n1s):], mean_error[3, len(n1s):], label=algorithms[1], c=colors[0], ls=ls[1], lw=3)\n#ax1.fill_between(ns[len(n1s):], \n# mean_error[3, len(n1s):] + 1.96*std_error[3, len(n1s):], \n# mean_error[3, len(n1s):] - 1.96*std_error[3, len(n1s):], \n# where=mean_error[3, len(n1s):] + 1.96*std_error[3, len(n1s):] >= mean_error[3, len(n1s):] - 1.96*std_error[3, len(n1s):], \n# facecolor=colors[0], \n# alpha=0.15,\n# interpolate=True)\n\nax1.set_ylabel('Generalization Error (%s)'%(TASK2), fontsize=fontsize)\nax1.legend(loc='upper right', fontsize=20, frameon=False)\n# ax1.set_ylim(-0.01, 0.22)\nax1.set_xlabel('Total Sample Size', fontsize=fontsize)\nax1.tick_params(labelsize=labelsize)\n# ax1.set_yticks([0.15, 0.25, 0.35])\nax1.set_yticks([0.15, 0.2])\nax1.set_xticks([250,750, 1500])\nax1.axvline(x=750, c='gray', linewidth=1.5, linestyle=\"dashed\")\n\nax1.set_ylim(0.11, 0.21)\n\nax1.set_xlim(-10)\nright_side = ax1.spines[\"right\"]\nright_side.set_visible(False)\ntop_side = ax1.spines[\"top\"]\ntop_side.set_visible(False)\n\n# ax1.set_ylim(0.14, 0.36)\nax1.text(250, np.mean(ax1.get_ylim()), \"%s\"%(TASK1), fontsize=26)\nax1.text(900, np.mean(ax1.get_ylim()), \"%s\"%(TASK2), fontsize=26)\n\nax1.set_title('N-XOR', fontsize=30)\n#plt.tight_layout()\n\n#plt.savefig('./result/figs/generalization_error_nxor.pdf',dpi=500)\n\n#####\nmean_error = unpickle('result/mean_te_xor_nxor.pickle')\nstd_error = unpickle('result/std_te_xor_nxor.pickle')\n\nalgorithms = ['Backward Transfer', 'Forward Transfer']\n\nTASK1='XOR'\nTASK2='N-XOR'\n\nax1 = fig.add_subplot(gs[7:,14:])\n\nax1.plot(ns, mean_error[0], label=algorithms[0], c=colors[0], ls=ls[0], lw=3)\n#ax1.fill_between(ns, \n# mean_error[0] + 1.96*std_error[0], \n# mean_error[0] - 1.96*std_error[0], \n# where=mean_error[1] + 1.96*std_error[0] >= mean_error[0] - 1.96*std_error[0], \n# facecolor=colors[0], \n# alpha=0.15,\n# interpolate=True)\n\nax1.plot(ns[len(n1s):], mean_error[1, len(n1s):], label=algorithms[1], c=colors[0], ls=ls[1], lw=3)\n#ax1.fill_between(ns[len(n1s):], \n# mean_error[1, len(n1s):] + 1.96*std_error[1, len(n1s):], \n# mean_error[1, len(n1s):] - 1.96*std_error[1, len(n1s):], \n# where=mean_error[1, len(n1s):] + 1.96*std_error[1, len(n1s):] >= mean_error[1, len(n1s):] - 1.96*std_error[1, len(n1s):], \n# facecolor=colors[0], \n# alpha=0.15,\n# interpolate=True)\n\nax1.set_ylabel('Transfer Efficiency', fontsize=fontsize)\nax1.legend(loc='upper right', fontsize=20, frameon=False)\nax1.set_ylim(.99, 1.4)\nax1.set_xlabel('Total Sample Size', fontsize=fontsize)\nax1.tick_params(labelsize=labelsize)\nax1.set_yticks([1,1.2,1.4])\nax1.set_xticks([250,750, 1500])\nax1.axvline(x=750, c='gray', linewidth=1.5, linestyle=\"dashed\")\nright_side = ax1.spines[\"right\"]\nright_side.set_visible(False)\ntop_side = ax1.spines[\"top\"]\ntop_side.set_visible(False)\nax1.hlines(1, 50,1500, colors='gray', linestyles='dashed',linewidth=1.5)\n\nax1.text(250, np.mean(ax1.get_ylim()), \"%s\"%(TASK1), fontsize=26)\nax1.text(900, np.mean(ax1.get_ylim()), \"%s\"%(TASK2), fontsize=26)\n\n#plt.tight_layout()\n\n#plt.savefig('./result/figs/TE.pdf',dpi=500)\n\n#####\ncolors = sns.color_palette('Dark2', n_colors=2)\n\nX, Y = generate_gaussian_parity(750, cov_scale=0.1, angle_params=0)\nZ, W = generate_gaussian_parity(750, cov_scale=0.1, angle_params=np.pi/2)\n\nax = fig.add_subplot(gs[:6,4:10])\nax.scatter(X[:, 0], X[:, 1], c=get_colors(colors, Y), s=50)\n\nax.set_xticks([])\nax.set_yticks([])\nax.set_title('Gaussian XOR', fontsize=30)\n\nplt.tight_layout()\nax.axis('off')\n#plt.savefig('./result/figs/gaussian-xor.pdf')\n\n###\ncolors = sns.color_palette('Dark2', n_colors=2)\n\nax = fig.add_subplot(gs[:6,11:16])\nax.scatter(Z[:, 0], Z[:, 1], c=get_colors(colors, W), s=50)\n\nax.set_xticks([])\nax.set_yticks([])\nax.set_title('Gaussian N-XOR', fontsize=30)\nax.axis('off')\n#plt.tight_layout()\nplt.savefig('./result/figs/xor_nxor_exp_sampling.pdf')\n\n# %%\n", "'''\nPrimary Author: Will LeVine\nEmail: [email protected]\n'''\n\nfrom sklearn.base import clone \n\nimport numpy as np\n\nfrom joblib import Parallel, delayed\n\nclass LifeLongDNN():\n def __init__(self, acorn = None, verbose = False, model = \"uf\", parallel = True, n_jobs = None):\n self.X_across_tasks = []\n self.y_across_tasks = []\n \n self.transformers_across_tasks = []\n \n #element [i, j] votes on decider from task i under representation from task j\n self.voters_across_tasks_matrix = []\n self.n_tasks = 0\n \n self.classes_across_tasks = []\n \n if acorn is not None:\n np.random.seed(acorn)\n \n self.verbose = verbose\n \n self.model = model\n \n self.parallel = parallel\n \n self.n_jobs = n_jobs\n \n def check_task_idx_(self, task_idx):\n if task_idx >= self.n_tasks:\n raise Exception(\"Invalid Task IDX\")\n \n def new_forest(self, \n X, \n y, \n epochs = 100, \n lr = 5e-4, \n n_estimators = 100, \n max_samples = .63,\n bootstrap = False,\n max_depth = 30,\n min_samples_leaf = 1,\n acorn = None,\n parallel = False,\n n_jobs = None):\n \n if self.model == \"dnn\":\n from honest_dnn import HonestDNN \n if self.model == \"uf\":\n from uncertainty_forest import UncertaintyForest\n \n self.X_across_tasks.append(X)\n self.y_across_tasks.append(y)\n \n if self.model == \"dnn\":\n new_honest_dnn = HonestDNN(verbose = self.verbose)\n new_honest_dnn.fit(X, y, epochs = epochs, lr = lr)\n if self.model == \"uf\":\n new_honest_dnn = UncertaintyForest(n_estimators = n_estimators,\n max_samples = max_samples,\n bootstrap = bootstrap,\n max_depth = max_depth,\n min_samples_leaf = min_samples_leaf,\n parallel = parallel,\n n_jobs = n_jobs)\n new_honest_dnn.fit(X, y)\n new_transformer = new_honest_dnn.get_transformer()\n new_voter = new_honest_dnn.get_voter()\n new_classes = new_honest_dnn.classes_\n \n self.transformers_across_tasks.append(new_transformer)\n self.classes_across_tasks.append(new_classes)\n \n #add one voter to previous task voter lists under the new transformation\n for task_idx in range(self.n_tasks):\n X_of_task, y_of_task = self.X_across_tasks[task_idx], self.y_across_tasks[task_idx]\n if self.model == \"dnn\":\n X_of_task_under_new_transform = new_transformer.predict(X_of_task) \n if self.model == \"uf\":\n X_of_task_under_new_transform = new_transformer(X_of_task) \n unfit_task_voter_under_new_transformation = clone(new_voter)\n if self.model == \"uf\":\n unfit_task_voter_under_new_transformation.classes_ = self.voters_across_tasks_matrix[task_idx][0].classes_\n task_voter_under_new_transformation = unfit_task_voter_under_new_transformation.fit(\n X_of_task_under_new_transform, \n y_of_task,\n tree_id_to_leaf_profile = new_voter.tree_id_to_leaf_profile\n )\n #print(task_voter_under_new_transformation.tree_id_to_leaf_profile,'hi\\n',task_voter_under_new_transformation.tree_idx_to_node_ids_to_posterior_map)\n self.voters_across_tasks_matrix[task_idx].append(task_voter_under_new_transformation)\n \n #add n_tasks voters to new task voter list under previous transformations \n new_voters_under_previous_task_transformation = []\n for task_idx in range(self.n_tasks):\n transformer_of_task = self.transformers_across_tasks[task_idx]\n if self.model == \"dnn\":\n X_under_task_transformation = transformer_of_task.predict(X)\n if self.model == \"uf\":\n X_under_task_transformation = transformer_of_task(X)\n unfit_new_task_voter_under_task_transformation = clone(self.voters_across_tasks_matrix[task_idx][task_idx])\n if self.model == \"uf\":\n unfit_new_task_voter_under_task_transformation.classes_ = new_voter.classes_\n new_task_voter_under_task_transformation = unfit_new_task_voter_under_task_transformation.fit(\n X_under_task_transformation,\n y,\n tree_id_to_leaf_profile = self.voters_across_tasks_matrix[task_idx][task_idx].tree_id_to_leaf_profile\n )\n new_voters_under_previous_task_transformation.append(new_task_voter_under_task_transformation)\n \n #make sure to add the voter of the new task under its own transformation\n new_voters_under_previous_task_transformation.append(new_voter)\n \n self.voters_across_tasks_matrix.append(new_voters_under_previous_task_transformation)\n \n self.n_tasks += 1\n \n def _estimate_posteriors(self, X, representation = 0, decider = 0):\n self.check_task_idx_(decider)\n \n if representation == \"all\":\n representation = range(self.n_tasks)\n elif isinstance(representation, int):\n representation = np.array([representation])\n \n def worker(transformer_task_idx):\n transformer = self.transformers_across_tasks[transformer_task_idx]\n voter = self.voters_across_tasks_matrix[decider][transformer_task_idx]\n if self.model == \"dnn\":\n return voter.predict_proba(transformer.predict(X))\n if self.model == \"uf\":\n return voter.predict_proba(transformer(X))\n \n if self.parallel:\n posteriors_across_tasks = np.array(\n Parallel(n_jobs=self.n_jobs if self.n_jobs != None else len(representation))(\n delayed(worker)(transformer_task_idx) for transformer_task_idx in representation\n )\n ) \n else:\n posteriors_across_tasks = np.array([worker(transformer_task_idx) for transformer_task_idx in representation]) \n \n return np.mean(posteriors_across_tasks, axis = 0)\n \n def predict(self, X, representation = 0, decider = 0):\n task_classes = self.classes_across_tasks[decider]\n return task_classes[np.argmax(self._estimate_posteriors(X, representation, decider), axis = -1)]\n \n", "#%%\nimport random\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport tensorflow.keras as keras\nimport seaborn as sns \n\nimport numpy as np\nimport pickle\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom math import log2, ceil \n\nimport sys\nsys.path.append(\"../src/\")\nfrom lifelong_dnn import LifeLongDNN\nfrom joblib import Parallel, delayed\n\n#%%\ndef unpickle(file):\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\ndef get_colors(colors, inds):\n c = [colors[i] for i in inds]\n return c\n\ndef generate_2d_rotation(theta=0, acorn=None):\n if acorn is not None:\n np.random.seed(acorn)\n \n R = np.array([\n [np.cos(theta), np.sin(theta)],\n [-np.sin(theta), np.cos(theta)]\n ])\n \n return R\n\n\ndef generate_gaussian_parity(n, mean=np.array([-1, -1]), cov_scale=1, angle_params=None, k=1, acorn=None):\n if acorn is not None:\n np.random.seed(acorn)\n \n d = len(mean)\n \n if mean[0] == -1 and mean[1] == -1:\n mean = mean + 1 / 2**k\n \n mnt = np.random.multinomial(n, 1/(4**k) * np.ones(4**k))\n cumsum = np.cumsum(mnt)\n cumsum = np.concatenate(([0], cumsum))\n \n Y = np.zeros(n)\n X = np.zeros((n, d))\n \n for i in range(2**k):\n for j in range(2**k):\n temp = np.random.multivariate_normal(mean, cov_scale * np.eye(d), \n size=mnt[i*(2**k) + j])\n temp[:, 0] += i*(1/2**(k-1))\n temp[:, 1] += j*(1/2**(k-1))\n \n X[cumsum[i*(2**k) + j]:cumsum[i*(2**k) + j + 1]] = temp\n \n if i % 2 == j % 2:\n Y[cumsum[i*(2**k) + j]:cumsum[i*(2**k) + j + 1]] = 0\n else:\n Y[cumsum[i*(2**k) + j]:cumsum[i*(2**k) + j + 1]] = 1\n \n if d == 2:\n if angle_params is None:\n angle_params = np.random.uniform(0, 2*np.pi)\n \n R = generate_2d_rotation(angle_params)\n X = X @ R\n \n else:\n raise ValueError('d=%i not implemented!'%(d))\n \n return X, Y.astype(int)\n\n#%% Plotting the result\n#mc_rep = 50\nmean_error = unpickle('result/mean_xor_nxor2.pickle')\nstd_error = unpickle('result/std_xor_nxor2.pickle')\n\nn_xor = (100*np.arange(0.5, 7.25, step=0.25)).astype(int)\nn_nxor = (100*np.arange(0.5, 7.50, step=0.25)).astype(int)\n\nn1s = n_xor\nn2s = n_nxor\n\nns = np.concatenate((n1s, n2s + n1s[-1]))\nls=['-', '--']\nalgorithms = ['Uncertainty Forest', 'Lifelong Forest']\n\n\nTASK1='XOR'\nTASK2='N-XOR'\n\nfontsize=30\nlabelsize=28\n\ncolors = sns.color_palette(\"Set1\", n_colors = 2)\n\nfig = plt.figure(constrained_layout=True,figsize=(21,14))\ngs = fig.add_gridspec(14, 21)\nax1 = fig.add_subplot(gs[7:,:6])\n# for i, algo in enumerate(algorithms):\nax1.plot(ns, mean_error[0], label=algorithms[0], c=colors[1], ls=ls[np.sum(0 > 1).astype(int)], lw=3)\n#ax1.fill_between(ns, \n# mean_error[0] + 1.96*std_error[0], \n# mean_error[0] - 1.96*std_error[0], \n# where=mean_error[0] + 1.96*std_error[0] >= mean_error[0] - 1.96*std_error[0], \n# facecolor=colors[1], \n# alpha=0.15,\n# interpolate=True)\n\nax1.plot(ns, mean_error[1], label=algorithms[1], c=colors[0], ls=ls[np.sum(1 > 1).astype(int)], lw=3)\n#ax1.fill_between(ns, \n# mean_error[1] + 1.96*std_error[1, ], \n# mean_error[1] - 1.96*std_error[1, ], \n# where=mean_error[1] + 1.96*std_error[1] >= mean_error[1] - 1.96*std_error[1], \n# facecolor=colors[0], \n# alpha=0.15,\n# interpolate=True)\n\nax1.set_ylabel('Generalization Error (%s)'%(TASK1), fontsize=fontsize)\nax1.legend(loc='upper right', fontsize=20, frameon=False)\nax1.set_ylim(0.1, 0.21)\nax1.set_xlabel('Total Sample Size', fontsize=fontsize)\nax1.tick_params(labelsize=labelsize)\nax1.set_yticks([0.15, 0.2])\nax1.set_xticks([250,750,1500])\nax1.axvline(x=750, c='gray', linewidth=1.5, linestyle=\"dashed\")\nax1.set_title('XOR', fontsize=30)\n\nright_side = ax1.spines[\"right\"]\nright_side.set_visible(False)\ntop_side = ax1.spines[\"top\"]\ntop_side.set_visible(False)\n\nax1.text(400, np.mean(ax1.get_ylim()), \"%s\"%(TASK1), fontsize=26)\nax1.text(900, np.mean(ax1.get_ylim()), \"%s\"%(TASK2), fontsize=26)\n\n#plt.tight_layout()\n\n#plt.savefig('./result/figs/generalization_error_xor.pdf',dpi=500)\n\n#####\nmean_error = unpickle('result/mean_xor_nxor2.pickle')\nstd_error = unpickle('result/std_xor_nxor2.pickle')\n\nalgorithms = ['Uncertainty Forest', 'Lifelong Forest']\n\nTASK1='XOR'\nTASK2='N-XOR'\n\nax1 = fig.add_subplot(gs[7:,7:13])\n# for i, algo in enumerate(algorithms):\nax1.plot(ns[len(n1s):], mean_error[2, len(n1s):], label=algorithms[0], c=colors[1], ls=ls[1], lw=3)\n#ax1.fill_between(ns[len(n1s):], \n# mean_error[2, len(n1s):] + 1.96*std_error[2, len(n1s):], \n# mean_error[2, len(n1s):] - 1.96*std_error[2, len(n1s):], \n# where=mean_error[2, len(n1s):] + 1.96*std_error[2, len(n1s):] >= mean_error[2, len(n1s):] - 1.96*std_error[2, len(n1s):], \n# facecolor=colors[1], \n# alpha=0.15,\n# interpolate=True)\n\nax1.plot(ns[len(n1s):], mean_error[3, len(n1s):], label=algorithms[1], c=colors[0], ls=ls[1], lw=3)\n#ax1.fill_between(ns[len(n1s):], \n# mean_error[3, len(n1s):] + 1.96*std_error[3, len(n1s):], \n# mean_error[3, len(n1s):] - 1.96*std_error[3, len(n1s):], \n# where=mean_error[3, len(n1s):] + 1.96*std_error[3, len(n1s):] >= mean_error[3, len(n1s):] - 1.96*std_error[3, len(n1s):], \n# facecolor=colors[0], \n# alpha=0.15,\n# interpolate=True)\n\nax1.set_ylabel('Generalization Error (%s)'%(TASK2), fontsize=fontsize)\nax1.legend(loc='upper right', fontsize=20, frameon=False)\n# ax1.set_ylim(-0.01, 0.22)\nax1.set_xlabel('Total Sample Size', fontsize=fontsize)\nax1.tick_params(labelsize=labelsize)\n# ax1.set_yticks([0.15, 0.25, 0.35])\n#ax1.set_yticks([0.15, 0.2])\nax1.set_xticks([250,750,1500])\nax1.axvline(x=750, c='gray', linewidth=1.5, linestyle=\"dashed\")\n\n#ax1.set_ylim(0.11, 0.21)\n\nax1.set_xlim(-10)\nright_side = ax1.spines[\"right\"]\nright_side.set_visible(False)\ntop_side = ax1.spines[\"top\"]\ntop_side.set_visible(False)\n\n# ax1.set_ylim(0.14, 0.36)\nax1.text(400, np.mean(ax1.get_ylim()), \"%s\"%(TASK1), fontsize=26)\nax1.text(900, np.mean(ax1.get_ylim()), \"%s\"%(TASK2), fontsize=26)\n\nax1.set_title('N-XOR', fontsize=30)\n#plt.tight_layout()\n\n#plt.savefig('./result/figs/generalization_error_nxor.pdf',dpi=500)\n\n#####\nmean_error = unpickle('result/mean_te_xor_nxor2.pickle')\nstd_error = unpickle('result/std_te_xor_nxor2.pickle')\n\nalgorithms = ['Backward Transfer', 'Forward Transfer']\n\nTASK1='XOR'\nTASK2='N-XOR'\n\nax1 = fig.add_subplot(gs[7:,14:])\n\nax1.plot(ns, mean_error[0], label=algorithms[0], c=colors[0], ls=ls[0], lw=3)\n#ax1.fill_between(ns, \n# mean_error[0] + 1.96*std_error[0], \n# mean_error[0] - 1.96*std_error[0], \n# where=mean_error[1] + 1.96*std_error[0] >= mean_error[0] - 1.96*std_error[0], \n# facecolor=colors[0], \n# alpha=0.15,\n# interpolate=True)\n\nax1.plot(ns[len(n1s):], mean_error[1, len(n1s):], label=algorithms[1], c=colors[0], ls=ls[1], lw=3)\n#ax1.fill_between(ns[len(n1s):], \n# mean_error[1, len(n1s):] + 1.96*std_error[1, len(n1s):], \n# mean_error[1, len(n1s):] - 1.96*std_error[1, len(n1s):], \n# where=mean_error[1, len(n1s):] + 1.96*std_error[1, len(n1s):] >= mean_error[1, len(n1s):] - 1.96*std_error[1, len(n1s):], \n# facecolor=colors[0], \n# alpha=0.15,\n# interpolate=True)\n\nax1.set_ylabel('Transfer Efficiency', fontsize=fontsize)\nax1.legend(loc='upper right', fontsize=20, frameon=False)\n#ax1.set_ylim(.99, 1.4)\nax1.set_xlabel('Total Sample Size', fontsize=fontsize)\nax1.tick_params(labelsize=labelsize)\n#ax1.set_yticks([1,1.2,1.4])\nax1.set_xticks([250,750,1500])\nax1.axvline(x=750, c='gray', linewidth=1.5, linestyle=\"dashed\")\nright_side = ax1.spines[\"right\"]\nright_side.set_visible(False)\ntop_side = ax1.spines[\"top\"]\ntop_side.set_visible(False)\nax1.hlines(1, 50,1500, colors='gray', linestyles='dashed',linewidth=1.5)\n\nax1.text(400, np.mean(ax1.get_ylim()), \"%s\"%(TASK1), fontsize=26)\nax1.text(900, np.mean(ax1.get_ylim()), \"%s\"%(TASK2), fontsize=26)\n\n#plt.tight_layout()\n\n#plt.savefig('./result/figs/TE.pdf',dpi=500)\n\n#####\ncolors = sns.color_palette('Dark2', n_colors=2)\n\nX, Y = generate_gaussian_parity(750, cov_scale=0.1, angle_params=0)\nZ, W = generate_gaussian_parity(750, cov_scale=0.1, angle_params=np.pi/2)\n\nax = fig.add_subplot(gs[:6,4:10])\nax.scatter(X[:, 0], X[:, 1], c=get_colors(colors, Y), s=50)\n\nax.set_xticks([])\nax.set_yticks([])\nax.set_title('Gaussian XOR', fontsize=30)\n\nplt.tight_layout()\nax.axis('off')\n#plt.savefig('./result/figs/gaussian-xor.pdf')\n\n###\ncolors = sns.color_palette('Dark2', n_colors=2)\n\nax = fig.add_subplot(gs[:6,11:16])\nax.scatter(Z[:, 0], Z[:, 1], c=get_colors(colors, W), s=50)\n\nax.set_xticks([])\nax.set_yticks([])\nax.set_title('Gaussian N-XOR', fontsize=30)\nax.axis('off')\n#plt.tight_layout()\nplt.savefig('./result/figs/xor_nxor_exp.pdf')\n\n# %%\n", "#%%\nimport random\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport tensorflow.keras as keras\nimport seaborn as sns \nimport matplotlib\nimport numpy as np\nimport pickle\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom math import log2, ceil \n\nimport sys\nsys.path.append(\"../../src/\")\nfrom lifelong_dnn import LifeLongDNN\n\n#%%\ndef unpickle(file):\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\ndef get_colors(colors, inds):\n c = [colors[i] for i in inds]\n return c\n\ndef generate_2d_rotation(theta=0, acorn=None):\n if acorn is not None:\n np.random.seed(acorn)\n \n R = np.array([\n [np.cos(theta), np.sin(theta)],\n [-np.sin(theta), np.cos(theta)]\n ])\n \n return R\n\ndef generate_gaussian_parity(n, mean=np.array([-1, -1]), cov_scale=1, angle_params=None, k=1, acorn=None):\n if acorn is not None:\n np.random.seed(acorn)\n \n d = len(mean)\n \n if mean[0] == -1 and mean[1] == -1:\n mean = mean + 1 / 2**k\n \n mnt = np.random.multinomial(n, 1/(4**k) * np.ones(4**k))\n cumsum = np.cumsum(mnt)\n cumsum = np.concatenate(([0], cumsum))\n \n Y = np.zeros(n)\n X = np.zeros((n, d))\n \n for i in range(2**k):\n for j in range(2**k):\n temp = np.random.multivariate_normal(mean, cov_scale * np.eye(d), \n size=mnt[i*(2**k) + j])\n temp[:, 0] += i*(1/2**(k-1))\n temp[:, 1] += j*(1/2**(k-1))\n \n X[cumsum[i*(2**k) + j]:cumsum[i*(2**k) + j + 1]] = temp\n \n if i % 2 == j % 2:\n Y[cumsum[i*(2**k) + j]:cumsum[i*(2**k) + j + 1]] = 0\n else:\n Y[cumsum[i*(2**k) + j]:cumsum[i*(2**k) + j + 1]] = 1\n \n if d == 2:\n if angle_params is None:\n angle_params = np.random.uniform(0, 2*np.pi)\n \n R = generate_2d_rotation(angle_params)\n X = X @ R\n \n else:\n raise ValueError('d=%i not implemented!'%(d))\n \n return X, Y.astype(int)\n\n#%%#%% Plotting the result\n#mc_rep = 50\nfontsize=30\nlabelsize=28\n\n\nfig = plt.figure(constrained_layout=True,figsize=(21,30))\ngs = fig.add_gridspec(30, 21)\n\ncolors = sns.color_palette('Dark2', n_colors=2)\n\nX, Y = generate_gaussian_parity(750, cov_scale=0.1, angle_params=0)\nZ, W = generate_gaussian_parity(750, cov_scale=0.1, angle_params=np.pi/2)\nP, Q = generate_gaussian_parity(750, cov_scale=0.1, angle_params=np.pi/4)\n\nax = fig.add_subplot(gs[:6,:6])\nax.scatter(X[:, 0], X[:, 1], c=get_colors(colors, Y), s=50)\n\nax.set_xticks([])\nax.set_yticks([])\nax.set_title('Gaussian XOR', fontsize=30)\n\nplt.tight_layout()\nax.axis('off')\n#plt.savefig('./result/figs/gaussian-xor.pdf')\n\n#####################\nax = fig.add_subplot(gs[:6,7:13])\nax.scatter(Z[:, 0], Z[:, 1], c=get_colors(colors, W), s=50)\n\nax.set_xticks([])\nax.set_yticks([])\nax.set_title('Gaussian N-XOR', fontsize=30)\nax.axis('off')\n\n#####################\nax = fig.add_subplot(gs[:6,14:20])\nax.scatter(P[:, 0], P[:, 1], c=get_colors(colors, Q), s=50)\n\nax.set_xticks([])\nax.set_yticks([])\nax.set_title('Gaussian R-XOR', fontsize=30)\nax.axis('off')\n\n######################\nmean_error = unpickle('../xor_nxor_exp/result/mean_xor_nxor.pickle')\n\nn_xor = (100*np.arange(0.5, 7.25, step=0.25)).astype(int)\nn_nxor = (100*np.arange(0.5, 7.50, step=0.25)).astype(int)\n\nn1s = n_xor\nn2s = n_nxor\n\nns = np.concatenate((n1s, n2s + n1s[-1]))\nls=['-', '--']\nalgorithms = ['Uncertainty Forest', 'Lifelong Forest']\n\n\nTASK1='XOR'\nTASK2='N-XOR'\n\ncolors = sns.color_palette(\"Set1\", n_colors = 2)\n\nax = fig.add_subplot(gs[7:13,2:9])\n\nax.plot(ns, mean_error[0], label=algorithms[0], c=colors[1], ls=ls[np.sum(0 > 1).astype(int)], lw=3)\nax.plot(ns, mean_error[1], label=algorithms[1], c=colors[0], ls=ls[np.sum(1 > 1).astype(int)], lw=3)\n\nax.set_ylabel('Generalization Error (%s)'%(TASK1), fontsize=fontsize)\nax.legend(loc='upper right', fontsize=20, frameon=False)\nax.set_ylim(0.1, 0.2)\nax.set_xlabel('Total Sample Size', fontsize=fontsize)\nax.tick_params(labelsize=labelsize)\nax.set_yticks([.1,0.15, 0.2])\nax.set_xticks([250,750,1500])\nax.axvline(x=750, c='gray', linewidth=1.5, linestyle=\"dashed\")\nax.set_title('XOR', fontsize=30)\n\nright_side = ax.spines[\"right\"]\nright_side.set_visible(False)\ntop_side = ax.spines[\"top\"]\ntop_side.set_visible(False)\n\nax.text(400, np.mean(ax.get_ylim()), \"%s\"%(TASK1), fontsize=26)\nax.text(900, np.mean(ax.get_ylim()), \"%s\"%(TASK2), fontsize=26)\n\n\n#######################\nmean_error = unpickle('../xor_nxor_exp/result/mean_xor_nxor.pickle')\n\nalgorithms = ['Uncertainty Forest', 'Lifelong Forest']\n\nTASK1='XOR'\nTASK2='N-XOR'\nax = fig.add_subplot(gs[7:13,12:19])\n\nax.plot(ns[len(n1s):], mean_error[2, len(n1s):], label=algorithms[0], c=colors[1], ls=ls[1], lw=3)\nax.plot(ns[len(n1s):], mean_error[3, len(n1s):], label=algorithms[1], c=colors[0], ls=ls[1], lw=3)\n\nax.set_ylabel('Generalization Error (%s)'%(TASK2), fontsize=fontsize)\nax.legend(loc='upper right', fontsize=20, frameon=False)\nax.set_xlabel('Total Sample Size', fontsize=fontsize)\nax.tick_params(labelsize=labelsize)\nax.set_yticks([.1,0.15, 0.2])\nax.set_xticks([250,750,1500])\nax.axvline(x=750, c='gray', linewidth=1.5, linestyle=\"dashed\")\n\nax.set_ylim(0.1, 0.2)\n\nax.set_xlim(-10)\nright_side = ax.spines[\"right\"]\nright_side.set_visible(False)\ntop_side = ax.spines[\"top\"]\ntop_side.set_visible(False)\n\nax.text(400, np.mean(ax.get_ylim()), \"%s\"%(TASK1), fontsize=26)\nax.text(900, np.mean(ax.get_ylim()), \"%s\"%(TASK2), fontsize=26)\n\nax.set_title('N-XOR', fontsize=30)\n\n##################\nmean_error = unpickle('../xor_nxor_exp/result/mean_te_xor_nxor.pickle')\nstd_error = unpickle('../xor_nxor_exp/result/std_te_xor_nxor.pickle')\n\nalgorithms = ['Backward Transfer', 'Forward Transfer']\n\nTASK1='XOR'\nTASK2='N-XOR'\n\nax = fig.add_subplot(gs[15:21,2:9])\n\nax.plot(ns, mean_error[0], label=algorithms[0], c=colors[0], ls=ls[0], lw=3)\n\nax.plot(ns[len(n1s):], mean_error[1, len(n1s):], label=algorithms[1], c=colors[0], ls=ls[1], lw=3)\n\nax.set_title('Transfer Efficiency for XOR and N-XOR',fontsize=fontsize)\nax.set_ylabel('Transfer Efficiency', fontsize=fontsize)\nax.legend(loc='upper right', fontsize=20, frameon=False)\nax.set_ylim(.99, 1.42)\nax.set_xlabel('Total Sample Size', fontsize=fontsize)\nax.tick_params(labelsize=labelsize)\nax.set_yticks([1,1.2,1.4])\nax.set_xticks([250,750,1500])\nax.axvline(x=750, c='gray', linewidth=1.5, linestyle=\"dashed\")\nright_side = ax.spines[\"right\"]\nright_side.set_visible(False)\ntop_side = ax.spines[\"top\"]\ntop_side.set_visible(False)\nax.hlines(1, 50,1500, colors='gray', linestyles='dashed',linewidth=1.5)\n\nax.text(400, np.mean(ax.get_ylim()), \"%s\"%(TASK1), fontsize=26)\nax.text(900, np.mean(ax.get_ylim()), \"%s\"%(TASK2), fontsize=26)\n\n######################\nmean_error = unpickle('./result/mean_te_xor_rxor.pickle')\n\nalgorithms = ['Backward Transfer', 'Forward Transfer']\n\nTASK1='XOR'\nTASK2='R-XOR'\n\nax = fig.add_subplot(gs[15:21,12:19])\n\nax.plot(ns, mean_error[0], label=algorithms[0], c=colors[0], ls=ls[0], lw=3)\n\nax.plot(ns[len(n1s):], mean_error[1, len(n1s):], label=algorithms[1], c=colors[0], ls=ls[1], lw=3)\n\nax.set_title('Transfer Efficiency for XOR and R-XOR',fontsize=fontsize)\nax.set_ylabel('Transfer Efficiency', fontsize=fontsize)\nax.legend(loc='upper right', fontsize=20, frameon=False)\nax.set_ylim(0.96, 1.045)\nax.set_xlabel('Total Sample Size', fontsize=fontsize)\nax.tick_params(labelsize=labelsize)\nax.set_yticks([0.96,1, 1.04])\nax.set_xticks([250,750,1500])\nax.axvline(x=750, c='gray', linewidth=1.5, linestyle=\"dashed\")\nright_side = ax.spines[\"right\"]\nright_side.set_visible(False)\ntop_side = ax.spines[\"top\"]\ntop_side.set_visible(False)\nax.hlines(1, 50,1500, colors='gray', linestyles='dashed',linewidth=1.5)\n\nax.text(400, np.mean(ax.get_ylim())+.005, \"%s\"%(TASK1), fontsize=26)\nax.text(900, np.mean(ax.get_ylim())+.005, \"%s\"%(TASK2), fontsize=26)\n\n########################################################\nax = fig.add_subplot(gs[23:29,2:9])\nalg_name = ['L2F']\nangles = np.arange(0,91,1)\ntes = [[] for _ in range(len(alg_name))]\n\nfor algo_no,alg in enumerate(alg_name):\n for angle in angles:\n orig_error, transfer_error = pickle.load(\n open(\"../rotation_xor/bte_90/results/angle_\" + str(angle) + \".pickle\", \"rb\")\n )\n tes[algo_no].append(orig_error / transfer_error)\n\nclr = [\"#e41a1c\"]\nc = sns.color_palette(clr, n_colors=len(clr))\n\nfor alg_no,alg in enumerate(alg_name):\n if alg_no<2:\n ax.plot(angles,tes[alg_no], c=c[alg_no], label=alg_name[alg_no], linewidth=3)\n else:\n ax.plot(angles,tes[alg_no], c=c[alg_no], label=alg_name[alg_no])\n\n\nax.set_xticks(range(0, 90 + 15, 15))\nax.set_yticks([0.6,1.0,1.8])\nax.tick_params(labelsize=labelsize)\nax.set_xlabel('Angle of Rotation (Degrees)', fontsize=fontsize)\nax.set_ylabel('Backward Transfer Efficiency (XOR)', fontsize=fontsize)\n#ax.set_title(\"XOR vs. Rotated-XOR\", fontsize = fontsize)\nax.hlines(1,0,90, colors='grey', linestyles='dashed',linewidth=1.5)\n\nright_side = ax.spines[\"right\"]\nright_side.set_visible(False)\ntop_side = ax.spines[\"top\"]\ntop_side.set_visible(False)\n\n\nax = fig.add_subplot(gs[23:29,12:19])\nte_ra = []\nn1_ra = (2**np.arange(np.log2(60), np.log2(5010)+1, .25)).astype('int')\n#print(n1_ra)\nfor n1 in n1_ra:\n te_across_reps = []\n for rep in range(1000):\n filename = '../rotation_xor/te_exp/result/'+str(n1)+'_'+str(rep)+'.pickle'\n df = unpickle(filename)\n te_across_reps.append(float(df['te']))\n te_ra.append(np.mean(te_across_reps))\n \nax.plot(n1_ra, te_ra, c=\"#e41a1c\", linewidth = 2.6)\nax.set_xscale('log')\nax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())\n#ax.set_xticks([])\nax.tick_params(labelsize=labelsize)\nax.set_xticks([100, 500, 5000])\nax.set_yticks([0.7,1.0,1.2])\n#ax.text(100, 0.1, \"100\", fontsize=labelsize)\n#ax.text(500, 0.1, \"500\", fontsize=labelsize)\n#ax.text(2500, 0.434, \"2500\", fontsize=labelsize)\n#ax.text(5000, 0.434, \"5000\", fontsize=labelsize)\n#ax.text(500, 0.43, 'Number of Task 1 Training Samples', fontsize=labelsize)\n\nax.hlines(1, min(n1_ra), max(n1_ra), colors='grey', linestyles='dashed',linewidth=1.5)\nax.set_xlabel(r'Number of $10^\\circ$-RXOR Training Samples', fontsize=fontsize)\nax.set_ylabel('Backward Transfer Efficiency (XOR)', fontsize=fontsize)\n#ax.set_title(\"Training Set Size Effect\", fontsize = fontsize)\n\nright_side = ax.spines[\"right\"]\nright_side.set_visible(False)\ntop_side = ax.spines[\"top\"]\ntop_side.set_visible(False)\n\nplt.savefig('./result/figs/xor_nxor_rxor_exp.pdf')\n\n# %%\n" ]
[ [ "matplotlib.pyplot.tight_layout", "numpy.random.seed", "numpy.meshgrid", "numpy.arange", "numpy.eye", "numpy.cumsum", "matplotlib.pyplot.savefig", "numpy.ones", "numpy.concatenate", "numpy.cos", "numpy.std", "numpy.sin", "numpy.mean", "numpy.random.uniform", "numpy.array", "numpy.zeros", "numpy.sum", "matplotlib.pyplot.figure" ], [ "sklearn.base.clone", "numpy.array", "numpy.mean", "numpy.random.seed" ], [ "matplotlib.pyplot.tight_layout", "numpy.random.seed", "numpy.arange", "numpy.eye", "numpy.cumsum", "matplotlib.pyplot.savefig", "numpy.ones", "numpy.concatenate", "numpy.cos", "numpy.sin", "numpy.random.uniform", "numpy.array", "numpy.zeros", "numpy.sum", "matplotlib.pyplot.figure" ], [ "matplotlib.pyplot.tight_layout", "numpy.log2", "numpy.random.seed", "numpy.arange", "numpy.eye", "numpy.cumsum", "matplotlib.pyplot.savefig", "numpy.ones", "numpy.concatenate", "numpy.random.uniform", "numpy.cos", "numpy.sin", "numpy.mean", "matplotlib.ticker.ScalarFormatter", "numpy.array", "numpy.zeros", "numpy.sum", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
stefan-woerner/aqua
[ "12e1b867e254977d9c5992612a7919d8fe016cb4", "12e1b867e254977d9c5992612a7919d8fe016cb4", "12e1b867e254977d9c5992612a7919d8fe016cb4", "12e1b867e254977d9c5992612a7919d8fe016cb4" ]
[ "qiskit/optimization/applications/ising/knapsack.py", "qiskit/finance/components/uncertainty_problems/european_call_delta.py", "qiskit/chemistry/results/electronic_structure_result.py", "qiskit/aqua/components/reciprocals/long_division.py" ]
[ "# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2020, 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"\nConvert knapsack parameters instances into Pauli list\nThe parameters are a list of values a list of weights and a maximum weight of the knapsack.\n\nIn the Knapsack Problem we are given a list of objects that each has a weight and a value.\nWe are also given a maximum weight we can carry. We need to pick a subset of the objects\nso as to maximize the total value without going over the maximum weight.\n\nIf we have the weights w[i], the values v[i] and the maximum weight W_max.\nWe express the solution as a binary array x[i]\nwhere we have a 1 for the items we take in the solution set.\nWe need to maximize sum(x[i]*v[i]) while respecting W_max >= sum(x[i]*w[i])\n\n\"\"\"\n\nimport logging\nimport math\nimport numpy as np\n\nfrom qiskit.quantum_info import Pauli\nfrom qiskit.aqua.operators import WeightedPauliOperator\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_operator(values, weights, max_weight):\n \"\"\"\n Generate Hamiltonian for the knapsack problem.\n\n Notes:\n To build the cost function for the Hamiltonian we add a term S\n that will vary with our solution. In order to make it change wit the solution\n we enhance X with a number of additional bits X' = [x_0,..x_{n-1},y_{n}..y_{n+m-1}].\n The bytes y[i] will be the binary representation of S.\n In this way the optimizer will be able to optimize S as well as X.\n\n The cost function is\n $$C(X') = M(W_{max} - \\\\sum_{i=0}^{n-1} x_{i}w_{i} - S)^2 - \\\\sum_{i}^{n-1} x_{i}v_{i}$$\n where S = sum(2**j * y[j]), j goes from n to n+log(W_max).\n M is a number large enough to dominate the sum of values.\n\n Because S can only be positive, when W_max >= sum(x[i]*w[i])\n the optimizer can find an S (or better the y[j] that compose S)\n so that it will take the first term to 0.\n This way the function is dominated by the sum of values.\n If W_max < sum(x[i]*w[i]) then the first term can never be 0\n and, multiplied by a large M, will always dominate the function.\n\n The minimum value of the function will be that where the constraint is respected\n and the sum of values is maximized.\n\n Args:\n values (list of non-negative integers) : a list of values\n weights (list of non-negative integers) : a list of weights\n max_weight (non negative integer) : the maximum weight the knapsack can carry\n\n Returns:\n WeightedPauliOperator: operator for the Hamiltonian\n float: a constant shift for the obj function.\n\n Raises:\n ValueError: values and weights have different lengths\n ValueError: A value or a weight is negative\n ValueError: All values are zero\n ValueError: max_weight is negative\n\n \"\"\"\n if len(values) != len(weights):\n raise ValueError(\"The values and weights must have the same length\")\n\n if any(v < 0 for v in values) or any(w < 0 for w in weights):\n raise ValueError(\"The values and weights cannot be negative\")\n\n if all(v == 0 for v in values):\n raise ValueError(\"The values cannot all be 0\")\n\n if max_weight < 0:\n raise ValueError(\"max_weight cannot be negative\")\n\n y_size = int(math.log(max_weight, 2)) + 1 if max_weight > 0 else 1\n n = len(values)\n num_values = n + y_size\n pauli_list = []\n shift = 0\n\n # pylint: disable=invalid-name\n M = 10 * np.sum(values)\n\n # term for sum(x_i*w_i)**2\n for i in range(n):\n for j in range(n):\n coefficient = -1 * 0.25 * weights[i] * weights[j] * M\n pauli_op = _get_pauli_op(num_values, [j])\n pauli_list.append([coefficient, pauli_op])\n shift -= coefficient\n\n pauli_op = _get_pauli_op(num_values, [i])\n pauli_list.append([coefficient, pauli_op])\n shift -= coefficient\n\n coefficient = -1 * coefficient\n pauli_op = _get_pauli_op(num_values, [i, j])\n pauli_list.append([coefficient, pauli_op])\n shift -= coefficient\n\n # term for sum(2**j*y_j)**2\n for i in range(y_size):\n for j in range(y_size):\n coefficient = -1 * 0.25 * (2 ** i) * (2 ** j) * M\n\n pauli_op = _get_pauli_op(num_values, [n + j])\n pauli_list.append([coefficient, pauli_op])\n shift -= coefficient\n\n pauli_op = _get_pauli_op(num_values, [n + i])\n pauli_list.append([coefficient, pauli_op])\n shift -= coefficient\n\n coefficient = -1 * coefficient\n pauli_op = _get_pauli_op(num_values, [n + i, n + j])\n pauli_list.append([coefficient, pauli_op])\n shift -= coefficient\n\n # term for -2*W_max*sum(x_i*w_i)\n for i in range(n):\n coefficient = max_weight * weights[i] * M\n\n pauli_op = _get_pauli_op(num_values, [i])\n pauli_list.append([coefficient, pauli_op])\n shift -= coefficient\n\n # term for -2*W_max*sum(2**j*y_j)\n for j in range(y_size):\n coefficient = max_weight * (2 ** j) * M\n\n pauli_op = _get_pauli_op(num_values, [n + j])\n pauli_list.append([coefficient, pauli_op])\n shift -= coefficient\n\n for i in range(n):\n for j in range(y_size):\n coefficient = -1 * 0.5 * weights[i] * (2 ** j) * M\n\n pauli_op = _get_pauli_op(num_values, [n + j])\n pauli_list.append([coefficient, pauli_op])\n shift -= coefficient\n\n pauli_op = _get_pauli_op(num_values, [i])\n pauli_list.append([coefficient, pauli_op])\n shift -= coefficient\n\n coefficient = -1 * coefficient\n pauli_op = _get_pauli_op(num_values, [i, n + j])\n pauli_list.append([coefficient, pauli_op])\n shift -= coefficient\n\n # term for sum(x_i*v_i)\n for i in range(n):\n coefficient = 0.5 * values[i]\n\n pauli_op = _get_pauli_op(num_values, [i])\n pauli_list.append([coefficient, pauli_op])\n shift -= coefficient\n\n return WeightedPauliOperator(paulis=pauli_list), shift\n\n\ndef get_solution(x, values):\n \"\"\"\n Get the solution to the knapsack problem\n from the bitstring that represents\n to the ground state of the Hamiltonian\n\n Args:\n x (numpy.ndarray): the ground state of the Hamiltonian.\n values (numpy.ndarray): the list of values\n\n Returns:\n numpy.ndarray: a bit string that has a '1' at the indexes\n corresponding to values that have been taken in the knapsack.\n i.e. if the solution has a '1' at index i then\n the value values[i] has been taken in the knapsack\n \"\"\"\n return x[:len(values)]\n\n\ndef knapsack_value_weight(solution, values, weights):\n \"\"\"\n Get the total wight and value of the items taken in the knapsack.\n\n Args:\n solution (numpy.ndarray) : binary string that represents the solution to the problem.\n values (numpy.ndarray) : the list of values\n weights (numpy.ndarray) : the list of weights\n\n Returns:\n tuple: the total value and weight of the items in the knapsack\n \"\"\"\n value = np.sum(solution * values)\n weight = np.sum(solution * weights)\n return value, weight\n\n\ndef _get_pauli_op(num_values, indexes):\n pauli_x = np.zeros(num_values, dtype=bool)\n pauli_z = np.zeros(num_values, dtype=bool)\n for i in indexes:\n pauli_z[i] = not pauli_z[i]\n\n return Pauli((pauli_z, pauli_x))\n", "# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2018, 2020.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"The European Call Option Delta.\"\"\"\n\nfrom typing import Optional, Union, List\nimport numpy as np\nfrom qiskit.circuit.library import IntegerComparator\nfrom qiskit.aqua.components.uncertainty_models import UnivariateDistribution\nfrom qiskit.aqua.components.uncertainty_problems import UncertaintyProblem\n\n# pylint: disable=invalid-name\n\n\nclass EuropeanCallDelta(UncertaintyProblem):\n \"\"\"The European Call Option Delta.\n\n Evaluates the variance for a European call option given an uncertainty model.\n The payoff function is f(S, K) = max(0, S - K) for a spot price S and strike price K.\n \"\"\"\n\n def __init__(self,\n uncertainty_model: UnivariateDistribution,\n strike_price: float,\n i_state: Optional[Union[List[int], np.ndarray]] = None,\n i_objective: Optional[int] = None) -> None:\n \"\"\"\n Constructor.\n\n Args:\n uncertainty_model: uncertainty model for spot price\n strike_price: strike price of the European option\n i_state: indices of qubits representing the uncertainty\n i_objective: index of qubit for objective function\n \"\"\"\n super().__init__(uncertainty_model.num_target_qubits + 1)\n\n self._uncertainty_model = uncertainty_model\n self._strike_price = strike_price\n\n if i_state is None:\n i_state = list(range(uncertainty_model.num_target_qubits))\n self.i_state = i_state\n if i_objective is None:\n i_objective = uncertainty_model.num_target_qubits\n self.i_objective = i_objective\n\n # map strike price to {0, ..., 2^n-1}\n lb = uncertainty_model.low\n ub = uncertainty_model.high\n self._mapped_strike_price = \\\n int(np.ceil((strike_price - lb) / (ub - lb) * (uncertainty_model.num_values - 1)))\n\n # create comparator\n self._comparator = IntegerComparator(uncertainty_model.num_target_qubits,\n self._mapped_strike_price)\n\n def required_ancillas(self):\n num_uncertainty_ancillas = self._uncertainty_model.required_ancillas()\n num_comparator_ancillas = self._comparator.num_ancillas\n num_ancillas = num_uncertainty_ancillas + num_comparator_ancillas\n return num_ancillas\n\n def required_ancillas_controlled(self):\n num_uncertainty_ancillas = self._uncertainty_model.required_ancillas_controlled()\n num_comparator_ancillas = self._comparator.num_ancillas\n num_ancillas_controlled = num_uncertainty_ancillas + num_comparator_ancillas\n return num_ancillas_controlled\n\n def build(self, qc, q, q_ancillas=None, params=None):\n # get qubit lists\n q_state = [q[i] for i in self.i_state]\n q_objective = q[self.i_objective]\n\n # apply uncertainty model\n self._uncertainty_model.build(qc, q_state, q_ancillas)\n\n # apply comparator to compare qubit\n qubits = q_state[:] + [q_objective]\n if q_ancillas:\n qubits += q_ancillas[:self.required_ancillas()]\n qc.append(self._comparator.to_instruction(), qubits)\n", "# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2020.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"The electronic structure result.\"\"\"\n\nfrom typing import List, Optional, Tuple, cast\n\nimport logging\nimport numpy as np\n\nfrom qiskit.chemistry import QMolecule\n\nfrom .eigenstate_result import EigenstateResult\n\nlogger = logging.getLogger(__name__)\n\n# A dipole moment, when present as X, Y and Z components will normally have float values for all\n# the components. However when using Z2Symmetries, if the dipole component operator does not\n# commute with the symmetry then no evaluation is done and None will be used as the 'value'\n# indicating no measurement of the observable took place\nDipoleTuple = Tuple[Optional[float], Optional[float], Optional[float]]\n\n\nclass ElectronicStructureResult(EigenstateResult):\n \"\"\"The electronic structure result.\"\"\"\n\n @property\n def hartree_fock_energy(self) -> float:\n \"\"\" Returns Hartree-Fock energy \"\"\"\n return self.get('hartree_fock_energy')\n\n @hartree_fock_energy.setter\n def hartree_fock_energy(self, value: float) -> None:\n \"\"\" Sets Hartree-Fock energy \"\"\"\n self.data['hartree_fock_energy'] = value\n\n @property\n def nuclear_repulsion_energy(self) -> Optional[float]:\n \"\"\" Returns nuclear repulsion energy when available from driver \"\"\"\n return self.get('nuclear_repulsion_energy')\n\n @nuclear_repulsion_energy.setter\n def nuclear_repulsion_energy(self, value: float) -> None:\n \"\"\" Sets nuclear repulsion energy \"\"\"\n self.data['nuclear_repulsion_energy'] = value\n\n @property\n def nuclear_dipole_moment(self) -> Optional[DipoleTuple]:\n \"\"\" Returns nuclear dipole moment X,Y,Z components in A.U when available from driver \"\"\"\n return self.get('nuclear_dipole_moment')\n\n @nuclear_dipole_moment.setter\n def nuclear_dipole_moment(self, value: DipoleTuple) -> None:\n \"\"\" Sets nuclear dipole moment in A.U \"\"\"\n self.data['nuclear_dipole_moment'] = value\n\n # TODO we need to be able to extract the statevector or the optimal parameters that can\n # construct the circuit of the GS from here (if the algorithm supports this)\n\n @property\n def total_energies(self) -> np.ndarray:\n \"\"\" Returns ground state energy if nuclear_repulsion_energy is available from driver \"\"\"\n nre = self.nuclear_repulsion_energy if self.nuclear_repulsion_energy is not None else 0\n # Adding float to np.ndarray adds it to each entry\n return self.electronic_energies + nre\n\n @property\n def electronic_energies(self) -> np.ndarray:\n \"\"\" Returns electronic part of ground state energy \"\"\"\n # TODO the fact that this property is computed on the fly breaks the `.combine()`\n # functionality\n # Adding float to np.ndarray adds it to each entry\n return (self.computed_energies\n + self.ph_extracted_energy\n + self.frozen_extracted_energy)\n\n @property\n def computed_energies(self) -> np.ndarray:\n \"\"\" Returns computed electronic part of ground state energy \"\"\"\n return self.get('computed_energies')\n\n @computed_energies.setter\n def computed_energies(self, value: np.ndarray) -> None:\n \"\"\" Sets computed electronic part of ground state energy \"\"\"\n self.data['computed_energies'] = value\n\n @property\n def ph_extracted_energy(self) -> float:\n \"\"\" Returns particle hole extracted part of ground state energy \"\"\"\n return self.get('ph_extracted_energy')\n\n @ph_extracted_energy.setter\n def ph_extracted_energy(self, value: float) -> None:\n \"\"\" Sets particle hole extracted part of ground state energy \"\"\"\n self.data['ph_extracted_energy'] = value\n\n @property\n def frozen_extracted_energy(self) -> float:\n \"\"\" Returns frozen extracted part of ground state energy \"\"\"\n return self.get('frozen_extracted_energy')\n\n @frozen_extracted_energy.setter\n def frozen_extracted_energy(self, value: float) -> None:\n \"\"\" Sets frozen extracted part of ground state energy \"\"\"\n self.data['frozen_extracted_energy'] = value\n\n # Dipole moment results. Note dipole moments of tuples of X, Y and Z components. Chemistry\n # drivers either support dipole integrals or not. Note that when using Z2 symmetries of\n\n def has_dipole(self) -> bool:\n \"\"\" Returns whether dipole moment is present in result or not \"\"\"\n return self.nuclear_dipole_moment is not None and self.electronic_dipole_moment is not None\n\n @property\n def reverse_dipole_sign(self) -> bool:\n \"\"\" Returns if electronic dipole moment sign should be reversed when adding to nuclear \"\"\"\n return self.get('reverse_dipole_sign')\n\n @reverse_dipole_sign.setter\n def reverse_dipole_sign(self, value: bool) -> None:\n \"\"\" Sets if electronic dipole moment sign should be reversed when adding to nuclear \"\"\"\n self.data['reverse_dipole_sign'] = value\n\n @property\n def total_dipole_moment(self) -> Optional[List[float]]:\n \"\"\" Returns total dipole of moment \"\"\"\n if self.dipole_moment is None:\n return None # No dipole at all\n tdm: List[float] = []\n for dip in self.dipole_moment:\n if np.any(np.equal(list(dip), None)):\n tdm.append(None) # One or more components in the dipole is None\n else:\n tdm.append(np.sqrt(np.sum(np.power(list(dip), 2))))\n return tdm\n\n @property\n def total_dipole_moment_in_debye(self) -> Optional[List[float]]:\n \"\"\" Returns total dipole of moment in Debye \"\"\"\n tdm = self.total_dipole_moment\n if tdm is None:\n return None\n return [dip / QMolecule.DEBYE for dip in tdm]\n\n @property\n def dipole_moment(self) -> Optional[List[DipoleTuple]]:\n \"\"\" Returns dipole moment \"\"\"\n edm = self.electronic_dipole_moment\n if self.reverse_dipole_sign:\n edm = [cast(DipoleTuple, tuple(-1 * x if x is not None else None for x in dip))\n for dip in edm]\n return [_dipole_tuple_add(dip, self.nuclear_dipole_moment) for dip in edm]\n\n @property\n def dipole_moment_in_debye(self) -> Optional[List[DipoleTuple]]:\n \"\"\" Returns dipole moment in Debye \"\"\"\n dipm = self.dipole_moment\n if dipm is None:\n return None\n dipmd = []\n for dip in dipm:\n dipmd0 = dip[0]/QMolecule.DEBYE if dip[0] is not None else None\n dipmd1 = dip[1]/QMolecule.DEBYE if dip[1] is not None else None\n dipmd2 = dip[2]/QMolecule.DEBYE if dip[2] is not None else None\n dipmd += [(dipmd0, dipmd1, dipmd2)]\n return dipmd\n\n @property\n def electronic_dipole_moment(self) -> Optional[List[DipoleTuple]]:\n \"\"\" Returns electronic dipole moment \"\"\"\n return [_dipole_tuple_add(comp_dip, _dipole_tuple_add(ph_dip, frozen_dip)) for\n comp_dip, ph_dip, frozen_dip in zip(self.computed_dipole_moment,\n self.ph_extracted_dipole_moment,\n self.frozen_extracted_dipole_moment)]\n\n @property\n def computed_dipole_moment(self) -> Optional[List[DipoleTuple]]:\n \"\"\" Returns computed electronic part of dipole moment \"\"\"\n return self.get('computed_dipole_moment')\n\n @computed_dipole_moment.setter\n def computed_dipole_moment(self, value: List[DipoleTuple]) -> None:\n \"\"\" Sets computed electronic part of dipole moment \"\"\"\n self.data['computed_dipole_moment'] = value\n\n @property\n def ph_extracted_dipole_moment(self) -> Optional[List[DipoleTuple]]:\n \"\"\" Returns particle hole extracted part of dipole moment \"\"\"\n return self.get('ph_extracted_dipole_moment')\n\n @ph_extracted_dipole_moment.setter\n def ph_extracted_dipole_moment(self, value: List[DipoleTuple]) -> None:\n \"\"\" Sets particle hole extracted part of dipole moment \"\"\"\n self.data['ph_extracted_dipole_moment'] = value\n\n @property\n def frozen_extracted_dipole_moment(self) -> Optional[List[DipoleTuple]]:\n \"\"\" Returns frozen extracted part of dipole moment \"\"\"\n return self.get('frozen_extracted_dipole_moment')\n\n @frozen_extracted_dipole_moment.setter\n def frozen_extracted_dipole_moment(self, value: List[DipoleTuple]) -> None:\n \"\"\" Sets frozen extracted part of dipole moment \"\"\"\n self.data['frozen_extracted_dipole_moment'] = value\n\n # Other measured operators. If these are not evaluated then None will be returned\n # instead of any measured value.\n\n def has_observables(self):\n \"\"\" Returns whether result has aux op observables such as spin, num particles \"\"\"\n return self.total_angular_momentum is not None \\\n or self.num_particles is not None \\\n or self.magnetization is not None\n\n @property\n def total_angular_momentum(self) -> Optional[List[float]]:\n \"\"\" Returns total angular momentum (S^2) \"\"\"\n return self.get('total_angular_momentum')\n\n @total_angular_momentum.setter\n def total_angular_momentum(self, value: List[float]) -> None:\n \"\"\" Sets total angular momentum \"\"\"\n self.data['total_angular_momentum'] = value\n\n @property\n def spin(self) -> Optional[List[float]]:\n \"\"\" Returns computed spin \"\"\"\n if self.total_angular_momentum is None:\n return None\n spin = []\n for total_angular_momentum in self.total_angular_momentum:\n spin.append((-1.0 + np.sqrt(1 + 4 * total_angular_momentum)) / 2)\n return spin\n\n @property\n def num_particles(self) -> Optional[List[float]]:\n \"\"\" Returns measured number of particles \"\"\"\n return self.get('num_particles')\n\n @num_particles.setter\n def num_particles(self, value: List[float]) -> None:\n \"\"\" Sets measured number of particles \"\"\"\n self.data['num_particles'] = value\n\n @property\n def magnetization(self) -> Optional[List[float]]:\n \"\"\" Returns measured magnetization \"\"\"\n return self.get('magnetization')\n\n @magnetization.setter\n def magnetization(self, value: List[float]) -> None:\n \"\"\" Sets measured magnetization \"\"\"\n self.data['magnetization'] = value\n\n def __str__(self) -> str:\n \"\"\" Printable formatted result \"\"\"\n return '\\n'.join(self.formatted)\n\n @property\n def formatted(self) -> List[str]:\n \"\"\" Formatted result as a list of strings \"\"\"\n lines = []\n lines.append('=== GROUND STATE ENERGY ===')\n lines.append(' ')\n lines.append('* Electronic ground state energy (Hartree): {}'.\n format(round(self.electronic_energies[0], 12)))\n lines.append(' - computed part: {}'.\n format(round(self.computed_energies[0], 12)))\n lines.append(' - frozen energy part: {}'.\n format(round(self.frozen_extracted_energy, 12)))\n lines.append(' - particle hole part: {}'\n .format(round(self.ph_extracted_energy, 12)))\n if self.nuclear_repulsion_energy is not None:\n lines.append('~ Nuclear repulsion energy (Hartree): {}'.\n format(round(self.nuclear_repulsion_energy, 12)))\n lines.append('> Total ground state energy (Hartree): {}'.\n format(round(self.total_energies[0], 12)))\n\n if len(self.computed_energies) > 1:\n lines.append(' ')\n lines.append('=== EXCITED STATE ENERGIES ===')\n lines.append(' ')\n for idx, (elec_energy, total_energy) in enumerate(zip(self.electronic_energies[1:],\n self.total_energies[1:])):\n lines.append('{: 3d}: '.format(idx+1))\n lines.append('* Electronic excited state energy (Hartree): {}'.\n format(round(elec_energy, 12)))\n lines.append('> Total excited state energy (Hartree): {}'.\n format(round(total_energy, 12)))\n\n if self.has_observables():\n lines.append(' ')\n lines.append('=== MEASURED OBSERVABLES ===')\n lines.append(' ')\n for idx, (num_particles, spin, total_angular_momentum, magnetization) in enumerate(zip(\n self.num_particles, self.spin, self.total_angular_momentum,\n self.magnetization)):\n line = '{: 3d}: '.format(idx)\n if num_particles is not None:\n line += ' # Particles: {:.3f}'.format(num_particles)\n if spin is not None:\n line += ' S: {:.3f}'.format(spin)\n if total_angular_momentum is not None:\n line += ' S^2: {:.3f}'.format(total_angular_momentum)\n if magnetization is not None:\n line += ' M: {:.3f}'.format(magnetization)\n lines.append(line)\n\n if self.has_dipole():\n lines.append(' ')\n lines.append('=== DIPOLE MOMENTS ===')\n lines.append(' ')\n if self.nuclear_dipole_moment is not None:\n lines.append('~ Nuclear dipole moment (a.u.): {}'\n .format(_dipole_to_string(self.nuclear_dipole_moment)))\n lines.append(' ')\n for idx, (elec_dip, comp_dip, frozen_dip, ph_dip, dip, tot_dip, dip_db, tot_dip_db) in \\\n enumerate(zip(\n self.electronic_dipole_moment, self.computed_dipole_moment,\n self.frozen_extracted_dipole_moment, self.ph_extracted_dipole_moment,\n self.dipole_moment, self.total_dipole_moment,\n self.dipole_moment_in_debye, self.total_dipole_moment_in_debye)):\n lines.append('{: 3d}: '.format(idx))\n lines.append(' * Electronic dipole moment (a.u.): {}'\n .format(_dipole_to_string(elec_dip)))\n lines.append(' - computed part: {}'\n .format(_dipole_to_string(comp_dip)))\n lines.append(' - frozen energy part: {}'\n .format(_dipole_to_string(frozen_dip)))\n lines.append(' - particle hole part: {}'\n .format(_dipole_to_string(ph_dip)))\n if self.nuclear_dipole_moment is not None:\n lines.append(' > Dipole moment (a.u.): {} Total: {}'\n .format(_dipole_to_string(dip), _float_to_string(tot_dip)))\n lines.append(' (debye): {} Total: {}'\n .format(_dipole_to_string(dip_db), _float_to_string(tot_dip_db)))\n lines.append(' ')\n\n return lines\n\n\ndef _dipole_tuple_add(x: Optional[DipoleTuple],\n y: Optional[DipoleTuple]) -> Optional[DipoleTuple]:\n \"\"\" Utility to add two dipole tuples element-wise for dipole additions \"\"\"\n if x is None or y is None:\n return None\n return _element_add(x[0], y[0]), _element_add(x[1], y[1]), _element_add(x[2], y[2])\n\n\ndef _element_add(x: Optional[float], y: Optional[float]):\n \"\"\" Add dipole elements where a value may be None then None is returned \"\"\"\n return x + y if x is not None and y is not None else None\n\n\ndef _dipole_to_string(dipole: DipoleTuple):\n dips = [round(x, 8) if x is not None else x for x in dipole]\n value = '['\n for i, _ in enumerate(dips):\n value += _float_to_string(dips[i]) if dips[i] is not None else 'None'\n value += ' ' if i < len(dips)-1 else ']'\n return value\n\n\ndef _float_to_string(value: Optional[float], precision: int = 8) -> str:\n if value is None:\n return 'None'\n else:\n return '0.0' if value == 0 else ('{:.' + str(precision) + 'f}').format(value).rstrip('0')\n", "# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2018, 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\n\"\"\"The Long Division Rotation for Reciprocals.\n\nIt finds the reciprocal with long division method and rotates the ancillary\nqubit by C/lambda. This is a first order approximation of arcsin(C/lambda).\n\"\"\"\n\nfrom typing import Optional\nimport numpy as np\nfrom qiskit import QuantumRegister, QuantumCircuit\nfrom qiskit.aqua.components.reciprocals import Reciprocal\n\n# pylint: disable=invalid-name\n\n\nclass LongDivision(Reciprocal):\n\n \"\"\"\n The Long Division Rotation for Reciprocals.\n\n This method calculates inverse of eigenvalues using binary long division and performs the\n corresponding rotation. Long division is implemented as a sequence of subtraction (utilizing\n ripple carry adder module) and bit shifting. The method allows for adjusting of the reciprocal\n precision by changing number of iterations. The method was optimized for register conventions\n used in HHL algorithm (i.e. eigenvalues rescaled to values between 0 and 1).\n\n The rotation value is always scaled down additionally to the normal scale parameter by 0.5 to\n get the angle into the linear part of the arcsin(x).\n\n It finds the reciprocal with long division method and rotates the ancillary\n qubit by C/lambda. This is a first order approximation of arcsin(C/lambda).\n \"\"\"\n\n def __init__(\n self,\n scale: float = 0,\n precision: Optional[int] = None,\n negative_evals: bool = False,\n evo_time: Optional[float] = None,\n lambda_min: Optional[float] = None) -> None:\n r\"\"\"\n Args:\n scale: The scale of rotation angle, corresponds to HHL constant C. This parameter is\n used to scale the reciprocals such that for a scale C, the rotation is performed\n by an angle :math:`\\arcsin{\\frac{C}{\\lambda}}`. If neither the `scale` nor the\n `evo_time` and `lambda_min` parameters are specified, the smallest resolvable\n Eigenvalue is used.\n precision: Number of qubits that defines the precision of long division. The parameter\n sets minimum desired bit precision for the reciprocal. Due to shifting some of\n reciprocals, however, are effectively estimated with higher than this minimum\n specified precision.\n negative_evals: Indicate if negative eigenvalues need to be handled\n evo_time: The evolution time. This parameter scales the Eigenvalues in the phase\n estimation onto the range (0,1] ( (-0.5,0.5] for negative Eigenvalues ).\n lambda_min: The smallest expected eigenvalue\n \"\"\"\n\n super().__init__()\n self._negative_evals = negative_evals\n self._scale = scale\n self._precision = precision\n self._evo_time = evo_time\n self._lambda_min = lambda_min\n self._circuit = None\n self._ev = None\n self._rec = None\n self._anc = None\n self._reg_size = 0\n self._neg_offset = 0\n self._n = 0\n self._num_ancillae = None\n self._a = None\n self._b0 = None\n self._anc1 = None\n self._z = None\n self._c = None\n\n def sv_to_resvec(self, statevector, num_q):\n half = int(len(statevector) / 2)\n sv_good = statevector[half:]\n vec = np.array([])\n for i in range(2 ** num_q):\n vec = np.append(vec, sum(x for x in sv_good[i::2 ** num_q]))\n return vec\n\n def _ld_circuit(self):\n\n def subtract(qc, a, b, b0, c, z, r, rj, n):\n\n def subtract_in(qc, a, b, b0, c, z, r, n): # pylint: disable=unused-argument\n \"\"\"subtraction realized with ripple carry adder\"\"\"\n\n def maj(p, a, b, c):\n p.cx(c, b)\n p.cx(c, a)\n p.ccx(a, b, c)\n\n def uma(p, a, b, c):\n p.ccx(a, b, c)\n p.cx(c, a)\n p.cx(a, b)\n\n for i in range(n):\n qc.x(a[i])\n maj(qc, c[0], a[0], b[n - 2])\n\n for i in range(n - 2):\n maj(qc, b[n - 2 - i + self._neg_offset],\n a[i + 1], b[n - 3 - i + self._neg_offset])\n\n maj(qc, b[self._neg_offset + 0], a[n - 1], b0[0])\n qc.cx(a[n - 1], z[0])\n uma(qc, b[self._neg_offset + 0], a[n - 1], b0[0])\n\n for i in range(2, n):\n uma(qc, b[self._neg_offset + i - 1], a[n - i], b[self._neg_offset + i - 2])\n\n uma(qc, c[0], a[0], b[n - 2 + self._neg_offset])\n\n for i in range(n):\n qc.x(a[i])\n\n qc.x(z[0])\n\n def u_maj(p, a, b, c, r):\n p.ccx(c, r, b)\n p.ccx(c, r, a)\n p.mct([r, a, b], c, None, mode='noancilla')\n\n def u_uma(p, a, b, c, r):\n p.mct([r, a, b], c, None, mode='noancilla')\n p.ccx(c, r, a)\n p.ccx(a, r, b)\n\n def unsubtract(qc, a, b, b0, c, z, r, n):\n \"\"\"controlled inverse subtraction to uncompute the registers(when\n the result of the subtraction is negative)\"\"\"\n\n for i in range(n):\n qc.cx(r, a[i])\n u_maj(qc, c[0], a[0], b[n - 2], r)\n\n for i in range(n - 2):\n u_maj(qc, b[n - 2 - i + self._neg_offset],\n a[i + 1], b[n - 3 - i + self._neg_offset], r)\n\n u_maj(qc, b[self._neg_offset + 0], a[n - 1], b0[0], r)\n qc.ccx(a[n - 1], r, z[0])\n u_uma(qc, b[self._neg_offset + 0], a[n - 1], b0[0], r)\n\n for i in range(2, n):\n u_uma(qc, b[self._neg_offset + i - 1],\n a[n - i], b[self._neg_offset + i - 2], r)\n\n u_uma(qc, c[0], a[0], b[n - 2 + self._neg_offset], r)\n\n for i in range(n):\n qc.cx(r, a[i])\n\n un_qc = qc.reverse_ops()\n un_qc.cx(r, z[0])\n return un_qc\n\n # assembling circuit for controlled subtraction\n subtract_in(qc, a, b, b0, c, z, r[rj], n)\n qc.x(a[n - 1])\n qc.cx(a[n - 1], r[rj])\n qc.x(a[n - 1])\n\n qc.x(r[rj])\n unsubtract(qc, a, b, b0, c, z, r[rj], n)\n qc.x(r[rj])\n\n return qc\n\n def shift_to_one(qc, b, anc, n):\n \"\"\"controlled bit shifting for the initial alignment of the most\n significant bits \"\"\"\n\n for i in range(n - 2): # set all the anc1 qubits to 1\n qc.x(anc[i])\n\n for j2 in range(n - 2): # if msb is 1, change ancilla j2 to 0\n qc.cx(b[0 + self._neg_offset], anc[j2])\n for i in np.arange(0, n - 2):\n i = int(i) # which activates shifting with the 2 Toffoli gates\n qc.ccx(anc[j2], b[i + 1 + self._neg_offset], b[i + self._neg_offset])\n qc.ccx(anc[j2], b[i + self._neg_offset], b[i + 1 + self._neg_offset])\n\n for i in range(n - 2): # negate all the ancilla\n qc.x(anc[i])\n\n def shift_one_left(qc, b, n):\n for i in np.arange(n - 1, 0, -1):\n i = int(i)\n qc.cx(b[i - 1], b[i])\n qc.cx(b[i], b[i - 1])\n\n def shift_one_leftc(qc, b, ctrl, n):\n for i in np.arange(n - 2, 0, -1):\n i = int(i)\n qc.ccx(ctrl, b[i - 1], b[i])\n qc.ccx(ctrl, b[i], b[i - 1])\n return qc\n\n def shift_one_rightc(qc, b, ctrl, n):\n for i in np.arange(0, n - 1):\n i = int(i)\n qc.ccx(ctrl, b[n - 2 - i + self._neg_offset], b[n - 1 - i + self._neg_offset])\n qc.ccx(ctrl, b[n - 1 - i + self._neg_offset], b[n - 2 - i + self._neg_offset])\n\n # executing long division:\n self._circuit.x(self._a[self._n - 2])\n # initial alignment of most significant bits\n shift_to_one(self._circuit, self._ev, self._anc1, self._n)\n\n for rj in range(self._precision): # iterated subtraction and shifting\n subtract(self._circuit, self._a, self._ev, self._b0, self._c,\n self._z, self._rec, rj, self._n)\n shift_one_left(self._circuit, self._a, self._n)\n\n for ish in range(self._n - 2): # unshifting due to initial alignment\n shift_one_leftc(self._circuit, self._rec, self._anc1[ish],\n self._precision + self._num_ancillae)\n self._circuit.x(self._anc1[ish])\n shift_one_rightc(self._circuit, self._ev, self._anc1[ish], self._num_ancillae)\n self._circuit.x(self._anc1[ish])\n\n def _rotation(self):\n qc = self._circuit\n rec_reg = self._rec\n ancilla = self._anc\n\n if self._negative_evals:\n for i in range(0, self._precision + self._num_ancillae):\n qc.cu(self._scale * 2 ** (-i), 0, 0, 0, rec_reg[i], ancilla)\n qc.cry(2 * np.pi, self._ev[0], ancilla) # correcting the sign\n else:\n for i in range(0, self._precision + self._num_ancillae):\n qc.cu(self._scale * 2 ** (-i), 0, 0, 0, rec_reg[i], ancilla)\n\n self._circuit = qc\n self._rec = rec_reg\n self._anc = ancilla\n\n def construct_circuit(self, mode, register=None, circuit=None):\n \"\"\"Construct the Long Division Rotation circuit.\n\n Args:\n mode (str): construction mode, 'matrix' not supported\n register (QuantumRegister): input register, typically output register of Eigenvalues\n circuit (QuantumCircuit): Quantum Circuit or None\n Returns:\n QuantumCircuit: containing the Long Division Rotation circuit.\n Raises:\n NotImplementedError: mode not supported\n \"\"\"\n\n if mode == 'matrix':\n raise NotImplementedError('The matrix mode is not supported.')\n self._ev = register\n\n if self._scale == 0:\n self._scale = 2**-len(register)\n\n if self._negative_evals:\n self._neg_offset = 1\n\n self._num_ancillae = len(self._ev) - self._neg_offset\n if self._num_ancillae < 3:\n self._num_ancillae = 3\n if self._negative_evals is True:\n if self._num_ancillae < 4:\n self._num_ancillae = 4\n\n self._n = self._num_ancillae + 1\n\n if self._precision is None:\n self._precision = self._num_ancillae\n\n self._a = QuantumRegister(self._n, 'one') # register storing 1\n self._b0 = QuantumRegister(1, 'b0') # extension of b - required by subtraction\n # ancilla for the initial shifting\n self._anc1 = QuantumRegister(self._num_ancillae - 1, 'algn_anc')\n self._z = QuantumRegister(1, 'z') # subtraction overflow\n self._c = QuantumRegister(1, 'c') # carry\n # reciprocal result\n self._rec = QuantumRegister(self._precision + self._num_ancillae, 'res')\n self._anc = QuantumRegister(1, 'anc')\n qc = QuantumCircuit(self._a, self._b0, self._ev, self._anc1, self._c,\n self._z, self._rec, self._anc)\n\n self._circuit = qc\n self._ld_circuit()\n self._rotation()\n\n return self._circuit\n" ]
[ [ "numpy.zeros", "numpy.sum" ], [ "numpy.ceil" ], [ "numpy.sqrt" ], [ "numpy.arange", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
theHamsta/PYRO-NN-Layers
[ "c776c3d7315f483937a7cebf667c6d491ecd57e6" ]
[ "cuda_operator.py" ]
[ "# Copyright [2019] [Christopher Syben]\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# Makes every implemented operator in python available under the namespace pyronn_layers\n# PYRO-NN is developed as an Open Source project under the Apache License, Version 2.0.\n#\nimport os.path\nimport tensorflow as tf\nimport pyronn_layers\n\n\nif tf.test.is_built_with_cuda():\n _pyronn_layers_module = tf.load_op_library(os.path.dirname(__file__)+'/pyronn_layers.so')\n ''' TODO: Improve the getattr method to add only real kernel methods and not everything '''\n for obj in dir(_pyronn_layers_module):\n setattr(pyronn_layers, obj, getattr(_pyronn_layers_module, obj))\n\n\n" ]
[ [ "tensorflow.test.is_built_with_cuda" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
EnjoyLifeFund/macHighSierra-py36-pkgs
[ "5668b5785296b314ea1321057420bcd077dba9ea", "5668b5785296b314ea1321057420bcd077dba9ea", "5668b5785296b314ea1321057420bcd077dba9ea", "5668b5785296b314ea1321057420bcd077dba9ea", "5668b5785296b314ea1321057420bcd077dba9ea", "5668b5785296b314ea1321057420bcd077dba9ea", "1606c16005a5338333b4943f782f57311c6b5e49", "5668b5785296b314ea1321057420bcd077dba9ea", "5668b5785296b314ea1321057420bcd077dba9ea", "1606c16005a5338333b4943f782f57311c6b5e49", "5668b5785296b314ea1321057420bcd077dba9ea", "5668b5785296b314ea1321057420bcd077dba9ea", "5668b5785296b314ea1321057420bcd077dba9ea", "5668b5785296b314ea1321057420bcd077dba9ea", "5668b5785296b314ea1321057420bcd077dba9ea", "5668b5785296b314ea1321057420bcd077dba9ea", "5668b5785296b314ea1321057420bcd077dba9ea", "5668b5785296b314ea1321057420bcd077dba9ea", "5668b5785296b314ea1321057420bcd077dba9ea" ]
[ "torch/utils/model_zoo.py", "mir_eval/segment.py", "cvxpy_tinoco/functions/log_sum_exp.py", "numpy-1.14.0.dev0+68a58e0-py3.6-macosx-10.13-x86_64.egg/numpy/lib/nanfunctions.py", "astropy/io/fits/hdu/hdulist.py", "torch/nn/init.py", "pywt/_dwt.py", "astropy/stats/tests/test_biweight.py", "pydsm/delsig/_synthesizeNTF.py", "pywt/_cwt.py", "torch/autograd/_functions/compare.py", "cvxpy_tinoco/functions/geo_mean.py", "chainer/functions/math/logarithm_1p.py", "cvxpy_tinoco/sets/semidefinite_cone.py", "pytools/obj_array.py", "resampy/core.py", "torch/legacy/nn/Normalize.py", "astropy/modeling/fitting.py", "torch/nn/utils/rnn.py" ]
[ "import torch\n\nimport hashlib\nimport os\nimport re\nimport shutil\nimport sys\nimport tempfile\nif sys.version_info[0] == 2:\n from urlparse import urlparse\n from urllib2 import urlopen\nelse:\n from urllib.request import urlopen\n from urllib.parse import urlparse\ntry:\n from tqdm import tqdm\nexcept ImportError:\n tqdm = None # defined below\n\n# matches bfd8deac from resnet18-bfd8deac.pth\nHASH_REGEX = re.compile(r'-([a-f0-9]*)\\.')\n\n\ndef load_url(url, model_dir=None, map_location=None):\n r\"\"\"Loads the Torch serialized object at the given URL.\n\n If the object is already present in `model_dir`, it's deserialized and\n returned. The filename part of the URL should follow the naming convention\n ``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or more\n digits of the SHA256 hash of the contents of the file. The hash is used to\n ensure unique names and to verify the contents of the file.\n\n The default value of `model_dir` is ``$TORCH_HOME/models`` where\n ``$TORCH_HOME`` defaults to ``~/.torch``. The default directory can be\n overriden with the ``$TORCH_MODEL_ZOO`` environment variable.\n\n Args:\n url (string): URL of the object to download\n model_dir (string, optional): directory in which to save the object\n map_location (optional): a function or a dict specifying how to remap storage locations (see torch.load)\n\n Example:\n >>> state_dict = torch.utils.model_zoo.load_url('https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth')\n\n \"\"\"\n if model_dir is None:\n torch_home = os.path.expanduser(os.getenv('TORCH_HOME', '~/.torch'))\n model_dir = os.getenv('TORCH_MODEL_ZOO', os.path.join(torch_home, 'models'))\n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n parts = urlparse(url)\n filename = os.path.basename(parts.path)\n cached_file = os.path.join(model_dir, filename)\n if not os.path.exists(cached_file):\n sys.stderr.write('Downloading: \"{}\" to {}\\n'.format(url, cached_file))\n hash_prefix = HASH_REGEX.search(filename).group(1)\n _download_url_to_file(url, cached_file, hash_prefix)\n return torch.load(cached_file, map_location=map_location)\n\n\ndef _download_url_to_file(url, dst, hash_prefix):\n u = urlopen(url)\n meta = u.info()\n if hasattr(meta, 'getheaders'):\n file_size = int(meta.getheaders(\"Content-Length\")[0])\n else:\n file_size = int(meta.get_all(\"Content-Length\")[0])\n\n f = tempfile.NamedTemporaryFile(delete=False)\n try:\n sha256 = hashlib.sha256()\n with tqdm(total=file_size) as pbar:\n while True:\n buffer = u.read(8192)\n if len(buffer) == 0:\n break\n f.write(buffer)\n sha256.update(buffer)\n pbar.update(len(buffer))\n\n f.close()\n digest = sha256.hexdigest()\n if digest[:len(hash_prefix)] != hash_prefix:\n raise RuntimeError('invalid hash value (expected \"{}\", got \"{}\")'\n .format(hash_prefix, digest))\n shutil.move(f.name, dst)\n finally:\n f.close()\n if os.path.exists(f.name):\n os.remove(f.name)\n\n\nif tqdm is None:\n # fake tqdm if it's not installed\n class tqdm(object):\n\n def __init__(self, total):\n self.total = total\n self.n = 0\n\n def update(self, n):\n self.n += n\n sys.stderr.write(\"\\r{0:.1f}%\".format(100 * self.n / float(self.total)))\n sys.stderr.flush()\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n sys.stderr.write('\\n')\n", "# CREATED:2013-08-13 12:02:42 by Brian McFee <[email protected]>\n'''\nEvaluation criteria for structural segmentation fall into two categories:\nboundary annotation and structural annotation. Boundary annotation is the task\nof predicting the times at which structural changes occur, such as when a verse\ntransitions to a refrain. Metrics for boundary annotation compare estimated\nsegment boundaries to reference boundaries. Structural annotation is the task\nof assigning labels to detected segments. The estimated labels may be\narbitrary strings - such as A, B, C, - and they need not describe functional\nconcepts. Metrics for structural annotation are similar to those used for\nclustering data.\n\nConventions\n-----------\n\nBoth boundary and structural annotation metrics require two dimensional arrays\nwith two columns, one for boundary start times and one for boundary end times.\nStructural annotation further require lists of reference and estimated segment\nlabels which must have a length which is equal to the number of rows in the\ncorresponding list of boundary edges. In both tasks, we assume that\nannotations express a partitioning of the track into intervals. The function\n:func:`mir_eval.util.adjust_intervals` can be used to pad or crop the segment\nboundaries to span the duration of the entire track.\n\n\nMetrics\n-------\n\n* :func:`mir_eval.segment.detection`: An estimated boundary is considered\n correct if it falls within a window around a reference boundary\n* :func:`mir_eval.segment.deviation`: Computes the median absolute time\n difference from a reference boundary to its nearest estimated boundary, and\n vice versa\n* :func:`mir_eval.segment.pairwise`: For classifying pairs of sampled time\n instants as belonging to the same structural component\n* :func:`mir_eval.segment.rand_index`: Clusters reference and estimated\n annotations and compares them by the Rand Index\n* :func:`mir_eval.segment.ari`: Computes the Rand index, adjusted for chance\n* :func:`mir_eval.segment.nce`: Interprets sampled reference and estimated\n labels as samples of random variables :math:`Y_R, Y_E` from which the\n conditional entropy of :math:`Y_R` given :math:`Y_E` (Under-Segmentation) and\n :math:`Y_E` given :math:`Y_R` (Over-Segmentation) are estimated\n* :func:`mir_eval.segment.mutual_information`: Computes the standard,\n normalized, and adjusted mutual information of sampled reference and\n estimated segments\n'''\n\nimport collections\nimport warnings\n\nimport numpy as np\nimport scipy.stats\nimport scipy.sparse\nimport scipy.misc\nimport scipy.special\n\nfrom . import util\n\n\ndef validate_boundary(reference_intervals, estimated_intervals, trim):\n \"\"\"Checks that the input annotations to a segment boundary estimation\n metric (i.e. one that only takes in segment intervals) look like valid\n segment times, and throws helpful errors if not.\n\n Parameters\n ----------\n reference_intervals : np.ndarray, shape=(n, 2)\n reference segment intervals, in the format returned by\n :func:`mir_eval.io.load_intervals` or\n :func:`mir_eval.io.load_labeled_intervals`.\n\n estimated_intervals : np.ndarray, shape=(m, 2)\n estimated segment intervals, in the format returned by\n :func:`mir_eval.io.load_intervals` or\n :func:`mir_eval.io.load_labeled_intervals`.\n\n trim : bool\n will the start and end events be trimmed?\n\n \"\"\"\n\n if trim:\n # If we're trimming, then we need at least 2 intervals\n min_size = 2\n else:\n # If we're not trimming, then we only need one interval\n min_size = 1\n\n if len(reference_intervals) < min_size:\n warnings.warn(\"Reference intervals are empty.\")\n\n if len(estimated_intervals) < min_size:\n warnings.warn(\"Estimated intervals are empty.\")\n\n for intervals in [reference_intervals, estimated_intervals]:\n util.validate_intervals(intervals)\n\n\ndef validate_structure(reference_intervals, reference_labels,\n estimated_intervals, estimated_labels):\n \"\"\"Checks that the input annotations to a structure estimation metric (i.e.\n one that takes in both segment boundaries and their labels) look like valid\n segment times and labels, and throws helpful errors if not.\n\n Parameters\n ----------\n reference_intervals : np.ndarray, shape=(n, 2)\n reference segment intervals, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n\n reference_labels : list, shape=(n,)\n reference segment labels, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n\n estimated_intervals : np.ndarray, shape=(m, 2)\n estimated segment intervals, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n\n estimated_labels : list, shape=(m,)\n estimated segment labels, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n\n \"\"\"\n for (intervals, labels) in [(reference_intervals, reference_labels),\n (estimated_intervals, estimated_labels)]:\n\n util.validate_intervals(intervals)\n if intervals.shape[0] != len(labels):\n raise ValueError('Number of intervals does not match number '\n 'of labels')\n\n # Check only when intervals are non-empty\n if intervals.size > 0:\n # Make sure intervals start at 0\n if not np.allclose(intervals.min(), 0.0):\n raise ValueError('Segment intervals do not start at 0')\n\n if reference_intervals.size == 0:\n warnings.warn(\"Reference intervals are empty.\")\n if estimated_intervals.size == 0:\n warnings.warn(\"Estimated intervals are empty.\")\n # Check only when intervals are non-empty\n if reference_intervals.size > 0 and estimated_intervals.size > 0:\n if not np.allclose(reference_intervals.max(),\n estimated_intervals.max()):\n raise ValueError('End times do not match')\n\n\ndef detection(reference_intervals, estimated_intervals,\n window=0.5, beta=1.0, trim=False):\n \"\"\"Boundary detection hit-rate.\n\n A hit is counted whenever an reference boundary is within ``window`` of a\n estimated boundary. Note that each boundary is matched at most once: this\n is achieved by computing the size of a maximal matching between reference\n and estimated boundary points, subject to the window constraint.\n\n Examples\n --------\n >>> ref_intervals, _ = mir_eval.io.load_labeled_intervals('ref.lab')\n >>> est_intervals, _ = mir_eval.io.load_labeled_intervals('est.lab')\n >>> # With 0.5s windowing\n >>> P05, R05, F05 = mir_eval.segment.detection(ref_intervals,\n ... est_intervals,\n ... window=0.5)\n >>> # With 3s windowing\n >>> P3, R3, F3 = mir_eval.segment.detection(ref_intervals,\n ... est_intervals,\n ... window=3)\n >>> # Ignoring hits for the beginning and end of track\n >>> P, R, F = mir_eval.segment.detection(ref_intervals,\n ... est_intervals,\n ... window=0.5,\n ... trim=True)\n\n Parameters\n ----------\n reference_intervals : np.ndarray, shape=(n, 2)\n reference segment intervals, in the format returned by\n :func:`mir_eval.io.load_intervals` or\n :func:`mir_eval.io.load_labeled_intervals`.\n estimated_intervals : np.ndarray, shape=(m, 2)\n estimated segment intervals, in the format returned by\n :func:`mir_eval.io.load_intervals` or\n :func:`mir_eval.io.load_labeled_intervals`.\n window : float > 0\n size of the window of 'correctness' around ground-truth beats\n (in seconds)\n (Default value = 0.5)\n beta : float > 0\n weighting constant for F-measure.\n (Default value = 1.0)\n trim : boolean\n if ``True``, the first and last boundary times are ignored.\n Typically, these denote start (0) and end-markers.\n (Default value = False)\n\n Returns\n -------\n precision : float\n precision of estimated predictions\n recall : float\n recall of reference reference boundaries\n f_measure : float\n F-measure (weighted harmonic mean of ``precision`` and ``recall``)\n\n \"\"\"\n\n validate_boundary(reference_intervals, estimated_intervals, trim)\n\n # Convert intervals to boundaries\n reference_boundaries = util.intervals_to_boundaries(reference_intervals)\n estimated_boundaries = util.intervals_to_boundaries(estimated_intervals)\n\n # Suppress the first and last intervals\n if trim:\n reference_boundaries = reference_boundaries[1:-1]\n estimated_boundaries = estimated_boundaries[1:-1]\n\n # If we have no boundaries, we get no score.\n if len(reference_boundaries) == 0 or len(estimated_boundaries) == 0:\n return 0.0, 0.0, 0.0\n\n matching = util.match_events(reference_boundaries,\n estimated_boundaries,\n window)\n\n precision = float(len(matching)) / len(estimated_boundaries)\n recall = float(len(matching)) / len(reference_boundaries)\n\n f_measure = util.f_measure(precision, recall, beta=beta)\n\n return precision, recall, f_measure\n\n\ndef deviation(reference_intervals, estimated_intervals, trim=False):\n \"\"\"Compute the median deviations between reference\n and estimated boundary times.\n\n Examples\n --------\n >>> ref_intervals, _ = mir_eval.io.load_labeled_intervals('ref.lab')\n >>> est_intervals, _ = mir_eval.io.load_labeled_intervals('est.lab')\n >>> r_to_e, e_to_r = mir_eval.boundary.deviation(ref_intervals,\n ... est_intervals)\n\n Parameters\n ----------\n reference_intervals : np.ndarray, shape=(n, 2)\n reference segment intervals, in the format returned by\n :func:`mir_eval.io.load_intervals` or\n :func:`mir_eval.io.load_labeled_intervals`.\n estimated_intervals : np.ndarray, shape=(m, 2)\n estimated segment intervals, in the format returned by\n :func:`mir_eval.io.load_intervals` or\n :func:`mir_eval.io.load_labeled_intervals`.\n trim : boolean\n if ``True``, the first and last intervals are ignored.\n Typically, these denote start (0.0) and end-of-track markers.\n (Default value = False)\n\n Returns\n -------\n reference_to_estimated : float\n median time from each reference boundary to the\n closest estimated boundary\n estimated_to_reference : float\n median time from each estimated boundary to the\n closest reference boundary\n\n \"\"\"\n\n validate_boundary(reference_intervals, estimated_intervals, trim)\n\n # Convert intervals to boundaries\n reference_boundaries = util.intervals_to_boundaries(reference_intervals)\n estimated_boundaries = util.intervals_to_boundaries(estimated_intervals)\n\n # Suppress the first and last intervals\n if trim:\n reference_boundaries = reference_boundaries[1:-1]\n estimated_boundaries = estimated_boundaries[1:-1]\n\n # If we have no boundaries, we get no score.\n if len(reference_boundaries) == 0 or len(estimated_boundaries) == 0:\n return np.nan, np.nan\n\n dist = np.abs(np.subtract.outer(reference_boundaries,\n estimated_boundaries))\n\n estimated_to_reference = np.median(dist.min(axis=0))\n reference_to_estimated = np.median(dist.min(axis=1))\n\n return reference_to_estimated, estimated_to_reference\n\n\ndef pairwise(reference_intervals, reference_labels,\n estimated_intervals, estimated_labels,\n frame_size=0.1, beta=1.0):\n \"\"\"Frame-clustering segmentation evaluation by pair-wise agreement.\n\n Examples\n --------\n >>> (ref_intervals,\n ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')\n >>> (est_intervals,\n ... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')\n >>> # Trim or pad the estimate to match reference timing\n >>> (ref_intervals,\n ... ref_labels) = mir_eval.util.adjust_intervals(ref_intervals,\n ... ref_labels,\n ... t_min=0)\n >>> (est_intervals,\n ... est_labels) = mir_eval.util.adjust_intervals(\n ... est_intervals, est_labels, t_min=0, t_max=ref_intervals.max())\n >>> precision, recall, f = mir_eval.structure.pairwise(ref_intervals,\n ... ref_labels,\n ... est_intervals,\n ... est_labels)\n\n Parameters\n ----------\n reference_intervals : np.ndarray, shape=(n, 2)\n reference segment intervals, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n reference_labels : list, shape=(n,)\n reference segment labels, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n estimated_intervals : np.ndarray, shape=(m, 2)\n estimated segment intervals, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n estimated_labels : list, shape=(m,)\n estimated segment labels, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n frame_size : float > 0\n length (in seconds) of frames for clustering\n (Default value = 0.1)\n beta : float > 0\n beta value for F-measure\n (Default value = 1.0)\n\n Returns\n -------\n precision : float > 0\n Precision of detecting whether frames belong in the same cluster\n recall : float > 0\n Recall of detecting whether frames belong in the same cluster\n f : float > 0\n F-measure of detecting whether frames belong in the same cluster\n\n \"\"\"\n validate_structure(reference_intervals, reference_labels,\n estimated_intervals, estimated_labels)\n\n # Check for empty annotations. Don't need to check labels because\n # validate_structure makes sure they're the same size as intervals\n if reference_intervals.size == 0 or estimated_intervals.size == 0:\n return 0., 0., 0.\n\n # Generate the cluster labels\n y_ref = util.intervals_to_samples(reference_intervals,\n reference_labels,\n sample_size=frame_size)[-1]\n\n y_ref = util.index_labels(y_ref)[0]\n\n # Map to index space\n y_est = util.intervals_to_samples(estimated_intervals,\n estimated_labels,\n sample_size=frame_size)[-1]\n\n y_est = util.index_labels(y_est)[0]\n\n # Build the reference label agreement matrix\n agree_ref = np.equal.outer(y_ref, y_ref)\n # Count the unique pairs\n n_agree_ref = (agree_ref.sum() - len(y_ref)) / 2.0\n\n # Repeat for estimate\n agree_est = np.equal.outer(y_est, y_est)\n n_agree_est = (agree_est.sum() - len(y_est)) / 2.0\n\n # Find where they agree\n matches = np.logical_and(agree_ref, agree_est)\n n_matches = (matches.sum() - len(y_ref)) / 2.0\n\n precision = n_matches / n_agree_est\n recall = n_matches / n_agree_ref\n f_measure = util.f_measure(precision, recall, beta=beta)\n\n return precision, recall, f_measure\n\n\ndef rand_index(reference_intervals, reference_labels,\n estimated_intervals, estimated_labels,\n frame_size=0.1, beta=1.0):\n \"\"\"(Non-adjusted) Rand index.\n\n Examples\n --------\n >>> (ref_intervals,\n ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')\n >>> (est_intervals,\n ... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')\n >>> # Trim or pad the estimate to match reference timing\n >>> (ref_intervals,\n ... ref_labels) = mir_eval.util.adjust_intervals(ref_intervals,\n ... ref_labels,\n ... t_min=0)\n >>> (est_intervals,\n ... est_labels) = mir_eval.util.adjust_intervals(\n ... est_intervals, est_labels, t_min=0, t_max=ref_intervals.max())\n >>> rand_index = mir_eval.structure.rand_index(ref_intervals,\n ... ref_labels,\n ... est_intervals,\n ... est_labels)\n\n Parameters\n ----------\n reference_intervals : np.ndarray, shape=(n, 2)\n reference segment intervals, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n reference_labels : list, shape=(n,)\n reference segment labels, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n estimated_intervals : np.ndarray, shape=(m, 2)\n estimated segment intervals, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n estimated_labels : list, shape=(m,)\n estimated segment labels, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n frame_size : float > 0\n length (in seconds) of frames for clustering\n (Default value = 0.1)\n beta : float > 0\n beta value for F-measure\n (Default value = 1.0)\n\n Returns\n -------\n rand_index : float > 0\n Rand index\n\n \"\"\"\n\n validate_structure(reference_intervals, reference_labels,\n estimated_intervals, estimated_labels)\n\n # Check for empty annotations. Don't need to check labels because\n # validate_structure makes sure they're the same size as intervals\n if reference_intervals.size == 0 or estimated_intervals.size == 0:\n return 0., 0., 0.\n\n # Generate the cluster labels\n y_ref = util.intervals_to_samples(reference_intervals,\n reference_labels,\n sample_size=frame_size)[-1]\n\n y_ref = util.index_labels(y_ref)[0]\n\n # Map to index space\n y_est = util.intervals_to_samples(estimated_intervals,\n estimated_labels,\n sample_size=frame_size)[-1]\n\n y_est = util.index_labels(y_est)[0]\n\n # Build the reference label agreement matrix\n agree_ref = np.equal.outer(y_ref, y_ref)\n\n # Repeat for estimate\n agree_est = np.equal.outer(y_est, y_est)\n\n # Find where they agree\n matches_pos = np.logical_and(agree_ref, agree_est)\n\n # Find where they disagree\n matches_neg = np.logical_and(~agree_ref, ~agree_est)\n\n n_pairs = len(y_ref) * (len(y_ref) - 1) / 2.0\n\n n_matches_pos = (matches_pos.sum() - len(y_ref)) / 2.0\n n_matches_neg = matches_neg.sum() / 2.0\n rand = (n_matches_pos + n_matches_neg) / n_pairs\n\n return rand\n\n\ndef _contingency_matrix(reference_indices, estimated_indices):\n \"\"\"Computes the contingency matrix of a true labeling vs an estimated one.\n\n Parameters\n ----------\n reference_indices : np.ndarray\n Array of reference indices\n estimated_indices : np.ndarray\n Array of estimated indices\n\n Returns\n -------\n contingency_matrix : np.ndarray\n Contingency matrix, shape=(#reference indices, #estimated indices)\n .. note:: Based on sklearn.metrics.cluster.contingency_matrix\n\n \"\"\"\n ref_classes, ref_class_idx = np.unique(reference_indices,\n return_inverse=True)\n est_classes, est_class_idx = np.unique(estimated_indices,\n return_inverse=True)\n n_ref_classes = ref_classes.shape[0]\n n_est_classes = est_classes.shape[0]\n # Using coo_matrix is faster than histogram2d\n return scipy.sparse.coo_matrix((np.ones(ref_class_idx.shape[0]),\n (ref_class_idx, est_class_idx)),\n shape=(n_ref_classes, n_est_classes),\n dtype=np.int).toarray()\n\n\ndef _adjusted_rand_index(reference_indices, estimated_indices):\n \"\"\"Compute the Rand index, adjusted for change.\n\n Parameters\n ----------\n reference_indices : np.ndarray\n Array of reference indices\n estimated_indices : np.ndarray\n Array of estimated indices\n\n Returns\n -------\n ari : float\n Adjusted Rand index\n\n .. note:: Based on sklearn.metrics.cluster.adjusted_rand_score\n\n \"\"\"\n n_samples = len(reference_indices)\n ref_classes = np.unique(reference_indices)\n est_classes = np.unique(estimated_indices)\n # Special limit cases: no clustering since the data is not split;\n # or trivial clustering where each document is assigned a unique cluster.\n # These are perfect matches hence return 1.0.\n if (ref_classes.shape[0] == est_classes.shape[0] == 1 or\n ref_classes.shape[0] == est_classes.shape[0] == 0 or\n (ref_classes.shape[0] == est_classes.shape[0] ==\n len(reference_indices))):\n return 1.0\n\n contingency = _contingency_matrix(reference_indices, estimated_indices)\n\n # Compute the ARI using the contingency data\n sum_comb_c = sum(scipy.misc.comb(n_c, 2, exact=1) for n_c in\n contingency.sum(axis=1))\n sum_comb_k = sum(scipy.misc.comb(n_k, 2, exact=1) for n_k in\n contingency.sum(axis=0))\n\n sum_comb = sum((scipy.misc.comb(n_ij, 2, exact=1) for n_ij in\n contingency.flatten()))\n prod_comb = (sum_comb_c * sum_comb_k)/float(scipy.misc.comb(n_samples, 2))\n mean_comb = (sum_comb_k + sum_comb_c)/2.\n return ((sum_comb - prod_comb)/(mean_comb - prod_comb))\n\n\ndef ari(reference_intervals, reference_labels,\n estimated_intervals, estimated_labels,\n frame_size=0.1):\n \"\"\"Adjusted Rand Index (ARI) for frame clustering segmentation evaluation.\n\n Examples\n --------\n >>> (ref_intervals,\n ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')\n >>> (est_intervals,\n ... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')\n >>> # Trim or pad the estimate to match reference timing\n >>> (ref_intervals,\n ... ref_labels) = mir_eval.util.adjust_intervals(ref_intervals,\n ... ref_labels,\n ... t_min=0)\n >>> (est_intervals,\n ... est_labels) = mir_eval.util.adjust_intervals(\n ... est_intervals, est_labels, t_min=0, t_max=ref_intervals.max())\n >>> ari_score = mir_eval.structure.ari(ref_intervals, ref_labels,\n ... est_intervals, est_labels)\n\n Parameters\n ----------\n reference_intervals : np.ndarray, shape=(n, 2)\n reference segment intervals, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n reference_labels : list, shape=(n,)\n reference segment labels, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n estimated_intervals : np.ndarray, shape=(m, 2)\n estimated segment intervals, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n estimated_labels : list, shape=(m,)\n estimated segment labels, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n frame_size : float > 0\n length (in seconds) of frames for clustering\n (Default value = 0.1)\n\n Returns\n -------\n ari_score : float > 0\n Adjusted Rand index between segmentations.\n\n \"\"\"\n validate_structure(reference_intervals, reference_labels,\n estimated_intervals, estimated_labels)\n\n # Check for empty annotations. Don't need to check labels because\n # validate_structure makes sure they're the same size as intervals\n if reference_intervals.size == 0 or estimated_intervals.size == 0:\n return 0., 0., 0.\n\n # Generate the cluster labels\n y_ref = util.intervals_to_samples(reference_intervals,\n reference_labels,\n sample_size=frame_size)[-1]\n\n y_ref = util.index_labels(y_ref)[0]\n\n # Map to index space\n y_est = util.intervals_to_samples(estimated_intervals,\n estimated_labels,\n sample_size=frame_size)[-1]\n\n y_est = util.index_labels(y_est)[0]\n\n return _adjusted_rand_index(y_ref, y_est)\n\n\ndef _mutual_info_score(reference_indices, estimated_indices, contingency=None):\n \"\"\"Compute the mutual information between two sequence labelings.\n\n Parameters\n ----------\n reference_indices : np.ndarray\n Array of reference indices\n estimated_indices : np.ndarray\n Array of estimated indices\n contingency : np.ndarray\n Pre-computed contingency matrix. If None, one will be computed.\n (Default value = None)\n\n Returns\n -------\n mi : float\n Mutual information\n\n .. note:: Based on sklearn.metrics.cluster.mutual_info_score\n\n \"\"\"\n if contingency is None:\n contingency = _contingency_matrix(reference_indices,\n estimated_indices).astype(float)\n contingency_sum = np.sum(contingency)\n pi = np.sum(contingency, axis=1)\n pj = np.sum(contingency, axis=0)\n outer = np.outer(pi, pj)\n nnz = contingency != 0.0\n # normalized contingency\n contingency_nm = contingency[nnz]\n log_contingency_nm = np.log(contingency_nm)\n contingency_nm /= contingency_sum\n # log(a / b) should be calculated as log(a) - log(b) for\n # possible loss of precision\n log_outer = -np.log(outer[nnz]) + np.log(pi.sum()) + np.log(pj.sum())\n mi = (contingency_nm * (log_contingency_nm - np.log(contingency_sum)) +\n contingency_nm * log_outer)\n return mi.sum()\n\n\ndef _entropy(labels):\n \"\"\"Calculates the entropy for a labeling.\n\n Parameters\n ----------\n labels : list-like\n List of labels.\n\n Returns\n -------\n entropy : float\n Entropy of the labeling.\n\n .. note:: Based on sklearn.metrics.cluster.entropy\n\n \"\"\"\n if len(labels) == 0:\n return 1.0\n label_idx = np.unique(labels, return_inverse=True)[1]\n pi = np.bincount(label_idx).astype(np.float)\n pi = pi[pi > 0]\n pi_sum = np.sum(pi)\n # log(a / b) should be calculated as log(a) - log(b) for\n # possible loss of precision\n return -np.sum((pi / pi_sum) * (np.log(pi) - np.log(pi_sum)))\n\n\ndef _adjusted_mutual_info_score(reference_indices, estimated_indices):\n \"\"\"Compute the mutual information between two sequence labelings, adjusted for\n chance.\n\n Parameters\n ----------\n reference_indices : np.ndarray\n Array of reference indices\n\n estimated_indices : np.ndarray\n Array of estimated indices\n\n Returns\n -------\n ami : float <= 1.0\n Mutual information\n\n .. note:: Based on sklearn.metrics.cluster.adjusted_mutual_info_score\n and sklearn.metrics.cluster.expected_mutual_info_score\n\n \"\"\"\n n_samples = len(reference_indices)\n ref_classes = np.unique(reference_indices)\n est_classes = np.unique(estimated_indices)\n # Special limit cases: no clustering since the data is not split.\n # This is a perfect match hence return 1.0.\n if (ref_classes.shape[0] == est_classes.shape[0] == 1 or\n ref_classes.shape[0] == est_classes.shape[0] == 0):\n return 1.0\n contingency = _contingency_matrix(reference_indices,\n estimated_indices).astype(float)\n # Calculate the MI for the two clusterings\n mi = _mutual_info_score(reference_indices, estimated_indices,\n contingency=contingency)\n # The following code is based on\n # sklearn.metrics.cluster.expected_mutual_information\n R, C = contingency.shape\n N = float(n_samples)\n a = np.sum(contingency, axis=1).astype(np.int32)\n b = np.sum(contingency, axis=0).astype(np.int32)\n # There are three major terms to the EMI equation, which are multiplied to\n # and then summed over varying nij values.\n # While nijs[0] will never be used, having it simplifies the indexing.\n nijs = np.arange(0, max(np.max(a), np.max(b)) + 1, dtype='float')\n # Stops divide by zero warnings. As its not used, no issue.\n nijs[0] = 1\n # term1 is nij / N\n term1 = nijs / N\n # term2 is log((N*nij) / (a * b)) == log(N * nij) - log(a * b)\n # term2 uses the outer product\n log_ab_outer = np.log(np.outer(a, b))\n # term2 uses N * nij\n log_Nnij = np.log(N * nijs)\n # term3 is large, and involved many factorials. Calculate these in log\n # space to stop overflows.\n gln_a = scipy.special.gammaln(a + 1)\n gln_b = scipy.special.gammaln(b + 1)\n gln_Na = scipy.special.gammaln(N - a + 1)\n gln_Nb = scipy.special.gammaln(N - b + 1)\n gln_N = scipy.special.gammaln(N + 1)\n gln_nij = scipy.special.gammaln(nijs + 1)\n # start and end values for nij terms for each summation.\n start = np.array([[v - N + w for w in b] for v in a], dtype='int')\n start = np.maximum(start, 1)\n end = np.minimum(np.resize(a, (C, R)).T, np.resize(b, (R, C))) + 1\n # emi itself is a summation over the various values.\n emi = 0\n for i in range(R):\n for j in range(C):\n for nij in range(start[i, j], end[i, j]):\n term2 = log_Nnij[nij] - log_ab_outer[i, j]\n # Numerators are positive, denominators are negative.\n gln = (gln_a[i] + gln_b[j] + gln_Na[i] + gln_Nb[j] -\n gln_N - gln_nij[nij] -\n scipy.special.gammaln(a[i] - nij + 1) -\n scipy.special.gammaln(b[j] - nij + 1) -\n scipy.special.gammaln(N - a[i] - b[j] + nij + 1))\n term3 = np.exp(gln)\n emi += (term1[nij] * term2 * term3)\n # Calculate entropy for each labeling\n h_true, h_pred = _entropy(reference_indices), _entropy(estimated_indices)\n ami = (mi - emi) / (max(h_true, h_pred) - emi)\n return ami\n\n\ndef _normalized_mutual_info_score(reference_indices, estimated_indices):\n \"\"\"Compute the mutual information between two sequence labelings, adjusted for\n chance.\n\n Parameters\n ----------\n reference_indices : np.ndarray\n Array of reference indices\n\n estimated_indices : np.ndarray\n Array of estimated indices\n\n Returns\n -------\n nmi : float <= 1.0\n Normalized mutual information\n\n .. note:: Based on sklearn.metrics.cluster.normalized_mutual_info_score\n\n \"\"\"\n ref_classes = np.unique(reference_indices)\n est_classes = np.unique(estimated_indices)\n # Special limit cases: no clustering since the data is not split.\n # This is a perfect match hence return 1.0.\n if (ref_classes.shape[0] == est_classes.shape[0] == 1 or\n ref_classes.shape[0] == est_classes.shape[0] == 0):\n return 1.0\n contingency = _contingency_matrix(reference_indices,\n estimated_indices).astype(float)\n contingency = np.array(contingency, dtype='float')\n # Calculate the MI for the two clusterings\n mi = _mutual_info_score(reference_indices, estimated_indices,\n contingency=contingency)\n # Calculate the expected value for the mutual information\n # Calculate entropy for each labeling\n h_true, h_pred = _entropy(reference_indices), _entropy(estimated_indices)\n nmi = mi / max(np.sqrt(h_true * h_pred), 1e-10)\n return nmi\n\n\ndef mutual_information(reference_intervals, reference_labels,\n estimated_intervals, estimated_labels,\n frame_size=0.1):\n \"\"\"Frame-clustering segmentation: mutual information metrics.\n\n Examples\n --------\n >>> (ref_intervals,\n ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')\n >>> (est_intervals,\n ... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')\n >>> # Trim or pad the estimate to match reference timing\n >>> (ref_intervals,\n ... ref_labels) = mir_eval.util.adjust_intervals(ref_intervals,\n ... ref_labels,\n ... t_min=0)\n >>> (est_intervals,\n ... est_labels) = mir_eval.util.adjust_intervals(\n ... est_intervals, est_labels, t_min=0, t_max=ref_intervals.max())\n >>> mi, ami, nmi = mir_eval.structure.mutual_information(ref_intervals,\n ... ref_labels,\n ... est_intervals,\n ... est_labels)\n\n Parameters\n ----------\n reference_intervals : np.ndarray, shape=(n, 2)\n reference segment intervals, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n reference_labels : list, shape=(n,)\n reference segment labels, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n estimated_intervals : np.ndarray, shape=(m, 2)\n estimated segment intervals, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n estimated_labels : list, shape=(m,)\n estimated segment labels, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n frame_size : float > 0\n length (in seconds) of frames for clustering\n (Default value = 0.1)\n\n Returns\n -------\n MI : float > 0\n Mutual information between segmentations\n AMI : float\n Adjusted mutual information between segmentations.\n NMI : float > 0\n Normalize mutual information between segmentations\n\n \"\"\"\n validate_structure(reference_intervals, reference_labels,\n estimated_intervals, estimated_labels)\n\n # Check for empty annotations. Don't need to check labels because\n # validate_structure makes sure they're the same size as intervals\n if reference_intervals.size == 0 or estimated_intervals.size == 0:\n return 0., 0., 0.\n\n # Generate the cluster labels\n y_ref = util.intervals_to_samples(reference_intervals,\n reference_labels,\n sample_size=frame_size)[-1]\n\n y_ref = util.index_labels(y_ref)[0]\n\n # Map to index space\n y_est = util.intervals_to_samples(estimated_intervals,\n estimated_labels,\n sample_size=frame_size)[-1]\n\n y_est = util.index_labels(y_est)[0]\n\n # Mutual information\n mutual_info = _mutual_info_score(y_ref, y_est)\n\n # Adjusted mutual information\n adj_mutual_info = _adjusted_mutual_info_score(y_ref, y_est)\n\n # Normalized mutual information\n norm_mutual_info = _normalized_mutual_info_score(y_ref, y_est)\n\n return mutual_info, adj_mutual_info, norm_mutual_info\n\n\ndef nce(reference_intervals, reference_labels, estimated_intervals,\n estimated_labels, frame_size=0.1, beta=1.0):\n \"\"\"Frame-clustering segmentation: normalized conditional entropy\n\n Computes cross-entropy of cluster assignment, normalized by the\n max-entropy.\n\n Examples\n --------\n >>> (ref_intervals,\n ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')\n >>> (est_intervals,\n ... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')\n >>> # Trim or pad the estimate to match reference timing\n >>> (ref_intervals,\n ... ref_labels) = mir_eval.util.adjust_intervals(ref_intervals,\n ... ref_labels,\n ... t_min=0)\n >>> (est_intervals,\n ... est_labels) = mir_eval.util.adjust_intervals(\n ... est_intervals, est_labels, t_min=0, t_max=ref_intervals.max())\n >>> S_over, S_under, S_F = mir_eval.structure.nce(ref_intervals,\n ... ref_labels,\n ... est_intervals,\n ... est_labels)\n\n Parameters\n ----------\n reference_intervals : np.ndarray, shape=(n, 2)\n reference segment intervals, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n reference_labels : list, shape=(n,)\n reference segment labels, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n estimated_intervals : np.ndarray, shape=(m, 2)\n estimated segment intervals, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n estimated_labels : list, shape=(m,)\n estimated segment labels, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n frame_size : float > 0\n length (in seconds) of frames for clustering\n (Default value = 0.1)\n beta : float > 0\n beta for F-measure\n (Default value = 1.0)\n\n Returns\n -------\n S_over\n Over-clustering score:\n ``1 - H(y_est | y_ref) / log(|y_est|)``\n If `|y_est|==1`, then `S_over` will be 0.\n S_under\n Under-clustering score:\n ``1 - H(y_ref | y_est) / log(|y_ref|)``\n If `|y_ref|==1`, then `S_under` will be 0.\n S_F\n F-measure for (S_over, S_under)\n\n \"\"\"\n\n validate_structure(reference_intervals, reference_labels,\n estimated_intervals, estimated_labels)\n\n # Check for empty annotations. Don't need to check labels because\n # validate_structure makes sure they're the same size as intervals\n if reference_intervals.size == 0 or estimated_intervals.size == 0:\n return 0., 0., 0.\n\n # Generate the cluster labels\n y_ref = util.intervals_to_samples(reference_intervals,\n reference_labels,\n sample_size=frame_size)[-1]\n\n y_ref = util.index_labels(y_ref)[0]\n\n # Map to index space\n y_est = util.intervals_to_samples(estimated_intervals,\n estimated_labels,\n sample_size=frame_size)[-1]\n\n y_est = util.index_labels(y_est)[0]\n\n # Make the contingency table: shape = (n_ref, n_est)\n contingency = _contingency_matrix(y_ref, y_est).astype(float)\n\n # Normalize by the number of frames\n contingency = contingency / len(y_ref)\n\n # Compute the marginals\n p_est = contingency.sum(axis=0)\n p_ref = contingency.sum(axis=1)\n\n # H(true | prediction) = sum_j P[estimated = j] *\n # sum_i P[true = i | estimated = j] log P[true = i | estimated = j]\n # entropy sums over axis=0, which is true labels\n\n # The following scipy.stats.entropy calls are equivalent to\n # scipy.stats.entropy(contingency, base=2)\n # However the `base` kwarg has only been introduced in scipy 0.14.0\n true_given_est = p_est.dot(scipy.stats.entropy(contingency) / np.log(2))\n pred_given_ref = p_ref.dot(scipy.stats.entropy(contingency.T) / np.log(2))\n\n score_under = 0.0\n if contingency.shape[0] > 1:\n score_under = 1. - true_given_est / np.log2(contingency.shape[0])\n\n score_over = 0.0\n if contingency.shape[1] > 1:\n score_over = 1. - pred_given_ref / np.log2(contingency.shape[1])\n\n f_measure = util.f_measure(score_over, score_under, beta=beta)\n\n return score_over, score_under, f_measure\n\n\ndef evaluate(ref_intervals, ref_labels, est_intervals, est_labels, **kwargs):\n \"\"\"Compute all metrics for the given reference and estimated annotations.\n\n Examples\n --------\n >>> (ref_intervals,\n ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')\n >>> (est_intervals,\n ... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')\n >>> scores = mir_eval.segment.evaluate(ref_intervals, ref_labels,\n ... est_intervals, est_labels)\n\n Parameters\n ----------\n ref_intervals : np.ndarray, shape=(n, 2)\n reference segment intervals, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n ref_labels : list, shape=(n,)\n reference segment labels, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n est_intervals : np.ndarray, shape=(m, 2)\n estimated segment intervals, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n est_labels : list, shape=(m,)\n estimated segment labels, in the format returned by\n :func:`mir_eval.io.load_labeled_intervals`.\n kwargs\n Additional keyword arguments which will be passed to the\n appropriate metric or preprocessing functions.\n\n Returns\n -------\n scores : dict\n Dictionary of scores, where the key is the metric name (str) and\n the value is the (float) score achieved.\n\n \"\"\"\n\n # Adjust timespan of estimations relative to ground truth\n ref_intervals, ref_labels = \\\n util.adjust_intervals(ref_intervals, labels=ref_labels, t_min=0.0)\n\n est_intervals, est_labels = \\\n util.adjust_intervals(est_intervals, labels=est_labels, t_min=0.0,\n t_max=ref_intervals.max())\n\n # Now compute all the metrics\n scores = collections.OrderedDict()\n\n # Boundary detection\n # Force these values for window\n kwargs['window'] = .5\n scores['[email protected]'], scores['[email protected]'], scores['[email protected]'] = \\\n util.filter_kwargs(detection, ref_intervals, est_intervals, **kwargs)\n\n kwargs['window'] = 3.0\n scores['[email protected]'], scores['[email protected]'], scores['[email protected]'] = \\\n util.filter_kwargs(detection, ref_intervals, est_intervals, **kwargs)\n\n # Boundary deviation\n scores['Ref-to-est deviation'], scores['Est-to-ref deviation'] = \\\n util.filter_kwargs(deviation, ref_intervals, est_intervals, **kwargs)\n\n # Pairwise clustering\n (scores['Pairwise Precision'],\n scores['Pairwise Recall'],\n scores['Pairwise F-measure']) = util.filter_kwargs(pairwise,\n ref_intervals,\n ref_labels,\n est_intervals,\n est_labels, **kwargs)\n\n # Rand index\n scores['Rand Index'] = util.filter_kwargs(rand_index, ref_intervals,\n ref_labels, est_intervals,\n est_labels, **kwargs)\n # Adjusted rand index\n scores['Adjusted Rand Index'] = util.filter_kwargs(ari, ref_intervals,\n ref_labels,\n est_intervals,\n est_labels, **kwargs)\n\n # Mutual information metrics\n (scores['Mutual Information'],\n scores['Adjusted Mutual Information'],\n scores['Normalized Mutual Information']) = \\\n util.filter_kwargs(mutual_information, ref_intervals, ref_labels,\n est_intervals, est_labels, **kwargs)\n\n # Conditional entropy metrics\n scores['NCE Over'], scores['NCE Under'], scores['NCE F-measure'] = \\\n util.filter_kwargs(nce, ref_intervals, ref_labels, est_intervals,\n est_labels, **kwargs)\n\n return scores\n", "#***********************************************************************#\n# Copyright (C) 2010-2012 Tomas Tinoco De Rubira #\n# #\n# This file is part of CVXPY # \n# #\n# CVXPY is free software: you can redistribute it and/or modify #\n# it under the terms of the GNU General Public License as published by #\n# the Free Software Foundation, either version 3 of the License, or # \n# (at your option) any later version. # \n# #\n# CVXPY is distributed in the hope that it will be useful, #\n# but WITHOUT ANY WARRANTY; without even the implied warranty of #\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #\n# GNU General Public License for more details. #\n# #\n# You should have received a copy of the GNU General Public License #\n# along with this program. If not, see <http://www.gnu.org/licenses/>. #\n#***********************************************************************#\n\nimport numpy as np\nfrom ..defs import *\nfrom ..utils import *\nfrom ..sets import *\nfrom ..interface import *\nfrom ..arrays import cvxpy_array\nfrom ..arrays import cvxpy_matrix\n\n# log_sum_exp\ndef log_sum_exp(x):\n \"\"\"\n | :math:`\\mbox{log\\_sum\\_exp} :\n \\mathbb{R}^n \\\\to \\mathbb{R},\n \\ \\mbox{log\\_sum\\_exp}(x) = \n \\mbox{log} \\\\big( \\sum_{i = 1}^n e^{x_i} \\\\big)`.\n | Convex and increasing.\n\n :param x: number, \n :ref:`scalar object<scalar_ref>` or\n :ref:`multidimensional object<multi_ref>`.\n :return: number or \n :ref:`scalar object<scalar_ref>`.\n \"\"\"\n\n # Check input\n if (np.isscalar(x) or \n type(x).__name__ in SCALAR_OBJS):\n return x\n elif (type(x) is not cvxpy_matrix and\n type(x).__name__ not in ARRAY_OBJS):\n raise TypeError('Invalid argument type')\n\n # Must be column\n if x.shape[1] != 1:\n raise ValueError('Invalid argument dimensions')\n\n # Single element\n if x.shape == (1,1):\n return x[0,0]\n\n # Construct program\n t = variable()\n z = variable(x.shape[0],1)\n v = variable(x.shape[0],1)\n w = variable(x.shape[0],1)\n constr = [equals(sum(w),1)]\n for i in range(0,x.shape[0],1):\n constr += [belongs(vstack((v[i,0]-t,1.,w[i,0])),\n exp_cone),\n less_equals(z[i,0],v[i,0])]\n p = program(minimize(t),\n constr,\n [z], \n name='log_sum_exp')\n\n # Return \n return p(x)\n", "\"\"\"\nFunctions that ignore NaN.\n\nFunctions\n---------\n\n- `nanmin` -- minimum non-NaN value\n- `nanmax` -- maximum non-NaN value\n- `nanargmin` -- index of minimum non-NaN value\n- `nanargmax` -- index of maximum non-NaN value\n- `nansum` -- sum of non-NaN values\n- `nanprod` -- product of non-NaN values\n- `nancumsum` -- cumulative sum of non-NaN values\n- `nancumprod` -- cumulative product of non-NaN values\n- `nanmean` -- mean of non-NaN values\n- `nanvar` -- variance of non-NaN values\n- `nanstd` -- standard deviation of non-NaN values\n- `nanmedian` -- median of non-NaN values\n- `nanpercentile` -- qth percentile of non-NaN values\n\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\n\nimport warnings\nimport numpy as np\nfrom numpy.lib.function_base import _ureduce as _ureduce\n\n\n__all__ = [\n 'nansum', 'nanmax', 'nanmin', 'nanargmax', 'nanargmin', 'nanmean',\n 'nanmedian', 'nanpercentile', 'nanvar', 'nanstd', 'nanprod',\n 'nancumsum', 'nancumprod'\n ]\n\n\ndef _replace_nan(a, val):\n \"\"\"\n If `a` is of inexact type, make a copy of `a`, replace NaNs with\n the `val` value, and return the copy together with a boolean mask\n marking the locations where NaNs were present. If `a` is not of\n inexact type, do nothing and return `a` together with a mask of None.\n\n Note that scalars will end up as array scalars, which is important\n for using the result as the value of the out argument in some\n operations.\n\n Parameters\n ----------\n a : array-like\n Input array.\n val : float\n NaN values are set to val before doing the operation.\n\n Returns\n -------\n y : ndarray\n If `a` is of inexact type, return a copy of `a` with the NaNs\n replaced by the fill value, otherwise return `a`.\n mask: {bool, None}\n If `a` is of inexact type, return a boolean mask marking locations of\n NaNs, otherwise return None.\n\n \"\"\"\n a = np.array(a, subok=True, copy=True)\n\n if a.dtype == np.object_:\n # object arrays do not support `isnan` (gh-9009), so make a guess\n mask = a != a\n elif issubclass(a.dtype.type, np.inexact):\n mask = np.isnan(a)\n else:\n mask = None\n\n if mask is not None:\n np.copyto(a, val, where=mask)\n\n return a, mask\n\n\ndef _copyto(a, val, mask):\n \"\"\"\n Replace values in `a` with NaN where `mask` is True. This differs from\n copyto in that it will deal with the case where `a` is a numpy scalar.\n\n Parameters\n ----------\n a : ndarray or numpy scalar\n Array or numpy scalar some of whose values are to be replaced\n by val.\n val : numpy scalar\n Value used a replacement.\n mask : ndarray, scalar\n Boolean array. Where True the corresponding element of `a` is\n replaced by `val`. Broadcasts.\n\n Returns\n -------\n res : ndarray, scalar\n Array with elements replaced or scalar `val`.\n\n \"\"\"\n if isinstance(a, np.ndarray):\n np.copyto(a, val, where=mask, casting='unsafe')\n else:\n a = a.dtype.type(val)\n return a\n\n\ndef _remove_nan_1d(arr1d, overwrite_input=False):\n \"\"\"\n Equivalent to arr1d[~arr1d.isnan()], but in a different order\n\n Presumably faster as it incurs fewer copies\n\n Parameters\n ----------\n arr1d : ndarray\n Array to remove nans from\n overwrite_input : bool\n True if `arr1d` can be modified in place\n\n Returns\n -------\n res : ndarray\n Array with nan elements removed\n overwrite_input : bool\n True if `res` can be modified in place, given the constraint on the\n input\n \"\"\"\n\n c = np.isnan(arr1d)\n s = np.nonzero(c)[0]\n if s.size == arr1d.size:\n warnings.warn(\"All-NaN slice encountered\", RuntimeWarning, stacklevel=4)\n return arr1d[:0], True\n elif s.size == 0:\n return arr1d, overwrite_input\n else:\n if not overwrite_input:\n arr1d = arr1d.copy()\n # select non-nans at end of array\n enonan = arr1d[-s.size:][~c[-s.size:]]\n # fill nans in beginning of array with non-nans of end\n arr1d[s[:enonan.size]] = enonan\n\n return arr1d[:-s.size], True\n\n\ndef _divide_by_count(a, b, out=None):\n \"\"\"\n Compute a/b ignoring invalid results. If `a` is an array the division\n is done in place. If `a` is a scalar, then its type is preserved in the\n output. If out is None, then then a is used instead so that the\n division is in place. Note that this is only called with `a` an inexact\n type.\n\n Parameters\n ----------\n a : {ndarray, numpy scalar}\n Numerator. Expected to be of inexact type but not checked.\n b : {ndarray, numpy scalar}\n Denominator.\n out : ndarray, optional\n Alternate output array in which to place the result. The default\n is ``None``; if provided, it must have the same shape as the\n expected output, but the type will be cast if necessary.\n\n Returns\n -------\n ret : {ndarray, numpy scalar}\n The return value is a/b. If `a` was an ndarray the division is done\n in place. If `a` is a numpy scalar, the division preserves its type.\n\n \"\"\"\n with np.errstate(invalid='ignore', divide='ignore'):\n if isinstance(a, np.ndarray):\n if out is None:\n return np.divide(a, b, out=a, casting='unsafe')\n else:\n return np.divide(a, b, out=out, casting='unsafe')\n else:\n if out is None:\n return a.dtype.type(a / b)\n else:\n # This is questionable, but currently a numpy scalar can\n # be output to a zero dimensional array.\n return np.divide(a, b, out=out, casting='unsafe')\n\n\ndef nanmin(a, axis=None, out=None, keepdims=np._NoValue):\n \"\"\"\n Return minimum of an array or minimum along an axis, ignoring any NaNs.\n When all-NaN slices are encountered a ``RuntimeWarning`` is raised and\n Nan is returned for that slice.\n\n Parameters\n ----------\n a : array_like\n Array containing numbers whose minimum is desired. If `a` is not an\n array, a conversion is attempted.\n axis : int, optional\n Axis along which the minimum is computed. The default is to compute\n the minimum of the flattened array.\n out : ndarray, optional\n Alternate output array in which to place the result. The default\n is ``None``; if provided, it must have the same shape as the\n expected output, but the type will be cast if necessary. See\n `doc.ufuncs` for details.\n\n .. versionadded:: 1.8.0\n keepdims : bool, optional\n If this is set to True, the axes which are reduced are left\n in the result as dimensions with size one. With this option,\n the result will broadcast correctly against the original `a`.\n\n If the value is anything but the default, then\n `keepdims` will be passed through to the `min` method\n of sub-classes of `ndarray`. If the sub-classes methods\n does not implement `keepdims` any exceptions will be raised.\n\n .. versionadded:: 1.8.0\n\n Returns\n -------\n nanmin : ndarray\n An array with the same shape as `a`, with the specified axis\n removed. If `a` is a 0-d array, or if axis is None, an ndarray\n scalar is returned. The same dtype as `a` is returned.\n\n See Also\n --------\n nanmax :\n The maximum value of an array along a given axis, ignoring any NaNs.\n amin :\n The minimum value of an array along a given axis, propagating any NaNs.\n fmin :\n Element-wise minimum of two arrays, ignoring any NaNs.\n minimum :\n Element-wise minimum of two arrays, propagating any NaNs.\n isnan :\n Shows which elements are Not a Number (NaN).\n isfinite:\n Shows which elements are neither NaN nor infinity.\n\n amax, fmax, maximum\n\n Notes\n -----\n NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic\n (IEEE 754). This means that Not a Number is not equivalent to infinity.\n Positive infinity is treated as a very large number and negative\n infinity is treated as a very small (i.e. negative) number.\n\n If the input has a integer type the function is equivalent to np.min.\n\n Examples\n --------\n >>> a = np.array([[1, 2], [3, np.nan]])\n >>> np.nanmin(a)\n 1.0\n >>> np.nanmin(a, axis=0)\n array([ 1., 2.])\n >>> np.nanmin(a, axis=1)\n array([ 1., 3.])\n\n When positive infinity and negative infinity are present:\n\n >>> np.nanmin([1, 2, np.nan, np.inf])\n 1.0\n >>> np.nanmin([1, 2, np.nan, np.NINF])\n -inf\n\n \"\"\"\n kwargs = {}\n if keepdims is not np._NoValue:\n kwargs['keepdims'] = keepdims\n if type(a) is np.ndarray and a.dtype != np.object_:\n # Fast, but not safe for subclasses of ndarray, or object arrays,\n # which do not implement isnan (gh-9009), or fmin correctly (gh-8975)\n res = np.fmin.reduce(a, axis=axis, out=out, **kwargs)\n if np.isnan(res).any():\n warnings.warn(\"All-NaN axis encountered\", RuntimeWarning, stacklevel=2)\n else:\n # Slow, but safe for subclasses of ndarray\n a, mask = _replace_nan(a, +np.inf)\n res = np.amin(a, axis=axis, out=out, **kwargs)\n if mask is None:\n return res\n\n # Check for all-NaN axis\n mask = np.all(mask, axis=axis, **kwargs)\n if np.any(mask):\n res = _copyto(res, np.nan, mask)\n warnings.warn(\"All-NaN axis encountered\", RuntimeWarning, stacklevel=2)\n return res\n\n\ndef nanmax(a, axis=None, out=None, keepdims=np._NoValue):\n \"\"\"\n Return the maximum of an array or maximum along an axis, ignoring any\n NaNs. When all-NaN slices are encountered a ``RuntimeWarning`` is\n raised and NaN is returned for that slice.\n\n Parameters\n ----------\n a : array_like\n Array containing numbers whose maximum is desired. If `a` is not an\n array, a conversion is attempted.\n axis : int, optional\n Axis along which the maximum is computed. The default is to compute\n the maximum of the flattened array.\n out : ndarray, optional\n Alternate output array in which to place the result. The default\n is ``None``; if provided, it must have the same shape as the\n expected output, but the type will be cast if necessary. See\n `doc.ufuncs` for details.\n\n .. versionadded:: 1.8.0\n keepdims : bool, optional\n If this is set to True, the axes which are reduced are left\n in the result as dimensions with size one. With this option,\n the result will broadcast correctly against the original `a`.\n\n If the value is anything but the default, then\n `keepdims` will be passed through to the `max` method\n of sub-classes of `ndarray`. If the sub-classes methods\n does not implement `keepdims` any exceptions will be raised.\n\n .. versionadded:: 1.8.0\n\n Returns\n -------\n nanmax : ndarray\n An array with the same shape as `a`, with the specified axis removed.\n If `a` is a 0-d array, or if axis is None, an ndarray scalar is\n returned. The same dtype as `a` is returned.\n\n See Also\n --------\n nanmin :\n The minimum value of an array along a given axis, ignoring any NaNs.\n amax :\n The maximum value of an array along a given axis, propagating any NaNs.\n fmax :\n Element-wise maximum of two arrays, ignoring any NaNs.\n maximum :\n Element-wise maximum of two arrays, propagating any NaNs.\n isnan :\n Shows which elements are Not a Number (NaN).\n isfinite:\n Shows which elements are neither NaN nor infinity.\n\n amin, fmin, minimum\n\n Notes\n -----\n NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic\n (IEEE 754). This means that Not a Number is not equivalent to infinity.\n Positive infinity is treated as a very large number and negative\n infinity is treated as a very small (i.e. negative) number.\n\n If the input has a integer type the function is equivalent to np.max.\n\n Examples\n --------\n >>> a = np.array([[1, 2], [3, np.nan]])\n >>> np.nanmax(a)\n 3.0\n >>> np.nanmax(a, axis=0)\n array([ 3., 2.])\n >>> np.nanmax(a, axis=1)\n array([ 2., 3.])\n\n When positive infinity and negative infinity are present:\n\n >>> np.nanmax([1, 2, np.nan, np.NINF])\n 2.0\n >>> np.nanmax([1, 2, np.nan, np.inf])\n inf\n\n \"\"\"\n kwargs = {}\n if keepdims is not np._NoValue:\n kwargs['keepdims'] = keepdims\n if type(a) is np.ndarray and a.dtype != np.object_:\n # Fast, but not safe for subclasses of ndarray, or object arrays,\n # which do not implement isnan (gh-9009), or fmax correctly (gh-8975)\n res = np.fmax.reduce(a, axis=axis, out=out, **kwargs)\n if np.isnan(res).any():\n warnings.warn(\"All-NaN slice encountered\", RuntimeWarning, stacklevel=2)\n else:\n # Slow, but safe for subclasses of ndarray\n a, mask = _replace_nan(a, -np.inf)\n res = np.amax(a, axis=axis, out=out, **kwargs)\n if mask is None:\n return res\n\n # Check for all-NaN axis\n mask = np.all(mask, axis=axis, **kwargs)\n if np.any(mask):\n res = _copyto(res, np.nan, mask)\n warnings.warn(\"All-NaN axis encountered\", RuntimeWarning, stacklevel=2)\n return res\n\n\ndef nanargmin(a, axis=None):\n \"\"\"\n Return the indices of the minimum values in the specified axis ignoring\n NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results\n cannot be trusted if a slice contains only NaNs and Infs.\n\n Parameters\n ----------\n a : array_like\n Input data.\n axis : int, optional\n Axis along which to operate. By default flattened input is used.\n\n Returns\n -------\n index_array : ndarray\n An array of indices or a single index value.\n\n See Also\n --------\n argmin, nanargmax\n\n Examples\n --------\n >>> a = np.array([[np.nan, 4], [2, 3]])\n >>> np.argmin(a)\n 0\n >>> np.nanargmin(a)\n 2\n >>> np.nanargmin(a, axis=0)\n array([1, 1])\n >>> np.nanargmin(a, axis=1)\n array([1, 0])\n\n \"\"\"\n a, mask = _replace_nan(a, np.inf)\n res = np.argmin(a, axis=axis)\n if mask is not None:\n mask = np.all(mask, axis=axis)\n if np.any(mask):\n raise ValueError(\"All-NaN slice encountered\")\n return res\n\n\ndef nanargmax(a, axis=None):\n \"\"\"\n Return the indices of the maximum values in the specified axis ignoring\n NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the\n results cannot be trusted if a slice contains only NaNs and -Infs.\n\n\n Parameters\n ----------\n a : array_like\n Input data.\n axis : int, optional\n Axis along which to operate. By default flattened input is used.\n\n Returns\n -------\n index_array : ndarray\n An array of indices or a single index value.\n\n See Also\n --------\n argmax, nanargmin\n\n Examples\n --------\n >>> a = np.array([[np.nan, 4], [2, 3]])\n >>> np.argmax(a)\n 0\n >>> np.nanargmax(a)\n 1\n >>> np.nanargmax(a, axis=0)\n array([1, 0])\n >>> np.nanargmax(a, axis=1)\n array([1, 1])\n\n \"\"\"\n a, mask = _replace_nan(a, -np.inf)\n res = np.argmax(a, axis=axis)\n if mask is not None:\n mask = np.all(mask, axis=axis)\n if np.any(mask):\n raise ValueError(\"All-NaN slice encountered\")\n return res\n\n\ndef nansum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue):\n \"\"\"\n Return the sum of array elements over a given axis treating Not a\n Numbers (NaNs) as zero.\n\n In NumPy versions <= 1.8.0 Nan is returned for slices that are all-NaN or\n empty. In later versions zero is returned.\n\n Parameters\n ----------\n a : array_like\n Array containing numbers whose sum is desired. If `a` is not an\n array, a conversion is attempted.\n axis : int, optional\n Axis along which the sum is computed. The default is to compute the\n sum of the flattened array.\n dtype : data-type, optional\n The type of the returned array and of the accumulator in which the\n elements are summed. By default, the dtype of `a` is used. An\n exception is when `a` has an integer type with less precision than\n the platform (u)intp. In that case, the default will be either\n (u)int32 or (u)int64 depending on whether the platform is 32 or 64\n bits. For inexact inputs, dtype must be inexact.\n\n .. versionadded:: 1.8.0\n out : ndarray, optional\n Alternate output array in which to place the result. The default\n is ``None``. If provided, it must have the same shape as the\n expected output, but the type will be cast if necessary. See\n `doc.ufuncs` for details. The casting of NaN to integer can yield\n unexpected results.\n\n .. versionadded:: 1.8.0\n keepdims : bool, optional\n If this is set to True, the axes which are reduced are left\n in the result as dimensions with size one. With this option,\n the result will broadcast correctly against the original `a`.\n\n\n If the value is anything but the default, then\n `keepdims` will be passed through to the `mean` or `sum` methods\n of sub-classes of `ndarray`. If the sub-classes methods\n does not implement `keepdims` any exceptions will be raised.\n\n .. versionadded:: 1.8.0\n\n Returns\n -------\n nansum : ndarray.\n A new array holding the result is returned unless `out` is\n specified, in which it is returned. The result has the same\n size as `a`, and the same shape as `a` if `axis` is not None\n or `a` is a 1-d array.\n\n See Also\n --------\n numpy.sum : Sum across array propagating NaNs.\n isnan : Show which elements are NaN.\n isfinite: Show which elements are not NaN or +/-inf.\n\n Notes\n -----\n If both positive and negative infinity are present, the sum will be Not\n A Number (NaN).\n\n Examples\n --------\n >>> np.nansum(1)\n 1\n >>> np.nansum([1])\n 1\n >>> np.nansum([1, np.nan])\n 1.0\n >>> a = np.array([[1, 1], [1, np.nan]])\n >>> np.nansum(a)\n 3.0\n >>> np.nansum(a, axis=0)\n array([ 2., 1.])\n >>> np.nansum([1, np.nan, np.inf])\n inf\n >>> np.nansum([1, np.nan, np.NINF])\n -inf\n >>> np.nansum([1, np.nan, np.inf, -np.inf]) # both +/- infinity present\n nan\n\n \"\"\"\n a, mask = _replace_nan(a, 0)\n return np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)\n\n\ndef nanprod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue):\n \"\"\"\n Return the product of array elements over a given axis treating Not a\n Numbers (NaNs) as ones.\n\n One is returned for slices that are all-NaN or empty.\n\n .. versionadded:: 1.10.0\n\n Parameters\n ----------\n a : array_like\n Array containing numbers whose sum is desired. If `a` is not an\n array, a conversion is attempted.\n axis : int, optional\n Axis along which the product is computed. The default is to compute\n the product of the flattened array.\n dtype : data-type, optional\n The type of the returned array and of the accumulator in which the\n elements are summed. By default, the dtype of `a` is used. An\n exception is when `a` has an integer type with less precision than\n the platform (u)intp. In that case, the default will be either\n (u)int32 or (u)int64 depending on whether the platform is 32 or 64\n bits. For inexact inputs, dtype must be inexact.\n out : ndarray, optional\n Alternate output array in which to place the result. The default\n is ``None``. If provided, it must have the same shape as the\n expected output, but the type will be cast if necessary. See\n `doc.ufuncs` for details. The casting of NaN to integer can yield\n unexpected results.\n keepdims : bool, optional\n If True, the axes which are reduced are left in the result as\n dimensions with size one. With this option, the result will\n broadcast correctly against the original `arr`.\n\n Returns\n -------\n nanprod : ndarray\n A new array holding the result is returned unless `out` is\n specified, in which case it is returned.\n\n See Also\n --------\n numpy.prod : Product across array propagating NaNs.\n isnan : Show which elements are NaN.\n\n Examples\n --------\n >>> np.nanprod(1)\n 1\n >>> np.nanprod([1])\n 1\n >>> np.nanprod([1, np.nan])\n 1.0\n >>> a = np.array([[1, 2], [3, np.nan]])\n >>> np.nanprod(a)\n 6.0\n >>> np.nanprod(a, axis=0)\n array([ 3., 2.])\n\n \"\"\"\n a, mask = _replace_nan(a, 1)\n return np.prod(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)\n\n\ndef nancumsum(a, axis=None, dtype=None, out=None):\n \"\"\"\n Return the cumulative sum of array elements over a given axis treating Not a\n Numbers (NaNs) as zero. The cumulative sum does not change when NaNs are\n encountered and leading NaNs are replaced by zeros.\n\n Zeros are returned for slices that are all-NaN or empty.\n\n .. versionadded:: 1.12.0\n\n Parameters\n ----------\n a : array_like\n Input array.\n axis : int, optional\n Axis along which the cumulative sum is computed. The default\n (None) is to compute the cumsum over the flattened array.\n dtype : dtype, optional\n Type of the returned array and of the accumulator in which the\n elements are summed. If `dtype` is not specified, it defaults\n to the dtype of `a`, unless `a` has an integer dtype with a\n precision less than that of the default platform integer. In\n that case, the default platform integer is used.\n out : ndarray, optional\n Alternative output array in which to place the result. It must\n have the same shape and buffer length as the expected output\n but the type will be cast if necessary. See `doc.ufuncs`\n (Section \"Output arguments\") for more details.\n\n Returns\n -------\n nancumsum : ndarray.\n A new array holding the result is returned unless `out` is\n specified, in which it is returned. The result has the same\n size as `a`, and the same shape as `a` if `axis` is not None\n or `a` is a 1-d array.\n\n See Also\n --------\n numpy.cumsum : Cumulative sum across array propagating NaNs.\n isnan : Show which elements are NaN.\n\n Examples\n --------\n >>> np.nancumsum(1)\n array([1])\n >>> np.nancumsum([1])\n array([1])\n >>> np.nancumsum([1, np.nan])\n array([ 1., 1.])\n >>> a = np.array([[1, 2], [3, np.nan]])\n >>> np.nancumsum(a)\n array([ 1., 3., 6., 6.])\n >>> np.nancumsum(a, axis=0)\n array([[ 1., 2.],\n [ 4., 2.]])\n >>> np.nancumsum(a, axis=1)\n array([[ 1., 3.],\n [ 3., 3.]])\n\n \"\"\"\n a, mask = _replace_nan(a, 0)\n return np.cumsum(a, axis=axis, dtype=dtype, out=out)\n\n\ndef nancumprod(a, axis=None, dtype=None, out=None):\n \"\"\"\n Return the cumulative product of array elements over a given axis treating Not a\n Numbers (NaNs) as one. The cumulative product does not change when NaNs are\n encountered and leading NaNs are replaced by ones.\n\n Ones are returned for slices that are all-NaN or empty.\n\n .. versionadded:: 1.12.0\n\n Parameters\n ----------\n a : array_like\n Input array.\n axis : int, optional\n Axis along which the cumulative product is computed. By default\n the input is flattened.\n dtype : dtype, optional\n Type of the returned array, as well as of the accumulator in which\n the elements are multiplied. If *dtype* is not specified, it\n defaults to the dtype of `a`, unless `a` has an integer dtype with\n a precision less than that of the default platform integer. In\n that case, the default platform integer is used instead.\n out : ndarray, optional\n Alternative output array in which to place the result. It must\n have the same shape and buffer length as the expected output\n but the type of the resulting values will be cast if necessary.\n\n Returns\n -------\n nancumprod : ndarray\n A new array holding the result is returned unless `out` is\n specified, in which case it is returned.\n\n See Also\n --------\n numpy.cumprod : Cumulative product across array propagating NaNs.\n isnan : Show which elements are NaN.\n\n Examples\n --------\n >>> np.nancumprod(1)\n array([1])\n >>> np.nancumprod([1])\n array([1])\n >>> np.nancumprod([1, np.nan])\n array([ 1., 1.])\n >>> a = np.array([[1, 2], [3, np.nan]])\n >>> np.nancumprod(a)\n array([ 1., 2., 6., 6.])\n >>> np.nancumprod(a, axis=0)\n array([[ 1., 2.],\n [ 3., 2.]])\n >>> np.nancumprod(a, axis=1)\n array([[ 1., 2.],\n [ 3., 3.]])\n\n \"\"\"\n a, mask = _replace_nan(a, 1)\n return np.cumprod(a, axis=axis, dtype=dtype, out=out)\n\n\ndef nanmean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue):\n \"\"\"\n Compute the arithmetic mean along the specified axis, ignoring NaNs.\n\n Returns the average of the array elements. The average is taken over\n the flattened array by default, otherwise over the specified axis.\n `float64` intermediate and return values are used for integer inputs.\n\n For all-NaN slices, NaN is returned and a `RuntimeWarning` is raised.\n\n .. versionadded:: 1.8.0\n\n Parameters\n ----------\n a : array_like\n Array containing numbers whose mean is desired. If `a` is not an\n array, a conversion is attempted.\n axis : int, optional\n Axis along which the means are computed. The default is to compute\n the mean of the flattened array.\n dtype : data-type, optional\n Type to use in computing the mean. For integer inputs, the default\n is `float64`; for inexact inputs, it is the same as the input\n dtype.\n out : ndarray, optional\n Alternate output array in which to place the result. The default\n is ``None``; if provided, it must have the same shape as the\n expected output, but the type will be cast if necessary. See\n `doc.ufuncs` for details.\n keepdims : bool, optional\n If this is set to True, the axes which are reduced are left\n in the result as dimensions with size one. With this option,\n the result will broadcast correctly against the original `a`.\n\n If the value is anything but the default, then\n `keepdims` will be passed through to the `mean` or `sum` methods\n of sub-classes of `ndarray`. If the sub-classes methods\n does not implement `keepdims` any exceptions will be raised.\n\n Returns\n -------\n m : ndarray, see dtype parameter above\n If `out=None`, returns a new array containing the mean values,\n otherwise a reference to the output array is returned. Nan is\n returned for slices that contain only NaNs.\n\n See Also\n --------\n average : Weighted average\n mean : Arithmetic mean taken while not ignoring NaNs\n var, nanvar\n\n Notes\n -----\n The arithmetic mean is the sum of the non-NaN elements along the axis\n divided by the number of non-NaN elements.\n\n Note that for floating-point input, the mean is computed using the same\n precision the input has. Depending on the input data, this can cause\n the results to be inaccurate, especially for `float32`. Specifying a\n higher-precision accumulator using the `dtype` keyword can alleviate\n this issue.\n\n Examples\n --------\n >>> a = np.array([[1, np.nan], [3, 4]])\n >>> np.nanmean(a)\n 2.6666666666666665\n >>> np.nanmean(a, axis=0)\n array([ 2., 4.])\n >>> np.nanmean(a, axis=1)\n array([ 1., 3.5])\n\n \"\"\"\n arr, mask = _replace_nan(a, 0)\n if mask is None:\n return np.mean(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)\n\n if dtype is not None:\n dtype = np.dtype(dtype)\n if dtype is not None and not issubclass(dtype.type, np.inexact):\n raise TypeError(\"If a is inexact, then dtype must be inexact\")\n if out is not None and not issubclass(out.dtype.type, np.inexact):\n raise TypeError(\"If a is inexact, then out must be inexact\")\n\n cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=keepdims)\n tot = np.sum(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)\n avg = _divide_by_count(tot, cnt, out=out)\n\n isbad = (cnt == 0)\n if isbad.any():\n warnings.warn(\"Mean of empty slice\", RuntimeWarning, stacklevel=2)\n # NaN is the only possible bad value, so no further\n # action is needed to handle bad results.\n return avg\n\n\ndef _nanmedian1d(arr1d, overwrite_input=False):\n \"\"\"\n Private function for rank 1 arrays. Compute the median ignoring NaNs.\n See nanmedian for parameter usage\n \"\"\"\n arr1d, overwrite_input = _remove_nan_1d(arr1d,\n overwrite_input=overwrite_input)\n if arr1d.size == 0:\n return np.nan\n\n return np.median(arr1d, overwrite_input=overwrite_input)\n\n\ndef _nanmedian(a, axis=None, out=None, overwrite_input=False):\n \"\"\"\n Private function that doesn't support extended axis or keepdims.\n These methods are extended to this function using _ureduce\n See nanmedian for parameter usage\n\n \"\"\"\n if axis is None or a.ndim == 1:\n part = a.ravel()\n if out is None:\n return _nanmedian1d(part, overwrite_input)\n else:\n out[...] = _nanmedian1d(part, overwrite_input)\n return out\n else:\n # for small medians use sort + indexing which is still faster than\n # apply_along_axis\n # benchmarked with shuffled (50, 50, x) containing a few NaN\n if a.shape[axis] < 600:\n return _nanmedian_small(a, axis, out, overwrite_input)\n result = np.apply_along_axis(_nanmedian1d, axis, a, overwrite_input)\n if out is not None:\n out[...] = result\n return result\n\n\ndef _nanmedian_small(a, axis=None, out=None, overwrite_input=False):\n \"\"\"\n sort + indexing median, faster for small medians along multiple\n dimensions due to the high overhead of apply_along_axis\n\n see nanmedian for parameter usage\n \"\"\"\n a = np.ma.masked_array(a, np.isnan(a))\n m = np.ma.median(a, axis=axis, overwrite_input=overwrite_input)\n for i in range(np.count_nonzero(m.mask.ravel())):\n warnings.warn(\"All-NaN slice encountered\", RuntimeWarning, stacklevel=3)\n if out is not None:\n out[...] = m.filled(np.nan)\n return out\n return m.filled(np.nan)\n\n\ndef nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=np._NoValue):\n \"\"\"\n Compute the median along the specified axis, while ignoring NaNs.\n\n Returns the median of the array elements.\n\n .. versionadded:: 1.9.0\n\n Parameters\n ----------\n a : array_like\n Input array or object that can be converted to an array.\n axis : {int, sequence of int, None}, optional\n Axis or axes along which the medians are computed. The default\n is to compute the median along a flattened version of the array.\n A sequence of axes is supported since version 1.9.0.\n out : ndarray, optional\n Alternative output array in which to place the result. It must\n have the same shape and buffer length as the expected output,\n but the type (of the output) will be cast if necessary.\n overwrite_input : bool, optional\n If True, then allow use of memory of input array `a` for\n calculations. The input array will be modified by the call to\n `median`. This will save memory when you do not need to preserve\n the contents of the input array. Treat the input as undefined,\n but it will probably be fully or partially sorted. Default is\n False. If `overwrite_input` is ``True`` and `a` is not already an\n `ndarray`, an error will be raised.\n keepdims : bool, optional\n If this is set to True, the axes which are reduced are left\n in the result as dimensions with size one. With this option,\n the result will broadcast correctly against the original `a`.\n\n If this is anything but the default value it will be passed\n through (in the special case of an empty array) to the\n `mean` function of the underlying array. If the array is\n a sub-class and `mean` does not have the kwarg `keepdims` this\n will raise a RuntimeError.\n\n Returns\n -------\n median : ndarray\n A new array holding the result. If the input contains integers\n or floats smaller than ``float64``, then the output data-type is\n ``np.float64``. Otherwise, the data-type of the output is the\n same as that of the input. If `out` is specified, that array is\n returned instead.\n\n See Also\n --------\n mean, median, percentile\n\n Notes\n -----\n Given a vector ``V`` of length ``N``, the median of ``V`` is the\n middle value of a sorted copy of ``V``, ``V_sorted`` - i.e.,\n ``V_sorted[(N-1)/2]``, when ``N`` is odd and the average of the two\n middle values of ``V_sorted`` when ``N`` is even.\n\n Examples\n --------\n >>> a = np.array([[10.0, 7, 4], [3, 2, 1]])\n >>> a[0, 1] = np.nan\n >>> a\n array([[ 10., nan, 4.],\n [ 3., 2., 1.]])\n >>> np.median(a)\n nan\n >>> np.nanmedian(a)\n 3.0\n >>> np.nanmedian(a, axis=0)\n array([ 6.5, 2., 2.5])\n >>> np.median(a, axis=1)\n array([ 7., 2.])\n >>> b = a.copy()\n >>> np.nanmedian(b, axis=1, overwrite_input=True)\n array([ 7., 2.])\n >>> assert not np.all(a==b)\n >>> b = a.copy()\n >>> np.nanmedian(b, axis=None, overwrite_input=True)\n 3.0\n >>> assert not np.all(a==b)\n\n \"\"\"\n a = np.asanyarray(a)\n # apply_along_axis in _nanmedian doesn't handle empty arrays well,\n # so deal them upfront\n if a.size == 0:\n return np.nanmean(a, axis, out=out, keepdims=keepdims)\n\n r, k = _ureduce(a, func=_nanmedian, axis=axis, out=out,\n overwrite_input=overwrite_input)\n if keepdims and keepdims is not np._NoValue:\n return r.reshape(k)\n else:\n return r\n\n\ndef nanpercentile(a, q, axis=None, out=None, overwrite_input=False,\n interpolation='linear', keepdims=np._NoValue):\n \"\"\"\n Compute the qth percentile of the data along the specified axis,\n while ignoring nan values.\n\n Returns the qth percentile(s) of the array elements.\n\n .. versionadded:: 1.9.0\n\n Parameters\n ----------\n a : array_like\n Input array or object that can be converted to an array.\n q : float in range of [0,100] (or sequence of floats)\n Percentile to compute, which must be between 0 and 100\n inclusive.\n axis : {int, sequence of int, None}, optional\n Axis or axes along which the percentiles are computed. The\n default is to compute the percentile(s) along a flattened\n version of the array. A sequence of axes is supported since\n version 1.9.0.\n out : ndarray, optional\n Alternative output array in which to place the result. It must\n have the same shape and buffer length as the expected output,\n but the type (of the output) will be cast if necessary.\n overwrite_input : bool, optional\n If True, then allow use of memory of input array `a` for\n calculations. The input array will be modified by the call to\n `percentile`. This will save memory when you do not need to\n preserve the contents of the input array. In this case you\n should not make any assumptions about the contents of the input\n `a` after this function completes -- treat it as undefined.\n Default is False. If `a` is not already an array, this parameter\n will have no effect as `a` will be converted to an array\n internally regardless of the value of this parameter.\n interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}\n This optional parameter specifies the interpolation method to\n use when the desired quantile lies between two data points\n ``i < j``:\n * linear: ``i + (j - i) * fraction``, where ``fraction`` is\n the fractional part of the index surrounded by ``i`` and\n ``j``.\n * lower: ``i``.\n * higher: ``j``.\n * nearest: ``i`` or ``j``, whichever is nearest.\n * midpoint: ``(i + j) / 2``.\n keepdims : bool, optional\n If this is set to True, the axes which are reduced are left in\n the result as dimensions with size one. With this option, the\n result will broadcast correctly against the original array `a`.\n\n If this is anything but the default value it will be passed\n through (in the special case of an empty array) to the\n `mean` function of the underlying array. If the array is\n a sub-class and `mean` does not have the kwarg `keepdims` this\n will raise a RuntimeError.\n\n Returns\n -------\n percentile : scalar or ndarray\n If `q` is a single percentile and `axis=None`, then the result\n is a scalar. If multiple percentiles are given, first axis of\n the result corresponds to the percentiles. The other axes are\n the axes that remain after the reduction of `a`. If the input\n contains integers or floats smaller than ``float64``, the output\n data-type is ``float64``. Otherwise, the output data-type is the\n same as that of the input. If `out` is specified, that array is\n returned instead.\n\n See Also\n --------\n nanmean, nanmedian, percentile, median, mean\n\n Notes\n -----\n Given a vector ``V`` of length ``N``, the ``q``-th percentile of\n ``V`` is the value ``q/100`` of the way from the minimum to the\n maximum in a sorted copy of ``V``. The values and distances of\n the two nearest neighbors as well as the `interpolation` parameter\n will determine the percentile if the normalized ranking does not\n match the location of ``q`` exactly. This function is the same as\n the median if ``q=50``, the same as the minimum if ``q=0`` and the\n same as the maximum if ``q=100``.\n\n Examples\n --------\n >>> a = np.array([[10., 7., 4.], [3., 2., 1.]])\n >>> a[0][1] = np.nan\n >>> a\n array([[ 10., nan, 4.],\n [ 3., 2., 1.]])\n >>> np.percentile(a, 50)\n nan\n >>> np.nanpercentile(a, 50)\n 3.5\n >>> np.nanpercentile(a, 50, axis=0)\n array([ 6.5, 2., 2.5])\n >>> np.nanpercentile(a, 50, axis=1, keepdims=True)\n array([[ 7.],\n [ 2.]])\n >>> m = np.nanpercentile(a, 50, axis=0)\n >>> out = np.zeros_like(m)\n >>> np.nanpercentile(a, 50, axis=0, out=out)\n array([ 6.5, 2., 2.5])\n >>> m\n array([ 6.5, 2. , 2.5])\n\n >>> b = a.copy()\n >>> np.nanpercentile(b, 50, axis=1, overwrite_input=True)\n array([ 7., 2.])\n >>> assert not np.all(a==b)\n\n \"\"\"\n\n a = np.asanyarray(a)\n q = np.asanyarray(q)\n # apply_along_axis in _nanpercentile doesn't handle empty arrays well,\n # so deal them upfront\n if a.size == 0:\n return np.nanmean(a, axis, out=out, keepdims=keepdims)\n\n r, k = _ureduce(a, func=_nanpercentile, q=q, axis=axis, out=out,\n overwrite_input=overwrite_input,\n interpolation=interpolation)\n if keepdims and keepdims is not np._NoValue:\n return r.reshape(q.shape + k)\n else:\n return r\n\n\ndef _nanpercentile(a, q, axis=None, out=None, overwrite_input=False,\n interpolation='linear'):\n \"\"\"\n Private function that doesn't support extended axis or keepdims.\n These methods are extended to this function using _ureduce\n See nanpercentile for parameter usage\n\n \"\"\"\n if axis is None or a.ndim == 1:\n part = a.ravel()\n result = _nanpercentile1d(part, q, overwrite_input, interpolation)\n else:\n result = np.apply_along_axis(_nanpercentile1d, axis, a, q,\n overwrite_input, interpolation)\n # apply_along_axis fills in collapsed axis with results.\n # Move that axis to the beginning to match percentile's\n # convention.\n if q.ndim != 0:\n result = np.moveaxis(result, axis, 0)\n\n if out is not None:\n out[...] = result\n return result\n\n\ndef _nanpercentile1d(arr1d, q, overwrite_input=False, interpolation='linear'):\n \"\"\"\n Private function for rank 1 arrays. Compute percentile ignoring NaNs.\n See nanpercentile for parameter usage\n \"\"\"\n arr1d, overwrite_input = _remove_nan_1d(arr1d,\n overwrite_input=overwrite_input)\n if arr1d.size == 0:\n return np.full(q.shape, np.nan)[()] # convert to scalar\n\n return np.percentile(arr1d, q, overwrite_input=overwrite_input,\n interpolation=interpolation)\n\n\ndef nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue):\n \"\"\"\n Compute the variance along the specified axis, while ignoring NaNs.\n\n Returns the variance of the array elements, a measure of the spread of\n a distribution. The variance is computed for the flattened array by\n default, otherwise over the specified axis.\n\n For all-NaN slices or slices with zero degrees of freedom, NaN is\n returned and a `RuntimeWarning` is raised.\n\n .. versionadded:: 1.8.0\n\n Parameters\n ----------\n a : array_like\n Array containing numbers whose variance is desired. If `a` is not an\n array, a conversion is attempted.\n axis : int, optional\n Axis along which the variance is computed. The default is to compute\n the variance of the flattened array.\n dtype : data-type, optional\n Type to use in computing the variance. For arrays of integer type\n the default is `float32`; for arrays of float types it is the same as\n the array type.\n out : ndarray, optional\n Alternate output array in which to place the result. It must have\n the same shape as the expected output, but the type is cast if\n necessary.\n ddof : int, optional\n \"Delta Degrees of Freedom\": the divisor used in the calculation is\n ``N - ddof``, where ``N`` represents the number of non-NaN\n elements. By default `ddof` is zero.\n keepdims : bool, optional\n If this is set to True, the axes which are reduced are left\n in the result as dimensions with size one. With this option,\n the result will broadcast correctly against the original `a`.\n\n\n Returns\n -------\n variance : ndarray, see dtype parameter above\n If `out` is None, return a new array containing the variance,\n otherwise return a reference to the output array. If ddof is >= the\n number of non-NaN elements in a slice or the slice contains only\n NaNs, then the result for that slice is NaN.\n\n See Also\n --------\n std : Standard deviation\n mean : Average\n var : Variance while not ignoring NaNs\n nanstd, nanmean\n numpy.doc.ufuncs : Section \"Output arguments\"\n\n Notes\n -----\n The variance is the average of the squared deviations from the mean,\n i.e., ``var = mean(abs(x - x.mean())**2)``.\n\n The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``.\n If, however, `ddof` is specified, the divisor ``N - ddof`` is used\n instead. In standard statistical practice, ``ddof=1`` provides an\n unbiased estimator of the variance of a hypothetical infinite\n population. ``ddof=0`` provides a maximum likelihood estimate of the\n variance for normally distributed variables.\n\n Note that for complex numbers, the absolute value is taken before\n squaring, so that the result is always real and nonnegative.\n\n For floating-point input, the variance is computed using the same\n precision the input has. Depending on the input data, this can cause\n the results to be inaccurate, especially for `float32` (see example\n below). Specifying a higher-accuracy accumulator using the ``dtype``\n keyword can alleviate this issue.\n\n For this function to work on sub-classes of ndarray, they must define\n `sum` with the kwarg `keepdims`\n\n Examples\n --------\n >>> a = np.array([[1, np.nan], [3, 4]])\n >>> np.var(a)\n 1.5555555555555554\n >>> np.nanvar(a, axis=0)\n array([ 1., 0.])\n >>> np.nanvar(a, axis=1)\n array([ 0., 0.25])\n\n \"\"\"\n arr, mask = _replace_nan(a, 0)\n if mask is None:\n return np.var(arr, axis=axis, dtype=dtype, out=out, ddof=ddof,\n keepdims=keepdims)\n\n if dtype is not None:\n dtype = np.dtype(dtype)\n if dtype is not None and not issubclass(dtype.type, np.inexact):\n raise TypeError(\"If a is inexact, then dtype must be inexact\")\n if out is not None and not issubclass(out.dtype.type, np.inexact):\n raise TypeError(\"If a is inexact, then out must be inexact\")\n\n # Compute mean\n if type(arr) is np.matrix:\n _keepdims = np._NoValue\n else:\n _keepdims = True\n # we need to special case matrix for reverse compatibility\n # in order for this to work, these sums need to be called with\n # keepdims=True, however matrix now raises an error in this case, but\n # the reason that it drops the keepdims kwarg is to force keepdims=True\n # so this used to work by serendipity.\n cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=_keepdims)\n avg = np.sum(arr, axis=axis, dtype=dtype, keepdims=_keepdims)\n avg = _divide_by_count(avg, cnt)\n\n # Compute squared deviation from mean.\n np.subtract(arr, avg, out=arr, casting='unsafe')\n arr = _copyto(arr, 0, mask)\n if issubclass(arr.dtype.type, np.complexfloating):\n sqr = np.multiply(arr, arr.conj(), out=arr).real\n else:\n sqr = np.multiply(arr, arr, out=arr)\n\n # Compute variance.\n var = np.sum(sqr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)\n if var.ndim < cnt.ndim:\n # Subclasses of ndarray may ignore keepdims, so check here.\n cnt = cnt.squeeze(axis)\n dof = cnt - ddof\n var = _divide_by_count(var, dof)\n\n isbad = (dof <= 0)\n if np.any(isbad):\n warnings.warn(\"Degrees of freedom <= 0 for slice.\", RuntimeWarning, stacklevel=2)\n # NaN, inf, or negative numbers are all possible bad\n # values, so explicitly replace them with NaN.\n var = _copyto(var, np.nan, isbad)\n return var\n\n\ndef nanstd(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue):\n \"\"\"\n Compute the standard deviation along the specified axis, while\n ignoring NaNs.\n\n Returns the standard deviation, a measure of the spread of a\n distribution, of the non-NaN array elements. The standard deviation is\n computed for the flattened array by default, otherwise over the\n specified axis.\n\n For all-NaN slices or slices with zero degrees of freedom, NaN is\n returned and a `RuntimeWarning` is raised.\n\n .. versionadded:: 1.8.0\n\n Parameters\n ----------\n a : array_like\n Calculate the standard deviation of the non-NaN values.\n axis : int, optional\n Axis along which the standard deviation is computed. The default is\n to compute the standard deviation of the flattened array.\n dtype : dtype, optional\n Type to use in computing the standard deviation. For arrays of\n integer type the default is float64, for arrays of float types it\n is the same as the array type.\n out : ndarray, optional\n Alternative output array in which to place the result. It must have\n the same shape as the expected output but the type (of the\n calculated values) will be cast if necessary.\n ddof : int, optional\n Means Delta Degrees of Freedom. The divisor used in calculations\n is ``N - ddof``, where ``N`` represents the number of non-NaN\n elements. By default `ddof` is zero.\n\n keepdims : bool, optional\n If this is set to True, the axes which are reduced are left\n in the result as dimensions with size one. With this option,\n the result will broadcast correctly against the original `a`.\n\n If this value is anything but the default it is passed through\n as-is to the relevant functions of the sub-classes. If these\n functions do not have a `keepdims` kwarg, a RuntimeError will\n be raised.\n\n Returns\n -------\n standard_deviation : ndarray, see dtype parameter above.\n If `out` is None, return a new array containing the standard\n deviation, otherwise return a reference to the output array. If\n ddof is >= the number of non-NaN elements in a slice or the slice\n contains only NaNs, then the result for that slice is NaN.\n\n See Also\n --------\n var, mean, std\n nanvar, nanmean\n numpy.doc.ufuncs : Section \"Output arguments\"\n\n Notes\n -----\n The standard deviation is the square root of the average of the squared\n deviations from the mean: ``std = sqrt(mean(abs(x - x.mean())**2))``.\n\n The average squared deviation is normally calculated as\n ``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is\n specified, the divisor ``N - ddof`` is used instead. In standard\n statistical practice, ``ddof=1`` provides an unbiased estimator of the\n variance of the infinite population. ``ddof=0`` provides a maximum\n likelihood estimate of the variance for normally distributed variables.\n The standard deviation computed in this function is the square root of\n the estimated variance, so even with ``ddof=1``, it will not be an\n unbiased estimate of the standard deviation per se.\n\n Note that, for complex numbers, `std` takes the absolute value before\n squaring, so that the result is always real and nonnegative.\n\n For floating-point input, the *std* is computed using the same\n precision the input has. Depending on the input data, this can cause\n the results to be inaccurate, especially for float32 (see example\n below). Specifying a higher-accuracy accumulator using the `dtype`\n keyword can alleviate this issue.\n\n Examples\n --------\n >>> a = np.array([[1, np.nan], [3, 4]])\n >>> np.nanstd(a)\n 1.247219128924647\n >>> np.nanstd(a, axis=0)\n array([ 1., 0.])\n >>> np.nanstd(a, axis=1)\n array([ 0., 0.5])\n\n \"\"\"\n var = nanvar(a, axis=axis, dtype=dtype, out=out, ddof=ddof,\n keepdims=keepdims)\n if isinstance(var, np.ndarray):\n std = np.sqrt(var, out=var)\n else:\n std = var.dtype.type(np.sqrt(var))\n return std\n", "# Licensed under a 3-clause BSD style license - see PYFITS.rst\n\nfrom __future__ import print_function\n\nimport bz2\nimport gzip\nimport os\nimport shutil\nimport sys\nimport warnings\n\nimport numpy as np\n\nfrom . import compressed\nfrom .base import _BaseHDU, _ValidHDU, _NonstandardHDU, ExtensionHDU\nfrom .groups import GroupsHDU\nfrom .image import PrimaryHDU, ImageHDU\nfrom ..file import _File\nfrom ..header import _pad_length\nfrom ..util import (_is_int, _tmp_name, fileobj_closed, ignore_sigint,\n _get_array_mmap, _free_space_check)\nfrom ..verify import _Verify, _ErrList, VerifyError, VerifyWarning\nfrom ....extern.six import string_types, PY2\nfrom ....utils import indent\nfrom ....utils.exceptions import AstropyUserWarning\nfrom ....utils.decorators import deprecated_renamed_argument\nfrom ....extern.six.moves import range\n\n\ndef fitsopen(name, mode='readonly', memmap=None, save_backup=False,\n cache=True, lazy_load_hdus=None, **kwargs):\n \"\"\"Factory function to open a FITS file and return an `HDUList` object.\n\n Parameters\n ----------\n name : file path, file object, file-like object or pathlib.Path object\n File to be opened.\n\n mode : str, optional\n Open mode, 'readonly' (default), 'update', 'append', 'denywrite', or\n 'ostream'.\n\n If ``name`` is a file object that is already opened, ``mode`` must\n match the mode the file was opened with, readonly (rb), update (rb+),\n append (ab+), ostream (w), denywrite (rb)).\n\n memmap : bool, optional\n Is memory mapping to be used?\n\n save_backup : bool, optional\n If the file was opened in update or append mode, this ensures that a\n backup of the original file is saved before any changes are flushed.\n The backup has the same name as the original file with \".bak\" appended.\n If \"file.bak\" already exists then \"file.bak.1\" is used, and so on.\n\n cache : bool, optional\n If the file name is a URL, `~astropy.utils.data.download_file` is used\n to open the file. This specifies whether or not to save the file\n locally in Astropy's download cache (default: `True`).\n\n lazy_load_hdus : bool, option\n By default `~astropy.io.fits.open` will not read all the HDUs and\n headers in a FITS file immediately upon opening. This is an\n optimization especially useful for large files, as FITS has no way\n of determining the number and offsets of all the HDUs in a file\n without scanning through the file and reading all the headers.\n\n To disable lazy loading and read all HDUs immediately (the old\n behavior) use ``lazy_load_hdus=False``. This can lead to fewer\n surprises--for example with lazy loading enabled, ``len(hdul)``\n can be slow, as it means the entire FITS file needs to be read in\n order to determine the number of HDUs. ``lazy_load_hdus=False``\n ensures that all HDUs have already been loaded after the file has\n been opened.\n\n .. versionadded:: 1.3\n\n kwargs : dict, optional\n additional optional keyword arguments, possible values are:\n\n - **uint** : bool\n\n Interpret signed integer data where ``BZERO`` is the\n central value and ``BSCALE == 1`` as unsigned integer\n data. For example, ``int16`` data with ``BZERO = 32768``\n and ``BSCALE = 1`` would be treated as ``uint16`` data.\n This is enabled by default so that the pseudo-unsigned\n integer convention is assumed.\n\n Note, for backward compatibility, the kwarg **uint16** may\n be used instead. The kwarg was renamed when support was\n added for integers of any size.\n\n - **ignore_missing_end** : bool\n\n Do not issue an exception when opening a file that is\n missing an ``END`` card in the last header.\n\n - **checksum** : bool, str\n\n If `True`, verifies that both ``DATASUM`` and\n ``CHECKSUM`` card values (when present in the HDU header)\n match the header and data of all HDU's in the file. Updates to a\n file that already has a checksum will preserve and update the\n existing checksums unless this argument is given a value of\n 'remove', in which case the CHECKSUM and DATASUM values are not\n checked, and are removed when saving changes to the file.\n\n - **disable_image_compression** : bool\n\n If `True`, treats compressed image HDU's like normal\n binary table HDU's.\n\n - **do_not_scale_image_data** : bool\n\n If `True`, image data is not scaled using BSCALE/BZERO values\n when read.\n\n - **ignore_blank** : bool\n\n If `True`, the BLANK keyword is ignored if present.\n\n - **scale_back** : bool\n\n If `True`, when saving changes to a file that contained scaled\n image data, restore the data to the original type and reapply the\n original BSCALE/BZERO values. This could lead to loss of accuracy\n if scaling back to integer values after performing floating point\n operations on the data.\n\n Returns\n -------\n hdulist : an `HDUList` object\n `HDUList` containing all of the header data units in the\n file.\n\n \"\"\"\n\n from .. import conf\n\n if memmap is None:\n # distinguish between True (kwarg explicitly set)\n # and None (preference for memmap in config, might be ignored)\n memmap = None if conf.use_memmap else False\n else:\n memmap = bool(memmap)\n\n if lazy_load_hdus is None:\n lazy_load_hdus = conf.lazy_load_hdus\n else:\n lazy_load_hdus = bool(lazy_load_hdus)\n\n if 'uint' not in kwargs:\n kwargs['uint'] = conf.enable_uint\n\n if not name:\n raise ValueError('Empty filename: {!r}'.format(name))\n\n return HDUList.fromfile(name, mode, memmap, save_backup, cache,\n lazy_load_hdus, **kwargs)\n\n\nclass HDUList(list, _Verify):\n \"\"\"\n HDU list class. This is the top-level FITS object. When a FITS\n file is opened, a `HDUList` object is returned.\n \"\"\"\n\n def __init__(self, hdus=[], file=None):\n \"\"\"\n Construct a `HDUList` object.\n\n Parameters\n ----------\n hdus : sequence of HDU objects or single HDU, optional\n The HDU object(s) to comprise the `HDUList`. Should be\n instances of HDU classes like `ImageHDU` or `BinTableHDU`.\n\n file : file object, bytes, optional\n The opened physical file associated with the `HDUList`\n or a bytes object containing the contents of the FITS\n file.\n \"\"\"\n\n if isinstance(file, bytes):\n self._data = file\n self._file = None\n else:\n self._file = file\n self._data = None\n\n self._save_backup = False\n\n # For internal use only--the keyword args passed to fitsopen /\n # HDUList.fromfile/string when opening the file\n self._open_kwargs = {}\n self._in_read_next_hdu = False\n\n # If we have read all the HDUs from the file or not\n # The assumes that all HDUs have been written when we first opened the\n # file; we do not currently support loading additional HDUs from a file\n # while it is being streamed to. In the future that might be supported\n # but for now this is only used for the purpose of lazy-loading of\n # existing HDUs.\n if file is None:\n self._read_all = True\n elif self._file is not None:\n # Should never attempt to read HDUs in ostream mode\n self._read_all = self._file.mode == 'ostream'\n else:\n self._read_all = False\n\n if hdus is None:\n hdus = []\n\n # can take one HDU, as well as a list of HDU's as input\n if isinstance(hdus, _ValidHDU):\n hdus = [hdus]\n elif not isinstance(hdus, (HDUList, list)):\n raise TypeError(\"Invalid input for HDUList.\")\n\n for idx, hdu in enumerate(hdus):\n if not isinstance(hdu, _BaseHDU):\n raise TypeError(\"Element {} in the HDUList input is \"\n \"not an HDU.\".format(idx))\n\n super(HDUList, self).__init__(hdus)\n\n if file is None:\n # Only do this when initializing from an existing list of HDUs\n # When initalizing from a file, this will be handled by the\n # append method after the first HDU is read\n self.update_extend()\n\n def __len__(self):\n if not self._in_read_next_hdu:\n while self._read_next_hdu():\n pass\n\n return super(HDUList, self).__len__()\n\n def __repr__(self):\n # In order to correctly repr an HDUList we need to load all the\n # HDUs as well\n while self._read_next_hdu():\n pass\n\n return super(HDUList, self).__repr__()\n\n def __iter__(self):\n # While effectively this does the same as:\n # for idx in range(len(self)):\n # yield self[idx]\n # the more complicated structure is here to prevent the use of len(),\n # which would break the lazy loading\n idx = 0\n while True:\n try:\n yield self[idx]\n except IndexError:\n break\n idx += 1\n\n def __getitem__(self, key):\n \"\"\"\n Get an HDU from the `HDUList`, indexed by number or name.\n \"\"\"\n\n # If the key is a slice we need to make sure the necessary HDUs\n # have been loaded before passing the slice on to super.\n if isinstance(key, slice):\n max_idx = key.stop\n # Check for and handle the case when no maximum was\n # specified (e.g. [1:]).\n # The first part of the or below is for python 2.7, the second\n # part for python 3.\n if max_idx == sys.maxsize or max_idx is None:\n # We need all of the HDUs, so load them\n # and reset the maximum to the actual length.\n max_idx = len(self)\n\n # Just in case the max_idx is negative...\n max_idx = self._positive_index_of(max_idx)\n\n number_loaded = super(HDUList, self).__len__()\n\n if max_idx >= number_loaded:\n # We need more than we have, try loading up to and including\n # max_idx. Note we do not try to be clever about skipping HDUs\n # even though key.step might conceivably allow it.\n for i in range(number_loaded, max_idx):\n # Read until max_idx or to the end of the file, whichever\n # comes first.\n if not self._read_next_hdu():\n break\n\n try:\n hdus = super(HDUList, self).__getitem__(key)\n except IndexError as e:\n # Raise a more helpful IndexError if the file was not fully read.\n if self._read_all:\n raise e\n else:\n raise IndexError('HDU not found, possibly because the index '\n 'is out of range, or because the file was '\n 'closed before all HDUs were read')\n else:\n return HDUList(hdus)\n\n # Originally this used recursion, but hypothetically an HDU with\n # a very large number of HDUs could blow the stack, so use a loop\n # instead\n try:\n return self._try_while_unread_hdus(super(HDUList, self).__getitem__,\n self._positive_index_of(key))\n except IndexError as e:\n # Raise a more helpful IndexError if the file was not fully read.\n if self._read_all:\n raise e\n else:\n raise IndexError('HDU not found, possibly because the index '\n 'is out of range, or because the file was '\n 'closed before all HDUs were read')\n\n def __contains__(self, item):\n \"\"\"\n Returns `True` if ``HDUList.index_of(item)`` succeeds.\n \"\"\"\n\n try:\n self._try_while_unread_hdus(self.index_of, item)\n except KeyError:\n return False\n\n return True\n\n def __setitem__(self, key, hdu):\n \"\"\"\n Set an HDU to the `HDUList`, indexed by number or name.\n \"\"\"\n\n _key = self._positive_index_of(key)\n if isinstance(hdu, (slice, list)):\n if _is_int(_key):\n raise ValueError('An element in the HDUList must be an HDU.')\n for item in hdu:\n if not isinstance(item, _BaseHDU):\n raise ValueError('{} is not an HDU.'.format(item))\n else:\n if not isinstance(hdu, _BaseHDU):\n raise ValueError('{} is not an HDU.'.format(hdu))\n\n try:\n self._try_while_unread_hdus(super(HDUList, self).__setitem__,\n _key, hdu)\n except IndexError:\n raise IndexError('Extension {} is out of bound or not found.'\n .format(key))\n\n self._resize = True\n self._truncate = False\n\n def __delitem__(self, key):\n \"\"\"\n Delete an HDU from the `HDUList`, indexed by number or name.\n \"\"\"\n\n if isinstance(key, slice):\n end_index = len(self)\n else:\n key = self._positive_index_of(key)\n end_index = len(self) - 1\n\n self._try_while_unread_hdus(super(HDUList, self).__delitem__, key)\n\n if (key == end_index or key == -1 and not self._resize):\n self._truncate = True\n else:\n self._truncate = False\n self._resize = True\n\n if PY2: # don't fall through to list.__getslice__, __delslice__\n def __getslice__(self, start, end):\n return self.__getitem__(slice(start, end))\n\n def __delslice__(self, start, stop):\n \"\"\"\n Delete a slice of HDUs from the `HDUList`, indexed by number only.\n \"\"\"\n self.__delitem__(slice(start, stop))\n\n # Support the 'with' statement\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n self.close()\n\n @classmethod\n def fromfile(cls, fileobj, mode=None, memmap=None,\n save_backup=False, cache=True, lazy_load_hdus=True,\n **kwargs):\n \"\"\"\n Creates an `HDUList` instance from a file-like object.\n\n The actual implementation of ``fitsopen()``, and generally shouldn't\n be used directly. Use :func:`open` instead (and see its\n documentation for details of the parameters accepted by this method).\n \"\"\"\n\n return cls._readfrom(fileobj=fileobj, mode=mode, memmap=memmap,\n save_backup=save_backup, cache=cache,\n lazy_load_hdus=lazy_load_hdus, **kwargs)\n\n @classmethod\n def fromstring(cls, data, **kwargs):\n \"\"\"\n Creates an `HDUList` instance from a string or other in-memory data\n buffer containing an entire FITS file. Similar to\n :meth:`HDUList.fromfile`, but does not accept the mode or memmap\n arguments, as they are only relevant to reading from a file on disk.\n\n This is useful for interfacing with other libraries such as CFITSIO,\n and may also be useful for streaming applications.\n\n Parameters\n ----------\n data : str, buffer, memoryview, etc.\n A string or other memory buffer containing an entire FITS file. It\n should be noted that if that memory is read-only (such as a Python\n string) the returned :class:`HDUList`'s data portions will also be\n read-only.\n\n kwargs : dict\n Optional keyword arguments. See\n :func:`astropy.io.fits.open` for details.\n\n Returns\n -------\n hdul : HDUList\n An :class:`HDUList` object representing the in-memory FITS file.\n \"\"\"\n\n try:\n # Test that the given object supports the buffer interface by\n # ensuring an ndarray can be created from it\n np.ndarray((), dtype='ubyte', buffer=data)\n except TypeError:\n raise TypeError(\n 'The provided object {} does not contain an underlying '\n 'memory buffer. fromstring() requires an object that '\n 'supports the buffer interface such as bytes, str '\n '(in Python 2.x but not in 3.x), buffer, memoryview, '\n 'ndarray, etc. This restriction is to ensure that '\n 'efficient access to the array/table data is possible.'\n ''.format(data))\n\n return cls._readfrom(data=data, **kwargs)\n\n def fileinfo(self, index):\n \"\"\"\n Returns a dictionary detailing information about the locations\n of the indexed HDU within any associated file. The values are\n only valid after a read or write of the associated file with\n no intervening changes to the `HDUList`.\n\n Parameters\n ----------\n index : int\n Index of HDU for which info is to be returned.\n\n Returns\n -------\n fileinfo : dict or None\n\n The dictionary details information about the locations of\n the indexed HDU within an associated file. Returns `None`\n when the HDU is not associated with a file.\n\n Dictionary contents:\n\n ========== ========================================================\n Key Value\n ========== ========================================================\n file File object associated with the HDU\n filename Name of associated file object\n filemode Mode in which the file was opened (readonly,\n update, append, denywrite, ostream)\n resized Flag that when `True` indicates that the data has been\n resized since the last read/write so the returned values\n may not be valid.\n hdrLoc Starting byte location of header in file\n datLoc Starting byte location of data block in file\n datSpan Data size including padding\n ========== ========================================================\n\n \"\"\"\n\n if self._file is not None:\n output = self[index].fileinfo()\n\n if not output:\n # OK, the HDU associated with this index is not yet\n # tied to the file associated with the HDUList. The only way\n # to get the file object is to check each of the HDU's in the\n # list until we find the one associated with the file.\n f = None\n\n for hdu in self:\n info = hdu.fileinfo()\n\n if info:\n f = info['file']\n fm = info['filemode']\n break\n\n output = {'file': f, 'filemode': fm, 'hdrLoc': None,\n 'datLoc': None, 'datSpan': None}\n\n output['filename'] = self._file.name\n output['resized'] = self._wasresized()\n else:\n output = None\n\n return output\n\n def insert(self, index, hdu):\n \"\"\"\n Insert an HDU into the `HDUList` at the given ``index``.\n\n Parameters\n ----------\n index : int\n Index before which to insert the new HDU.\n\n hdu : HDU object\n The HDU object to insert\n \"\"\"\n\n if not isinstance(hdu, _BaseHDU):\n raise ValueError('{} is not an HDU.'.format(hdu))\n\n num_hdus = len(self)\n\n if index == 0 or num_hdus == 0:\n if num_hdus != 0:\n # We are inserting a new Primary HDU so we need to\n # make the current Primary HDU into an extension HDU.\n if isinstance(self[0], GroupsHDU):\n raise ValueError(\n \"The current Primary HDU is a GroupsHDU. \"\n \"It can't be made into an extension HDU, \"\n \"so another HDU cannot be inserted before it.\")\n\n hdu1 = ImageHDU(self[0].data, self[0].header)\n\n # Insert it into position 1, then delete HDU at position 0.\n super(HDUList, self).insert(1, hdu1)\n super(HDUList, self).__delitem__(0)\n\n if not isinstance(hdu, (PrimaryHDU, _NonstandardHDU)):\n # You passed in an Extension HDU but we need a Primary HDU.\n # If you provided an ImageHDU then we can convert it to\n # a primary HDU and use that.\n if isinstance(hdu, ImageHDU):\n hdu = PrimaryHDU(hdu.data, hdu.header)\n else:\n # You didn't provide an ImageHDU so we create a\n # simple Primary HDU and append that first before\n # we append the new Extension HDU.\n phdu = PrimaryHDU()\n\n super(HDUList, self).insert(0, phdu)\n index = 1\n else:\n if isinstance(hdu, GroupsHDU):\n raise ValueError('A GroupsHDU must be inserted as a '\n 'Primary HDU.')\n\n if isinstance(hdu, PrimaryHDU):\n # You passed a Primary HDU but we need an Extension HDU\n # so create an Extension HDU from the input Primary HDU.\n hdu = ImageHDU(hdu.data, hdu.header)\n\n super(HDUList, self).insert(index, hdu)\n hdu._new = True\n self._resize = True\n self._truncate = False\n # make sure the EXTEND keyword is in primary HDU if there is extension\n self.update_extend()\n\n def append(self, hdu):\n \"\"\"\n Append a new HDU to the `HDUList`.\n\n Parameters\n ----------\n hdu : HDU object\n HDU to add to the `HDUList`.\n \"\"\"\n\n if not isinstance(hdu, _BaseHDU):\n raise ValueError('HDUList can only append an HDU.')\n\n if len(self) > 0:\n if isinstance(hdu, GroupsHDU):\n raise ValueError(\n \"Can't append a GroupsHDU to a non-empty HDUList\")\n\n if isinstance(hdu, PrimaryHDU):\n # You passed a Primary HDU but we need an Extension HDU\n # so create an Extension HDU from the input Primary HDU.\n # TODO: This isn't necessarily sufficient to copy the HDU;\n # _header_offset and friends need to be copied too.\n hdu = ImageHDU(hdu.data, hdu.header)\n else:\n if not isinstance(hdu, (PrimaryHDU, _NonstandardHDU)):\n # You passed in an Extension HDU but we need a Primary\n # HDU.\n # If you provided an ImageHDU then we can convert it to\n # a primary HDU and use that.\n if isinstance(hdu, ImageHDU):\n hdu = PrimaryHDU(hdu.data, hdu.header)\n else:\n # You didn't provide an ImageHDU so we create a\n # simple Primary HDU and append that first before\n # we append the new Extension HDU.\n phdu = PrimaryHDU()\n super(HDUList, self).append(phdu)\n\n super(HDUList, self).append(hdu)\n hdu._new = True\n self._resize = True\n self._truncate = False\n\n # make sure the EXTEND keyword is in primary HDU if there is extension\n self.update_extend()\n\n def index_of(self, key):\n \"\"\"\n Get the index of an HDU from the `HDUList`.\n\n Parameters\n ----------\n key : int, str or tuple of (string, int)\n The key identifying the HDU. If ``key`` is a tuple, it is of the\n form ``(key, ver)`` where ``ver`` is an ``EXTVER`` value that must\n match the HDU being searched for.\n\n If the key is ambiguous (e.g. there are multiple 'SCI' extensions)\n the first match is returned. For a more precise match use the\n ``(name, ver)`` pair.\n\n If even the ``(name, ver)`` pair is ambiguous (it shouldn't be\n but it's not impossible) the numeric index must be used to index\n the duplicate HDU.\n\n Returns\n -------\n index : int\n The index of the HDU in the `HDUList`.\n \"\"\"\n\n if _is_int(key):\n return key\n elif isinstance(key, tuple):\n _key, _ver = key\n else:\n _key = key\n _ver = None\n\n if not isinstance(_key, string_types):\n raise KeyError(\n '{} indices must be integers, extension names as strings, '\n 'or (extname, version) tuples; got {}'\n ''.format(self.__class__.__name__, _key))\n\n _key = (_key.strip()).upper()\n\n found = None\n for idx, hdu in enumerate(self):\n name = hdu.name\n if isinstance(name, string_types):\n name = name.strip().upper()\n # 'PRIMARY' should always work as a reference to the first HDU\n if ((name == _key or (_key == 'PRIMARY' and idx == 0)) and\n (_ver is None or _ver == hdu.ver)):\n found = idx\n break\n\n if (found is None):\n raise KeyError('Extension {!r} not found.'.format(key))\n else:\n return found\n\n def _positive_index_of(self, key):\n \"\"\"\n Same as index_of, but ensures always returning a positive index\n or zero.\n\n (Really this should be called non_negative_index_of but it felt\n too long.)\n\n This means that if the key is a negative integer, we have to\n convert it to the corresponding positive index. This means\n knowing the length of the HDUList, which in turn means loading\n all HDUs. Therefore using negative indices on HDULists is inherently\n inefficient.\n \"\"\"\n\n index = self.index_of(key)\n\n if index >= 0:\n return index\n\n if abs(index) > len(self):\n raise IndexError(\n 'Extension {} is out of bound or not found.'.format(index))\n\n return len(self) + index\n\n def readall(self):\n \"\"\"\n Read data of all HDUs into memory.\n \"\"\"\n\n for hdu in self:\n if hdu.data is not None:\n continue\n\n @ignore_sigint\n def flush(self, output_verify='fix', verbose=False):\n \"\"\"\n Force a write of the `HDUList` back to the file (for append and\n update modes only).\n\n Parameters\n ----------\n output_verify : str\n Output verification option. Must be one of ``\"fix\"``,\n ``\"silentfix\"``, ``\"ignore\"``, ``\"warn\"``, or\n ``\"exception\"``. May also be any combination of ``\"fix\"`` or\n ``\"silentfix\"`` with ``\"+ignore\"``, ``+warn``, or ``+exception\"\n (e.g. ``\"fix+warn\"``). See :ref:`verify` for more info.\n\n verbose : bool\n When `True`, print verbose messages\n \"\"\"\n\n if self._file.mode not in ('append', 'update', 'ostream'):\n warnings.warn(\"Flush for '{}' mode is not supported.\"\n .format(self._file.mode), AstropyUserWarning)\n return\n\n if self._save_backup and self._file.mode in ('append', 'update'):\n filename = self._file.name\n if os.path.exists(filename):\n # The the file doesn't actually exist anymore for some reason\n # then there's no point in trying to make a backup\n backup = filename + '.bak'\n idx = 1\n while os.path.exists(backup):\n backup = filename + '.bak.' + str(idx)\n idx += 1\n warnings.warn('Saving a backup of {} to {}.'.format(\n filename, backup), AstropyUserWarning)\n try:\n shutil.copy(filename, backup)\n except IOError as exc:\n raise IOError('Failed to save backup to destination {}: '\n '{}'.format(filename, exc))\n\n self.verify(option=output_verify)\n\n if self._file.mode in ('append', 'ostream'):\n for hdu in self:\n if verbose:\n try:\n extver = str(hdu._header['extver'])\n except KeyError:\n extver = ''\n\n # only append HDU's which are \"new\"\n if hdu._new:\n hdu._prewriteto(checksum=hdu._output_checksum)\n with _free_space_check(self):\n hdu._writeto(self._file)\n if verbose:\n print('append HDU', hdu.name, extver)\n hdu._new = False\n hdu._postwriteto()\n\n elif self._file.mode == 'update':\n self._flush_update()\n\n def update_extend(self):\n \"\"\"\n Make sure that if the primary header needs the keyword ``EXTEND`` that\n it has it and it is correct.\n \"\"\"\n\n if not len(self):\n return\n\n if not isinstance(self[0], PrimaryHDU):\n # A PrimaryHDU will be automatically inserted at some point, but it\n # might not have been added yet\n return\n\n hdr = self[0].header\n\n def get_first_ext():\n try:\n return self[1]\n except IndexError:\n return None\n\n if 'EXTEND' in hdr:\n if not hdr['EXTEND'] and get_first_ext() is not None:\n hdr['EXTEND'] = True\n elif get_first_ext() is not None:\n if hdr['NAXIS'] == 0:\n hdr.set('EXTEND', True, after='NAXIS')\n else:\n n = hdr['NAXIS']\n hdr.set('EXTEND', True, after='NAXIS' + str(n))\n\n @deprecated_renamed_argument('clobber', 'overwrite', '2.0')\n def writeto(self, fileobj, output_verify='exception', overwrite=False,\n checksum=False):\n \"\"\"\n Write the `HDUList` to a new file.\n\n Parameters\n ----------\n fileobj : file path, file object or file-like object\n File to write to. If a file object, must be opened in a\n writeable mode.\n\n output_verify : str\n Output verification option. Must be one of ``\"fix\"``,\n ``\"silentfix\"``, ``\"ignore\"``, ``\"warn\"``, or\n ``\"exception\"``. May also be any combination of ``\"fix\"`` or\n ``\"silentfix\"`` with ``\"+ignore\"``, ``+warn``, or ``+exception\"\n (e.g. ``\"fix+warn\"``). See :ref:`verify` for more info.\n\n overwrite : bool, optional\n If ``True``, overwrite the output file if it exists. Raises an\n ``OSError`` (``IOError`` for Python 2) if ``False`` and the\n output file exists. Default is ``False``.\n\n .. versionchanged:: 1.3\n ``overwrite`` replaces the deprecated ``clobber`` argument.\n\n checksum : bool\n When `True` adds both ``DATASUM`` and ``CHECKSUM`` cards\n to the headers of all HDU's written to the file.\n \"\"\"\n\n if (len(self) == 0):\n warnings.warn(\"There is nothing to write.\", AstropyUserWarning)\n return\n\n self.verify(option=output_verify)\n\n # make sure the EXTEND keyword is there if there is extension\n self.update_extend()\n\n # make note of whether the input file object is already open, in which\n # case we should not close it after writing (that should be the job\n # of the caller)\n closed = isinstance(fileobj, string_types) or fileobj_closed(fileobj)\n\n # writeto is only for writing a new file from scratch, so the most\n # sensible mode to require is 'ostream'. This can accept an open\n # file object that's open to write only, or in append/update modes\n # but only if the file doesn't exist.\n fileobj = _File(fileobj, mode='ostream', overwrite=overwrite)\n hdulist = self.fromfile(fileobj)\n try:\n dirname = os.path.dirname(hdulist._file.name)\n except AttributeError:\n dirname = None\n\n with _free_space_check(self, dirname=dirname):\n for hdu in self:\n hdu._prewriteto(checksum=checksum)\n hdu._writeto(hdulist._file)\n hdu._postwriteto()\n hdulist.close(output_verify=output_verify, closed=closed)\n\n def close(self, output_verify='exception', verbose=False, closed=True):\n \"\"\"\n Close the associated FITS file and memmap object, if any.\n\n Parameters\n ----------\n output_verify : str\n Output verification option. Must be one of ``\"fix\"``,\n ``\"silentfix\"``, ``\"ignore\"``, ``\"warn\"``, or\n ``\"exception\"``. May also be any combination of ``\"fix\"`` or\n ``\"silentfix\"`` with ``\"+ignore\"``, ``+warn``, or ``+exception\"\n (e.g. ``\"fix+warn\"``). See :ref:`verify` for more info.\n\n verbose : bool\n When `True`, print out verbose messages.\n\n closed : bool\n When `True`, close the underlying file object.\n \"\"\"\n\n try:\n if (self._file and self._file.mode in ('append', 'update')\n and not self._file.closed):\n self.flush(output_verify=output_verify, verbose=verbose)\n finally:\n if self._file and closed and hasattr(self._file, 'close'):\n self._file.close()\n\n # Give individual HDUs an opportunity to do on-close cleanup\n for hdu in self:\n hdu._close(closed=closed)\n\n def info(self, output=None):\n \"\"\"\n Summarize the info of the HDUs in this `HDUList`.\n\n Note that this function prints its results to the console---it\n does not return a value.\n\n Parameters\n ----------\n output : file, bool, optional\n A file-like object to write the output to. If `False`, does not\n output to a file and instead returns a list of tuples representing\n the HDU info. Writes to ``sys.stdout`` by default.\n \"\"\"\n\n if output is None:\n output = sys.stdout\n\n if self._file is None:\n name = '(No file associated with this HDUList)'\n else:\n name = self._file.name\n\n results = ['Filename: {}'.format(name),\n 'No. Name Ver Type Cards Dimensions Format']\n\n format = '{:3d} {:10} {:3} {:11} {:5d} {} {} {}'\n default = ('', '', '', 0, (), '', '')\n for idx, hdu in enumerate(self):\n summary = hdu._summary()\n if len(summary) < len(default):\n summary += default[len(summary):]\n summary = (idx,) + summary\n if output:\n results.append(format.format(*summary))\n else:\n results.append(summary)\n\n if output:\n output.write('\\n'.join(results))\n output.write('\\n')\n output.flush()\n else:\n return results[2:]\n\n def filename(self):\n \"\"\"\n Return the file name associated with the HDUList object if one exists.\n Otherwise returns None.\n\n Returns\n -------\n filename : a string containing the file name associated with the\n HDUList object if an association exists. Otherwise returns\n None.\n \"\"\"\n if self._file is not None:\n if hasattr(self._file, 'name'):\n return self._file.name\n return None\n\n @classmethod\n def _readfrom(cls, fileobj=None, data=None, mode=None,\n memmap=None, save_backup=False, cache=True,\n lazy_load_hdus=True, **kwargs):\n \"\"\"\n Provides the implementations from HDUList.fromfile and\n HDUList.fromstring, both of which wrap this method, as their\n implementations are largely the same.\n \"\"\"\n\n if fileobj is not None:\n if not isinstance(fileobj, _File):\n # instantiate a FITS file object (ffo)\n fileobj = _File(fileobj, mode=mode, memmap=memmap, cache=cache)\n # The Astropy mode is determined by the _File initializer if the\n # supplied mode was None\n mode = fileobj.mode\n hdulist = cls(file=fileobj)\n else:\n if mode is None:\n # The default mode\n mode = 'readonly'\n\n hdulist = cls(file=data)\n # This method is currently only called from HDUList.fromstring and\n # HDUList.fromfile. If fileobj is None then this must be the\n # fromstring case; the data type of ``data`` will be checked in the\n # _BaseHDU.fromstring call.\n\n hdulist._save_backup = save_backup\n hdulist._open_kwargs = kwargs\n\n if fileobj is not None and fileobj.writeonly:\n # Output stream--not interested in reading/parsing\n # the HDUs--just writing to the output file\n return hdulist\n\n # Make sure at least the PRIMARY HDU can be read\n read_one = hdulist._read_next_hdu()\n\n # If we're trying to read only and no header units were found,\n # raise an exception\n if not read_one and mode in ('readonly', 'denywrite'):\n # Close the file if necessary (issue #6168)\n if hdulist._file.close_on_error:\n hdulist._file.close()\n\n raise IOError('Empty or corrupt FITS file')\n\n if not lazy_load_hdus:\n # Go ahead and load all HDUs\n while hdulist._read_next_hdu():\n pass\n\n # initialize/reset attributes to be used in \"update/append\" mode\n hdulist._resize = False\n hdulist._truncate = False\n\n return hdulist\n\n def _try_while_unread_hdus(self, func, *args, **kwargs):\n \"\"\"\n Attempt an operation that accesses an HDU by index/name\n that can fail if not all HDUs have been read yet. Keep\n reading HDUs until the operation succeeds or there are no\n more HDUs to read.\n \"\"\"\n\n while True:\n try:\n return func(*args, **kwargs)\n except Exception:\n if self._read_next_hdu():\n continue\n else:\n raise\n\n def _read_next_hdu(self):\n \"\"\"\n Lazily load a single HDU from the fileobj or data string the `HDUList`\n was opened from, unless no further HDUs are found.\n\n Returns True if a new HDU was loaded, or False otherwise.\n \"\"\"\n\n if self._read_all:\n return False\n\n saved_compression_enabled = compressed.COMPRESSION_ENABLED\n fileobj, data, kwargs = self._file, self._data, self._open_kwargs\n\n if fileobj is not None and fileobj.closed:\n return False\n\n try:\n self._in_read_next_hdu = True\n\n if ('disable_image_compression' in kwargs and\n kwargs['disable_image_compression']):\n compressed.COMPRESSION_ENABLED = False\n\n # read all HDUs\n try:\n if fileobj is not None:\n try:\n # Make sure we're back to the end of the last read\n # HDU\n if len(self) > 0:\n last = self[len(self) - 1]\n if last._data_offset is not None:\n offset = last._data_offset + last._data_size\n fileobj.seek(offset, os.SEEK_SET)\n\n hdu = _BaseHDU.readfrom(fileobj, **kwargs)\n except EOFError:\n self._read_all = True\n return False\n except IOError:\n # Close the file: see\n # https://github.com/astropy/astropy/issues/6168\n #\n if self._file.close_on_error:\n self._file.close()\n\n if fileobj.writeonly:\n self._read_all = True\n return False\n else:\n raise\n else:\n if not data:\n self._read_all = True\n return False\n hdu = _BaseHDU.fromstring(data, **kwargs)\n self._data = data[hdu._data_offset + hdu._data_size:]\n\n super(HDUList, self).append(hdu)\n if len(self) == 1:\n # Check for an extension HDU and update the EXTEND\n # keyword of the primary HDU accordingly\n self.update_extend()\n\n hdu._new = False\n if 'checksum' in kwargs:\n hdu._output_checksum = kwargs['checksum']\n # check in the case there is extra space after the last HDU or\n # corrupted HDU\n except (VerifyError, ValueError) as exc:\n warnings.warn(\n 'Error validating header for HDU #{} (note: Astropy '\n 'uses zero-based indexing).\\n{}\\n'\n 'There may be extra bytes after the last HDU or the '\n 'file is corrupted.'.format(\n len(self), indent(str(exc))), VerifyWarning)\n del exc\n self._read_all = True\n return False\n finally:\n compressed.COMPRESSION_ENABLED = saved_compression_enabled\n self._in_read_next_hdu = False\n\n return True\n\n def _verify(self, option='warn'):\n errs = _ErrList([], unit='HDU')\n\n # the first (0th) element must be a primary HDU\n if len(self) > 0 and (not isinstance(self[0], PrimaryHDU)) and \\\n (not isinstance(self[0], _NonstandardHDU)):\n err_text = \"HDUList's 0th element is not a primary HDU.\"\n fix_text = 'Fixed by inserting one as 0th HDU.'\n\n def fix(self=self):\n self.insert(0, PrimaryHDU())\n\n err = self.run_option(option, err_text=err_text,\n fix_text=fix_text, fix=fix)\n errs.append(err)\n\n if len(self) > 1 and ('EXTEND' not in self[0].header or\n self[0].header['EXTEND'] is not True):\n err_text = ('Primary HDU does not contain an EXTEND keyword '\n 'equal to T even though there are extension HDUs.')\n fix_text = 'Fixed by inserting or updating the EXTEND keyword.'\n\n def fix(header=self[0].header):\n naxis = header['NAXIS']\n if naxis == 0:\n after = 'NAXIS'\n else:\n after = 'NAXIS' + str(naxis)\n header.set('EXTEND', value=True, after=after)\n\n errs.append(self.run_option(option, err_text=err_text,\n fix_text=fix_text, fix=fix))\n\n # each element calls their own verify\n for idx, hdu in enumerate(self):\n if idx > 0 and (not isinstance(hdu, ExtensionHDU)):\n err_text = (\"HDUList's element {} is not an \"\n \"extension HDU.\".format(str(idx)))\n\n err = self.run_option(option, err_text=err_text, fixable=False)\n errs.append(err)\n\n else:\n result = hdu._verify(option)\n if result:\n errs.append(result)\n return errs\n\n def _flush_update(self):\n \"\"\"Implements flushing changes to a file in update mode.\"\"\"\n\n for hdu in self:\n # Need to all _prewriteto() for each HDU first to determine if\n # resizing will be necessary\n hdu._prewriteto(checksum=hdu._output_checksum, inplace=True)\n\n try:\n self._wasresized()\n\n # if the HDUList is resized, need to write out the entire contents of\n # the hdulist to the file.\n if self._resize or self._file.compression:\n self._flush_resize()\n else:\n # if not resized, update in place\n for hdu in self:\n hdu._writeto(self._file, inplace=True)\n\n # reset the modification attributes after updating\n for hdu in self:\n hdu._header._modified = False\n finally:\n for hdu in self:\n hdu._postwriteto()\n\n def _flush_resize(self):\n \"\"\"\n Implements flushing changes in update mode when parts of one or more HDU\n need to be resized.\n \"\"\"\n\n old_name = self._file.name\n old_memmap = self._file.memmap\n name = _tmp_name(old_name)\n\n if not self._file.file_like:\n old_mode = os.stat(old_name).st_mode\n # The underlying file is an actual file object. The HDUList is\n # resized, so we need to write it to a tmp file, delete the\n # original file, and rename the tmp file to the original file.\n if self._file.compression == 'gzip':\n new_file = gzip.GzipFile(name, mode='ab+')\n elif self._file.compression == 'bzip2':\n new_file = bz2.BZ2File(name, mode='w')\n else:\n new_file = name\n\n with self.fromfile(new_file, mode='append') as hdulist:\n\n for hdu in self:\n hdu._writeto(hdulist._file, inplace=True, copy=True)\n if sys.platform.startswith('win'):\n # Collect a list of open mmaps to the data; this well be\n # used later. See below.\n mmaps = [(idx, _get_array_mmap(hdu.data), hdu.data)\n for idx, hdu in enumerate(self) if hdu._has_data]\n\n hdulist._file.close()\n self._file.close()\n if sys.platform.startswith('win'):\n # Close all open mmaps to the data. This is only necessary on\n # Windows, which will not allow a file to be renamed or deleted\n # until all handles to that file have been closed.\n for idx, mmap, arr in mmaps:\n if mmap is not None:\n mmap.close()\n\n os.remove(self._file.name)\n\n # reopen the renamed new file with \"update\" mode\n os.rename(name, old_name)\n os.chmod(old_name, old_mode)\n\n if isinstance(new_file, gzip.GzipFile):\n old_file = gzip.GzipFile(old_name, mode='rb+')\n else:\n old_file = old_name\n\n ffo = _File(old_file, mode='update', memmap=old_memmap)\n\n self._file = ffo\n\n for hdu in self:\n # Need to update the _file attribute and close any open mmaps\n # on each HDU\n if hdu._has_data and _get_array_mmap(hdu.data) is not None:\n del hdu.data\n hdu._file = ffo\n\n if sys.platform.startswith('win'):\n # On Windows, all the original data mmaps were closed above.\n # However, it's possible that the user still has references to\n # the old data which would no longer work (possibly even cause\n # a segfault if they try to access it). This replaces the\n # buffers used by the original arrays with the buffers of mmap\n # arrays created from the new file. This seems to work, but\n # it's a flaming hack and carries no guarantees that it won't\n # lead to odd behavior in practice. Better to just not keep\n # references to data from files that had to be resized upon\n # flushing (on Windows--again, this is no problem on Linux).\n for idx, mmap, arr in mmaps:\n if mmap is not None:\n arr.data = self[idx].data.data\n del mmaps # Just to be sure\n\n else:\n # The underlying file is not a file object, it is a file like\n # object. We can't write out to a file, we must update the file\n # like object in place. To do this, we write out to a temporary\n # file, then delete the contents in our file like object, then\n # write the contents of the temporary file to the now empty file\n # like object.\n self.writeto(name)\n hdulist = self.fromfile(name)\n ffo = self._file\n\n ffo.truncate(0)\n ffo.seek(0)\n\n for hdu in hdulist:\n hdu._writeto(ffo, inplace=True, copy=True)\n\n # Close the temporary file and delete it.\n hdulist.close()\n os.remove(hdulist._file.name)\n\n # reset the resize attributes after updating\n self._resize = False\n self._truncate = False\n for hdu in self:\n hdu._header._modified = False\n hdu._new = False\n hdu._file = ffo\n\n def _wasresized(self, verbose=False):\n \"\"\"\n Determine if any changes to the HDUList will require a file resize\n when flushing the file.\n\n Side effect of setting the objects _resize attribute.\n \"\"\"\n\n if not self._resize:\n\n # determine if any of the HDU is resized\n for hdu in self:\n # Header:\n nbytes = len(str(hdu._header))\n if nbytes != (hdu._data_offset - hdu._header_offset):\n self._resize = True\n self._truncate = False\n if verbose:\n print('One or more header is resized.')\n break\n\n # Data:\n if not hdu._has_data:\n continue\n\n nbytes = hdu.size\n nbytes = nbytes + _pad_length(nbytes)\n if nbytes != hdu._data_size:\n self._resize = True\n self._truncate = False\n if verbose:\n print('One or more data area is resized.')\n break\n\n if self._truncate:\n try:\n self._file.truncate(hdu._data_offset + hdu._data_size)\n except IOError:\n self._resize = True\n self._truncate = False\n\n return self._resize\n", "import math\nimport random\n\nimport torch\nfrom torch.autograd import Variable\n\n\ndef calculate_gain(nonlinearity, param=None):\n \"\"\"Return the recommended gain value for the given nonlinearity function.\n The values are as follows:\n\n ============ ==========================================\n nonlinearity gain\n ============ ==========================================\n linear :math:`1`\n conv{1,2,3}d :math:`1`\n sigmoid :math:`1`\n tanh :math:`5 / 3`\n relu :math:`\\sqrt{2}`\n leaky_relu :math:`\\sqrt{2 / (1 + negative\\_slope^2)}`\n ============ ==========================================\n\n Args:\n nonlinearity: the nonlinear function (`nn.functional` name)\n param: optional parameter for the nonlinear function\n\n Examples:\n >>> gain = nn.init.gain('leaky_relu')\n \"\"\"\n linear_fns = ['linear', 'conv1d', 'conv2d', 'conv3d', 'conv_transpose1d', 'conv_transpose2d', 'conv_transpose3d']\n if nonlinearity in linear_fns or nonlinearity == 'sigmoid':\n return 1\n elif nonlinearity == 'tanh':\n return 5.0 / 3\n elif nonlinearity == 'relu':\n return math.sqrt(2.0)\n elif nonlinearity == 'leaky_relu':\n if param is None:\n negative_slope = 0.01\n elif not isinstance(param, bool) and isinstance(param, int) or isinstance(param, float):\n # True/False are instances of int, hence check above\n negative_slope = param\n else:\n raise ValueError(\"negative_slope {} not a valid number\".format(param))\n return math.sqrt(2.0 / (1 + negative_slope ** 2))\n else:\n raise ValueError(\"Unsupported nonlinearity {}\".format(nonlinearity))\n\n\ndef uniform(tensor, a=0, b=1):\n \"\"\"Fills the input Tensor or Variable with values drawn from the uniform\n distribution :math:`U(a, b)`.\n\n Args:\n tensor: an n-dimensional torch.Tensor or autograd.Variable\n a: the lower bound of the uniform distribution\n b: the upper bound of the uniform distribution\n\n Examples:\n >>> w = torch.Tensor(3, 5)\n >>> nn.init.uniform(w)\n \"\"\"\n if isinstance(tensor, Variable):\n uniform(tensor.data, a=a, b=b)\n return tensor\n\n return tensor.uniform_(a, b)\n\n\ndef normal(tensor, mean=0, std=1):\n \"\"\"Fills the input Tensor or Variable with values drawn from the normal\n distribution :math:`N(mean, std)`.\n\n Args:\n tensor: an n-dimensional torch.Tensor or autograd.Variable\n mean: the mean of the normal distribution\n std: the standard deviation of the normal distribution\n\n Examples:\n >>> w = torch.Tensor(3, 5)\n >>> nn.init.normal(w)\n \"\"\"\n if isinstance(tensor, Variable):\n normal(tensor.data, mean=mean, std=std)\n return tensor\n\n return tensor.normal_(mean, std)\n\n\ndef constant(tensor, val):\n \"\"\"Fills the input Tensor or Variable with the value `val`.\n\n Args:\n tensor: an n-dimensional torch.Tensor or autograd.Variable\n val: the value to fill the tensor with\n\n Examples:\n >>> w = torch.Tensor(3, 5)\n >>> nn.init.constant(w)\n \"\"\"\n if isinstance(tensor, Variable):\n constant(tensor.data, val)\n return tensor\n\n return tensor.fill_(val)\n\n\ndef eye(tensor):\n \"\"\"Fills the 2-dimensional input Tensor or Variable with the identity\n matrix. Preserves the identity of the inputs in Linear layers, where as\n many inputs are preserved as possible.\n\n Args:\n tensor: a 2-dimensional torch.Tensor or autograd.Variable\n\n Examples:\n >>> w = torch.Tensor(3, 5)\n >>> nn.init.eye(w)\n \"\"\"\n if tensor.ndimension() != 2:\n raise ValueError(\"Only tensors with 2 dimensions are supported\")\n\n if isinstance(tensor, Variable):\n eye(tensor.data)\n return tensor\n\n return tensor.copy_(torch.eye(tensor.size(0), tensor.size(1)))\n\n\ndef dirac(tensor):\n \"\"\"Fills the {3, 4, 5}-dimensional input Tensor or Variable with the Dirac\n delta function. Preserves the identity of the inputs in Convolutional\n layers, where as many input channels are preserved as possible.\n\n Args:\n tensor: a {3, 4, 5}-dimensional torch.Tensor or autograd.Variable\n\n Examples:\n >>> w = torch.Tensor(3, 16, 5, 5)\n >>> nn.init.dirac(w)\n \"\"\"\n dimensions = tensor.ndimension()\n if dimensions not in [3, 4, 5]:\n raise ValueError(\"Only tensors with 3, 4, or 5 dimensions are supported\")\n\n if isinstance(tensor, Variable):\n dirac(tensor.data)\n return tensor\n\n sizes = tensor.size()\n min_dim = min(sizes[0], sizes[1])\n tensor.zero_()\n\n for d in range(min_dim):\n if dimensions == 3: # Temporal convolution\n tensor[d, d, tensor.size(2) // 2] = 1\n elif dimensions == 4: # Spatial convolution\n tensor[d, d, tensor.size(2) // 2, tensor.size(3) // 2] = 1\n else: # Volumetric convolution\n tensor[d, d, tensor.size(2) // 2, tensor.size(3) // 2, tensor.size(4) // 2] = 1\n return tensor\n\n\ndef _calculate_fan_in_and_fan_out(tensor):\n dimensions = tensor.ndimension()\n if dimensions < 2:\n raise ValueError(\"Fan in and fan out can not be computed for tensor with less than 2 dimensions\")\n\n if dimensions == 2: # Linear\n fan_in = tensor.size(1)\n fan_out = tensor.size(0)\n else:\n num_input_fmaps = tensor.size(1)\n num_output_fmaps = tensor.size(0)\n receptive_field_size = 1\n if tensor.dim() > 2:\n receptive_field_size = tensor[0][0].numel()\n fan_in = num_input_fmaps * receptive_field_size\n fan_out = num_output_fmaps * receptive_field_size\n\n return fan_in, fan_out\n\n\ndef xavier_uniform(tensor, gain=1):\n \"\"\"Fills the input Tensor or Variable with values according to the method\n described in \"Understanding the difficulty of training deep feedforward\n neural networks\" - Glorot, X. & Bengio, Y. (2010), using a uniform\n distribution. The resulting tensor will have values sampled from\n :math:`U(-a, a)` where\n :math:`a = gain \\\\times \\sqrt{2 / (fan\\_in + fan\\_out)} \\\\times \\sqrt{3}`.\n Also known as Glorot initialisation.\n\n Args:\n tensor: an n-dimensional torch.Tensor or autograd.Variable\n gain: an optional scaling factor\n\n Examples:\n >>> w = torch.Tensor(3, 5)\n >>> nn.init.xavier_uniform(w, gain=nn.init.calculate_gain('relu'))\n \"\"\"\n if isinstance(tensor, Variable):\n xavier_uniform(tensor.data, gain=gain)\n return tensor\n\n fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)\n std = gain * math.sqrt(2.0 / (fan_in + fan_out))\n a = math.sqrt(3.0) * std # Calculate uniform bounds from standard deviation\n return tensor.uniform_(-a, a)\n\n\ndef xavier_normal(tensor, gain=1):\n \"\"\"Fills the input Tensor or Variable with values according to the method\n described in \"Understanding the difficulty of training deep feedforward\n neural networks\" - Glorot, X. & Bengio, Y. (2010), using a normal\n distribution. The resulting tensor will have values sampled from\n :math:`N(0, std)` where\n :math:`std = gain \\\\times \\sqrt{2 / (fan\\_in + fan\\_out)}`.\n Also known as Glorot initialisation.\n\n Args:\n tensor: an n-dimensional torch.Tensor or autograd.Variable\n gain: an optional scaling factor\n\n Examples:\n >>> w = torch.Tensor(3, 5)\n >>> nn.init.xavier_normal(w)\n \"\"\"\n if isinstance(tensor, Variable):\n xavier_normal(tensor.data, gain=gain)\n return tensor\n\n fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)\n std = gain * math.sqrt(2.0 / (fan_in + fan_out))\n return tensor.normal_(0, std)\n\n\ndef _calculate_correct_fan(tensor, mode):\n mode = mode.lower()\n valid_modes = ['fan_in', 'fan_out']\n if mode not in valid_modes:\n raise ValueError(\"Mode {} not supported, please use one of {}\".format(mode, valid_modes))\n\n fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)\n return fan_in if mode == 'fan_in' else fan_out\n\n\ndef kaiming_uniform(tensor, a=0, mode='fan_in'):\n \"\"\"Fills the input Tensor or Variable with values according to the method\n described in \"Delving deep into rectifiers: Surpassing human-level\n performance on ImageNet classification\" - He, K. et al. (2015), using a\n uniform distribution. The resulting tensor will have values sampled from\n :math:`U(-bound, bound)` where\n :math:`bound = \\sqrt{2 / ((1 + a^2) \\\\times fan\\_in)} \\\\times \\sqrt{3}`.\n Also known as He initialisation.\n\n Args:\n tensor: an n-dimensional torch.Tensor or autograd.Variable\n a: the negative slope of the rectifier used after this layer (0 for ReLU\n by default)\n mode: either 'fan_in' (default) or 'fan_out'. Choosing `fan_in`\n preserves the magnitude of the variance of the weights in the\n forward pass. Choosing `fan_out` preserves the magnitudes in the\n backwards pass.\n\n Examples:\n >>> w = torch.Tensor(3, 5)\n >>> nn.init.kaiming_uniform(w, mode='fan_in')\n \"\"\"\n if isinstance(tensor, Variable):\n kaiming_uniform(tensor.data, a=a, mode=mode)\n return tensor\n\n fan = _calculate_correct_fan(tensor, mode)\n gain = calculate_gain('leaky_relu', a)\n std = gain / math.sqrt(fan)\n bound = math.sqrt(3.0) * std # Calculate uniform bounds from standard deviation\n return tensor.uniform_(-bound, bound)\n\n\ndef kaiming_normal(tensor, a=0, mode='fan_in'):\n \"\"\"Fills the input Tensor or Variable with values according to the method\n described in \"Delving deep into rectifiers: Surpassing human-level\n performance on ImageNet classification\" - He, K. et al. (2015), using a\n normal distribution. The resulting tensor will have values sampled from\n :math:`N(0, std)` where\n :math:`std = \\sqrt{2 / ((1 + a^2) \\\\times fan\\_in)}`. Also known as He\n initialisation.\n\n Args:\n tensor: an n-dimensional torch.Tensor or autograd.Variable\n a: the negative slope of the rectifier used after this layer (0 for ReLU\n by default)\n mode: either 'fan_in' (default) or 'fan_out'. Choosing `fan_in`\n preserves the magnitude of the variance of the weights in the\n forward pass. Choosing `fan_out` preserves the magnitudes in the\n backwards pass.\n\n Examples:\n >>> w = torch.Tensor(3, 5)\n >>> nn.init.kaiming_normal(w, mode='fan_out')\n \"\"\"\n if isinstance(tensor, Variable):\n kaiming_normal(tensor.data, a=a, mode=mode)\n return tensor\n\n fan = _calculate_correct_fan(tensor, mode)\n gain = calculate_gain('leaky_relu', a)\n std = gain / math.sqrt(fan)\n return tensor.normal_(0, std)\n\n\ndef orthogonal(tensor, gain=1):\n \"\"\"Fills the input Tensor or Variable with a (semi) orthogonal matrix, as\n described in \"Exact solutions to the nonlinear dynamics of learning in deep\n linear neural networks\" - Saxe, A. et al. (2013). The input tensor must have\n at least 2 dimensions, and for tensors with more than 2 dimensions the\n trailing dimensions are flattened.\n\n Args:\n tensor: an n-dimensional torch.Tensor or autograd.Variable, where n >= 2\n gain: optional scaling factor\n\n Examples:\n >>> w = torch.Tensor(3, 5)\n >>> nn.init.orthogonal(w)\n \"\"\"\n if isinstance(tensor, Variable):\n orthogonal(tensor.data, gain=gain)\n return tensor\n\n if tensor.ndimension() < 2:\n raise ValueError(\"Only tensors with 2 or more dimensions are supported\")\n\n rows = tensor.size(0)\n cols = tensor[0].numel()\n flattened = torch.Tensor(rows, cols).normal_(0, 1)\n # Compute the qr factorization\n q, r = torch.qr(flattened)\n # Make Q uniform according to https://arxiv.org/pdf/math-ph/0609050.pdf\n d = torch.diag(r, 0)\n ph = d.sign()\n q *= ph.expand_as(q)\n # Pad zeros to Q (if rows smaller than cols)\n if rows < cols:\n padding = torch.zeros(rows, cols - rows)\n if q.is_cuda:\n q = torch.cat([q, padding.cuda()], 1)\n else:\n q = torch.cat([q, padding], 1)\n\n tensor.view_as(q).copy_(q)\n tensor.mul_(gain)\n return tensor\n\n\ndef sparse(tensor, sparsity, std=0.01):\n \"\"\"Fills the 2D input Tensor or Variable as a sparse matrix, where the\n non-zero elements will be drawn from the normal distribution\n :math:`N(0, 0.01)`, as described in \"Deep learning via\n Hessian-free optimization\" - Martens, J. (2010).\n\n Args:\n tensor: an n-dimensional torch.Tensor or autograd.Variable\n sparsity: The fraction of elements in each column to be set to zero\n std: the standard deviation of the normal distribution used to generate\n the non-zero values\n\n Examples:\n >>> w = torch.Tensor(3, 5)\n >>> nn.init.sparse(w, sparsity=0.1)\n \"\"\"\n if isinstance(tensor, Variable):\n sparse(tensor.data, sparsity, std=std)\n return tensor\n\n if tensor.ndimension() != 2:\n raise ValueError(\"Only tensors with 2 dimensions are supported\")\n\n tensor.normal_(0, std)\n rows, cols = tensor.size(0), tensor.size(1)\n num_zeros = int(math.ceil(rows * sparsity))\n\n for col_idx in range(tensor.size(1)):\n row_indices = list(range(rows))\n random.shuffle(row_indices)\n zero_indices = row_indices[:num_zeros]\n for row_idx in zero_indices:\n tensor[row_idx, col_idx] = 0\n\n return tensor\n", "import numpy as np\n\nfrom ._extensions._pywt import Wavelet, Modes, _check_dtype\nfrom ._extensions._dwt import (dwt_single, dwt_axis, idwt_single, idwt_axis,\n upcoef as _upcoef, downcoef as _downcoef,\n dwt_max_level as _dwt_max_level,\n dwt_coeff_len as _dwt_coeff_len)\n\n__all__ = [\"dwt\", \"idwt\", \"downcoef\", \"upcoef\", \"dwt_max_level\", \"dwt_coeff_len\"]\n\n\ndef dwt_max_level(data_len, filter_len):\n \"\"\"\n dwt_max_level(data_len, filter_len)\n\n Compute the maximum useful level of decomposition.\n\n Parameters\n ----------\n data_len : int\n Input data length.\n filter_len : int\n Wavelet filter length.\n\n Returns\n -------\n max_level : int\n Maximum level.\n\n Examples\n --------\n >>> import pywt\n >>> w = pywt.Wavelet('sym5')\n >>> pywt.dwt_max_level(data_len=1000, filter_len=w.dec_len)\n 6\n >>> pywt.dwt_max_level(1000, w)\n 6\n \"\"\"\n if isinstance(filter_len, Wavelet):\n filter_len = filter_len.dec_len\n\n return _dwt_max_level(data_len, filter_len)\n\n\ndef dwt_coeff_len(data_len, filter_len, mode):\n \"\"\"\n dwt_coeff_len(data_len, filter_len, mode='symmetric')\n\n Returns length of dwt output for given data length, filter length and mode\n\n Parameters\n ----------\n data_len : int\n Data length.\n filter_len : int\n Filter length.\n mode : str, optional (default: 'symmetric')\n Signal extension mode, see Modes\n\n Returns\n -------\n len : int\n Length of dwt output.\n\n Notes\n -----\n For all modes except periodization::\n\n len(cA) == len(cD) == floor((len(data) + wavelet.dec_len - 1) / 2)\n\n for periodization mode (\"per\")::\n\n len(cA) == len(cD) == ceil(len(data) / 2)\n\n \"\"\"\n if isinstance(filter_len, Wavelet):\n filter_len = filter_len.dec_len\n\n return _dwt_coeff_len(data_len, filter_len, Modes.from_object(mode))\n\n\ndef dwt(data, wavelet, mode='symmetric', axis=-1):\n \"\"\"\n dwt(data, wavelet, mode='symmetric', axis=-1)\n\n Single level Discrete Wavelet Transform.\n\n Parameters\n ----------\n data : array_like\n Input signal\n wavelet : Wavelet object or name\n Wavelet to use\n mode : str, optional\n Signal extension mode, see Modes\n axis: int, optional\n Axis over which to compute the DWT. If not given, the\n last axis is used.\n\n\n Returns\n -------\n (cA, cD) : tuple\n Approximation and detail coefficients.\n\n Notes\n -----\n Length of coefficients arrays depends on the selected mode.\n For all modes except periodization:\n\n ``len(cA) == len(cD) == floor((len(data) + wavelet.dec_len - 1) / 2)``\n\n For periodization mode (\"per\"):\n\n ``len(cA) == len(cD) == ceil(len(data) / 2)``\n\n Examples\n --------\n >>> import pywt\n >>> (cA, cD) = pywt.dwt([1, 2, 3, 4, 5, 6], 'db1')\n >>> cA\n array([ 2.12132034, 4.94974747, 7.77817459])\n >>> cD\n array([-0.70710678, -0.70710678, -0.70710678])\n\n \"\"\"\n if np.iscomplexobj(data):\n data = np.asarray(data)\n cA_r, cD_r = dwt(data.real, wavelet, mode, axis)\n cA_i, cD_i = dwt(data.imag, wavelet, mode, axis)\n return (cA_r + 1j*cA_i, cD_r + 1j*cD_i)\n\n # accept array_like input; make a copy to ensure a contiguous array\n dt = _check_dtype(data)\n data = np.array(data, dtype=dt)\n mode = Modes.from_object(mode)\n if not isinstance(wavelet, Wavelet):\n wavelet = Wavelet(wavelet)\n\n if axis < 0:\n axis = axis + data.ndim\n if not 0 <= axis < data.ndim:\n raise ValueError(\"Axis greater than data dimensions\")\n\n if data.ndim == 1:\n cA, cD = dwt_single(data, wavelet, mode)\n # TODO: Check whether this makes a copy\n cA, cD = np.asarray(cA, dt), np.asarray(cD, dt)\n else:\n cA, cD = dwt_axis(data, wavelet, mode, axis=axis)\n\n return (cA, cD)\n\n\ndef idwt(cA, cD, wavelet, mode='symmetric', axis=-1):\n \"\"\"\n idwt(cA, cD, wavelet, mode='symmetric', axis=-1)\n\n Single level Inverse Discrete Wavelet Transform.\n\n Parameters\n ----------\n cA : array_like or None\n Approximation coefficients. If None, will be set to array of zeros\n with same shape as `cD`.\n cD : array_like or None\n Detail coefficients. If None, will be set to array of zeros\n with same shape as `cA`.\n wavelet : Wavelet object or name\n Wavelet to use\n mode : str, optional (default: 'symmetric')\n Signal extension mode, see Modes\n axis: int, optional\n Axis over which to compute the inverse DWT. If not given, the\n last axis is used.\n\n\n Returns\n -------\n rec: array_like\n Single level reconstruction of signal from given coefficients.\n\n \"\"\"\n # TODO: Lots of possible allocations to eliminate (zeros_like, asarray(rec))\n # accept array_like input; make a copy to ensure a contiguous array\n\n if cA is None and cD is None:\n raise ValueError(\"At least one coefficient parameter must be \"\n \"specified.\")\n\n # for complex inputs: compute real and imaginary separately then combine\n if np.iscomplexobj(cA) or np.iscomplexobj(cD):\n if cA is None:\n cD = np.asarray(cD)\n cA = np.zeros_like(cD)\n elif cD is None:\n cA = np.asarray(cA)\n cD = np.zeros_like(cA)\n return (idwt(cA.real, cD.real, wavelet, mode, axis) +\n 1j*idwt(cA.imag, cD.imag, wavelet, mode, axis))\n\n if cA is not None:\n dt = _check_dtype(cA)\n cA = np.array(cA, dtype=dt)\n if cD is not None:\n dt = _check_dtype(cD)\n cD = np.array(cD, dtype=dt)\n\n if cA is not None and cD is not None:\n if cA.dtype != cD.dtype:\n # need to upcast to common type\n cA = cA.astype(np.float64)\n cD = cD.astype(np.float64)\n elif cA is None:\n cA = np.zeros_like(cD)\n elif cD is None:\n cD = np.zeros_like(cA)\n\n # cA and cD should be same dimension by here\n ndim = cA.ndim\n\n mode = Modes.from_object(mode)\n if not isinstance(wavelet, Wavelet):\n wavelet = Wavelet(wavelet)\n\n if axis < 0:\n axis = axis + ndim\n if not 0 <= axis < ndim:\n raise ValueError(\"Axis greater than coefficient dimensions\")\n\n if ndim == 1:\n rec = idwt_single(cA, cD, wavelet, mode)\n else:\n rec = idwt_axis(cA, cD, wavelet, mode, axis=axis)\n\n return rec\n\n\ndef downcoef(part, data, wavelet, mode='symmetric', level=1):\n \"\"\"\n downcoef(part, data, wavelet, mode='symmetric', level=1)\n\n Partial Discrete Wavelet Transform data decomposition.\n\n Similar to `pywt.dwt`, but computes only one set of coefficients.\n Useful when you need only approximation or only details at the given level.\n\n Parameters\n ----------\n part : str\n Coefficients type:\n\n * 'a' - approximations reconstruction is performed\n * 'd' - details reconstruction is performed\n\n data : array_like\n Input signal.\n wavelet : Wavelet object or name\n Wavelet to use\n mode : str, optional\n Signal extension mode, see `Modes`. Default is 'symmetric'.\n level : int, optional\n Decomposition level. Default is 1.\n\n Returns\n -------\n coeffs : ndarray\n 1-D array of coefficients.\n\n See Also\n --------\n upcoef\n\n \"\"\"\n if np.iscomplexobj(data):\n return (downcoef(part, data.real, wavelet, mode, level) +\n 1j*downcoef(part, data.imag, wavelet, mode, level))\n # accept array_like input; make a copy to ensure a contiguous array\n dt = _check_dtype(data)\n data = np.array(data, dtype=dt)\n if part not in 'ad':\n raise ValueError(\"Argument 1 must be 'a' or 'd', not '%s'.\" % part)\n mode = Modes.from_object(mode)\n if not isinstance(wavelet, Wavelet):\n wavelet = Wavelet(wavelet)\n return np.asarray(_downcoef(part == 'a', data, wavelet, mode, level))\n\n\ndef upcoef(part, coeffs, wavelet, level=1, take=0):\n \"\"\"\n upcoef(part, coeffs, wavelet, level=1, take=0)\n\n Direct reconstruction from coefficients.\n\n Parameters\n ----------\n part : str\n Coefficients type:\n * 'a' - approximations reconstruction is performed\n * 'd' - details reconstruction is performed\n coeffs : array_like\n Coefficients array to recontruct\n wavelet : Wavelet object or name\n Wavelet to use\n level : int, optional\n Multilevel reconstruction level. Default is 1.\n take : int, optional\n Take central part of length equal to 'take' from the result.\n Default is 0.\n\n Returns\n -------\n rec : ndarray\n 1-D array with reconstructed data from coefficients.\n\n See Also\n --------\n downcoef\n\n Examples\n --------\n >>> import pywt\n >>> data = [1,2,3,4,5,6]\n >>> (cA, cD) = pywt.dwt(data, 'db2', 'smooth')\n >>> pywt.upcoef('a', cA, 'db2') + pywt.upcoef('d', cD, 'db2')\n array([-0.25 , -0.4330127 , 1. , 2. , 3. ,\n 4. , 5. , 6. , 1.78589838, -1.03108891])\n >>> n = len(data)\n >>> pywt.upcoef('a', cA, 'db2', take=n) + pywt.upcoef('d', cD, 'db2', take=n)\n array([ 1., 2., 3., 4., 5., 6.])\n\n \"\"\"\n if np.iscomplexobj(coeffs):\n return (upcoef(part, coeffs.real, wavelet, level, take) +\n 1j*upcoef(part, coeffs.imag, wavelet, level, take))\n # accept array_like input; make a copy to ensure a contiguous array\n dt = _check_dtype(coeffs)\n coeffs = np.array(coeffs, dtype=dt)\n if not isinstance(wavelet, Wavelet):\n wavelet = Wavelet(wavelet)\n if part not in 'ad':\n raise ValueError(\"Argument 1 must be 'a' or 'd', not '%s'.\" % part)\n return np.asarray(_upcoef(part == 'a', coeffs, wavelet, level, take))\n", "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport pytest\nimport numpy as np\nfrom numpy.random import randn, normal\nfrom numpy.testing import assert_equal\nfrom numpy.testing.utils import assert_allclose\n\nfrom ..biweight import (biweight_location, biweight_scale,\n biweight_midvariance, biweight_midcovariance,\n biweight_midcorrelation)\n\nfrom ...extern.six.moves import range\nfrom ...tests.helper import catch_warnings\nfrom ...utils.misc import NumpyRNGContext\n\n\ndef test_biweight_location():\n with NumpyRNGContext(12345):\n # test that it runs\n randvar = randn(10000)\n cbl = biweight_location(randvar)\n assert abs(cbl - 0) < 1e-2\n\n\ndef test_biweight_location_small():\n cbl = biweight_location([1, 3, 5, 500, 2])\n assert abs(cbl - 2.745) < 1e-3\n\n\ndef test_biweight_location_axis():\n \"\"\"Test a 2D array with the axis keyword.\"\"\"\n with NumpyRNGContext(12345):\n ny = 100\n nx = 200\n data = normal(5, 2, (ny, nx))\n\n bw = biweight_location(data, axis=0)\n bwi = []\n for i in range(nx):\n bwi.append(biweight_location(data[:, i]))\n bwi = np.array(bwi)\n assert_allclose(bw, bwi)\n\n bw = biweight_location(data, axis=1)\n bwi = []\n for i in range(ny):\n bwi.append(biweight_location(data[i, :]))\n bwi = np.array(bwi)\n assert_allclose(bw, bwi)\n\n\ndef test_biweight_location_axis_3d():\n \"\"\"Test a 3D array with the axis keyword.\"\"\"\n with NumpyRNGContext(12345):\n nz = 3\n ny = 4\n nx = 5\n data = normal(5, 2, (nz, ny, nx))\n bw = biweight_location(data, axis=0)\n assert bw.shape == (ny, nx)\n\n y = 0\n bwi = []\n for i in range(nx):\n bwi.append(biweight_location(data[:, y, i]))\n bwi = np.array(bwi)\n assert_allclose(bw[y], bwi)\n\n\ndef test_biweight_scale():\n # NOTE: biweight_scale is covered by biweight_midvariance tests\n data = [1, 3, 5, 500, 2]\n scl = biweight_scale(data)\n var = biweight_midvariance(data)\n assert_allclose(scl, np.sqrt(var))\n\n\ndef test_biweight_midvariance():\n with NumpyRNGContext(12345):\n # test that it runs\n randvar = randn(10000)\n var = biweight_midvariance(randvar)\n assert_allclose(var, 1.0, rtol=0.02)\n\n\ndef test_biweight_midvariance_small():\n data = [1, 3, 5, 500, 2]\n var = biweight_midvariance(data)\n assert_allclose(var, 2.9238456) # verified with R\n\n var = biweight_midvariance(data, modify_sample_size=True)\n assert_allclose(var, 2.3390765)\n\n\ndef test_biweight_midvariance_5127():\n # test a regression introduced in #5127\n rand = np.random.RandomState(12345)\n data = rand.normal(loc=0., scale=20., size=(100, 100))\n var = biweight_midvariance(data)\n assert_allclose(var, 406.86938710817344) # verified with R\n\n\ndef test_biweight_midvariance_axis():\n \"\"\"Test a 2D array with the axis keyword.\"\"\"\n with NumpyRNGContext(12345):\n ny = 100\n nx = 200\n data = normal(5, 2, (ny, nx))\n\n bw = biweight_midvariance(data, axis=0)\n bwi = []\n for i in range(nx):\n bwi.append(biweight_midvariance(data[:, i]))\n bwi = np.array(bwi)\n assert_allclose(bw, bwi)\n\n bw = biweight_midvariance(data, axis=1)\n bwi = []\n for i in range(ny):\n bwi.append(biweight_midvariance(data[i, :]))\n bwi = np.array(bwi)\n assert_allclose(bw, bwi)\n\n\ndef test_biweight_midvariance_axis_3d():\n \"\"\"Test a 3D array with the axis keyword.\"\"\"\n with NumpyRNGContext(12345):\n nz = 3\n ny = 4\n nx = 5\n data = normal(5, 2, (nz, ny, nx))\n bw = biweight_midvariance(data, axis=0)\n assert bw.shape == (ny, nx)\n\n y = 0\n bwi = []\n for i in range(nx):\n bwi.append(biweight_midvariance(data[:, y, i]))\n bwi = np.array(bwi)\n assert_allclose(bw[y], bwi)\n\n\ndef test_biweight_midcovariance_1d():\n d = [0, 1, 2]\n cov = biweight_midcovariance(d)\n var = biweight_midvariance(d)\n assert_allclose(cov, [[var]])\n\n\ndef test_biweight_midcovariance_2d():\n d = [[0, 1, 2], [2, 1, 0]]\n cov = biweight_midcovariance(d)\n val = 0.70121809\n assert_allclose(cov, [[val, -val], [-val, val]]) # verified with R\n\n d = [[5, 1, 10], [500, 5, 2]]\n cov = biweight_midcovariance(d)\n assert_allclose(cov, [[14.54159077, -7.79026256], # verified with R\n [-7.79026256, 6.92087252]])\n\n cov = biweight_midcovariance(d, modify_sample_size=True)\n assert_allclose(cov, [[14.54159077, -5.19350838],\n [-5.19350838, 4.61391501]])\n\n\ndef test_biweight_midcovariance_midvariance():\n \"\"\"\n Test that biweight_midcovariance diagonal elements agree with\n biweight_midvariance.\n \"\"\"\n\n rng = np.random.RandomState(1)\n d = rng.normal(0, 2, size=(100, 3))\n cov = biweight_midcovariance(d)\n var = [biweight_midvariance(a) for a in d]\n assert_allclose(cov.diagonal(), var)\n\n cov2 = biweight_midcovariance(d, modify_sample_size=True)\n var2 = [biweight_midvariance(a, modify_sample_size=True)\n for a in d]\n assert_allclose(cov2.diagonal(), var2)\n\n\ndef test_midcovariance_shape():\n \"\"\"\n Test that biweight_midcovariance raises error with a 3D array.\n \"\"\"\n\n d = np.ones(27).reshape(3, 3, 3)\n with pytest.raises(ValueError) as e:\n biweight_midcovariance(d)\n assert 'The input array must be 2D or 1D.' in str(e.value)\n\n\ndef test_midcovariance_M_shape():\n \"\"\"\n Test that biweight_midcovariance raises error when M is not a scalar\n or 1D array.\n \"\"\"\n\n d = [0, 1, 2]\n M = [[0, 1], [2, 3]]\n with pytest.raises(ValueError) as e:\n biweight_midcovariance(d, M=M)\n assert 'M must be a scalar or 1D array.' in str(e.value)\n\n\ndef test_biweight_midcovariance_symmetric():\n \"\"\"\n Regression test to ensure that midcovariance matrix is symmetric\n when ``modify_sample_size=True`` (see #5972).\n \"\"\"\n\n rng = np.random.RandomState(1)\n d = rng.gamma(2, 2, size=(3, 500))\n cov = biweight_midcovariance(d)\n assert_equal(cov, cov.T)\n\n cov = biweight_midcovariance(d, modify_sample_size=True)\n assert_equal(cov, cov.T)\n\n\ndef test_biweight_midcorrelation():\n x = [0, 1, 2]\n y = [2, 1, 0]\n assert_allclose(biweight_midcorrelation(x, x), 1.0)\n assert_allclose(biweight_midcorrelation(x, y), -1.0)\n\n x = [5, 1, 10, 12.4, 13.2]\n y = [500, 5, 2, 7.1, 0.9]\n # verified with R\n assert_allclose(biweight_midcorrelation(x, y), -0.14411038976763313)\n\n\ndef test_biweight_midcorrelation_inputs():\n a1 = np.ones((3, 3))\n a2 = np.ones(5)\n a3 = np.ones(7)\n\n with pytest.raises(ValueError) as e:\n biweight_midcorrelation(a1, a2)\n assert 'x must be a 1D array.' in str(e.value)\n\n with pytest.raises(ValueError) as e:\n biweight_midcorrelation(a2, a1)\n assert 'y must be a 1D array.' in str(e.value)\n\n with pytest.raises(ValueError) as e:\n biweight_midcorrelation(a2, a3)\n assert 'x and y must have the same shape.' in str(e.value)\n\n\ndef test_biweight_32bit_runtime_warnings():\n \"\"\"Regression test for #6905.\"\"\"\n with NumpyRNGContext(12345):\n data = np.random.random(100).astype(np.float32)\n data[50] = 30000.\n\n with catch_warnings(RuntimeWarning) as warning_lines:\n biweight_scale(data)\n assert len(warning_lines) == 0\n\n with catch_warnings(RuntimeWarning) as warning_lines:\n biweight_midvariance(data)\n assert len(warning_lines) == 0\n", "# -*- coding: utf-8 -*-\n\n# Copyright (c) 2012, Sergio Callegari\n# All rights reserved.\n\n# This file is part of PyDSM.\n\n# PyDSM is free software: you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# PyDSM is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with PyDSM. If not, see <http://www.gnu.org/licenses/>.\n\n# This file includes code ported from the DELSIG Matlab toolbox\n# (see http://www.mathworks.com/matlabcentral/fileexchange/19)\n# covered by the following copyright and permission notice\n#\n# Copyright (c) 2009 Richard Schreier\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the distribution\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\nEntry point for DELSIG-like Delta-Sigma NTF synthesis function\n==============================================================\n\"\"\"\n\nimport numpy as np\nfrom warnings import warn\nfrom ..exceptions import PyDsmApproximationWarning\nfrom ._synthesizeNTF0 import synthesizeNTF0\nfrom ._synthesizeNTF1 import synthesizeNTF1\nfrom ..utilities import digested_options\n\n__all__ = [\"synthesizeNTF\"]\n\n\ndef synthesizeNTF(order=3, osr=64, opt=0, H_inf=1.5, f0=0.0,\n **options):\n \"\"\"\n Synthesizes an NTF for a DS modulator by Schreier's approach.\n\n Parameters\n ----------\n order : int, optional\n the order of the modulator, defaults to 3\n osr : float, optional\n the oversamping ratio (based on the actual signal bandwidth)\n opt : int or list of floats, optional\n flag for optimized zeros, defaults to 0\n\n * 0 -> not optimized,\n * 1 -> optimized,\n * 2 -> optimized with at least one zero at band-center,\n * 3 -> optimized zeros (with optimizer)\n * 4 -> same as 3, but with at least one zero at band-center\n * [z] -> zero locations in complex form\n\n H_inf : real, optional\n max allowed peak value of the NTF. Defaults to 1.5\n f0 : real, optional\n center frequency for BP modulators, or 0 for LP modulators.\n Defaults to 0.\n 1 corresponds to the sampling frequency, so that 0.5 is the\n maximum value. Value 0 specifies an LP modulator.\n\n Returns\n -------\n ntf : tuple\n noise transfer function in zpk form.\n\n Other Parameters\n ----------------\n use_optimizer : bool\n Use: True for for optimizing the zeros with a fast optimization code,\n False otherwise. Defaults can be set by changing the function\n ``default_options`` attribute.\n\n Raises\n ------\n ValueError\n 'Frequency f0 must be less than 0.5' if f0 is out of range\n\n 'Order must be even for a bandpass modulator' if the order is\n incompatible with the modulator type.\n\n 'The opt vector must be of length xxx' if opt is used to explicitly\n pass the NTF zeros and these are in the wrong number.\n\n RuntimeError\n 'Cannot synthesize NTF zeros' if the synthesis fails for some\n unspecified reason.\n\n Warns\n -----\n PyDsmApproximationWarning\n 'Creating a lowpass ntf.' if the center frequency is different\n from zero, but so low that a low pass modulator must be designed.\n\n 'Unable to achieve specified H_inf ...' if the desired H_inf\n cannot be achieved.\n\n 'Iteration limit exceeded' if the routine converges too\n slowly.\n\n Notes\n -----\n This is actually a wrapper function which calls the appropriate version\n of synthesizeNTF, based on the control flag `optimize_NTF` which\n determines whether to use optimization tools.\n\n Parameter H_inf is used to enforce the Lee stability criterion.\n\n If osr or H_inf are low, then the NTF is non optimal. Use\n synthesizeChebyshevNTF instead.\n \"\"\"\n # Manage options\n opts = digested_options(options, synthesizeNTF.default_options,\n ['use_optimizer'])\n use_optimizer = opts['use_optimizer']\n # Do the computation\n if f0 > 0.5:\n raise ValueError('Frequency f0 must be less than 0.5')\n if f0 != 0 and f0 < 0.25/osr:\n warn('Creating a lowpass ntf.', PyDsmApproximationWarning)\n f0 = 0\n if f0 != 0 and order % 2 != 0:\n raise ValueError('Order must be even for a bandpass modulator')\n opt = np.asarray(opt)\n if opt.ndim > 1 or (opt.ndim == 1 and opt.size != order):\n raise ValueError('The opt vector must be of length %d' % order)\n\n if not use_optimizer:\n ntf = synthesizeNTF0(order, osr, opt, H_inf, f0)\n else:\n ntf = synthesizeNTF1(order, osr, opt, H_inf, f0)\n return ntf\n\nsynthesizeNTF.default_options = {'use_optimizer': True}\n", "import numpy as np\n\nfrom ._extensions._pywt import (DiscreteContinuousWavelet, ContinuousWavelet,\n Wavelet, _check_dtype)\nfrom ._functions import integrate_wavelet, scale2frequency\n\n__all__ = [\"cwt\"]\n\n\ndef cwt(data, scales, wavelet, sampling_period=1.):\n \"\"\"\n cwt(data, scales, wavelet)\n\n One dimensional Continuous Wavelet Transform.\n\n Parameters\n ----------\n data : array_like\n Input signal\n scales : array_like\n scales to use\n wavelet : Wavelet object or name\n Wavelet to use\n sampling_period : float\n Sampling period for frequencies output (optional)\n\n Returns\n -------\n coefs : array_like\n Continous wavelet transform of the input signal for the given scales\n and wavelet\n frequencies : array_like\n if the unit of sampling period are seconds and given, than frequencies\n are in hertz. Otherwise Sampling period of 1 is assumed.\n\n Notes\n -----\n Size of coefficients arrays depends on the length of the input array and\n the length of given scales.\n\n Examples\n --------\n >>> import pywt\n >>> import numpy as np\n >>> import matplotlib.pyplot as plt\n >>> x = np.arange(512)\n >>> y = np.sin(2*np.pi*x/32)\n >>> coef, freqs=pywt.cwt(y,np.arange(1,129),'gaus1')\n >>> plt.matshow(coef) # doctest: +SKIP\n >>> plt.show() # doctest: +SKIP\n ----------\n >>> import pywt\n >>> import numpy as np\n >>> import matplotlib.pyplot as plt\n >>> t = np.linspace(-1, 1, 200, endpoint=False)\n >>> sig = np.cos(2 * np.pi * 7 * t) + np.real(np.exp(-7*(t-0.4)**2)*np.exp(1j*2*np.pi*2*(t-0.4)))\n >>> widths = np.arange(1, 31)\n >>> cwtmatr, freqs = pywt.cwt(sig, widths, 'mexh')\n >>> plt.imshow(cwtmatr, extent=[-1, 1, 1, 31], cmap='PRGn', aspect='auto',\n ... vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max()) # doctest: +SKIP\n >>> plt.show() # doctest: +SKIP\n \"\"\"\n\n # accept array_like input; make a copy to ensure a contiguous array\n dt = _check_dtype(data)\n data = np.array(data, dtype=dt)\n if not isinstance(wavelet, (ContinuousWavelet, Wavelet)):\n wavelet = DiscreteContinuousWavelet(wavelet)\n if np.isscalar(scales):\n scales = np.array([scales])\n if data.ndim == 1:\n if wavelet.complex_cwt:\n out = np.zeros((np.size(scales), data.size), dtype=complex)\n else:\n out = np.zeros((np.size(scales), data.size))\n for i in np.arange(np.size(scales)):\n precision = 10\n int_psi, x = integrate_wavelet(wavelet, precision=precision)\n step = x[1] - x[0]\n j = np.floor(\n np.arange(scales[i] * (x[-1] - x[0]) + 1) / (scales[i] * step))\n if np.max(j) >= np.size(int_psi):\n j = np.delete(j, np.where((j >= np.size(int_psi)))[0])\n coef = - np.sqrt(scales[i]) * np.diff(\n np.convolve(data, int_psi[j.astype(np.int)][::-1]))\n d = (coef.size - data.size) / 2.\n out[i, :] = coef[int(np.floor(d)):int(-np.ceil(d))]\n frequencies = scale2frequency(wavelet, scales, precision)\n if np.isscalar(frequencies):\n frequencies = np.array([frequencies])\n for i in np.arange(len(frequencies)):\n frequencies[i] /= sampling_period\n return out, frequencies\n else:\n raise ValueError(\"Only dim == 1 supportet\")\n", "import torch\n\nfrom ..function import Function\nfrom .utils import maybe_unexpand, maybe_unexpand_or_view\n\n\n# TODO: once Cpp-style functions are implemented we can detach a and b\n# before calling forward.\nclass _CompareOp(Function):\n\n @classmethod\n def forward(cls, ctx, a, b):\n ctx.a_size = a.size()\n ctx.b_tensor = torch.is_tensor(b)\n ctx.b_size = b.size() if ctx.b_tensor else None\n ctx.input_type = type(a)\n mask = getattr(a, cls.fn_name)(b)\n ctx.mark_non_differentiable(mask)\n return mask\n\n @staticmethod\n def backward(ctx, grad_output):\n grad_input = (grad_output * 0).type(ctx.input_type)\n return (maybe_unexpand(grad_input, ctx.a_size),\n maybe_unexpand_or_view(grad_input, ctx.b_size) if ctx.b_tensor else None)\n\n\nclass Eq(_CompareOp):\n fn_name = 'eq'\n\n\nclass Ne(_CompareOp):\n fn_name = 'ne'\n\n\nclass Gt(_CompareOp):\n fn_name = 'gt'\n\n\nclass Ge(_CompareOp):\n fn_name = 'ge'\n\n\nclass Lt(_CompareOp):\n fn_name = 'lt'\n\n\nclass Le(_CompareOp):\n fn_name = 'le'\n", "#***********************************************************************#\n# Copyright (C) 2010-2012 Tomas Tinoco De Rubira #\n# #\n# This file is part of CVXPY # \n# #\n# CVXPY is free software: you can redistribute it and/or modify #\n# it under the terms of the GNU General Public License as published by #\n# the Free Software Foundation, either version 3 of the License, or # \n# (at your option) any later version. # \n# #\n# CVXPY is distributed in the hope that it will be useful, #\n# but WITHOUT ANY WARRANTY; without even the implied warranty of #\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #\n# GNU General Public License for more details. #\n# #\n# You should have received a copy of the GNU General Public License #\n# along with this program. If not, see <http://www.gnu.org/licenses/>. #\n#***********************************************************************#\n\nimport numpy as np\nfrom ..defs import *\nfrom ..sets import *\nfrom ..utils import *\nfrom ..interface import *\nfrom ..arrays import cvxpy_matrix\n\n# Geometric Mean\ndef geo_mean(x):\n \"\"\"\n | :math:`\\mbox{geo\\_mean} :\n \\mathbb{R}_+^n \\\\to \\mathbb{R},\n \\ \\mbox{geo\\_mean}(x) = \\\\big( \\prod_{i=1}^n x_i \\\\big)^{1/n}`.\n | Concave and increasing.\n\n :param x: number,\n :ref:`scalar object<scalar_ref>` or\n :ref:`multidimensional object<multi_ref>`.\n :return: number or \n :ref:`tree<tree_obj>`.\n \"\"\"\n\n # Process input\n if (np.isscalar(x) or\n type(x).__name__ in SCALAR_OBJS):\n x = vstack([x])\n elif (type(x) is not cvxpy_matrix and\n type(x).__name__ not in ARRAY_OBJS):\n raise TypeError('Invalid argument type')\n\n # x must be a vector\n (m,n) = x.shape\n if n!=1:\n raise ValueError('Invalid argument dimension')\n\n # Check nonnegativity if cvxpy_matrix\n if (type(x) is cvxpy_matrix and\n not np.all(x >= 0)):\n return -np.inf \n\n # Construct program\n z = variable(m,1)\n v = variable(m,1)\n t = variable()\n p = program(maximize(t),\n [belongs(vstack((v,t)),geo_mean_cone),\n greater_equals(z,v), geq(v,0)],\n [z],\n name='geo_mean')\n return p(x)\n", "import numpy\n\nfrom chainer import cuda\nfrom chainer import function_node\nfrom chainer import utils\nfrom chainer.utils import type_check\n\n\nclass Log1p(function_node.FunctionNode):\n\n @property\n def label(self):\n return 'log1p'\n\n def check_type_forward(self, in_types):\n type_check.expect(in_types.size() == 1)\n type_check.expect(in_types[0].dtype.kind == 'f')\n\n def forward_cpu(self, x):\n self.retain_inputs((0,))\n return utils.force_array(numpy.log1p(x[0])),\n\n def forward_gpu(self, x):\n self.retain_inputs((0,))\n return cuda.cupy.log1p(x[0]),\n\n def backward(self, indexes, gy):\n x = self.get_retained_inputs()\n return gy[0] / (x[0] + 1.0),\n\n\ndef log1p(x):\n \"\"\"Elementwise natural logarithm plus one function.\"\"\"\n return Log1p().apply((x,))[0]\n", "#***********************************************************************#\n# Copyright (C) 2010-2012 Tomas Tinoco De Rubira #\n# #\n# This file is part of CVXPY # \n# #\n# CVXPY is free software: you can redistribute it and/or modify #\n# it under the terms of the GNU General Public License as published by #\n# the Free Software Foundation, either version 3 of the License, or # \n# (at your option) any later version. # \n# #\n# CVXPY is distributed in the hope that it will be useful, #\n# but WITHOUT ANY WARRANTY; without even the implied warranty of #\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #\n# GNU General Public License for more details. #\n# #\n# You should have received a copy of the GNU General Public License #\n# along with this program. If not, see <http://www.gnu.org/licenses/>. #\n#***********************************************************************#\n\nimport numpy as np\nimport cvxopt as opt\nfrom ..defs import *\nfrom ..scalars import cvxpy_obj\n\n# Class definition\nclass cvxpy_semidefinite_cone(object):\n \"\"\"\n | :math:`\\{X \\in \\mathbb{R}^{n \\\\times n} \\ |\n \\ X = X^T, \\ X \\succeq 0 \\} = \\mathbb{S}_+^n`.\n \"\"\"\n\n # Method: __init__\n def __init__(self):\n \"\"\"\n Class constructor.\n \"\"\"\n\n self.type = SET\n self.name = 'semidefinite_cone'\n self.expansion_type = SDC\n \n # Method: valid_shape\n def valid_shape(self,shape):\n \n return shape[0] == shape[1]\n\n # Method: __str__\n def __str__(self):\n\n return self.name\n \n # Method: _construct\n def _construct(self,el,mp,n):\n\n m = int(el.shape[0])\n G = opt.spmatrix(0.0,[],[],(m*m,n))\n h = opt.matrix(0.0,(m*m,1))\n for j in range(0,m,1):\n for i in range(0,m,1):\n if np.isscalar(el[i,j]):\n h[j*m+i,0] = el[i,j]*1.\n elif type(el[i,j]) is cvxpy_obj:\n h[j*m+i,0] = el[i,j].value*1.\n else:\n G[j*m+i,mp[el[i,j]]] = -1.\n return G,h,m\n\n# Create instance\nsemidefinite_cone = cvxpy_semidefinite_cone()\n", "from __future__ import absolute_import, division\nimport numpy as np\nfrom pytools import my_decorator as decorator, MovedFunctionDeprecationWrapper\n\n__doc__ = \"\"\"\nHandling :mod:`numpy` Object Arrays\n===================================\n\n.. autofunction:: oarray_real\n.. autofunction:: oarray_imag\n.. autofunction:: oarray_real_copy\n.. autofunction:: oarray_imag_copy\n\nCreation\n--------\n\n.. autofunction:: join_fields\n.. autofunction:: make_obj_array\n\nMapping\n-------\n\n.. autofunction:: with_object_array_or_scalar\n.. autofunction:: with_object_array_or_scalar_n_args\n\"\"\"\n\n\ndef gen_len(expr):\n from pytools.obj_array import is_obj_array\n if is_obj_array(expr):\n return len(expr)\n else:\n return 1\n\n\ndef gen_slice(expr, slice):\n result = expr[slice]\n if len(result) == 1:\n return result[0]\n else:\n return result\n\n\ndef is_obj_array(val):\n try:\n return isinstance(val, np.ndarray) and val.dtype == object\n except AttributeError:\n return False\n\n\ndef to_obj_array(ary):\n ls = log_shape(ary)\n result = np.empty(ls, dtype=object)\n\n from pytools import indices_in_shape\n for i in indices_in_shape(ls):\n result[i] = ary[i]\n\n return result\n\n\ndef is_field_equal(a, b):\n if is_obj_array(a):\n return is_obj_array(b) and (a.shape == b.shape) and (a == b).all()\n else:\n return not is_obj_array(b) and a == b\n\n\ndef make_obj_array(res_list):\n result = np.empty((len(res_list),), dtype=object)\n for i, v in enumerate(res_list):\n result[i] = v\n\n return result\n\n\ndef setify_field(f):\n from hedge.tools import is_obj_array\n if is_obj_array(f):\n return set(f)\n else:\n return set([f])\n\n\ndef obj_array_to_hashable(f):\n if is_obj_array(f):\n return tuple(f)\n else:\n return f\n\n\nhashable_field = MovedFunctionDeprecationWrapper(obj_array_to_hashable)\n\n\ndef obj_array_equal(a, b):\n a_is_oa = is_obj_array(a)\n assert a_is_oa == is_obj_array(b)\n\n if a_is_oa:\n return np.array_equal(a, b)\n else:\n return a == b\n\n\nfield_equal = MovedFunctionDeprecationWrapper(obj_array_equal)\n\n\ndef join_fields(*args):\n res_list = []\n for arg in args:\n if isinstance(arg, list):\n res_list.extend(arg)\n elif isinstance(arg, np.ndarray):\n if log_shape(arg) == ():\n res_list.append(arg)\n else:\n res_list.extend(arg.flat)\n else:\n res_list.append(arg)\n\n return make_obj_array(res_list)\n\n\ndef log_shape(array):\n \"\"\"Returns the \"logical shape\" of the array.\n\n The \"logical shape\" is the shape that's left when the node-depending\n dimension has been eliminated.\"\"\"\n\n try:\n if array.dtype.char == \"O\":\n return array.shape\n else:\n return array.shape[:-1]\n except AttributeError:\n return ()\n\n\ndef with_object_array_or_scalar(f, field, obj_array_only=False):\n if obj_array_only:\n if is_obj_array(field):\n ls = field.shape\n else:\n ls = ()\n else:\n ls = log_shape(field)\n if ls != ():\n from pytools import indices_in_shape\n result = np.zeros(ls, dtype=object)\n for i in indices_in_shape(ls):\n result[i] = f(field[i])\n return result\n else:\n return f(field)\n\n\nas_oarray_func = decorator(with_object_array_or_scalar)\n\n\ndef with_object_array_or_scalar_n_args(f, *args):\n oarray_arg_indices = []\n for i, arg in enumerate(args):\n if is_obj_array(arg):\n oarray_arg_indices.append(i)\n\n if not oarray_arg_indices:\n return f(*args)\n\n leading_oa_index = oarray_arg_indices[0]\n\n ls = log_shape(args[leading_oa_index])\n if ls != ():\n from pytools import indices_in_shape\n result = np.zeros(ls, dtype=object)\n\n new_args = list(args)\n for i in indices_in_shape(ls):\n for arg_i in oarray_arg_indices:\n new_args[arg_i] = args[arg_i][i]\n\n result[i] = f(*new_args)\n return result\n else:\n return f(*args)\n\n\nas_oarray_func_n_args = decorator(with_object_array_or_scalar_n_args)\n\n\ndef cast_field(field, dtype):\n return with_object_array_or_scalar(\n lambda f: f.astype(dtype), field)\n\n\ndef oarray_real(ary):\n return with_object_array_or_scalar(lambda x: x.real, ary)\n\n\ndef oarray_imag(ary):\n return with_object_array_or_scalar(lambda x: x.imag, ary)\n\n\ndef oarray_real_copy(ary):\n return with_object_array_or_scalar(lambda x: x.real.copy(), ary)\n\n\ndef oarray_imag_copy(ary):\n return with_object_array_or_scalar(lambda x: x.imag.copy(), ary)\n", "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''Core resampling interface'''\n\nimport numpy as np\n\nfrom .filters import get_filter\n\nfrom .interpn import resample_f\n\n__all__ = ['resample']\n\n\ndef resample(x, sr_orig, sr_new, axis=-1, filter='kaiser_best', **kwargs):\n '''Resample a signal x from sr_orig to sr_new along a given axis.\n\n Parameters\n ----------\n x : np.ndarray, dtype=np.float*\n The input signal(s) to resample.\n\n sr_orig : int > 0\n The sampling rate of x\n\n sr_new : int > 0\n The target sampling rate of the output signal(s)\n\n axis : int\n The target axis along which to resample `x`\n\n filter : optional, str or callable\n The resampling filter to use.\n\n By default, uses the `kaiser_best` (pre-computed filter).\n\n kwargs\n additional keyword arguments provided to the specified filter\n\n Returns\n -------\n y : np.ndarray\n `x` resampled to `sr_new`\n\n Raises\n ------\n ValueError\n if `sr_orig` or `sr_new` is not positive\n\n TypeError\n if the input signal `x` has an unsupported data type.\n\n Examples\n --------\n >>> # Generate a sine wave at 440 Hz for 5 seconds\n >>> sr_orig = 44100.0\n >>> x = np.sin(2 * np.pi * 440.0 / sr_orig * np.arange(5 * sr_orig))\n >>> x\n array([ 0. , 0.063, ..., -0.125, -0.063])\n >>> # Resample to 22050 with default parameters\n >>> resampy.resample(x, sr_orig, 22050)\n array([ 0.011, 0.123, ..., -0.193, -0.103])\n >>> # Resample using the fast (low-quality) filter\n >>> resampy.resample(x, sr_orig, 22050, filter='kaiser_fast')\n array([ 0.013, 0.121, ..., -0.189, -0.102])\n >>> # Resample using a high-quality filter\n >>> resampy.resample(x, sr_orig, 22050, filter='kaiser_best')\n array([ 0.011, 0.123, ..., -0.193, -0.103])\n >>> # Resample using a Hann-windowed sinc filter\n >>> resampy.resample(x, sr_orig, 22050, filter='sinc_window',\n ... window=scipy.signal.hann)\n array([ 0.011, 0.123, ..., -0.193, -0.103])\n\n >>> # Generate stereo data\n >>> x_right = np.sin(2 * np.pi * 880.0 / sr_orig * np.arange(len(x)))])\n >>> x_stereo = np.stack([x, x_right])\n >>> x_stereo.shape\n (2, 220500)\n >>> # Resample along the time axis (1)\n >>> y_stereo = resampy.resample(x, sr_orig, 22050, axis=1)\n >>> y_stereo.shape\n (2, 110250)\n '''\n\n if sr_orig <= 0:\n raise ValueError('Invalid sample rate: sr_orig={}'.format(sr_orig))\n\n if sr_new <= 0:\n raise ValueError('Invalid sample rate: sr_new={}'.format(sr_new))\n\n sample_ratio = float(sr_new) / sr_orig\n\n # Set up the output shape\n shape = list(x.shape)\n shape[axis] = int(shape[axis] * sample_ratio)\n\n if shape[axis] < 1:\n raise ValueError('Input signal length={} is too small to '\n 'resample from {}->{}'.format(x.shape[axis], sr_orig, sr_new))\n\n y = np.zeros(shape, dtype=x.dtype)\n\n interp_win, precision, _ = get_filter(filter, **kwargs)\n\n if sample_ratio < 1:\n interp_win *= sample_ratio\n\n interp_delta = np.zeros_like(interp_win)\n interp_delta[:-1] = np.diff(interp_win)\n\n # Construct 2d views of the data with the resampling axis on the first dimension\n x_2d = x.swapaxes(0, axis).reshape((x.shape[axis], -1))\n y_2d = y.swapaxes(0, axis).reshape((y.shape[axis], -1))\n resample_f(x_2d, y_2d, sample_ratio, interp_win, interp_delta, precision)\n\n return y\n", "import torch\nfrom .Module import Module\nfrom .utils import clear\n\n\nclass Normalize(Module):\n\n def __init__(self, p, eps=1e-10):\n super(Normalize, self).__init__()\n assert p > 0\n self.p = p\n self.eps = eps\n\n self._output = None\n self.norm = None\n self.buffer = None\n self._indices = None\n self.normp = None\n self._gradInput = None\n self.cross = None\n self.buffer2 = None\n\n def updateOutput(self, input):\n assert input.dim() == 2\n input_size = input.size()\n\n if self._output is None:\n self._output = input.new()\n if self.norm is None:\n self.norm = input.new()\n if self.buffer is None:\n self.buffer = input.new()\n\n self._output.resize_as_(input)\n\n # specialization for the infinity norm\n if self.p == float('inf'):\n if not self._indices:\n self._indices = torch.cuda.FloatTensor() if torch.typename(self.output) == 'torch.cuda.FloatTensor' \\\n else torch.LongTensor()\n\n torch.abs(input, out=self.buffer)\n torch.max(self._indices, self.buffer, 1, out=self.norm, keepdim=True)\n self.norm.add_(self.eps)\n else:\n if self.normp is None:\n self.normp = input.new()\n if self.p % 2 != 0:\n torch.abs(input, out=self.buffer).pow_(self.p)\n else:\n torch.pow(input, self.p, out=self.buffer)\n\n torch.sum(self.buffer, 1, out=self.normp, keepdim=True).add_(self.eps)\n torch.pow(self.normp, 1. / self.p, out=self.norm)\n\n torch.div(input, self.norm.view(-1, 1).expand_as(input), out=self._output)\n\n self.output = self._output.view(input_size)\n return self.output\n\n def updateGradInput(self, input, gradOutput):\n assert input.dim() == 2\n assert gradOutput.dim() == 2\n\n input_size = input.size()\n n = input.size(0) # batch size\n d = input.size(1) # dimensionality of vectors\n\n if self._gradInput is None:\n self._gradInput = input.new()\n if self.cross is None:\n self.cross = input.new()\n # compute diagonal term with gradOutput\n self._gradInput.resize_(n, d)\n if self.p == float('inf'):\n # specialization for the inf case\n torch.mul(self.norm.view(n, 1, 1).expand(n, d, 1), gradOutput, out=self._gradInput)\n self.buffer.resize_as_(input).zero_()\n self.cross.resize_(n, 1)\n torch.gather(input, 1, self._indices, out=self.cross)\n self.cross.div_(self.norm)\n self.buffer.scatter_(1, self._indices, self.cross)\n else:\n torch.mul(self.normp.view(n, 1).expand(n, d), gradOutput, out=self._gradInput)\n # small optimizations for different p\n # buffer = input*|input|^(p-2)\n # for non-even p, need to add absolute value\n if self.p % 2 != 0:\n if self.p < 2:\n # add eps to avoid possible division by 0\n torch.abs(input, out=self.buffer).add_(self.eps).pow_(self.p - 2).mul_(input)\n else:\n torch.abs(input, out=self.buffer).pow_(self.p - 2).mul_(input)\n # special case for p == 2, pow(x, 0) = 1\n elif self.p == 2:\n self.buffer.copy_(input)\n else:\n # p is even and > 2, pow(x, p) is always positive\n torch.pow(input, self.p - 2, out=self.buffer).mul_(input)\n\n # compute cross term in two steps\n self.cross.resize_(n, 1)\n\n # instead of having a huge temporary matrix (b1*b2),\n #: the computations as b1*(b2*gradOutput). This avoids redundant\n # computation and also a huge buffer of size n*d^2\n if self.buffer2 is None:\n self.buffer2 = input.new() # nxd\n torch.mul(input, gradOutput, out=self.buffer2)\n torch.sum(self.buffer2, 1, out=self.cross, keepdim=True)\n\n self.buffer.mul_(self.cross.expand_as(self.buffer))\n self._gradInput.add_(-1, self.buffer)\n\n # reuse cross buffer for normalization\n if self.p == float('inf'):\n torch.mul(self.norm, self.norm, out=self.cross)\n else:\n torch.mul(self.normp, self.norm, out=self.cross)\n\n self._gradInput.div_(self.cross.expand(n, d))\n\n self.gradInput = self._gradInput.view(input_size)\n return self.gradInput\n\n def __repr__(self):\n return super(Normalize, self).__repr__() + '({})'.format(self.p)\n\n def type(self, type, tensorCache=None):\n if not type:\n return self._type\n # torch.max expects a LongTensor as indices, whereas cutorch.max expects a CudaTensor.\n if type == 'torch.cuda.FloatTensor':\n super(Normalize, self).type(type, tensorCache)\n else:\n # self._indices must be a LongTensor. Setting it to nil temporarily avoids\n # unnecessary memory allocations.\n indices, self._indices = self._indices, None\n super(Normalize, self).type(type, tensorCache)\n self._indices = indices.long() if indices else None\n\n return self\n\n def clearState(self):\n clear(self, [\n '_output',\n '_indices',\n '_gradInput',\n 'buffer',\n 'norm',\n 'normp',\n 'cross',\n ])\n return super(Normalize, self).clearState()\n", "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\n\"\"\"\nThis module implements classes (called Fitters) which combine optimization\nalgorithms (typically from `scipy.optimize`) with statistic functions to perform\nfitting. Fitters are implemented as callable classes. In addition to the data\nto fit, the ``__call__`` method takes an instance of\n`~astropy.modeling.core.FittableModel` as input, and returns a copy of the\nmodel with its parameters determined by the optimizer.\n\nOptimization algorithms, called \"optimizers\" are implemented in\n`~astropy.modeling.optimizers` and statistic functions are in\n`~astropy.modeling.statistic`. The goal is to provide an easy to extend\nframework and allow users to easily create new fitters by combining statistics\nwith optimizers.\n\nThere are two exceptions to the above scheme.\n`~astropy.modeling.fitting.LinearLSQFitter` uses Numpy's `~numpy.linalg.lstsq`\nfunction. `~astropy.modeling.fitting.LevMarLSQFitter` uses\n`~scipy.optimize.leastsq` which combines optimization and statistic in one\nimplementation.\n\"\"\"\n\nfrom __future__ import (absolute_import, unicode_literals, division,\n print_function)\n\nimport abc\nimport inspect\nimport operator\nimport warnings\n\nfrom functools import reduce, wraps\n\nimport numpy as np\n\nfrom .utils import poly_map_domain, _combine_equivalency_dict\nfrom ..units import Quantity\nfrom ..utils.exceptions import AstropyUserWarning\nfrom ..extern import six\nfrom ..extern.six.moves import range\nfrom .optimizers import (SLSQP, Simplex)\nfrom .statistic import (leastsquare)\n\n# Check pkg_resources exists\ntry:\n from pkg_resources import iter_entry_points\n HAS_PKG = True\nexcept ImportError:\n HAS_PKG = False\n\n\n__all__ = ['LinearLSQFitter', 'LevMarLSQFitter', 'FittingWithOutlierRemoval',\n 'SLSQPLSQFitter', 'SimplexLSQFitter', 'JointFitter', 'Fitter']\n\n\n# Statistic functions implemented in `astropy.modeling.statistic.py\nSTATISTICS = [leastsquare]\n\n# Optimizers implemented in `astropy.modeling.optimizers.py\nOPTIMIZERS = [Simplex, SLSQP]\n\nfrom .optimizers import (DEFAULT_MAXITER, DEFAULT_EPS, DEFAULT_ACC)\n\n\nclass ModelsError(Exception):\n \"\"\"Base class for model exceptions\"\"\"\n\n\nclass ModelLinearityError(ModelsError):\n \"\"\" Raised when a non-linear model is passed to a linear fitter.\"\"\"\n\n\nclass UnsupportedConstraintError(ModelsError, ValueError):\n \"\"\"\n Raised when a fitter does not support a type of constraint.\n \"\"\"\n\n\nclass _FitterMeta(abc.ABCMeta):\n \"\"\"\n Currently just provides a registry for all Fitter classes.\n \"\"\"\n\n registry = set()\n\n def __new__(mcls, name, bases, members):\n cls = super(_FitterMeta, mcls).__new__(mcls, name, bases, members)\n\n if not inspect.isabstract(cls) and not name.startswith('_'):\n mcls.registry.add(cls)\n\n return cls\n\n\ndef fitter_unit_support(func):\n \"\"\"\n This is a decorator that can be used to add support for dealing with\n quantities to any __call__ method on a fitter which may not support\n quantities itself. This is done by temporarily removing units from all\n parameters then adding them back once the fitting has completed.\n \"\"\"\n @wraps(func)\n def wrapper(self, model, x, y, z=None, **kwargs):\n equivalencies = kwargs.pop('equivalencies', None)\n\n data_has_units = (isinstance(x, Quantity) or\n isinstance(y, Quantity) or\n isinstance(z, Quantity))\n\n model_has_units = model._has_units\n\n if data_has_units or model_has_units:\n\n if model._supports_unit_fitting:\n\n # We now combine any instance-level input equivalencies with user\n # specified ones at call-time.\n\n\n input_units_equivalencies = _combine_equivalency_dict(\n model.inputs, equivalencies, model.input_units_equivalencies)\n\n # If input_units is defined, we transform the input data into those\n # expected by the model. We hard-code the input names 'x', and 'y'\n # here since FittableModel instances have input names ('x',) or\n # ('x', 'y')\n\n if model.input_units is not None:\n if isinstance(x, Quantity):\n x = x.to(model.input_units['x'], equivalencies=input_units_equivalencies['x'])\n if isinstance(y, Quantity) and z is not None:\n y = y.to(model.input_units['y'], equivalencies=input_units_equivalencies['y'])\n\n # We now strip away the units from the parameters, taking care to\n # first convert any parameters to the units that correspond to the\n # input units (to make sure that initial guesses on the parameters)\n # are in the right unit system\n\n model = model.without_units_for_data(x=x, y=y, z=z)\n\n # We strip away the units from the input itself\n\n add_back_units = False\n\n if isinstance(x, Quantity):\n add_back_units = True\n xdata = x.value\n else:\n xdata = np.asarray(x)\n\n if isinstance(y, Quantity):\n add_back_units = True\n ydata = y.value\n else:\n ydata = np.asarray(y)\n\n if z is not None:\n if isinstance(y, Quantity):\n add_back_units = True\n zdata = z.value\n else:\n zdata = np.asarray(z)\n\n # We run the fitting\n if z is None:\n model_new = func(self, model, xdata, ydata, **kwargs)\n else:\n model_new = func(self, model, xdata, ydata, zdata, **kwargs)\n\n # And finally we add back units to the parameters\n if add_back_units:\n model_new = model_new.with_units_from_data(x=x, y=y, z=z)\n\n return model_new\n\n else:\n\n raise NotImplementedError(\"This model does not support being fit to data with units\")\n\n else:\n\n return func(self, model, x, y, z=z, **kwargs)\n\n return wrapper\n\n\[email protected]_metaclass(_FitterMeta)\nclass Fitter(object):\n \"\"\"\n Base class for all fitters.\n\n Parameters\n ----------\n optimizer : callable\n A callable implementing an optimization algorithm\n statistic : callable\n Statistic function\n \"\"\"\n\n def __init__(self, optimizer, statistic):\n if optimizer is None:\n raise ValueError(\"Expected an optimizer.\")\n if statistic is None:\n raise ValueError(\"Expected a statistic function.\")\n if inspect.isclass(optimizer):\n # a callable class\n self._opt_method = optimizer()\n elif inspect.isfunction(optimizer):\n self._opt_method = optimizer\n else:\n raise ValueError(\"Expected optimizer to be a callable class or a function.\")\n if inspect.isclass(statistic):\n self._stat_method = statistic()\n else:\n self._stat_method = statistic\n\n def objective_function(self, fps, *args):\n \"\"\"\n Function to minimize.\n\n Parameters\n ----------\n fps : list\n parameters returned by the fitter\n args : list\n [model, [other_args], [input coordinates]]\n other_args may include weights or any other quantities specific for\n a statistic\n\n Notes\n -----\n The list of arguments (args) is set in the `__call__` method.\n Fitters may overwrite this method, e.g. when statistic functions\n require other arguments.\n\n \"\"\"\n model = args[0]\n meas = args[-1]\n _fitter_to_model_params(model, fps)\n res = self._stat_method(meas, model, *args[1:-1])\n return res\n\n @abc.abstractmethod\n def __call__(self):\n \"\"\"\n This method performs the actual fitting and modifies the parameter list\n of a model.\n\n Fitter subclasses should implement this method.\n \"\"\"\n\n raise NotImplementedError(\"Subclasses should implement this method.\")\n\n\n# TODO: I have ongoing branch elsewhere that's refactoring this module so that\n# all the fitter classes in here are Fitter subclasses. In the meantime we\n# need to specify that _FitterMeta is its metaclass.\[email protected]_metaclass(_FitterMeta)\nclass LinearLSQFitter(object):\n \"\"\"\n A class performing a linear least square fitting.\n\n Uses `numpy.linalg.lstsq` to do the fitting.\n Given a model and data, fits the model to the data and changes the\n model's parameters. Keeps a dictionary of auxiliary fitting information.\n \"\"\"\n\n supported_constraints = ['fixed']\n\n def __init__(self):\n self.fit_info = {'residuals': None,\n 'rank': None,\n 'singular_values': None,\n 'params': None\n }\n\n @staticmethod\n def _deriv_with_constraints(model, param_indices, x=None, y=None):\n if y is None:\n d = np.array(model.fit_deriv(x, *model.parameters))\n else:\n d = np.array(model.fit_deriv(x, y, *model.parameters))\n\n if model.col_fit_deriv:\n return d[param_indices]\n else:\n return d[..., param_indices]\n\n def _map_domain_window(self, model, x, y=None):\n \"\"\"\n Maps domain into window for a polynomial model which has these\n attributes.\n \"\"\"\n\n if y is None:\n if hasattr(model, 'domain') and model.domain is None:\n model.domain = [x.min(), x.max()]\n if hasattr(model, 'window') and model.window is None:\n model.window = [-1, 1]\n return poly_map_domain(x, model.domain, model.window)\n else:\n if hasattr(model, 'x_domain') and model.x_domain is None:\n model.x_domain = [x.min(), x.max()]\n if hasattr(model, 'y_domain') and model.y_domain is None:\n model.y_domain = [y.min(), y.max()]\n if hasattr(model, 'x_window') and model.x_window is None:\n model.x_window = [-1., 1.]\n if hasattr(model, 'y_window') and model.y_window is None:\n model.y_window = [-1., 1.]\n\n xnew = poly_map_domain(x, model.x_domain, model.x_window)\n ynew = poly_map_domain(y, model.y_domain, model.y_window)\n return xnew, ynew\n\n @fitter_unit_support\n def __call__(self, model, x, y, z=None, weights=None, rcond=None):\n \"\"\"\n Fit data to this model.\n\n Parameters\n ----------\n model : `~astropy.modeling.FittableModel`\n model to fit to x, y, z\n x : array\n input coordinates\n y : array\n input coordinates\n z : array (optional)\n input coordinates\n weights : array (optional)\n weights\n rcond : float, optional\n Cut-off ratio for small singular values of ``a``.\n Singular values are set to zero if they are smaller than ``rcond``\n times the largest singular value of ``a``.\n equivalencies : list or None, optional and keyword-only argument\n List of *additional* equivalencies that are should be applied in\n case x, y and/or z have units. Default is None.\n\n Returns\n -------\n model_copy : `~astropy.modeling.FittableModel`\n a copy of the input model with parameters set by the fitter\n \"\"\"\n\n if not model.fittable:\n raise ValueError(\"Model must be a subclass of FittableModel\")\n\n if not model.linear:\n raise ModelLinearityError('Model is not linear in parameters, '\n 'linear fit methods should not be used.')\n\n _validate_constraints(self.supported_constraints, model)\n\n model_copy = model.copy()\n _, fitparam_indices = _model_to_fit_params(model_copy)\n\n if model_copy.n_inputs == 2 and z is None:\n raise ValueError(\"Expected x, y and z for a 2 dimensional model.\")\n\n farg = _convert_input(x, y, z, n_models=len(model_copy),\n model_set_axis=model_copy.model_set_axis)\n\n has_fixed = any(model_copy.fixed.values())\n\n if has_fixed:\n\n # The list of fixed params is the complement of those being fitted:\n fixparam_indices = [idx for idx in\n range(len(model_copy.param_names))\n if idx not in fitparam_indices]\n\n # Construct matrix of user-fixed parameters that can be dotted with\n # the corresponding fit_deriv() terms, to evaluate corrections to\n # the dependent variable in order to fit only the remaining terms:\n fixparams = np.asarray([getattr(model_copy,\n model_copy.param_names[idx]).value\n for idx in fixparam_indices])\n\n if len(farg) == 2:\n x, y = farg\n\n # map domain into window\n if hasattr(model_copy, 'domain'):\n x = self._map_domain_window(model_copy, x)\n if has_fixed:\n lhs = self._deriv_with_constraints(model_copy,\n fitparam_indices,\n x=x)\n fixderivs = self._deriv_with_constraints(model_copy,\n fixparam_indices,\n x=x)\n else:\n lhs = model_copy.fit_deriv(x, *model_copy.parameters)\n sum_of_implicit_terms = model_copy.sum_of_implicit_terms(x)\n rhs = y\n else:\n x, y, z = farg\n\n # map domain into window\n if hasattr(model_copy, 'x_domain'):\n x, y = self._map_domain_window(model_copy, x, y)\n\n if has_fixed:\n lhs = self._deriv_with_constraints(model_copy,\n fitparam_indices, x=x, y=y)\n fixderivs = self._deriv_with_constraints(model_copy,\n fixparam_indices, x=x, y=y)\n else:\n lhs = model_copy.fit_deriv(x, y, *model_copy.parameters)\n sum_of_implicit_terms = model_copy.sum_of_implicit_terms(x, y)\n\n if len(model_copy) > 1:\n if z.ndim > 2:\n # Basically this code here is making the assumption that if\n # z has 3 dimensions it represents multiple models where\n # the value of z is one plane per model. It's then\n # flattening each plane and transposing so that the model\n # axis is *last*. That's fine, but this could be\n # generalized for other dimensionalities of z.\n # TODO: See above comment\n rhs = np.array([i.flatten() for i in z]).T\n else:\n rhs = z.T\n else:\n rhs = z.flatten()\n\n # If the derivative is defined along rows (as with non-linear models)\n if model_copy.col_fit_deriv:\n lhs = np.asarray(lhs).T\n\n # Subtract any terms fixed by the user from (a copy of) the RHS, in\n # order to fit the remaining terms correctly:\n if has_fixed:\n if model_copy.col_fit_deriv:\n fixderivs = np.asarray(fixderivs).T # as for lhs above\n rhs = rhs - fixderivs.dot(fixparams) # evaluate user-fixed terms\n\n # Subtract any terms implicit in the model from the RHS, which, like\n # user-fixed terms, affect the dependent variable but are not fitted:\n if sum_of_implicit_terms is not None:\n # If we have a model set, the extra axis must be added to\n # sum_of_implicit_terms as its innermost dimension, to match the\n # dimensionality of rhs after _convert_input \"rolls\" it as needed\n # by np.linalg.lstsq. The vector then gets broadcast to the right\n # number of sets (columns). This assumes all the models share the\n # same input co-ordinates, as is currently the case.\n if len(model_copy) > 1:\n sum_of_implicit_terms = sum_of_implicit_terms[..., np.newaxis]\n rhs = rhs - sum_of_implicit_terms\n\n if weights is not None:\n weights = np.asarray(weights, dtype=np.float)\n if len(x) != len(weights):\n raise ValueError(\"x and weights should have the same length\")\n if rhs.ndim == 2:\n lhs *= weights[:, np.newaxis]\n # Don't modify in-place in case rhs was the original dependent\n # variable array\n rhs = rhs * weights[:, np.newaxis]\n else:\n lhs *= weights[:, np.newaxis]\n rhs = rhs * weights\n\n if rcond is None:\n rcond = len(x) * np.finfo(x.dtype).eps\n\n scl = (lhs * lhs).sum(0)\n lacoef, resids, rank, sval = np.linalg.lstsq(lhs / scl, rhs, rcond)\n\n self.fit_info['residuals'] = resids\n self.fit_info['rank'] = rank\n self.fit_info['singular_values'] = sval\n\n lacoef = (lacoef.T / scl).T\n self.fit_info['params'] = lacoef\n\n # TODO: Only Polynomial models currently have an _order attribute;\n # maybe change this to read isinstance(model, PolynomialBase)\n if hasattr(model_copy, '_order') and rank != model_copy._order:\n warnings.warn(\"The fit may be poorly conditioned\\n\",\n AstropyUserWarning)\n\n _fitter_to_model_params(model_copy, lacoef.flatten())\n return model_copy\n\n\nclass FittingWithOutlierRemoval(object):\n \"\"\"\n This class combines an outlier removal technique with a fitting procedure.\n Basically, given a number of iterations ``niter``, outliers are removed\n and fitting is performed for each iteration.\n\n Parameters\n ----------\n fitter : An Astropy fitter\n An instance of any Astropy fitter, i.e., LinearLSQFitter,\n LevMarLSQFitter, SLSQPLSQFitter, SimplexLSQFitter, JointFitter.\n outlier_func : function\n A function for outlier removal.\n niter : int (optional)\n Number of iterations.\n outlier_kwargs : dict (optional)\n Keyword arguments for outlier_func.\n \"\"\"\n\n def __init__(self, fitter, outlier_func, niter=3, **outlier_kwargs):\n self.fitter = fitter\n self.outlier_func = outlier_func\n self.niter = niter\n self.outlier_kwargs = outlier_kwargs\n\n def __str__(self):\n return (\"Fitter: {0}\\nOutlier function: {1}\\nNum. of iterations: {2}\" +\n (\"\\nOutlier func. args.: {3}\"))\\\n .format(self.fitter__class__.__name__,\n self.outlier_func.__name__, self.niter,\n self.outlier_kwargs)\n\n def __repr__(self):\n return (\"{0}(fitter: {1}, outlier_func: {2},\" +\n \" niter: {3}, outlier_kwargs: {4})\")\\\n .format(self.__class__.__name__,\n self.fitter.__class__.__name__,\n self.outlier_func.__name__, self.niter,\n self.outlier_kwargs)\n\n def __call__(self, model, x, y, z=None, weights=None, **kwargs):\n \"\"\"\n Parameters\n ----------\n model : `~astropy.modeling.FittableModel`\n An analytic model which will be fit to the provided data.\n This also contains the initial guess for an optimization\n algorithm.\n x : array-like\n Input coordinates.\n y : array-like\n Data measurements (1D case) or input coordinates (2D case).\n z : array-like (optional)\n Data measurements (2D case).\n weights : array-like (optional)\n Weights to be passed to the fitter.\n kwargs : dict (optional)\n Keyword arguments to be passed to the fitter.\n\n Returns\n -------\n filtered_data : numpy.ma.core.MaskedArray\n Data used to perform the fitting after outlier removal.\n fitted_model : `~astropy.modeling.FittableModel`\n Fitted model after outlier removal.\n \"\"\"\n\n fitted_model = self.fitter(model, x, y, z, weights=weights, **kwargs)\n if z is None:\n filtered_data = y\n for n in range(self.niter):\n filtered_data = self.outlier_func(filtered_data - fitted_model(x),\n **self.outlier_kwargs)\n filtered_data += fitted_model(x)\n fitted_model = self.fitter(fitted_model,\n x[~filtered_data.mask],\n filtered_data.data[~filtered_data.mask],\n **kwargs)\n else:\n filtered_data = z\n for n in range(self.niter):\n filtered_data = self.outlier_func(filtered_data - fitted_model(x, y),\n **self.outlier_kwargs)\n filtered_data += fitted_model(x, y)\n fitted_model = self.fitter(fitted_model,\n x[~filtered_data.mask],\n y[~filtered_data.mask],\n filtered_data.data[~filtered_data.mask],\n **kwargs)\n return filtered_data, fitted_model\n\n\[email protected]_metaclass(_FitterMeta)\nclass LevMarLSQFitter(object):\n \"\"\"\n Levenberg-Marquardt algorithm and least squares statistic.\n\n Attributes\n ----------\n fit_info : dict\n The `scipy.optimize.leastsq` result for the most recent fit (see\n notes).\n\n Notes\n -----\n The ``fit_info`` dictionary contains the values returned by\n `scipy.optimize.leastsq` for the most recent fit, including the values from\n the ``infodict`` dictionary it returns. See the `scipy.optimize.leastsq`\n documentation for details on the meaning of these values. Note that the\n ``x`` return value is *not* included (as it is instead the parameter values\n of the returned model).\n\n Additionally, one additional element of ``fit_info`` is computed whenever a\n model is fit, with the key 'param_cov'. The corresponding value is the\n covariance matrix of the parameters as a 2D numpy array. The order of the\n matrix elements matches the order of the parameters in the fitted model\n (i.e., the same order as ``model.param_names``).\n \"\"\"\n\n supported_constraints = ['fixed', 'tied', 'bounds']\n \"\"\"\n The constraint types supported by this fitter type.\n \"\"\"\n\n def __init__(self):\n self.fit_info = {'nfev': None,\n 'fvec': None,\n 'fjac': None,\n 'ipvt': None,\n 'qtf': None,\n 'message': None,\n 'ierr': None,\n 'param_jac': None,\n 'param_cov': None}\n\n super(LevMarLSQFitter, self).__init__()\n\n def objective_function(self, fps, *args):\n \"\"\"\n Function to minimize.\n\n Parameters\n ----------\n fps : list\n parameters returned by the fitter\n args : list\n [model, [weights], [input coordinates]]\n \"\"\"\n\n model = args[0]\n weights = args[1]\n _fitter_to_model_params(model, fps)\n meas = args[-1]\n if weights is None:\n return np.ravel(model(*args[2: -1]) - meas)\n else:\n return np.ravel(weights * (model(*args[2: -1]) - meas))\n\n @fitter_unit_support\n def __call__(self, model, x, y, z=None, weights=None,\n maxiter=DEFAULT_MAXITER, acc=DEFAULT_ACC,\n epsilon=DEFAULT_EPS, estimate_jacobian=False):\n \"\"\"\n Fit data to this model.\n\n Parameters\n ----------\n model : `~astropy.modeling.FittableModel`\n model to fit to x, y, z\n x : array\n input coordinates\n y : array\n input coordinates\n z : array (optional)\n input coordinates\n weights : array (optional)\n weights\n maxiter : int\n maximum number of iterations\n acc : float\n Relative error desired in the approximate solution\n epsilon : float\n A suitable step length for the forward-difference\n approximation of the Jacobian (if model.fjac=None). If\n epsfcn is less than the machine precision, it is\n assumed that the relative errors in the functions are\n of the order of the machine precision.\n estimate_jacobian : bool\n If False (default) and if the model has a fit_deriv method,\n it will be used. Otherwise the Jacobian will be estimated.\n If True, the Jacobian will be estimated in any case.\n equivalencies : list or None, optional and keyword-only argument\n List of *additional* equivalencies that are should be applied in\n case x, y and/or z have units. Default is None.\n\n Returns\n -------\n model_copy : `~astropy.modeling.FittableModel`\n a copy of the input model with parameters set by the fitter\n \"\"\"\n\n from scipy import optimize\n\n model_copy = _validate_model(model, self.supported_constraints)\n farg = (model_copy, weights, ) + _convert_input(x, y, z)\n\n if model_copy.fit_deriv is None or estimate_jacobian:\n dfunc = None\n else:\n dfunc = self._wrap_deriv\n init_values, _ = _model_to_fit_params(model_copy)\n fitparams, cov_x, dinfo, mess, ierr = optimize.leastsq(\n self.objective_function, init_values, args=farg, Dfun=dfunc,\n col_deriv=model_copy.col_fit_deriv, maxfev=maxiter, epsfcn=epsilon,\n xtol=acc, full_output=True)\n _fitter_to_model_params(model_copy, fitparams)\n self.fit_info.update(dinfo)\n self.fit_info['cov_x'] = cov_x\n self.fit_info['message'] = mess\n self.fit_info['ierr'] = ierr\n if ierr not in [1, 2, 3, 4]:\n warnings.warn(\"The fit may be unsuccessful; check \"\n \"fit_info['message'] for more information.\",\n AstropyUserWarning)\n\n # now try to compute the true covariance matrix\n if (len(y) > len(init_values)) and cov_x is not None:\n sum_sqrs = np.sum(self.objective_function(fitparams, *farg)**2)\n dof = len(y) - len(init_values)\n self.fit_info['param_cov'] = cov_x * sum_sqrs / dof\n else:\n self.fit_info['param_cov'] = None\n\n return model_copy\n\n @staticmethod\n def _wrap_deriv(params, model, weights, x, y, z=None):\n \"\"\"\n Wraps the method calculating the Jacobian of the function to account\n for model constraints.\n\n `scipy.optimize.leastsq` expects the function derivative to have the\n above signature (parlist, (argtuple)). In order to accommodate model\n constraints, instead of using p directly, we set the parameter list in\n this function.\n \"\"\"\n\n if weights is None:\n weights = 1.0\n\n if any(model.fixed.values()) or any(model.tied.values()):\n\n if z is None:\n full_deriv = np.ravel(weights) * np.array(model.fit_deriv(x, *model.parameters))\n else:\n full_deriv = (np.ravel(weights) * np.array(model.fit_deriv(x, y, *model.parameters)).T).T\n\n pars = [getattr(model, name) for name in model.param_names]\n fixed = [par.fixed for par in pars]\n tied = [par.tied for par in pars]\n tied = list(np.where([par.tied is not False for par in pars],\n True, tied))\n fix_and_tie = np.logical_or(fixed, tied)\n ind = np.logical_not(fix_and_tie)\n\n if not model.col_fit_deriv:\n full_deriv = np.asarray(full_deriv).T\n residues = np.asarray(full_deriv[np.nonzero(ind)]).T\n else:\n residues = full_deriv[np.nonzero(ind)]\n\n return [np.ravel(_) for _ in residues]\n else:\n if z is None:\n return [np.ravel(_) for _ in np.ravel(weights) * np.array(model.fit_deriv(x, *params))]\n else:\n if not model.col_fit_deriv:\n return [np.ravel(_) for _ in (np.ravel(weights) * np.array(model.fit_deriv(x, y, *params)).T).T]\n else:\n return [np.ravel(_) for _ in (weights * np.array(model.fit_deriv(x, y, *params)))]\n\n\nclass SLSQPLSQFitter(Fitter):\n \"\"\"\n SLSQP optimization algorithm and least squares statistic.\n\n\n Raises\n ------\n ModelLinearityError\n A linear model is passed to a nonlinear fitter\n\n \"\"\"\n\n supported_constraints = SLSQP.supported_constraints\n\n def __init__(self):\n super(SLSQPLSQFitter, self).__init__(optimizer=SLSQP, statistic=leastsquare)\n self.fit_info = {}\n\n @fitter_unit_support\n def __call__(self, model, x, y, z=None, weights=None, **kwargs):\n \"\"\"\n Fit data to this model.\n\n Parameters\n ----------\n model : `~astropy.modeling.FittableModel`\n model to fit to x, y, z\n x : array\n input coordinates\n y : array\n input coordinates\n z : array (optional)\n input coordinates\n weights : array (optional)\n weights\n kwargs : dict\n optional keyword arguments to be passed to the optimizer or the statistic\n\n verblevel : int\n 0-silent\n 1-print summary upon completion,\n 2-print summary after each iteration\n maxiter : int\n maximum number of iterations\n epsilon : float\n the step size for finite-difference derivative estimates\n acc : float\n Requested accuracy\n equivalencies : list or None, optional and keyword-only argument\n List of *additional* equivalencies that are should be applied in\n case x, y and/or z have units. Default is None.\n\n Returns\n -------\n model_copy : `~astropy.modeling.FittableModel`\n a copy of the input model with parameters set by the fitter\n \"\"\"\n\n model_copy = _validate_model(model, self._opt_method.supported_constraints)\n farg = _convert_input(x, y, z)\n farg = (model_copy, weights, ) + farg\n p0, _ = _model_to_fit_params(model_copy)\n fitparams, self.fit_info = self._opt_method(\n self.objective_function, p0, farg, **kwargs)\n _fitter_to_model_params(model_copy, fitparams)\n\n return model_copy\n\n\nclass SimplexLSQFitter(Fitter):\n \"\"\"\n\n Simplex algorithm and least squares statistic.\n\n Raises\n ------\n ModelLinearityError\n A linear model is passed to a nonlinear fitter\n\n \"\"\"\n\n supported_constraints = Simplex.supported_constraints\n\n def __init__(self):\n super(SimplexLSQFitter, self).__init__(optimizer=Simplex,\n statistic=leastsquare)\n self.fit_info = {}\n\n @fitter_unit_support\n def __call__(self, model, x, y, z=None, weights=None, **kwargs):\n \"\"\"\n Fit data to this model.\n\n Parameters\n ----------\n model : `~astropy.modeling.FittableModel`\n model to fit to x, y, z\n x : array\n input coordinates\n y : array\n input coordinates\n z : array (optional)\n input coordinates\n weights : array (optional)\n weights\n kwargs : dict\n optional keyword arguments to be passed to the optimizer or the statistic\n\n maxiter : int\n maximum number of iterations\n acc : float\n Relative error in approximate solution\n equivalencies : list or None, optional and keyword-only argument\n List of *additional* equivalencies that are should be applied in\n case x, y and/or z have units. Default is None.\n\n Returns\n -------\n model_copy : `~astropy.modeling.FittableModel`\n a copy of the input model with parameters set by the fitter\n \"\"\"\n\n model_copy = _validate_model(model,\n self._opt_method.supported_constraints)\n farg = _convert_input(x, y, z)\n farg = (model_copy, weights, ) + farg\n\n p0, _ = _model_to_fit_params(model_copy)\n\n fitparams, self.fit_info = self._opt_method(\n self.objective_function, p0, farg, **kwargs)\n _fitter_to_model_params(model_copy, fitparams)\n return model_copy\n\n\[email protected]_metaclass(_FitterMeta)\nclass JointFitter(object):\n \"\"\"\n Fit models which share a parameter.\n\n For example, fit two gaussians to two data sets but keep\n the FWHM the same.\n\n Parameters\n ----------\n models : list\n a list of model instances\n jointparameters : list\n a list of joint parameters\n initvals : list\n a list of initial values\n \"\"\"\n\n def __init__(self, models, jointparameters, initvals):\n self.models = list(models)\n self.initvals = list(initvals)\n self.jointparams = jointparameters\n self._verify_input()\n self.fitparams = self._model_to_fit_params()\n\n # a list of model.n_inputs\n self.modeldims = [m.n_inputs for m in self.models]\n # sum all model dimensions\n self.ndim = np.sum(self.modeldims)\n\n def _model_to_fit_params(self):\n fparams = []\n fparams.extend(self.initvals)\n for model in self.models:\n params = [p.flatten() for p in model.parameters]\n joint_params = self.jointparams[model]\n param_metrics = model._param_metrics\n for param_name in joint_params:\n slice_ = param_metrics[param_name]['slice']\n del params[slice_]\n fparams.extend(params)\n return fparams\n\n def objective_function(self, fps, *args):\n \"\"\"\n Function to minimize.\n\n Parameters\n ----------\n fps : list\n the fitted parameters - result of an one iteration of the\n fitting algorithm\n args : dict\n tuple of measured and input coordinates\n args is always passed as a tuple from optimize.leastsq\n \"\"\"\n\n lstsqargs = list(args)\n fitted = []\n fitparams = list(fps)\n numjp = len(self.initvals)\n # make a separate list of the joint fitted parameters\n jointfitparams = fitparams[:numjp]\n del fitparams[:numjp]\n\n for model in self.models:\n joint_params = self.jointparams[model]\n margs = lstsqargs[:model.n_inputs + 1]\n del lstsqargs[:model.n_inputs + 1]\n # separate each model separately fitted parameters\n numfp = len(model._parameters) - len(joint_params)\n mfparams = fitparams[:numfp]\n\n del fitparams[:numfp]\n # recreate the model parameters\n mparams = []\n param_metrics = model._param_metrics\n for param_name in model.param_names:\n if param_name in joint_params:\n index = joint_params.index(param_name)\n # should do this with slices in case the\n # parameter is not a number\n mparams.extend([jointfitparams[index]])\n else:\n slice_ = param_metrics[param_name]['slice']\n plen = slice_.stop - slice_.start\n mparams.extend(mfparams[:plen])\n del mfparams[:plen]\n modelfit = model.evaluate(margs[:-1], *mparams)\n fitted.extend(modelfit - margs[-1])\n return np.ravel(fitted)\n\n def _verify_input(self):\n if len(self.models) <= 1:\n raise TypeError(\"Expected >1 models, {} is given\".format(\n len(self.models)))\n if len(self.jointparams.keys()) < 2:\n raise TypeError(\"At least two parameters are expected, \"\n \"{} is given\".format(len(self.jointparams.keys())))\n for j in self.jointparams.keys():\n if len(self.jointparams[j]) != len(self.initvals):\n raise TypeError(\"{} parameter(s) provided but {} expected\".format(\n len(self.jointparams[j]), len(self.initvals)))\n\n def __call__(self, *args):\n \"\"\"\n Fit data to these models keeping some of the parameters common to the\n two models.\n \"\"\"\n\n from scipy import optimize\n\n if len(args) != reduce(lambda x, y: x + 1 + y + 1, self.modeldims):\n raise ValueError(\"Expected {} coordinates in args but {} provided\"\n .format(reduce(lambda x, y: x + 1 + y + 1,\n self.modeldims), len(args)))\n\n self.fitparams[:], _ = optimize.leastsq(self.objective_function,\n self.fitparams, args=args)\n\n fparams = self.fitparams[:]\n numjp = len(self.initvals)\n # make a separate list of the joint fitted parameters\n jointfitparams = fparams[:numjp]\n del fparams[:numjp]\n\n for model in self.models:\n # extract each model's fitted parameters\n joint_params = self.jointparams[model]\n numfp = len(model._parameters) - len(joint_params)\n mfparams = fparams[:numfp]\n\n del fparams[:numfp]\n # recreate the model parameters\n mparams = []\n param_metrics = model._param_metrics\n for param_name in model.param_names:\n if param_name in joint_params:\n index = joint_params.index(param_name)\n # should do this with slices in case the parameter\n # is not a number\n mparams.extend([jointfitparams[index]])\n else:\n slice_ = param_metrics[param_name]['slice']\n plen = slice_.stop - slice_.start\n mparams.extend(mfparams[:plen])\n del mfparams[:plen]\n model.parameters = np.array(mparams)\n\n\ndef _convert_input(x, y, z=None, n_models=1, model_set_axis=0):\n \"\"\"Convert inputs to float arrays.\"\"\"\n\n x = np.asarray(x, dtype=np.float)\n y = np.asarray(y, dtype=np.float)\n\n if z is not None:\n z = np.asarray(z, dtype=np.float)\n\n # For compatibility with how the linear fitter code currently expects to\n # work, shift the dependent variable's axes to the expected locations\n if n_models > 1:\n if z is None:\n if y.shape[model_set_axis] != n_models:\n raise ValueError(\n \"Number of data sets (y array is expected to equal \"\n \"the number of parameter sets)\")\n # For a 1-D model the y coordinate's model-set-axis is expected to\n # be last, so that its first dimension is the same length as the x\n # coordinates. This is in line with the expectations of\n # numpy.linalg.lstsq:\n # http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html\n # That is, each model should be represented by a column. TODO:\n # Obviously this is a detail of np.linalg.lstsq and should be\n # handled specifically by any fitters that use it...\n y = np.rollaxis(y, model_set_axis, y.ndim)\n else:\n # Shape of z excluding model_set_axis\n z_shape = z.shape[:model_set_axis] + z.shape[model_set_axis + 1:]\n\n if not (x.shape == y.shape == z_shape):\n raise ValueError(\"x, y and z should have the same shape\")\n\n if z is None:\n farg = (x, y)\n else:\n farg = (x, y, z)\n return farg\n\n\n# TODO: These utility functions are really particular to handling\n# bounds/tied/fixed constraints for scipy.optimize optimizers that do not\n# support them inherently; this needs to be reworked to be clear about this\n# distinction (and the fact that these are not necessarily applicable to any\n# arbitrary fitter--as evidenced for example by the fact that JointFitter has\n# its own versions of these)\n# TODO: Most of this code should be entirely rewritten; it should not be as\n# inefficient as it is.\ndef _fitter_to_model_params(model, fps):\n \"\"\"\n Constructs the full list of model parameters from the fitted and\n constrained parameters.\n \"\"\"\n\n _, fit_param_indices = _model_to_fit_params(model)\n\n has_tied = any(model.tied.values())\n has_fixed = any(model.fixed.values())\n has_bound = any(b != (None, None) for b in model.bounds.values())\n\n if not (has_tied or has_fixed or has_bound):\n # We can just assign directly\n model.parameters = fps\n return\n\n fit_param_indices = set(fit_param_indices)\n offset = 0\n param_metrics = model._param_metrics\n for idx, name in enumerate(model.param_names):\n if idx not in fit_param_indices:\n continue\n\n slice_ = param_metrics[name]['slice']\n shape = param_metrics[name]['shape']\n # This is determining which range of fps (the fitted parameters) maps\n # to parameters of the model\n size = reduce(operator.mul, shape, 1)\n\n values = fps[offset:offset + size]\n\n # Check bounds constraints\n if model.bounds[name] != (None, None):\n _min, _max = model.bounds[name]\n if _min is not None:\n values = np.fmax(values, _min)\n if _max is not None:\n values = np.fmin(values, _max)\n\n model.parameters[slice_] = values\n offset += size\n\n # This has to be done in a separate loop due to how tied parameters are\n # currently evaluated (the fitted parameters need to actually be *set* on\n # the model first, for use in evaluating the \"tied\" expression--it might be\n # better to change this at some point\n if has_tied:\n for idx, name in enumerate(model.param_names):\n if model.tied[name]:\n value = model.tied[name](model)\n slice_ = param_metrics[name]['slice']\n model.parameters[slice_] = value\n\n\ndef _model_to_fit_params(model):\n \"\"\"\n Convert a model instance's parameter array to an array that can be used\n with a fitter that doesn't natively support fixed or tied parameters.\n In particular, it removes fixed/tied parameters from the parameter\n array.\n\n These may be a subset of the model parameters, if some of them are held\n constant or tied.\n \"\"\"\n\n fitparam_indices = list(range(len(model.param_names)))\n if any(model.fixed.values()) or any(model.tied.values()):\n params = list(model.parameters)\n param_metrics = model._param_metrics\n for idx, name in list(enumerate(model.param_names))[::-1]:\n if model.fixed[name] or model.tied[name]:\n slice_ = param_metrics[name]['slice']\n del params[slice_]\n del fitparam_indices[idx]\n return (np.array(params), fitparam_indices)\n else:\n return (model.parameters, fitparam_indices)\n\n\ndef _validate_constraints(supported_constraints, model):\n \"\"\"Make sure model constraints are supported by the current fitter.\"\"\"\n\n message = 'Optimizer cannot handle {0} constraints.'\n\n if (any(six.itervalues(model.fixed)) and\n 'fixed' not in supported_constraints):\n raise UnsupportedConstraintError(\n message.format('fixed parameter'))\n\n if any(six.itervalues(model.tied)) and 'tied' not in supported_constraints:\n raise UnsupportedConstraintError(\n message.format('tied parameter'))\n\n if (any(tuple(b) != (None, None) for b in six.itervalues(model.bounds)) and\n 'bounds' not in supported_constraints):\n raise UnsupportedConstraintError(\n message.format('bound parameter'))\n\n if model.eqcons and 'eqcons' not in supported_constraints:\n raise UnsupportedConstraintError(message.format('equality'))\n\n if model.ineqcons and 'ineqcons' not in supported_constraints:\n raise UnsupportedConstraintError(message.format('inequality'))\n\n\ndef _validate_model(model, supported_constraints):\n \"\"\"\n Check that model and fitter are compatible and return a copy of the model.\n \"\"\"\n\n if not model.fittable:\n raise ValueError(\"Model does not appear to be fittable.\")\n if model.linear:\n warnings.warn('Model is linear in parameters; '\n 'consider using linear fitting methods.',\n AstropyUserWarning)\n elif len(model) != 1:\n # for now only single data sets ca be fitted\n raise ValueError(\"Non-linear fitters can only fit \"\n \"one data set at a time.\")\n _validate_constraints(supported_constraints, model)\n\n model_copy = model.copy()\n return model_copy\n\n\ndef populate_entry_points(entry_points):\n \"\"\"\n This injects entry points into the `astropy.modeling.fitting` namespace.\n This provides a means of inserting a fitting routine without requirement\n of it being merged into astropy's core.\n\n Parameters\n ----------\n\n entry_points : a list of `~pkg_resources.EntryPoint`\n entry_points are objects which encapsulate\n importable objects and are defined on the\n installation of a package.\n Notes\n -----\n An explanation of entry points can be found `here <http://setuptools.readthedocs.io/en/latest/setuptools.html#dynamic-discovery-of-services-and-plugins>`\n\n \"\"\"\n\n for entry_point in entry_points:\n name = entry_point.name\n try:\n entry_point = entry_point.load()\n except Exception as e:\n # This stops the fitting from choking if an entry_point produces an error.\n warnings.warn(AstropyUserWarning('{type} error occurred in entry '\n 'point {name}.' .format(type=type(e).__name__, name=name)))\n else:\n if not inspect.isclass(entry_point):\n warnings.warn(AstropyUserWarning(\n 'Modeling entry point {0} expected to be a '\n 'Class.' .format(name)))\n else:\n if issubclass(entry_point, Fitter):\n name = entry_point.__name__\n globals()[name] = entry_point\n __all__.append(name)\n else:\n warnings.warn(AstropyUserWarning(\n 'Modeling entry point {0} expected to extend '\n 'astropy.modeling.Fitter' .format(name)))\n\n\n# this is so fitting doesn't choke if pkg_resources doesn't exist\nif HAS_PKG:\n populate_entry_points(iter_entry_points(group='astropy.modeling', name=None))\n", "from collections import namedtuple\nimport torch\nfrom torch.autograd import Variable\n\n\nPackedSequence_ = namedtuple('PackedSequence', ['data', 'batch_sizes'])\n\n\nclass PackedSequence(PackedSequence_):\n \"\"\"Holds the data and list of batch_sizes of a packed sequence.\n\n All RNN modules accept packed sequences as inputs.\n\n Note:\n Instances of this class should never be created manually. They are meant\n to be instantiated by functions like :func:`pack_padded_sequence`.\n\n Attributes:\n data (Variable): Variable containing packed sequence\n batch_sizes (list[int]): list of integers holding information about\n the batch size at each sequence step\n \"\"\"\n pass\n\n\ndef pack_padded_sequence(input, lengths, batch_first=False):\n \"\"\"Packs a Variable containing padded sequences of variable length.\n\n Input can be of size ``TxBx*`` where T is the length of the longest sequence\n (equal to ``lengths[0]``), B is the batch size, and * is any number of\n dimensions (including 0). If ``batch_first`` is True ``BxTx*`` inputs are\n expected.\n\n The sequences should be sorted by length in a decreasing order, i.e.\n ``input[:,0]`` should be the longest sequence, and ``input[:,B-1]`` the\n shortest one.\n\n Note:\n This function accept any input that has at least two dimensions. You\n can apply it to pack the labels, and use the output of the RNN with\n them to compute the loss directly. A Variable can be retrieved from\n a :class:`PackedSequence` object by accessing its ``.data`` attribute.\n\n Arguments:\n input (Variable): padded batch of variable length sequences.\n lengths (list[int]): list of sequences lengths of each batch element.\n batch_first (bool, optional): if True, the input is expected in BxTx*\n format.\n\n Returns:\n a :class:`PackedSequence` object\n \"\"\"\n if lengths[-1] <= 0:\n raise ValueError(\"length of all samples has to be greater than 0, \"\n \"but found an element in 'lengths' that is <=0\")\n if batch_first:\n input = input.transpose(0, 1)\n\n steps = []\n batch_sizes = []\n lengths_iter = reversed(lengths)\n current_length = next(lengths_iter)\n batch_size = input.size(1)\n if len(lengths) != batch_size:\n raise ValueError(\"lengths array has incorrect size\")\n\n for step, step_value in enumerate(input, 1):\n steps.append(step_value[:batch_size])\n batch_sizes.append(batch_size)\n\n while step == current_length:\n try:\n new_length = next(lengths_iter)\n except StopIteration:\n current_length = None\n break\n\n if current_length > new_length: # remember that new_length is the preceding length in the array\n raise ValueError(\"lengths array has to be sorted in decreasing order\")\n batch_size -= 1\n current_length = new_length\n if current_length is None:\n break\n return PackedSequence(torch.cat(steps), batch_sizes)\n\n\ndef pad_packed_sequence(sequence, batch_first=False):\n \"\"\"Pads a packed batch of variable length sequences.\n\n It is an inverse operation to :func:`pack_padded_sequence`.\n\n The returned Variable's data will be of size TxBx*, where T is the length\n of the longest sequence and B is the batch size. If ``batch_first`` is True,\n the data will be transposed into BxTx* format.\n\n Batch elements will be ordered decreasingly by their length.\n\n Arguments:\n sequence (PackedSequence): batch to pad\n batch_first (bool, optional): if True, the output will be in BxTx*\n format.\n\n Returns:\n Tuple of Variable containing the padded sequence, and a list of lengths\n of each sequence in the batch.\n \"\"\"\n var_data, batch_sizes = sequence\n max_batch_size = batch_sizes[0]\n output = var_data.data.new(len(batch_sizes), max_batch_size, *var_data.size()[1:]).zero_()\n output = Variable(output)\n\n lengths = []\n data_offset = 0\n prev_batch_size = batch_sizes[0]\n for i, batch_size in enumerate(batch_sizes):\n output[i, :batch_size] = var_data[data_offset:data_offset + batch_size]\n data_offset += batch_size\n\n dec = prev_batch_size - batch_size\n if dec > 0:\n lengths.extend((i,) * dec)\n prev_batch_size = batch_size\n lengths.extend((i + 1,) * batch_size)\n lengths.reverse()\n\n if batch_first:\n output = output.transpose(0, 1)\n return output, lengths\n" ]
[ [ "torch.load" ], [ "numpy.log", "numpy.resize", "numpy.maximum", "numpy.sqrt", "numpy.log2", "numpy.unique", "numpy.ones", "numpy.subtract.outer", "numpy.max", "numpy.bincount", "numpy.exp", "numpy.outer", "numpy.array", "numpy.logical_and", "numpy.sum", "numpy.equal.outer" ], [ "numpy.isscalar" ], [ "numpy.amax", "numpy.sqrt", "numpy.cumsum", "numpy.fmin.reduce", "numpy.dtype", "numpy.all", "numpy.fmax.reduce", "numpy.argmin", "numpy.any", "numpy.mean", "numpy.nanmean", "numpy.copyto", "numpy.var", "numpy.moveaxis", "numpy.divide", "numpy.subtract", "numpy.full", "numpy.argmax", "numpy.asanyarray", "numpy.apply_along_axis", "numpy.lib.function_base._ureduce", "numpy.nonzero", "numpy.multiply", "numpy.isnan", "numpy.amin", "numpy.median", "numpy.ma.median", "numpy.cumprod", "numpy.errstate", "numpy.array", "numpy.sum", "numpy.percentile", "numpy.prod" ], [ "numpy.ndarray" ], [ "torch.Tensor", "torch.zeros", "torch.cat", "torch.qr", "torch.diag" ], [ "numpy.asarray", "numpy.array", "numpy.zeros_like", "numpy.iscomplexobj" ], [ "numpy.testing.assert_equal", "numpy.random.random", "numpy.sqrt", "numpy.testing.utils.assert_allclose", "numpy.ones", "numpy.random.normal", "numpy.random.randn", "numpy.array", "numpy.random.RandomState" ], [ "numpy.asarray" ], [ "numpy.sqrt", "numpy.arange", "numpy.max", "numpy.size", "numpy.ceil", "numpy.isscalar", "numpy.floor", "numpy.array" ], [ "torch.is_tensor" ], [ "numpy.all", "numpy.isscalar" ], [ "numpy.log1p" ], [ "numpy.isscalar" ], [ "numpy.array_equal", "numpy.zeros", "numpy.empty" ], [ "numpy.zeros", "numpy.zeros_like", "numpy.diff" ], [ "torch.abs", "torch.LongTensor", "torch.max", "torch.typename", "torch.sum", "torch.cuda.FloatTensor", "torch.mul", "torch.gather", "torch.pow" ], [ "numpy.rollaxis", "numpy.logical_not", "numpy.nonzero", "numpy.asarray", "numpy.finfo", "numpy.logical_or", "numpy.linalg.lstsq", "scipy.optimize.leastsq", "numpy.fmax", "numpy.ravel", "numpy.array", "numpy.where", "numpy.sum", "numpy.fmin" ], [ "torch.cat", "torch.autograd.Variable" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
iksteen/pyxclib
[ "2948162dd780f8230a785abfd2ee57e8ab5cc156" ]
[ "xclib/classifier/_svm.py" ]
[ "from sklearn.svm import LinearSVC\nimport numpy as np\n\n\ndef apply_threshold(data, threshold):\n data[np.where(np.abs(data) < threshold)] = 0\n\ndef train_one(data, loss, C, verbose, max_iter, threshold, dual, tol):\n def _get_features(obj):\n # Index samples iff they are required\n # Helful in reducing memory footprint\n if obj['ind'] is None:\n return obj['data']\n else:\n return obj['data'].take(obj['ind'], axis=0)\n X, y = _get_features(data), data['Y']\n clf = LinearSVC(tol=tol,\n loss=loss,\n dual=dual,\n C=C,\n multi_class='ovr',\n fit_intercept=True,\n intercept_scaling=1,\n class_weight=None,\n verbose=verbose,\n random_state=0,\n max_iter=max_iter)\n try:\n clf.fit(X, y)\n weight, bias = clf.coef_, clf.intercept_\n except ValueError:\n # TODO Find a solution for this; choose randomly may be?\n weight, bias = np.zeros((1, X.shape[1]), dtype=np.float32), np.zeros(\n (1), dtype=np.float32)\n del clf\n apply_threshold(weight, threshold)\n return weight, bias\n " ]
[ [ "numpy.zeros", "numpy.abs", "sklearn.svm.LinearSVC" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
isi-vista/adam
[ "91f392f2529a98cd50c095a18769ae4b55ce4292" ]
[ "adam/learner/semantics_utils.py" ]
[ "from typing import Optional, Any, Dict\n\nimport numpy as np\nimport pandas as pd\nfrom more_itertools import first\nfrom networkx import Graph, to_numpy_matrix\nimport matplotlib.pyplot as plt\nimport seaborn as sb\n\nfrom adam.semantics import Concept, KindConcept, ObjectConcept, ActionConcept\n\n\nclass SemanticsManager:\n def __init__(self, semantics_graph: Graph) -> None:\n self.semantics_graph: Graph = Graph()\n # Create a new type of edge for each edge in the original semantics graph\n # If any of the nodes is an action concept, we want to make a distinct new node to track syntax\n for u, v, data in semantics_graph.edges(data=True):\n syntactic_position = data[\"slot\"]\n new_u = (\n self.concept_as_str_node(u, syntactic_position)\n if isinstance(u, ActionConcept)\n else self.concept_as_str_node(u)\n )\n new_v = (\n self.concept_as_str_node(v, syntactic_position)\n if isinstance(v, ActionConcept)\n else self.concept_as_str_node(v)\n )\n self.semantics_graph.add_edge(new_u, new_v, weight=data[\"weight\"])\n\n self.nodes = list(self.semantics_graph.nodes)\n self.semantics_matrix = to_numpy_matrix(self.semantics_graph)\n\n def object_concept_embedding(self, concept: str) -> Any:\n # Get a numpy array weighted adjacency embedding of the concept from the graph\n return self.semantics_matrix[self.nodes.index(concept)]\n\n def kind_concept_embedding(self, concept: str) -> Any:\n # Get a numpy array weighted adjacency embedding averaging the members of a kind concept in the graph\n member_embeddings = np.vstack(\n [\n self.object_concept_embedding(member)\n for member in self.semantics_graph.neighbors(concept)\n ]\n )\n return np.mean(member_embeddings, axis=0)\n\n def evaluate_kind_membership(self, word: str, kind: str) -> float:\n word_node = self.concept_as_str_node(ObjectConcept(word))\n kind_node = self.concept_as_str_node(KindConcept(kind))\n if kind_node not in self.nodes or word_node not in self.nodes:\n return 0\n return cos_sim(\n self.object_concept_embedding(word_node),\n self.kind_concept_embedding(kind_node),\n )\n\n @staticmethod\n def concept_as_str_node(concept: Concept, syntactic_position=\"\") -> str:\n if syntactic_position:\n return f\"{concept.debug_string}_{str(type(concept))}_{syntactic_position}\"\n else:\n return f\"{concept.debug_string}_{str(type(concept))}\"\n\n\ndef get_concept_node_from_graph(\n identifier: str, semantics_graph: Graph\n) -> Optional[Concept]:\n return first([n for n in semantics_graph.nodes if n.debug_string == identifier], None)\n\n\ndef cos_sim(a, b) -> float:\n dot = np.dot(a.reshape(1, -1), b.reshape(-1, 1))\n norma = np.linalg.norm(a.reshape(1, -1))\n normb = np.linalg.norm(b.reshape(1, -1))\n return dot / (norma * normb)\n\n\ndef generate_heatmap(nodes_to_embeddings: Dict[Concept, Any], filename: str):\n if not nodes_to_embeddings:\n return\n similarity_matrix = np.zeros((len(nodes_to_embeddings), len(nodes_to_embeddings)))\n for i, (_, embedding_1) in enumerate(nodes_to_embeddings.items()):\n for j, (_, embedding_2) in enumerate(nodes_to_embeddings.items()):\n similarity_matrix[i][j] = cos_sim(embedding_1, embedding_2)\n names = [n.debug_string for n in nodes_to_embeddings.keys()]\n df = pd.DataFrame(data=similarity_matrix, index=names, columns=names)\n plt.rcParams[\"figure.figsize\"] = (20.0, 20.0)\n plt.rcParams[\"font.family\"] = \"serif\"\n sb.clustermap(df, row_cluster=True, col_cluster=True)\n plt.savefig(f\"plots/{filename}.png\")\n plt.close()\n" ]
[ [ "matplotlib.pyplot.close", "numpy.mean", "matplotlib.pyplot.savefig", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
alexlee-gk/Theano
[ "e4e08782d3a10d010d3a99bc87fd0fc3b0465405", "e4e08782d3a10d010d3a99bc87fd0fc3b0465405" ]
[ "theano/gpuarray/tests/test_dnn.py", "theano/configdefaults.py" ]
[ "from __future__ import absolute_import, print_function, division\nimport logging\n\nfrom nose.plugins.skip import SkipTest\nfrom nose_parameterized import parameterized\nimport numpy\nfrom itertools import product, chain\n\nimport theano\nfrom six import StringIO\nimport theano.tensor as T\nimport theano.tests.unittest_tools as utt\nfrom theano.sandbox.neighbours import images2neibs\nfrom theano.tensor.signal.pool import pool_2d\nfrom theano.tensor.signal.pool import MaxPoolGrad, AveragePoolGrad\n\nfrom .. import dnn\nfrom ..basic_ops import GpuAllocEmpty\n\nfrom .config import mode_with_gpu, mode_without_gpu, test_ctx_name\nfrom . import test_nnet\n\nfrom theano.configdefaults import SUPPORTED_DNN_CONV_ALGO_FWD\n\n\ndef test_dnn_conv_desc_merge():\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n kern_shp = T.as_tensor_variable(\n numpy.asarray([3, 1, 2, 2]).astype('int64'))\n desc1 = dnn.GpuDnnConvDesc(border_mode='valid', subsample=(2, 2),\n conv_mode='conv')(kern_shp)\n desc2 = dnn.GpuDnnConvDesc(border_mode='full', subsample=(1, 1),\n conv_mode='cross')(kern_shp)\n # CDataType is not DeepCopyable so this will crash if we don't use\n # borrow=True\n f = theano.function([], [theano.Out(desc1, borrow=True),\n theano.Out(desc2, borrow=True)])\n\n d1, d2 = f()\n\n # This will be the case if they are merged, which would be bad.\n assert d1 != d2\n\n\ndef test_dnn_conv_merge():\n # This test that we merge correctly multiple dnn_conv.\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n img_shp = [2, 5, 6, 8]\n kern_shp = [3, 5, 5, 6]\n img = T.ftensor4('img')\n kern = T.ftensor4('kern')\n out = T.ftensor4('out')\n desc = dnn.GpuDnnConvDesc(\n border_mode='valid')(kern.shape)\n\n # Test forward op\n o1 = dnn.dnn_conv(img, kern)\n o2 = dnn.dnn_conv(img, kern)\n f = theano.function([img, kern], [o1, o2], mode=mode_with_gpu)\n d1, d2 = f(numpy.random.rand(*img_shp).astype('float32'),\n numpy.random.rand(*kern_shp).astype('float32'))\n topo = f.maker.fgraph.toposort()\n assert len([n for n in topo if isinstance(n.op, dnn.GpuDnnConv)]) == 1\n\n # Test grad w op\n o1 = dnn.GpuDnnConvGradW()(img, kern, out, desc)\n o2 = dnn.GpuDnnConvGradW()(img, kern, out, desc)\n f = theano.function([img, kern, out], [o1, o2], mode=mode_with_gpu)\n topo = f.maker.fgraph.toposort()\n assert len([n for n in topo if isinstance(n.op, dnn.GpuDnnConvGradW)]) == 1\n\n # Test grad i op\n o1 = dnn.GpuDnnConvGradI()(img, kern, out, desc)\n o2 = dnn.GpuDnnConvGradI()(img, kern, out, desc)\n f = theano.function([img, kern, out], [o1, o2], mode=mode_with_gpu)\n topo = f.maker.fgraph.toposort()\n assert len([n for n in topo if isinstance(n.op, dnn.GpuDnnConvGradI)]) == 1\n\n\ndef test_dnn_conv_inplace():\n \"\"\"This test that we have inplace work correctly even when\n GpuAllocEmpty get merged together.\n\n \"\"\"\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n img_shp = [2, 5, 6, 8]\n kern_shp = [3, 5, 5, 6]\n img = T.ftensor4('img')\n kern = T.ftensor4('kern')\n out = T.ftensor4('out')\n desc1 = dnn.GpuDnnConvDesc(border_mode='valid', conv_mode='conv')(\n kern.shape)\n desc2 = dnn.GpuDnnConvDesc(\n border_mode='valid', conv_mode='cross')(kern.shape)\n\n # Test forward op\n o1 = dnn.dnn_conv(img, kern, conv_mode='conv')\n o2 = dnn.dnn_conv(img, kern, conv_mode='cross')\n f = theano.function([img, kern], [o1, o2], mode=mode_with_gpu)\n d1, d2 = f(numpy.random.rand(*img_shp).astype('float32'),\n numpy.random.rand(*kern_shp).astype('float32'))\n topo = f.maker.fgraph.toposort()\n convs = [n for n in topo if isinstance(n.op, dnn.GpuDnnConv)]\n assert len(convs) == 2\n assert all([node.op.inplace for node in convs])\n assert len([n for n in topo if isinstance(n.op, GpuAllocEmpty)]) == 2\n\n # Test grad w op\n out = GpuAllocEmpty(kern.dtype, test_ctx_name)(*kern.shape)\n o1 = dnn.GpuDnnConvGradW()(img, kern, out, desc1)\n o2 = dnn.GpuDnnConvGradW()(img, kern, out, desc2)\n f = theano.function([img, kern], [o1, o2], mode=mode_with_gpu)\n topo = f.maker.fgraph.toposort()\n convs = [n for n in topo if isinstance(n.op, dnn.GpuDnnConvGradW)]\n assert len(convs) == 2\n assert all([node.op.inplace for node in convs])\n assert len([n for n in topo if isinstance(n.op, GpuAllocEmpty)]) == 2\n\n # Test grad i op\n out = GpuAllocEmpty(img.dtype, test_ctx_name)(*img.shape)\n o1 = dnn.GpuDnnConvGradI()(img, kern, out, desc1)\n o2 = dnn.GpuDnnConvGradI()(img, kern, out, desc2)\n f = theano.function([img, kern], [o1, o2], mode=mode_with_gpu)\n topo = f.maker.fgraph.toposort()\n convs = [n for n in topo if isinstance(n.op, dnn.GpuDnnConvGradI)]\n assert len(convs) == 2\n assert all([node.op.inplace for node in convs])\n assert len([n for n in topo if isinstance(n.op, GpuAllocEmpty)]) == 2\n\n\ndef pool_2d_i2n(input, ds=(2, 2), strides=None,\n pad=(0, 0),\n pool_function=T.max, mode='ignore_borders'):\n if strides is None:\n strides = ds\n\n if strides[0] > ds[0] or strides[1] > ds[1]:\n raise RuntimeError(\n \"strides should be smaller than or equal to ds,\"\n \" strides=(%d, %d) and ds=(%d, %d)\" %\n (strides + ds))\n shape = input.shape\n if pad != (0, 0):\n assert pool_function is T.max\n pad_x = pad[0]\n pad_y = pad[1]\n a = T.alloc(-numpy.inf, shape[0], shape[1], shape[2] + pad_x * 2,\n shape[3] + pad_y * 2)\n input = T.set_subtensor(a[:, :,\n pad_x:pad_x + shape[2],\n pad_y:pad_y + shape[3]],\n input)\n shape = input.shape\n\n neibs = images2neibs(input, ds, strides, mode=mode)\n pooled_neibs = pool_function(neibs, axis=1)\n\n output_width = (shape[2] - ds[0]) // strides[0] + 1\n output_height = (shape[3] - ds[1]) // strides[1] + 1\n\n pooled_output = pooled_neibs.reshape((shape[0], shape[1],\n output_width, output_height))\n return pooled_output\n\n\ndef test_pooling():\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n\n # 'average_exc_pad' is disabled for versions < 4004\n if dnn.version(raises=False) < 4004:\n modes = ('max', 'average_inc_pad')\n else:\n modes = ('max', 'average_inc_pad', 'average_exc_pad')\n\n x = T.ftensor4()\n for mode, pad in product(modes,\n ((0, 0), (1, 0), (1, 0), (2, 3), (3, 2))):\n if mode == 'max':\n func = T.max\n else:\n func = T.mean\n\n if pad != (0, 0) and func is T.mean:\n continue\n\n for ws in (4, 2, 5):\n for stride in (2, 3):\n if stride > ws:\n continue\n if pad[0] > stride or pad[1] > stride:\n # Not implemented\n continue\n # We will check that the opt introduced it.\n out1 = pool_2d(x, (ws, ws),\n st=(stride, stride),\n ignore_border=True,\n padding=pad, mode=mode)\n out2 = pool_2d_i2n(x, ds=(ws, ws), strides=(stride, stride),\n pad=pad,\n pool_function=func)\n mode_without_gpu2 = mode_without_gpu.including()\n mode_without_gpu2.check_isfinite = False\n f1 = theano.function([x], out1, mode=mode_with_gpu)\n assert any([isinstance(node.op, dnn.GpuDnnPool)\n for node in f1.maker.fgraph.apply_nodes])\n f2 = theano.function([x], out2, mode=mode_without_gpu2)\n assert not any([isinstance(node.op, dnn.GpuDnnPool)\n for node in f2.maker.fgraph.apply_nodes])\n for shp in [(1, 10, 100, 100),\n (1, 3, 99, 99),\n (32, 1, 147, 197),\n ]:\n data = numpy.random.normal(0, 1, shp).astype(\"float32\")\n a = f1(data)\n b = f2(data)\n\n utt.assert_allclose(a, b)\n\n # Test the grad\n for shp in [(1, 1, 2, 2),\n (1, 1, 3, 3)]:\n data = numpy.random.normal(0, 1, shp).astype(\"float32\") * 10\n\n ws = 2\n stride = 2\n if pad[0] > stride or pad[1] > stride:\n # Not implemented\n continue\n\n # This test the CPU grad + opt + GPU implemtentation\n def fn(x):\n return pool_2d(x, (ws, ws), ignore_border=True,\n padding=pad, mode=mode)\n utt.verify_grad(fn, [data],\n cast_to_output_type=False,\n mode=mode_with_gpu)\n # Confirm that the opt would have inserted it.\n fg = theano.function([x], theano.grad(fn(x).sum(), x),\n mode=mode_with_gpu)\n assert any([isinstance(node.op, dnn.GpuDnnPoolGrad)\n for node in fg.maker.fgraph.toposort()])\n\n # Test the GPU grad + GPU implementation\n def fn(x):\n dnn_op = dnn.dnn_pool(\n x, ws=(ws, ws),\n stride=(stride, stride),\n pad=pad,\n mode=mode)\n return dnn_op\n utt.verify_grad(fn, [data],\n cast_to_output_type=False,\n mode=mode_with_gpu)\n # Confirm that we get the good op.\n fg = theano.function([x], theano.grad(fn(x).sum(), x),\n mode=mode_with_gpu)\n assert any([isinstance(node.op, dnn.GpuDnnPoolGrad)\n for node in fg.maker.fgraph.toposort()])\n g_out = fg(data)\n\n # Compare against the CPU result\n out = pool_2d(x, (ws, ws),\n padding=pad,\n ignore_border=True, mode=mode)\n fc = theano.function([x], theano.grad(out.sum(), x),\n mode=mode_without_gpu)\n if mode == 'max':\n assert any([isinstance(node.op, MaxPoolGrad)\n for node in fc.maker.fgraph.toposort()])\n else:\n assert any([isinstance(node.op, AveragePoolGrad)\n for node in fc.maker.fgraph.toposort()])\n c_out = fc(data)\n utt.assert_allclose(c_out, g_out)\n\n\ndef test_pooling_with_tensor_vars():\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n x = T.ftensor4()\n ws = theano.shared(numpy.array([2, 2], dtype='int32'))\n st = theano.shared(numpy.array([1, 1], dtype='int32'))\n pad = theano.shared(numpy.array([0, 0], dtype='int32'))\n mode = 'max'\n\n def fn(x):\n dnn_op = dnn.dnn_pool(x,\n ws=ws,\n stride=st,\n pad=pad,\n mode=mode)\n return dnn_op\n\n for shp in [(1, 1, 2, 2),\n (1, 1, 3, 3)]:\n data = numpy.random.normal(0, 1, shp).astype(\"float32\") * 10\n theano.tests.unittest_tools.verify_grad(\n fn, [data],\n cast_to_output_type=False,\n mode=mode_with_gpu)\n\n out2 = pool_2d_i2n(x, ds=(2, 2), strides=(1, 1),\n pad=(0, 0),\n pool_function=T.max)\n\n mode_without_gpu2 = mode_without_gpu.including()\n mode_without_gpu2.check_isfinite = False\n\n f1 = theano.function([x], fn(x), mode=mode_with_gpu)\n assert any([isinstance(node.op, dnn.GpuDnnPool)\n for node in f1.maker.fgraph.apply_nodes])\n f2 = theano.function([x], out2, mode=mode_without_gpu2)\n assert not any([isinstance(node.op, dnn.GpuDnnPool)\n for node in f2.maker.fgraph.apply_nodes])\n for shp in [(1, 10, 100, 100),\n (1, 3, 99, 99),\n (32, 1, 147, 197),\n ]:\n data = numpy.random.normal(0, 1, shp).astype(\"float32\")\n a = f1(data).__array__()\n\n b = f2(data).__array__()\n utt.assert_allclose(a, b)\n\n\ndef test_pooling_opt():\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n\n x = T.fmatrix()\n\n f = theano.function(\n [x],\n pool_2d(x, ds=(2, 2), mode='average_inc_pad',\n ignore_border=True),\n mode=mode_with_gpu)\n\n assert any([isinstance(n.op, dnn.GpuDnnPool)\n for n in f.maker.fgraph.toposort()])\n\n f(numpy.zeros((10, 10), dtype='float32'))\n\n f = theano.function(\n [x],\n T.grad(pool_2d(x, ds=(2, 2), mode='average_inc_pad',\n ignore_border=True).sum(),\n x),\n mode=mode_with_gpu.including(\"cudnn\"))\n\n assert any([isinstance(n.op, dnn.GpuDnnPoolGrad)\n for n in f.maker.fgraph.toposort()])\n\n f(numpy.zeros((10, 10), dtype='float32'))\n\n\ndef test_dnn_tag():\n \"\"\"\n Test that if cudnn isn't avail we crash and that if it is avail, we use it.\n \"\"\"\n x = T.ftensor4()\n old = theano.config.on_opt_error\n theano.config.on_opt_error = \"raise\"\n\n sio = StringIO()\n handler = logging.StreamHandler(sio)\n logging.getLogger('theano.compile.tests.test_dnn').addHandler(handler)\n # Silence original handler when intentionnally generating warning messages\n logging.getLogger('theano').removeHandler(theano.logging_default_handler)\n raised = False\n try:\n f = theano.function(\n [x],\n pool_2d(x, ds=(2, 2), ignore_border=True),\n mode=mode_with_gpu.including(\"cudnn\"))\n except (AssertionError, RuntimeError):\n assert not dnn.dnn_available(test_ctx_name)\n raised = True\n finally:\n theano.config.on_opt_error = old\n logging.getLogger(\n 'theano.compile.tests.test_dnn').removeHandler(handler)\n logging.getLogger('theano').addHandler(theano.logging_default_handler)\n\n if not raised:\n assert dnn.dnn_available(test_ctx_name)\n assert any([isinstance(n.op, dnn.GpuDnnPool)\n for n in f.maker.fgraph.toposort()])\n\n\nclass TestDnnInferShapes(utt.InferShapeTester):\n\n border_modes = ['valid', 'full', 'half']\n conv_modes = ['conv', 'cross']\n\n def setUp(self):\n super(TestDnnInferShapes, self).setUp()\n self.mode = mode_with_gpu\n\n def test_softmax(self):\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n t = T.ftensor4('t')\n rand_tensor = numpy.asarray(\n numpy.random.rand(5, 4, 3, 2),\n dtype='float32'\n )\n self._compile_and_check(\n [t],\n [dnn.GpuDnnSoftmax('accurate', 'channel')(t)],\n [rand_tensor],\n dnn.GpuDnnSoftmax\n )\n\n self._compile_and_check(\n [t],\n [\n T.grad(\n dnn.GpuDnnSoftmax(\n 'accurate',\n 'channel'\n )(t).mean(),\n t\n )\n ],\n [rand_tensor],\n dnn.GpuDnnSoftmaxGrad\n )\n\n def _test_conv(self, img, kerns, out, img_val, kern_vals, border_mode, conv_mode, subsamples, algo):\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n\n img_val = numpy.asarray(img_val, dtype='float32')\n kern_vals = numpy.asarray(kern_vals, dtype='float32')\n\n for subsample in subsamples:\n out_vals = numpy.zeros(\n dnn.GpuDnnConv.get_out_shape(img_val.shape, kern_vals.shape,\n border_mode=border_mode,\n subsample=subsample),\n dtype='float32')\n desc = dnn.GpuDnnConvDesc(\n border_mode=border_mode,\n subsample=subsample,\n conv_mode=conv_mode\n )(kerns.shape)\n conv = dnn.GpuDnnConv(algo=algo)(img, kerns, out, desc)\n self._compile_and_check(\n [img, kerns, out],\n [conv],\n [img_val, kern_vals, out_vals],\n dnn.GpuDnnConv\n )\n\n @parameterized.expand(chain(product([SUPPORTED_DNN_CONV_ALGO_FWD[0]],\n border_modes,\n conv_modes),\n product(SUPPORTED_DNN_CONV_ALGO_FWD[1:],\n [border_modes[0]],\n [conv_modes[0]])),\n testcase_func_name=utt.custom_name_func)\n def test_conv(self, algo, border_mode, conv_mode):\n if algo == 'winograd' and dnn.version(raises=False) < 5000:\n raise SkipTest(dnn.dnn_available.msg)\n\n self._test_conv(T.ftensor4('img'),\n T.ftensor4('kerns'),\n T.ftensor4('out'),\n numpy.random.rand(7, 2, 8, 4),\n numpy.random.rand(8, 2, 4, 3),\n border_mode,\n conv_mode,\n [(1, 1), (2, 2)],\n algo)\n\n @parameterized.expand(product(border_modes, conv_modes), utt.custom_name_func)\n def test_conv3d_none(self, border_mode, conv_mode):\n ftensor5 = T.TensorType(dtype=\"float32\", broadcastable=(False,) * 5)\n self._test_conv(ftensor5('img'),\n ftensor5('kerns'),\n ftensor5('out'),\n numpy.random.rand(10, 2, 6, 4, 11),\n numpy.random.rand(8, 2, 4, 3, 1),\n border_mode,\n conv_mode,\n [(1, 1, 1), (2, 2, 2)],\n 'none')\n\n def _test_conv_gradw(self, img, kerns, out, img_val, kern_vals, border_mode, conv_mode, subsample):\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n\n img_val = numpy.asarray(\n img_val,\n dtype='float32'\n )\n kern_vals = numpy.asarray(\n kern_vals,\n dtype='float32'\n )\n\n temp_img = img.dimshuffle(1, 0, 2, 3)\n temp_kerns = kerns\n if conv_mode == 'conv':\n temp_kerns = temp_kerns[:, :, ::-1, ::-1]\n temp_kerns = temp_kerns.dimshuffle(1, 0, 2, 3)\n shape = (\n kern_vals.shape[1], img_val.shape[1],\n img_val.shape[2] - kern_vals.shape[2] + 1,\n img_val.shape[3] - kern_vals.shape[3] + 1\n )\n out_vals = numpy.zeros(shape, dtype='float32')\n desc = dnn.GpuDnnConvDesc(\n border_mode=border_mode,\n subsample=subsample,\n conv_mode=conv_mode\n )(out.shape)\n conv_grad_w = dnn.GpuDnnConvGradW()(\n temp_img,\n temp_kerns,\n out,\n desc,\n )\n self._compile_and_check(\n [temp_img, temp_kerns, out],\n [conv_grad_w],\n [img_val, kern_vals, out_vals],\n dnn.GpuDnnConvGradW\n )\n\n @parameterized.expand(product(border_modes, conv_modes), utt.custom_name_func)\n def test_conv_gradw(self, border_mode, conv_mode):\n self._test_conv_gradw(T.ftensor4('img'),\n T.ftensor4('kerns'),\n T.ftensor4('out'),\n numpy.random.rand(2, 5, 6, 8),\n numpy.random.rand(2, 1, 5, 6),\n border_mode,\n conv_mode,\n (1, 1))\n\n def test_conv_gradi(self):\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n img = T.ftensor4('img')\n kerns = T.ftensor4('kerns')\n out = T.ftensor4('out')\n kern_vals = numpy.asarray(\n numpy.random.rand(13, 14, 15, 16),\n dtype='float32'\n )\n out_vals = numpy.asarray(\n numpy.random.rand(3, 13, 5, 6),\n dtype='float32'\n )\n\n for params in product(\n ['valid'], # Should this work for 'full'?\n [(1, 1)],\n ['conv', 'cross']\n ):\n shape = (\n out_vals.shape[0], kern_vals.shape[1],\n out_vals.shape[2] + kern_vals.shape[2] - 1,\n out_vals.shape[3] + kern_vals.shape[3] - 1\n )\n img_vals = numpy.zeros(shape, dtype='float32')\n desc = dnn.GpuDnnConvDesc(\n border_mode=params[0],\n subsample=params[1],\n conv_mode=params[2]\n )(kerns.shape)\n conv_grad_i = dnn.GpuDnnConvGradI()(\n kerns,\n out,\n img,\n desc,\n )\n self._compile_and_check(\n [kerns, img, out],\n [conv_grad_i],\n [kern_vals, img_vals, out_vals],\n dnn.GpuDnnConvGradI\n )\n\n def test_pool(self):\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n img = T.ftensor4('img')\n img_val = numpy.asarray(\n numpy.random.rand(2, 3, 4, 5),\n dtype='float32'\n )\n\n # 'average_exc_pad' is disabled for versions < 4004\n if dnn.version(raises=False) < 4004:\n modes = ['max', 'average_inc_pad']\n else:\n modes = ['max', 'average_inc_pad', 'average_exc_pad']\n\n for params in product(\n [(1, 1), (2, 2), (3, 3)],\n [(1, 1), (2, 2), (3, 3)],\n modes\n ):\n self._compile_and_check(\n [img],\n [dnn.GpuDnnPool(mode=params[2])(img, params[0], params[1], (0, 0))],\n [img_val],\n dnn.GpuDnnPool\n )\n\n def test_pool_grad(self):\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n img = T.ftensor4('img')\n img_grad = T.ftensor4('img_grad')\n out = T.ftensor4('out')\n img_val = numpy.asarray(\n numpy.random.rand(2, 3, 4, 5),\n dtype='float32'\n )\n img_grad_val = numpy.asarray(\n numpy.random.rand(2, 3, 4, 5),\n dtype='float32'\n )\n out_val = numpy.asarray(\n numpy.random.rand(2, 3, 4, 5),\n dtype='float32'\n )\n\n for params in product(\n [(1, 1), (2, 2), (3, 3)],\n [(1, 1), (2, 2), (3, 3)],\n ['max', 'average_inc_pad']\n ):\n pool_grad = dnn.GpuDnnPoolGrad(mode=params[2])(\n img,\n out,\n img_grad,\n params[0],\n params[1],\n (0, 0)\n )\n self._compile_and_check(\n [img, img_grad, out],\n [pool_grad],\n [img_val, img_grad_val, out_val],\n dnn.GpuDnnPoolGrad\n )\n\n\n# this has been a problem in the past\ndef test_dnn_conv_border_mode():\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n img = T.ftensor4()\n kern = T.ftensor4()\n\n dnn.dnn_conv(img, kern, border_mode=1)\n dnn.dnn_conv(img, kern, border_mode=(2, 3))\n dnn.dnn_conv(img, kern, border_mode='full')\n dnn.dnn_conv(img, kern, border_mode='valid')\n dnn.dnn_conv(img, kern, border_mode='half')\n\n\ndef test_dnn_conv_alpha_output_merge():\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n img = T.ftensor4()\n kern = T.ftensor4()\n out = T.ftensor4()\n\n b = 1\n c = 4\n f = 3\n ih = 5\n iw = 8\n kh = 2\n kw = 6\n img_val = numpy.random.random((b, c, ih, iw)).astype('float32')\n kern_val = numpy.random.random((f, c, kh, kw)).astype('float32')\n out_val = numpy.random.random((b, f, ih - kh + 1,\n iw - kw + 1)).astype('float32')\n\n conv = dnn.dnn_conv(img, kern)\n gw = theano.grad(conv.sum(), kern)\n gi = theano.grad(conv.sum(), img)\n\n lr = numpy.asarray(0.05, dtype='float32')\n\n fr = lr * (conv + out)\n wr = kern + lr * gw\n ir = img + lr * gi\n\n f1 = theano.function([img, kern, out], [fr, wr, ir], mode=mode_with_gpu)\n assert isinstance(f1.maker.fgraph.outputs[0].owner.inputs[0].owner.op,\n dnn.GpuDnnConv)\n assert isinstance(f1.maker.fgraph.outputs[1].owner.inputs[0].owner.op,\n dnn.GpuDnnConvGradW)\n assert isinstance(f1.maker.fgraph.outputs[2].owner.inputs[0].owner.op,\n dnn.GpuDnnConvGradI)\n\n mode = mode_with_gpu\n mode = mode.excluding('local_dnn_conv_alpha_merge')\n mode = mode.excluding('local_dnn_convw_alpha_merge')\n mode = mode.excluding('local_dnn_convi_alpha_merge')\n mode = mode.excluding('local_dnn_conv_output_merge')\n mode = mode.excluding('local_dnn_convw_output_merge')\n mode = mode.excluding('local_dnn_convi_output_merge')\n\n f2 = theano.function([img, kern, out], [fr, wr, ir], mode=mode)\n\n assert not isinstance(f2.maker.fgraph.outputs[0].owner.inputs[0].owner.op,\n dnn.GpuDnnConv)\n assert not isinstance(f2.maker.fgraph.outputs[1].owner.inputs[0].owner.op,\n dnn.GpuDnnConvGradW)\n assert not isinstance(f2.maker.fgraph.outputs[2].owner.inputs[0].owner.op,\n dnn.GpuDnnConvGradI)\n\n out_f1 = f1(img_val, kern_val, out_val)\n out_f2 = f2(img_val, kern_val, out_val)\n\n assert len(out_f1) == len(out_f2)\n\n for v1, v2 in zip(out_f1, out_f2):\n utt.assert_allclose(v1, v2)\n\n\ndef test_dnn_conv_grad():\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n b = 1\n c = 4\n f = 3\n ih = 2\n iw = 8\n kh = 2\n kw = 2\n img_val = numpy.random.random((b, c, ih, iw)).astype('float32')\n kern_val = numpy.random.random((f, c, kh, kw)).astype('float32')\n out_val = numpy.random.random((b, f, ih - kw + 1,\n iw - kw + 1)).astype('float32')\n\n def dconv(img, kern, out):\n desc = dnn.GpuDnnConvDesc(border_mode='valid', subsample=(1, 1),\n conv_mode='conv')(kern.shape)\n return dnn.GpuDnnConv()(img, kern, out, desc, alpha=0.5, beta=0.75)\n\n def dconvi(img, kern, out):\n desc = dnn.GpuDnnConvDesc(border_mode='valid', subsample=(1, 1),\n conv_mode='conv')(kern.shape)\n return dnn.GpuDnnConvGradI()(kern, out, img, desc, alpha=-1.0,\n beta=0.0)\n\n def dconvw(img, kern, out):\n desc = dnn.GpuDnnConvDesc(border_mode='valid', subsample=(1, 1),\n conv_mode='conv')(kern.shape)\n return dnn.GpuDnnConvGradW()(img, out, kern, desc, alpha=0.75,\n beta=-1.0)\n\n utt.verify_grad(dconv, [img_val, kern_val, out_val])\n utt.verify_grad(dconvi, [img_val, kern_val, out_val])\n utt.verify_grad(dconvw, [img_val, kern_val, out_val])\n\n\ndef test_version():\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n assert isinstance(dnn.version(), int)\n\n\nclass test_SoftMax(test_nnet.test_SoftMax):\n gpu_op = dnn.GpuDnnSoftmax\n gpu_grad_op = dnn.GpuDnnSoftmaxGrad\n mode = mode_with_gpu\n\n def setUp(self):\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n\n def test_softmax_shape_0(self):\n raise SkipTest(\"Cudnn doesn't support 0 shapes\")\n\n def test_softmax_grad(self):\n def cmp(n, m, f, f_gpu):\n data = numpy.arange(n * m, dtype='float32').reshape(n, m)\n gdata = numpy.asarray(data)[:, :, None, None]\n\n out = f(data)\n gout = numpy.asarray(f_gpu(gdata))[:, :, 0, 0]\n utt.assert_allclose(out, gout)\n\n x = T.matrix('x', 'float32')\n x_gpu = T.tensor4('x_gpu', 'float32')\n f_z = T.nnet.softmax_op\n f_gpu = dnn.GpuDnnSoftmax(\n 'accurate',\n 'channel'\n )\n\n # Verify the grad operation\n dims = (2, 3, 4, 5)\n gdata = numpy.arange(\n numpy.product(dims),\n dtype='float32'\n ).reshape(dims)\n T.verify_grad(f_gpu, [gdata], rng=numpy.random,\n mode=mode_with_gpu)\n\n # Verify that the CPU and GPU implementations return the same results\n # up to a tolerance.\n\n self._test_softmax(\n x,\n x_gpu,\n f_z,\n f_gpu,\n cmp\n )\n\n self._test_softmax(\n x, x, f_z, f_z, self._cmp\n )\n\n # Verify that the SoftmaxGrad -> Gpu[Dnn]SoftmaxGrad\n # optimization is applied when cudnn is required\n y = T.fvector('y')\n f = theano.function(\n [y],\n T.grad(T.nnet.softmax(y).mean(), y),\n mode=mode_with_gpu\n )\n sorted_f = f.maker.fgraph.toposort()\n val = numpy.random.rand(5).astype('float32')\n out_dnn = f(val)\n assert(len([i\n for i in sorted_f\n if isinstance(\n i.op,\n self.gpu_grad_op)\n ]) == 1)\n assert(len([i\n for i in sorted_f\n if isinstance(\n i.op,\n theano.tensor.nnet.SoftmaxGrad)\n ]) == 0)\n\n # Verify that the SoftmaxGrad -> Gpu[Dnn]SoftmaxGrad\n # optimization is not applied when cudnn is excluded or not\n # available\n mode_wo_cudnn = mode_with_gpu.excluding(\"cudnn\")\n y = T.fvector('y')\n f = theano.function(\n [y],\n T.grad(T.nnet.softmax(y).mean(), y),\n mode=mode_wo_cudnn\n )\n sorted_f = f.maker.fgraph.toposort()\n out_cpu = f(val)\n utt.assert_allclose(out_dnn, out_cpu)\n assert(len([i\n for i in sorted_f\n if isinstance(\n i.op,\n self.gpu_grad_op)\n ]) == 0)\n assert(len([i\n for i in sorted_f\n if isinstance(\n i.op,\n theano.tensor.nnet.SoftmaxGrad)\n ]) == 1)\n\n # Verify that the SoftmaxGrad -> GpuDnnSoftmaxGrad do not\n # crash with manual graph\n y = T.fvector('y')\n o = theano.tensor.nnet.SoftmaxGrad()(y, y * 2)\n f = theano.function([y], o, mode=mode_with_gpu)\n sorted_f = f.maker.fgraph.toposort()\n assert(len([i\n for i in sorted_f\n if isinstance(\n i.op,\n self.gpu_grad_op)\n ]) == 1)\n assert(len([i\n for i in sorted_f\n if isinstance(\n i.op,\n theano.tensor.nnet.SoftmaxGrad)\n ]) == 0)\n\n def test_log_softmax(self):\n # This is a test for an optimization that depends on cuDNN v3 or\n # more recent. Don't test if the cuDNN version is too old.\n if dnn.version(raises=False) < 3000:\n raise SkipTest(\"Log-softmax is only in cudnn v3+\")\n\n x = T.ftensor4()\n softmax_out = dnn.GpuDnnSoftmax('accurate', 'channel')(x)\n log_out = T.log(T.as_tensor_variable(softmax_out))\n\n f = theano.function([x], log_out, mode=mode_with_gpu)\n\n # Ensure that the optimization has been applied\n dnn_softmax_nodes = [n for n in f.maker.fgraph.toposort() if\n isinstance(n.op, dnn.GpuDnnSoftmax)]\n assert len(dnn_softmax_nodes) == 1\n assert dnn_softmax_nodes[0].op.algo == \"log\"\n\n # Ensure that the output of the function is valid\n input_shapes = [(3, 4, 5, 6),\n (1025, 2, 3, 4),\n (2, 1025, 3, 4),\n (2, 3, 1025, 4),\n (2, 3, 4, 1025),\n (66000, 2, 3, 4),\n (2, 66000, 3, 4),\n (2, 3, 66000, 4),\n (2, 3, 4, 66000)]\n\n for inp_shape in input_shapes:\n input_val = numpy.random.normal(0, 1, inp_shape).astype(\"float32\")\n\n out = f(input_val)\n expected_out = numpy.log(numpy.exp(input_val) /\n numpy.exp(input_val).sum(1)[:, None, :, :])\n\n utt.assert_allclose(out, expected_out)\n\n def test_log_softmax2(self):\n # Test that the op LogSoftmax is correctly replaced by the op\n # DnnSoftmax with the 'log' mode.\n\n # This is a test for an optimization that depends on cuDNN v3 or\n # more recent. Don't test if the cuDNN version is too old.\n if dnn.version(raises=False) < 3000:\n raise SkipTest(\"Log-softmax is only in cudnn v3+\")\n\n # Compile a reference function, on the CPU, to be used to validate the\n # results of the other function.\n x = T.fmatrix()\n f_ref = theano.function([x], T.nnet.LogSoftmax()(x))\n\n # Build the first graph and ensure that the optimization is applied\n log_softmax_out = T.nnet.LogSoftmax()(x)\n f = theano.function([x], log_softmax_out, mode=mode_with_gpu)\n\n dnn_softmax_nodes = [n for n in f.maker.fgraph.toposort() if\n isinstance(n.op, dnn.GpuDnnSoftmax)]\n assert len(dnn_softmax_nodes) == 1\n assert dnn_softmax_nodes[0].op.algo == \"log\"\n\n # Compare the output of the function with the reference function\n inp = numpy.random.normal(0, 1, (5, 6)).astype(\"float32\")\n utt.assert_allclose(f(inp), f_ref(inp))\n\n # Build the first graph and ensure that the optimization is applied\n log_softmax_out = T.log(T.nnet.Softmax()(x))\n f = theano.function([x], log_softmax_out, mode=mode_with_gpu)\n\n dnn_softmax_nodes = [n for n in f.maker.fgraph.toposort() if\n isinstance(n.op, dnn.GpuDnnSoftmax)]\n assert len(dnn_softmax_nodes) == 1\n assert dnn_softmax_nodes[0].op.algo == \"log\"\n\n # Compare the output of the function with the reference function\n inp = numpy.random.normal(0, 1, (5, 6)).astype(\"float32\")\n utt.assert_allclose(f(inp), f_ref(inp))\n\n\ndef test_dnn_batchnorm_train():\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n if dnn.version(raises=False) < 5000:\n raise SkipTest(\"batch normalization requires cudnn v5+\")\n utt.seed_rng()\n\n for mode in ('per-activation', 'spatial'):\n for vartype in (T.ftensor4, T.ftensor3, T.fmatrix, T.fvector):\n x, scale, bias = (vartype(n) for n in ('x', 'scale', 'bias'))\n ndim = x.ndim\n eps = 5e-3 # some non-standard value to test if it's used\n\n # forward pass\n out, x_mean, x_invstd = dnn.dnn_batch_normalization_train(\n x, scale, bias, mode, eps)\n # reference forward pass\n if mode == 'per-activation':\n axes = (0,)\n elif mode == 'spatial':\n axes = (0,) + tuple(range(2, ndim))\n x_mean2 = x.mean(axis=axes, keepdims=True)\n x_invstd2 = T.inv(T.sqrt(x.var(axis=axes, keepdims=True) + eps))\n scale2 = T.addbroadcast(scale, *axes)\n bias2 = T.addbroadcast(bias, *axes)\n out2 = (x - x_mean2) * (scale2 * x_invstd2) + bias2\n # backward pass\n dy = vartype('dy')\n grads = T.grad(None, wrt=[x, scale, bias], known_grads={out: dy})\n # reference backward pass\n grads2 = T.grad(None, wrt=[x, scale, bias], known_grads={out2: dy})\n # compile\n f = theano.function([x, scale, bias, dy],\n [out, x_mean, x_invstd, out2, x_mean2, x_invstd2] +\n grads + grads2, mode=mode_with_gpu)\n # run\n for data_shape in ((10, 20, 30, 40), (4, 3, 1, 1), (1, 1, 5, 5)):\n data_shape = data_shape[:ndim]\n param_shape = tuple(1 if d in axes else s\n for d, s in enumerate(data_shape))\n X = 4 + 3 * numpy.random.randn(*data_shape).astype('float32')\n Dy = -1 + 2 * numpy.random.randn(*data_shape).astype('float32')\n Scale = numpy.random.randn(*param_shape).astype('float32')\n Bias = numpy.random.randn(*param_shape).astype('float32')\n outputs = f(X, Scale, Bias, Dy)\n # compare outputs\n utt.assert_allclose(outputs[0], outputs[0 + 3]) # out\n utt.assert_allclose(outputs[1], outputs[1 + 3]) # mean\n utt.assert_allclose(outputs[2], outputs[2 + 3]) # invstd\n # compare gradients\n utt.assert_allclose(outputs[6], outputs[6 + 3]) # dx\n utt.assert_allclose(outputs[7], outputs[7 + 3], rtol=3e-3) # dscale\n utt.assert_allclose(outputs[8], outputs[8 + 3]) # dbias\n\n\ndef test_batchnorm_inference():\n if not dnn.dnn_available(test_ctx_name):\n raise SkipTest(dnn.dnn_available.msg)\n if dnn.version(raises=False) < 5000:\n raise SkipTest(\"batch normalization requires cudnn v5+\")\n utt.seed_rng()\n\n for mode in ('per-activation', 'spatial'):\n for vartype in (T.ftensor4, T.ftensor3, T.fmatrix, T.fvector):\n x, scale, bias, mean, var = (vartype(n) for n in ('x', 'scale',\n 'bias', 'mean',\n 'var'))\n ndim = x.ndim\n eps = 5e-3 # some non-standard value to test if it's used\n\n # forward pass\n out = dnn.dnn_batch_normalization_test(x, scale, bias, mean,\n var, mode, eps)\n # reference forward pass\n if mode == 'per-activation':\n axes = (0,)\n elif mode == 'spatial':\n axes = (0,) + tuple(range(2, ndim))\n scale2, bias2, mean2, var2 = (T.addbroadcast(t, *axes)\n for t in (scale, bias, mean, var))\n out2 = (x - mean2) * (scale2 / T.sqrt(var2 + eps)) + bias2\n # backward pass\n dy = vartype('dy')\n grads = T.grad(None, wrt=[x, scale, bias, mean, var], known_grads={out: dy})\n # reference backward pass\n grads2 = T.grad(None, wrt=[x, scale, bias, mean, var], known_grads={out2: dy})\n # compile\n f = theano.function([x, scale, bias, mean, var, dy],\n [out, out2] + grads + grads2, mode=mode_with_gpu)\n # run\n for data_shape in ((10, 20, 30, 40), (4, 3, 1, 1), (1, 1, 5, 5)):\n data_shape = data_shape[:ndim]\n param_shape = tuple(1 if d in axes else s\n for d, s in enumerate(data_shape))\n X = 4 + 3 * numpy.random.randn(*data_shape).astype('float32')\n Dy = -1 + 2 * numpy.random.randn(*data_shape).astype('float32')\n Scale = numpy.random.randn(*param_shape).astype('float32')\n Bias = numpy.random.randn(*param_shape).astype('float32')\n Mean = numpy.random.randn(*param_shape).astype('float32')\n Var = numpy.random.rand(*param_shape).astype('float32')\n outputs = f(X, Scale, Bias, Mean, Var, Dy)\n # compare outputs\n utt.assert_allclose(outputs[0], outputs[1]) # out\n # compare gradients\n utt.assert_allclose(outputs[2], outputs[2 + 5]) # dx\n utt.assert_allclose(outputs[3], outputs[3 + 5]) # dscale\n utt.assert_allclose(outputs[4], outputs[4 + 5]) # dbias\n utt.assert_allclose(outputs[5], outputs[5 + 5]) # dmean\n utt.assert_allclose(outputs[6], outputs[6 + 5], atol=2e-5) # dvar\n", "from __future__ import absolute_import, print_function, division\nimport errno\nimport os\nimport sys\nimport logging\nimport numpy\nimport platform\nimport textwrap\nimport re\nimport socket\nimport struct\nimport warnings\n\nfrom six import string_types\n\nimport theano\nfrom theano.configparser import (AddConfigVar, BoolParam, ConfigParam, EnumStr,\n FloatParam, IntParam, StrParam,\n TheanoConfigParser, THEANO_FLAGS_DICT)\nfrom theano.misc.cpucount import cpuCount\nfrom theano.misc.windows import call_subprocess_Popen, output_subprocess_Popen\n\n\n_logger = logging.getLogger('theano.configdefaults')\n\nconfig = TheanoConfigParser()\n\n\ndef floatX_convert(s):\n if s == \"32\":\n return \"float32\"\n elif s == \"64\":\n return \"float64\"\n elif s == \"16\":\n return \"float16\"\n else:\n return s\n\nAddConfigVar('floatX',\n \"Default floating-point precision for python casts.\\n\"\n \"\\n\"\n \"Note: float16 support is experimental, use at your own risk.\",\n EnumStr('float64', 'float32', 'float16',\n convert=floatX_convert,),\n # TODO: see gh-4466 for how to remove it.\n in_c_key=True\n )\n\nAddConfigVar('warn_float64',\n \"Do an action when a tensor variable with float64 dtype is\"\n \" created. They can't be run on the GPU with the current(old)\"\n \" gpu back-end and are slow with gamer GPUs.\",\n EnumStr('ignore', 'warn', 'raise', 'pdb'),\n in_c_key=False,\n )\n\nAddConfigVar('cast_policy',\n 'Rules for implicit type casting',\n EnumStr('custom', 'numpy+floatX',\n # The 'numpy' policy was originally planned to provide a\n # smooth transition from numpy. It was meant to behave the\n # same as numpy+floatX, but keeping float64 when numpy\n # would. However the current implementation of some cast\n # mechanisms makes it a bit more complex to add than what\n # was expected, so it is currently not available.\n # numpy,\n ),\n )\n\n# python 2.* define int / int to return int and int // int to return int.\n# python 3* define int / int to return float and int // int to return int.\n# numpy 1.6.1 behaves as python 2.*. I think we should not change it faster\n# than numpy. When we will do the transition, we should create an int_warn\n# and floatX_warn option.\nAddConfigVar('int_division',\n \"What to do when one computes x / y, where both x and y are of \"\n \"integer types\",\n EnumStr('int', 'raise', 'floatX'),\n in_c_key=False)\n\n# gpu means let the driver select the gpu. Needed in case of gpu in\n# exclusive mode.\n# gpuX mean use the gpu number X.\n\n\nclass DeviceParam(ConfigParam):\n def __init__(self, default, *options, **kwargs):\n self.default = default\n\n def filter(val):\n if val == self.default or val.startswith('gpu') \\\n or val.startswith('opencl') or val.startswith('cuda'):\n return val\n else:\n raise ValueError(('Invalid value (\"%s\") for configuration '\n 'variable \"%s\". Valid options start with '\n 'one of \"%s\", \"gpu\", \"opencl\", \"cuda\"'\n % (self.default, val, self.fullname)))\n over = kwargs.get(\"allow_override\", True)\n super(DeviceParam, self).__init__(default, filter, over)\n\n def __str__(self):\n return '%s (%s, gpu*, opencl*, cuda*) ' % (self.fullname, self.default)\n\nAddConfigVar(\n 'device',\n (\"Default device for computations. If cuda* or opencl*, change the\"\n \"default to try to move computation to the GPU. Do not use upper case\"\n \"letters, only lower case even if NVIDIA uses capital letters.\"),\n DeviceParam('cpu', allow_override=False),\n in_c_key=False)\n\nAddConfigVar(\n 'init_gpu_device',\n (\"Initialize the gpu device to use, works only if device=cpu. \"\n \"Unlike 'device', setting this option will NOT move computations, \"\n \"nor shared variables, to the specified GPU. \"\n \"It can be used to run GPU-specific tests on a particular GPU.\"),\n DeviceParam('', allow_override=False),\n in_c_key=False)\n\nAddConfigVar(\n 'force_device',\n \"Raise an error if we can't use the specified device\",\n BoolParam(False, allow_override=False),\n in_c_key=False)\n\n\nclass ContextsParam(ConfigParam):\n def __init__(self):\n def filter(val):\n if val == '':\n return val\n for v in val.split(';'):\n s = v.split('->')\n if len(s) != 2:\n raise ValueError(\"Malformed context map: %s\" % (v,))\n if (s[0] == 'cpu' or s[0].startswith('cuda') or\n s[0].startswith('opencl')):\n raise ValueError(\"Cannot use %s as context name\" % (s[0],))\n return val\n ConfigParam.__init__(self, '', filter, False)\n\nAddConfigVar(\n 'contexts',\n \"\"\"\n Context map for multi-gpu operation. Format is a\n semicolon-separated list of names and device names in the\n 'name->dev_name' format. An example that would map name 'test' to\n device 'cuda0' and name 'test2' to device 'opencl0:0' follows:\n \"test->cuda0;test2->opencl0:0\".\n\n Invalid context names are 'cpu', 'cuda*' and 'opencl*'\n \"\"\", ContextsParam(), in_c_key=False)\n\nAddConfigVar(\n 'print_active_device',\n \"Print active device at when the GPU device is initialized.\",\n BoolParam(True, allow_override=False),\n in_c_key=False)\n\n\nAddConfigVar(\n 'enable_initial_driver_test',\n \"Tests the nvidia driver when a GPU device is initialized.\",\n BoolParam(True, allow_override=False),\n in_c_key=False)\n\n\ndef default_cuda_root():\n v = os.getenv('CUDA_ROOT', \"\")\n if v:\n return v\n s = os.getenv(\"PATH\")\n if not s:\n return ''\n for dir in s.split(os.path.pathsep):\n if os.path.exists(os.path.join(dir, \"nvcc\")):\n return os.path.dirname(os.path.abspath(dir))\n return ''\n\nAddConfigVar(\n 'cuda.root',\n \"\"\"directory with bin/, lib/, include/ for cuda utilities.\n This directory is included via -L and -rpath when linking\n dynamically compiled modules. If AUTO and nvcc is in the\n path, it will use one of nvcc parent directory. Otherwise\n /usr/local/cuda will be used. Leave empty to prevent extra\n linker directives. Default: environment variable \"CUDA_ROOT\"\n or else \"AUTO\".\n \"\"\",\n StrParam(default_cuda_root),\n in_c_key=False)\n\n\ndef filter_nvcc_flags(s):\n assert isinstance(s, str)\n flags = [flag for flag in s.split(' ') if flag]\n if any([f for f in flags if not f.startswith(\"-\")]):\n raise ValueError(\n \"Theano nvcc.flags support only parameter/value pairs without\"\n \" space between them. e.g.: '--machine 64' is not supported,\"\n \" but '--machine=64' is supported. Please add the '=' symbol.\"\n \" nvcc.flags value is '%s'\" % s)\n return ' '.join(flags)\n\nAddConfigVar('nvcc.flags',\n \"Extra compiler flags for nvcc\",\n ConfigParam(\"\", filter_nvcc_flags),\n # Not needed in c key as it is already added.\n # We remove it as we don't make the md5 of config to change\n # if theano.sandbox.cuda is loaded or not.\n in_c_key=False)\n\nAddConfigVar('nvcc.compiler_bindir',\n \"If defined, nvcc compiler driver will seek g++ and gcc\"\n \" in this directory\",\n StrParam(\"\"),\n in_c_key=False)\n\nAddConfigVar('nvcc.fastmath',\n \"\",\n BoolParam(False),\n # Not needed in c key as it is already added.\n # We remove it as we don't make the md5 of config to change\n # if theano.sandbox.cuda is loaded or not.\n in_c_key=False)\n\nAddConfigVar('gpuarray.sync',\n \"\"\"If True, every op will make sure its work is done before\n returning. Setting this to True will slow down execution,\n but give much more accurate results in profiling.\"\"\",\n BoolParam(False),\n in_c_key=True)\n\nAddConfigVar('gpuarray.preallocate',\n \"\"\"If negative it disables the allocation cache. If\n between 0 and 1 it enables the allocation cache and\n preallocates that fraction of the total GPU memory. If 1\n or greater it will preallocate that amount of memory (in\n megabytes).\"\"\",\n FloatParam(0),\n in_c_key=False)\n\nAddConfigVar('gpuarray.single_stream',\n \"\"\"\n If your computations are mostly lots of small elements,\n using single-stream will avoid the synchronization\n overhead and usually be faster. For larger elements it\n does not make a difference yet. In the future when true\n multi-stream is enabled in libgpuarray, this may change.\n If you want to make sure to have optimal performance,\n check both options.\n \"\"\",\n BoolParam(True),\n in_c_key=False)\n\n\ndef safe_no_dnn_workmem(workmem):\n \"\"\"\n Make sure the user is not attempting to use dnn.conv.workmem`.\n \"\"\"\n if workmem:\n raise RuntimeError(\n 'The option `dnn.conv.workmem` has been removed and should '\n 'not be used anymore. Please use the option '\n '`dnn.conv.algo_fwd` instead.')\n return True\n\nAddConfigVar('dnn.conv.workmem',\n \"This flag is deprecated; use dnn.conv.algo_fwd.\",\n ConfigParam('', allow_override=False, filter=safe_no_dnn_workmem),\n in_c_key=False)\n\n\ndef safe_no_dnn_workmem_bwd(workmem):\n \"\"\"\n Make sure the user is not attempting to use dnn.conv.workmem_bwd`.\n \"\"\"\n if workmem:\n raise RuntimeError(\n 'The option `dnn.conv.workmem_bwd` has been removed and '\n 'should not be used anymore. Please use the options '\n '`dnn.conv.algo_bwd_filter` and `dnn.conv.algo_bwd_data` instead.')\n return True\n\nAddConfigVar('dnn.conv.workmem_bwd',\n \"This flag is deprecated; use `dnn.conv.algo_bwd_filter` \"\n \"and `dnn.conv.algo_bwd_data` instead.\",\n ConfigParam('', allow_override=False,\n filter=safe_no_dnn_workmem_bwd),\n in_c_key=False)\n\n\ndef safe_no_dnn_algo_bwd(algo):\n \"\"\"\n Make sure the user is not attempting to use dnn.conv.algo_bwd`.\n \"\"\"\n if algo:\n raise RuntimeError(\n 'The option `dnn.conv.algo_bwd` has been removed and '\n 'should not be used anymore. Please use the options '\n '`dnn.conv.algo_bwd_filter` and `dnn.conv.algo_bwd_data` instead.')\n return True\n\n# Those are the supported algorithm by Theano,\n# The tests will reference those lists.\nSUPPORTED_DNN_CONV_ALGO_FWD = ('small', 'none', 'large', 'fft', 'fft_tiling',\n 'winograd', 'guess_once', 'guess_on_shape_change',\n 'time_once', 'time_on_shape_change')\n\nSUPPORTED_DNN_CONV_ALGO_BWD_DATA = ('none', 'deterministic', 'fft', 'fft_tiling',\n 'winograd', 'guess_once', 'guess_on_shape_change',\n 'time_once', 'time_on_shape_change')\n\nSUPPORTED_DNN_CONV_ALGO_BWD_FILTER = ('none', 'deterministic', 'fft', 'small',\n 'guess_once', 'guess_on_shape_change',\n 'time_once', 'time_on_shape_change')\n\nAddConfigVar('dnn.conv.algo_bwd',\n \"This flag is deprecated; use dnn.conv.algo_bwd_data and \"\n \"dnn.conv.algo_bwd_filter.\",\n ConfigParam('', allow_override=False,\n filter=safe_no_dnn_algo_bwd),\n in_c_key=False)\n\nAddConfigVar('dnn.conv.algo_fwd',\n \"Default implementation to use for cuDNN forward convolution.\",\n EnumStr(*SUPPORTED_DNN_CONV_ALGO_FWD),\n in_c_key=False)\n\nAddConfigVar('dnn.conv.algo_bwd_data',\n \"Default implementation to use for cuDNN backward convolution to \"\n \"get the gradients of the convolution with regard to the inputs.\",\n EnumStr(*SUPPORTED_DNN_CONV_ALGO_BWD_DATA),\n in_c_key=False)\n\nAddConfigVar('dnn.conv.algo_bwd_filter',\n \"Default implementation to use for cuDNN backward convolution to \"\n \"get the gradients of the convolution with regard to the \"\n \"filters.\",\n EnumStr(*SUPPORTED_DNN_CONV_ALGO_BWD_FILTER),\n in_c_key=False)\n\nAddConfigVar('dnn.conv.precision',\n \"Default data precision to use for the computation in cuDNN \"\n \"convolutions (defaults to the same dtype as the inputs of the \"\n \"convolutions, or float32 if inputs are float16).\",\n EnumStr('as_input_f32', 'as_input', 'float16', 'float32',\n 'float64'),\n in_c_key=False)\n\n\ndef default_dnn_path(suffix):\n def f(suffix=suffix):\n if theano.config.cuda.root == '':\n return ''\n return os.path.join(theano.config.cuda.root, suffix)\n return f\n\nAddConfigVar('dnn.include_path',\n \"Location of the cudnn header (defaults to the cuda root)\",\n StrParam(default_dnn_path('include')),\n # Added elsewhere in the c key only when needed.\n in_c_key=False)\n\nAddConfigVar('dnn.library_path',\n \"Location of the cudnn header (defaults to the cuda root)\",\n StrParam(default_dnn_path('lib' if sys.platform == 'darwin' else 'lib64')),\n # Added elsewhere in the c key only when needed.\n in_c_key=False)\n\nAddConfigVar('dnn.enabled',\n \"'auto', use cuDNN if available, but silently fall back\"\n \" to not using it if not present.\"\n \" If True and cuDNN can not be used, raise an error.\"\n \" If False, disable cudnn\",\n EnumStr(\"auto\", \"True\", \"False\"),\n in_c_key=False)\n\n# This flag determines whether or not to raise error/warning message if\n# there is a CPU Op in the computational graph.\nAddConfigVar(\n 'assert_no_cpu_op',\n \"Raise an error/warning if there is a CPU op in the computational graph.\",\n EnumStr('ignore', 'warn', 'raise', 'pdb', allow_override=True),\n in_c_key=False)\n\n\n# Do not add FAST_RUN_NOGC to this list (nor any other ALL CAPS shortcut).\n# The way to get FAST_RUN_NOGC is with the flag 'linker=c|py_nogc'.\n# The old all capital letter way of working is deprecated as it is not\n# scalable.\n# Also, please be careful not to modify the first item in the enum when adding\n# new modes, since it is the default mode.\nAddConfigVar(\n 'mode',\n \"Default compilation mode\",\n EnumStr('Mode', 'ProfileMode', 'DebugMode', 'FAST_RUN',\n 'NanGuardMode',\n 'FAST_COMPILE', 'PROFILE_MODE', 'DEBUG_MODE'),\n in_c_key=False)\n\nparam = \"g++\"\n\n# Test whether or not g++ is present: disable C code if it is not.\ntry:\n rc = call_subprocess_Popen(['g++', '-v'])\nexcept OSError:\n rc = 1\n\nif rc != 0:\n param = \"\"\n\n# On Mac we test for 'clang++' and use it by default\nif sys.platform == 'darwin':\n try:\n rc = call_subprocess_Popen(['clang++', '-v'])\n if rc == 0:\n param = \"clang++\"\n except OSError:\n pass\n\n# Try to find the full compiler path from the name\nif param != \"\":\n import distutils.spawn\n newp = distutils.spawn.find_executable(param)\n if newp is not None:\n param = newp\n del newp\n del distutils\n\nAddConfigVar('cxx',\n \"The C++ compiler to use. Currently only g++ is\"\n \" supported, but supporting additional compilers should not be \"\n \"too difficult. \"\n \"If it is empty, no C++ code is compiled.\",\n StrParam(param),\n in_c_key=False)\ndel param\n\nif rc == 0 and config.cxx != \"\":\n # Keep the default linker the same as the one for the mode FAST_RUN\n AddConfigVar('linker',\n (\"Default linker used if the theano flags mode is Mode \"\n \"or ProfileMode(deprecated)\"),\n EnumStr('cvm', 'c|py', 'py', 'c', 'c|py_nogc',\n 'vm', 'vm_nogc', 'cvm_nogc'),\n in_c_key=False)\nelse:\n # g++ is not present or the user disabled it,\n # linker should default to python only.\n AddConfigVar('linker',\n (\"Default linker used if the theano flags mode is Mode \"\n \"or ProfileMode(deprecated)\"),\n EnumStr('vm', 'py', 'vm_nogc'),\n in_c_key=False)\n try:\n # If the user provided an empty value for cxx, do not warn.\n theano.configparser.fetch_val_for_key('cxx')\n except KeyError:\n _logger.warning(\n 'g++ not detected ! Theano will be unable to execute '\n 'optimized C-implementations (for both CPU and GPU) and will '\n 'default to Python implementations. Performance will be severely '\n 'degraded. To remove this warning, set Theano flags cxx to an '\n 'empty string.')\n\n\n# Keep the default value the same as the one for the mode FAST_RUN\nAddConfigVar('allow_gc',\n \"Do we default to delete intermediate results during Theano\"\n \" function calls? Doing so lowers the memory requirement, but\"\n \" asks that we reallocate memory at the next function call.\"\n \" This is implemented for the default linker, but may not work\"\n \" for all linkers.\",\n BoolParam(True),\n in_c_key=False)\n\n# Keep the default optimizer the same as the one for the mode FAST_RUN\nAddConfigVar(\n 'optimizer',\n (\"Default optimizer. If not None, will use this linker with the Mode \"\n \"object (not ProfileMode(deprecated) or DebugMode)\"),\n EnumStr('fast_run', 'merge', 'fast_compile', 'None'),\n in_c_key=False)\n\nAddConfigVar('optimizer_verbose',\n \"If True, we print all optimization being applied\",\n BoolParam(False),\n in_c_key=False)\n\nAddConfigVar(\n 'on_opt_error',\n (\"What to do when an optimization crashes: warn and skip it, raise \"\n \"the exception, or fall into the pdb debugger.\"),\n EnumStr('warn', 'raise', 'pdb', 'ignore'),\n in_c_key=False)\n\n\ndef safe_no_home(home):\n \"\"\"\n Make sure the user is not attempting to use `config.home`.\n\n This config option was removed in Thenao 0.5 since it was redundant with\n `config.base_compiledir`. This filter function ensures people who were\n setting the location of their compilation directory through `config.home`\n switch to `config.basecompiledir` instead, by raising an error when\n `config.home` is used.\n \"\"\"\n if home:\n raise RuntimeError(\n 'The `config.home` option has been removed and should not be '\n 'used anymore. Please set the `config.base_compiledir` option '\n 'instead (for instance to: %s)' %\n os.path.join(home, '.theano'))\n return True\n\n\nAddConfigVar(\n 'home',\n \"This config option was removed in 0.5: do not use it!\",\n ConfigParam('', allow_override=False, filter=safe_no_home),\n in_c_key=False)\n\n\nAddConfigVar(\n 'nocleanup',\n \"Suppress the deletion of code files that did not compile cleanly\",\n BoolParam(False),\n in_c_key=False)\n\nAddConfigVar('on_unused_input',\n \"What to do if a variable in the 'inputs' list of \"\n \" theano.function() is not used in the graph.\",\n EnumStr('raise', 'warn', 'ignore'),\n in_c_key=False)\n\n# This flag is used when we import Theano to initialize global variables.\n# So changing it after import will not modify these global variables.\n# This could be done differently... but for now we simply prevent it from being\n# changed at runtime.\nAddConfigVar(\n 'tensor.cmp_sloppy',\n \"Relax tensor._allclose (0) not at all, (1) a bit, (2) more\",\n IntParam(0, lambda i: i in (0, 1, 2), allow_override=False),\n in_c_key=False)\n\nAddConfigVar(\n 'tensor.local_elemwise_fusion',\n (\"Enable or not in fast_run mode(fast_run optimization) the elemwise \"\n \"fusion optimization\"),\n BoolParam(True),\n in_c_key=False)\n\nAddConfigVar(\n 'gpu.local_elemwise_fusion',\n (\"Enable or not in fast_run mode(fast_run optimization) the gpu \"\n \"elemwise fusion optimization\"),\n BoolParam(True),\n in_c_key=False)\n\n# http://developer.amd.com/CPU/LIBRARIES/LIBM/Pages/default.aspx\nAddConfigVar(\n 'lib.amdlibm',\n \"Use amd's amdlibm numerical library\",\n BoolParam(False),\n # Added elsewhere in the c key only when needed.\n in_c_key=False)\n\nAddConfigVar(\n 'gpuelemwise.sync',\n \"when true, wait that the gpu fct finished and check it error code.\",\n BoolParam(True),\n in_c_key=False)\n\nAddConfigVar(\n 'traceback.limit',\n \"The number of stack to trace. -1 mean all.\",\n # We default to a number to be able to know where v1 + v2 is created in the\n # user script. The bigger this number is, the more run time it takes.\n # We need to default to 8 to support theano.tensor.tensor(...).\n # import theano, numpy\n # X = theano.tensor.matrix()\n # y = X.reshape((5,3,1))\n # assert y.tag.trace\n IntParam(8),\n in_c_key=False)\n\nAddConfigVar(\n 'traceback.compile_limit',\n \"The number of stack to trace to keep during compilation. -1 mean all.\"\n \" If greater then 0, will also make us save Theano internal stack trace.\",\n IntParam(0),\n in_c_key=False)\n\nAddConfigVar('experimental.mrg',\n \"Another random number generator that work on the gpu\",\n BoolParam(False))\n\nAddConfigVar('experimental.unpickle_gpu_on_cpu',\n \"Allow unpickling of pickled CudaNdarrays as numpy.ndarrays.\"\n \"This is useful, if you want to open a CudaNdarray without \"\n \"having cuda installed.\"\n \"If you have cuda installed, this will force unpickling to\"\n \"be done on the cpu to numpy.ndarray.\"\n \"Please be aware that this may get you access to the data,\"\n \"however, trying to unpicke gpu functions will not succeed.\"\n \"This flag is experimental and may be removed any time, when\"\n \"gpu<>cpu transparency is solved.\",\n BoolParam(default=False),\n in_c_key=False)\n\nAddConfigVar('numpy.seterr_all',\n (\"Sets numpy's behaviour for floating-point errors, \",\n \"see numpy.seterr. \"\n \"'None' means not to change numpy's default, which can be \"\n \"different for different numpy releases. \"\n \"This flag sets the default behaviour for all kinds of floating-\"\n \"point errors, its effect can be overriden for specific errors \"\n \"by the following flags: seterr_divide, seterr_over, \"\n \"seterr_under and seterr_invalid.\"),\n EnumStr('ignore', 'warn', 'raise', 'call', 'print', 'log', 'None',\n allow_override=False),\n in_c_key=False)\n\nAddConfigVar('numpy.seterr_divide',\n (\"Sets numpy's behavior for division by zero, see numpy.seterr. \"\n \"'None' means using the default, defined by numpy.seterr_all.\"),\n EnumStr('None', 'ignore', 'warn', 'raise', 'call', 'print', 'log',\n allow_override=False),\n in_c_key=False)\n\nAddConfigVar('numpy.seterr_over',\n (\"Sets numpy's behavior for floating-point overflow, \"\n \"see numpy.seterr. \"\n \"'None' means using the default, defined by numpy.seterr_all.\"),\n EnumStr('None', 'ignore', 'warn', 'raise', 'call', 'print', 'log',\n allow_override=False),\n in_c_key=False)\n\nAddConfigVar('numpy.seterr_under',\n (\"Sets numpy's behavior for floating-point underflow, \"\n \"see numpy.seterr. \"\n \"'None' means using the default, defined by numpy.seterr_all.\"),\n EnumStr('None', 'ignore', 'warn', 'raise', 'call', 'print', 'log',\n allow_override=False),\n in_c_key=False)\n\nAddConfigVar('numpy.seterr_invalid',\n (\"Sets numpy's behavior for invalid floating-point operation, \"\n \"see numpy.seterr. \"\n \"'None' means using the default, defined by numpy.seterr_all.\"),\n EnumStr('None', 'ignore', 'warn', 'raise', 'call', 'print', 'log',\n allow_override=False),\n in_c_key=False)\n\n###\n# To disable some warning about old bug that are fixed now.\n###\nAddConfigVar('warn.ignore_bug_before',\n (\"If 'None', we warn about all Theano bugs found by default. \"\n \"If 'all', we don't warn about Theano bugs found by default. \"\n \"If a version, we print only the warnings relative to Theano \"\n \"bugs found after that version. \"\n \"Warning for specific bugs can be configured with specific \"\n \"[warn] flags.\"),\n EnumStr('0.7', 'None', 'all', '0.3', '0.4', '0.4.1', '0.5', '0.6',\n '0.7', '0.8', '0.8.1', '0.8.2',\n allow_override=False),\n in_c_key=False)\n\n\ndef warn_default(version):\n \"\"\"\n Return True iff we should warn about bugs fixed after a given version.\n \"\"\"\n if config.warn.ignore_bug_before == 'None':\n return True\n if config.warn.ignore_bug_before == 'all':\n return False\n if config.warn.ignore_bug_before >= version:\n return False\n return True\n\n\nAddConfigVar('warn.argmax_pushdown_bug',\n (\"Warn if in past version of Theano we generated a bug with the \"\n \"theano.tensor.nnet.nnet.local_argmax_pushdown optimization. \"\n \"Was fixed 27 may 2010\"),\n BoolParam(warn_default('0.3')),\n in_c_key=False)\n\nAddConfigVar('warn.gpusum_01_011_0111_bug',\n (\"Warn if we are in a case where old version of Theano had a \"\n \"silent bug with GpuSum pattern 01,011 and 0111 when the first \"\n \"dimensions was bigger then 4096. Was fixed 31 may 2010\"),\n BoolParam(warn_default('0.3')),\n in_c_key=False)\n\nAddConfigVar('warn.sum_sum_bug',\n (\"Warn if we are in a case where Theano version between version \"\n \"9923a40c7b7a and the 2 august 2010 (fixed date), generated an \"\n \"error in that case. This happens when there are 2 consecutive \"\n \"sums in the graph, bad code was generated. \"\n \"Was fixed 2 August 2010\"),\n BoolParam(warn_default('0.3')),\n in_c_key=False)\n\nAddConfigVar('warn.sum_div_dimshuffle_bug',\n (\"Warn if previous versions of Theano (between rev. \"\n \"3bd9b789f5e8, 2010-06-16, and cfc6322e5ad4, 2010-08-03) \"\n \"would have given incorrect result. This bug was triggered by \"\n \"sum of division of dimshuffled tensors.\"),\n BoolParam(warn_default('0.3')),\n in_c_key=False)\n\nAddConfigVar(\n 'warn.subtensor_merge_bug',\n \"Warn if previous versions of Theano (before 0.5rc2) could have given \"\n \"incorrect results when indexing into a subtensor with negative \"\n \"stride (for instance, for instance, x[a:b:-1][c]).\",\n BoolParam(warn_default('0.5')),\n in_c_key=False)\n\nAddConfigVar(\n 'warn.gpu_set_subtensor1',\n \"Warn if previous versions of Theano (before 0.6) could have given \"\n \"incorrect results when moving to the gpu \"\n \"set_subtensor(x[int vector], new_value)\",\n BoolParam(warn_default('0.6')),\n in_c_key=False)\n\nAddConfigVar(\n 'warn.vm_gc_bug',\n \"There was a bug that existed in the default Theano configuration,\"\n \" only in the development version between July 5th 2012\"\n \" and July 30th 2012. This was not in a released version.\"\n \" If your code was affected by this bug, a warning\"\n \" will be printed during the code execution if you use the\"\n \" `linker=vm,vm.lazy=True,warn.vm_gc_bug=True` Theano flags.\"\n \" This warning is disabled by default as the bug was not released.\",\n BoolParam(False),\n in_c_key=False)\n\nAddConfigVar('warn.signal_conv2d_interface',\n (\"Warn we use the new signal.conv2d() when its interface\"\n \" changed mid June 2014\"),\n BoolParam(warn_default('0.7')),\n in_c_key=False)\n\nAddConfigVar('warn.reduce_join',\n ('Your current code is fine, but Theano versions '\n 'prior to 0.7 (or this development version) '\n 'might have given an incorrect result. '\n 'To disable this warning, set the Theano flag '\n 'warn.reduce_join to False. The problem was an '\n 'optimization, that modified the pattern '\n '\"Reduce{scalar.op}(Join(axis=0, a, b), axis=0)\", '\n 'did not check the reduction axis. So if the '\n 'reduction axis was not 0, you got a wrong answer.'),\n BoolParam(warn_default('0.7')),\n in_c_key=False)\n\nAddConfigVar('warn.inc_set_subtensor1',\n ('Warn if previous versions of Theano (before 0.7) could have '\n 'given incorrect results for inc_subtensor and set_subtensor '\n 'when using some patterns of advanced indexing (indexing with '\n 'one vector or matrix of ints).'),\n BoolParam(warn_default('0.7')),\n in_c_key=False)\n\nAddConfigVar(\n 'compute_test_value',\n (\"If 'True', Theano will run each op at graph build time, using \"\n \"Constants, SharedVariables and the tag 'test_value' as inputs \"\n \"to the function. This helps the user track down problems in the \"\n \"graph before it gets optimized.\"),\n EnumStr('off', 'ignore', 'warn', 'raise', 'pdb'),\n in_c_key=False)\n\n\nAddConfigVar(\n 'print_test_value',\n (\"If 'True', the __eval__ of a Theano variable will return its test_value \"\n \"when this is available. This has the practical conseguence that, e.g., \"\n \"in debugging `my_var` will print the same as `my_var.tag.test_value` \"\n \"when a test value is defined.\"),\n BoolParam(False),\n in_c_key=False)\n\n\nAddConfigVar('compute_test_value_opt',\n (\"For debugging Theano optimization only.\"\n \" Same as compute_test_value, but is used\"\n \" during Theano optimization\"),\n EnumStr('off', 'ignore', 'warn', 'raise', 'pdb'),\n in_c_key=False)\n\nAddConfigVar('unpickle_function',\n (\"Replace unpickled Theano functions with None. \"\n \"This is useful to unpickle old graphs that pickled\"\n \" them when it shouldn't\"),\n BoolParam(True),\n in_c_key=False)\n\nAddConfigVar(\n 'reoptimize_unpickled_function',\n \"Re-optimize the graph when a theano function is unpickled from the disk.\",\n BoolParam(False, allow_override=True),\n in_c_key=False)\n\n\"\"\"Note to developers:\n Generally your exceptions should use an apply node's __str__\n method when exception_verbosity == 'low'. When exception_verbosity\n == 'high', you should include a call to printing.min_informative_str\n on all important apply nodes.\n\"\"\"\nAddConfigVar(\n 'exception_verbosity',\n \"If 'low', the text of exceptions will generally refer \"\n \"to apply nodes with short names such as \"\n \"Elemwise{add_no_inplace}. If 'high', some exceptions \"\n \"will also refer to apply nodes with long descriptions \"\n \"\"\" like:\n A. Elemwise{add_no_inplace}\n B. log_likelihood_v_given_h\n C. log_likelihood_h\"\"\",\n EnumStr('low', 'high'),\n in_c_key=False)\n\n# Test if the env variable is set\nvar = os.getenv('OMP_NUM_THREADS', None)\nif var:\n try:\n int(var)\n except ValueError:\n raise TypeError(\"The environment variable OMP_NUM_THREADS\"\n \" should be a number, got '%s'.\" % var)\n else:\n default_openmp = not int(var) == 1\nelse:\n # Check the number of cores availables.\n count = cpuCount()\n if count == -1:\n _logger.warning(\"We are not able to detect the number of CPU cores.\"\n \" We disable openmp by default. To remove this\"\n \" warning, set the environment variable\"\n \" OMP_NUM_THREADS to the number of threads you\"\n \" want theano to use.\")\n default_openmp = count > 1\n\n# Disable it by default for now as currently only the ConvOp supports\n# it, and this causes slowdown by default as we do not disable it for\n# too small convolution.\ndefault_openmp = False\n\nAddConfigVar('openmp',\n \"Allow (or not) parallel computation on the CPU with OpenMP. \"\n \"This is the default value used when creating an Op that \"\n \"supports OpenMP parallelization. It is preferable to define it \"\n \"via the Theano configuration file ~/.theanorc or with the \"\n \"environment variable THEANO_FLAGS. Parallelization is only \"\n \"done for some operations that implement it, and even for \"\n \"operations that implement parallelism, each operation is free \"\n \"to respect this flag or not. You can control the number of \"\n \"threads used with the environment variable OMP_NUM_THREADS.\"\n \" If it is set to 1, we disable openmp in Theano by default.\",\n BoolParam(default_openmp),\n in_c_key=False,\n )\n\nAddConfigVar('openmp_elemwise_minsize',\n \"If OpenMP is enabled, this is the minimum size of vectors \"\n \"for which the openmp parallelization is enabled \"\n \"in element wise ops.\",\n IntParam(200000),\n in_c_key=False,\n )\n\nAddConfigVar(\n 'check_input',\n \"Specify if types should check their input in their C code. \"\n \"It can be used to speed up compilation, reduce overhead \"\n \"(particularly for scalars) and reduce the number of generated C \"\n \"files.\",\n BoolParam(True),\n in_c_key=True)\n\nAddConfigVar(\n 'cache_optimizations',\n \"WARNING: work in progress, does not work yet. \"\n \"Specify if the optimization cache should be used. This cache will \"\n \"any optimized graph and its optimization. Actually slow downs a lot \"\n \"the first optimization, and could possibly still contains some bugs. \"\n \"Use at your own risks.\",\n BoolParam(False),\n in_c_key=False)\n\n\ndef good_seed_param(seed):\n if seed == \"random\":\n return True\n try:\n int(seed)\n except Exception:\n return False\n return True\n\n\nAddConfigVar('unittests.rseed',\n \"Seed to use for randomized unit tests. \"\n \"Special value 'random' means using a seed of None.\",\n StrParam(666, is_valid=good_seed_param),\n in_c_key=False)\n\nAddConfigVar('NanGuardMode.nan_is_error',\n \"Default value for nan_is_error\",\n BoolParam(True),\n in_c_key=False)\n\nAddConfigVar('NanGuardMode.inf_is_error',\n \"Default value for inf_is_error\",\n BoolParam(True),\n in_c_key=False)\n\nAddConfigVar('NanGuardMode.big_is_error',\n \"Default value for big_is_error\",\n BoolParam(True),\n in_c_key=False)\n\nAddConfigVar('NanGuardMode.action',\n \"What NanGuardMode does when it finds a problem\",\n EnumStr('raise', 'warn', 'pdb'),\n in_c_key=False)\n\nAddConfigVar('ProfileMode.n_apply_to_print',\n \"Number of apply instances to print by default\",\n IntParam(15, lambda i: i > 0),\n in_c_key=False)\n\nAddConfigVar('ProfileMode.n_ops_to_print',\n \"Number of ops to print by default\",\n IntParam(20, lambda i: i > 0),\n in_c_key=False)\n\nAddConfigVar('ProfileMode.min_memory_size',\n \"For the memory profile, do not print apply nodes if the size \"\n \"of their outputs (in bytes) is lower then this threshold\",\n IntParam(1024, lambda i: i >= 0),\n in_c_key=False)\n\nAddConfigVar('ProfileMode.profile_memory',\n \"\"\"Enable profiling of memory used by Theano functions\"\"\",\n BoolParam(False),\n in_c_key=False)\n\nAddConfigVar('optimizer_excluding',\n (\"When using the default mode, we will remove optimizer with \"\n \"these tags. Separate tags with ':'.\"),\n StrParam(\"\", allow_override=False),\n in_c_key=False)\n\nAddConfigVar('optimizer_including',\n (\"When using the default mode, we will add optimizer with \"\n \"these tags. Separate tags with ':'.\"),\n StrParam(\"\", allow_override=False),\n in_c_key=False)\n\nAddConfigVar('optimizer_requiring',\n (\"When using the default mode, we will require optimizer with \"\n \"these tags. Separate tags with ':'.\"),\n StrParam(\"\", allow_override=False),\n in_c_key=False)\n\nAddConfigVar('DebugMode.patience',\n \"Optimize graph this many times to detect inconsistency\",\n IntParam(10, lambda i: i > 0),\n in_c_key=False)\n\nAddConfigVar('DebugMode.check_c',\n \"Run C implementations where possible\",\n BoolParam(\n lambda: bool(theano.config.cxx)),\n in_c_key=False)\n\nAddConfigVar('DebugMode.check_py',\n \"Run Python implementations where possible\",\n BoolParam(True),\n in_c_key=False)\n\nAddConfigVar('DebugMode.check_finite',\n \"True -> complain about NaN/Inf results\",\n BoolParam(True),\n in_c_key=False)\n\nAddConfigVar('DebugMode.check_strides',\n (\"Check that Python- and C-produced ndarrays have same strides. \"\n \"On difference: (0) - ignore, (1) warn, or (2) raise error\"),\n IntParam(0, lambda i: i in (0, 1, 2)),\n in_c_key=False)\n\nAddConfigVar('DebugMode.warn_input_not_reused',\n (\"Generate a warning when destroy_map or view_map says that an \"\n \"op works inplace, but the op did not reuse the input for its \"\n \"output.\"),\n BoolParam(True),\n in_c_key=False)\n\n\ndef is_valid_check_preallocated_output_param(param):\n if not isinstance(param, string_types):\n return False\n valid = [\"initial\", \"previous\", \"c_contiguous\", \"f_contiguous\",\n \"strided\", \"wrong_size\", \"ALL\", \"\"]\n for p in param.split(\":\"):\n if p not in valid:\n return False\n return True\n\nAddConfigVar('DebugMode.check_preallocated_output',\n ('Test thunks with pre-allocated memory as output storage. '\n 'This is a list of strings separated by \":\". Valid values are: '\n '\"initial\" (initial storage in storage map, happens with Scan),'\n '\"previous\" (previously-returned memory), '\n '\"c_contiguous\", \"f_contiguous\", '\n '\"strided\" (positive and negative strides), '\n '\"wrong_size\" (larger and smaller dimensions), and '\n '\"ALL\" (all of the above).'),\n StrParam('', is_valid=is_valid_check_preallocated_output_param),\n in_c_key=False)\n\nAddConfigVar('DebugMode.check_preallocated_output_ndim',\n ('When testing with \"strided\" preallocated output memory, '\n 'test all combinations of strides over that number of '\n '(inner-most) dimensions. You may want to reduce that number '\n 'to reduce memory or time usage, but it is advised to keep a '\n 'minimum of 2.'),\n IntParam(4, lambda i: i > 0),\n in_c_key=False)\n\nAddConfigVar('profiling.time_thunks',\n \"\"\"Time individual thunks when profiling\"\"\",\n BoolParam(True),\n in_c_key=False)\n\nAddConfigVar('profiling.n_apply',\n \"Number of Apply instances to print by default\",\n IntParam(20, lambda i: i > 0),\n in_c_key=False)\n\nAddConfigVar('profiling.n_ops',\n \"Number of Ops to print by default\",\n IntParam(20, lambda i: i > 0),\n in_c_key=False)\n\nAddConfigVar('profiling.output_line_width',\n \"Max line width for the profiling output\",\n IntParam(512, lambda i: i > 0),\n in_c_key=False)\n\nAddConfigVar('profiling.min_memory_size',\n \"\"\"For the memory profile, do not print Apply nodes if the size\n of their outputs (in bytes) is lower than this threshold\"\"\",\n IntParam(1024, lambda i: i >= 0),\n in_c_key=False)\n\nAddConfigVar('profiling.min_peak_memory',\n \"\"\"The min peak memory usage of the order\"\"\",\n BoolParam(False),\n in_c_key=False)\n\nAddConfigVar('profiling.destination',\n \"\"\"\n File destination of the profiling output\n \"\"\",\n StrParam('stderr'),\n in_c_key=False)\n\nAddConfigVar('profiling.debugprint',\n \"\"\"\n Do a debugprint of the profiled functions\n \"\"\",\n BoolParam(False),\n in_c_key=False)\n\nAddConfigVar('profiling.ignore_first_call',\n \"\"\"\n Do we ignore the first call of a Theano function.\n \"\"\",\n BoolParam(False),\n in_c_key=False)\n\nAddConfigVar('optdb.position_cutoff',\n 'Where to stop eariler during optimization. It represent the'\n ' position of the optimizer where to stop.',\n FloatParam(numpy.inf),\n in_c_key=False)\n\nAddConfigVar('optdb.max_use_ratio',\n 'A ratio that prevent infinite loop in EquilibriumOptimizer.',\n FloatParam(5),\n in_c_key=False)\n\nAddConfigVar('gcc.cxxflags',\n \"Extra compiler flags for gcc\",\n StrParam(\"\"),\n # Added elsewhere in the c key only when needed.\n in_c_key=False)\n\nAddConfigVar('cmodule.warn_no_version',\n \"If True, will print a warning when compiling one or more Op \"\n \"with C code that can't be cached because there is no \"\n \"c_code_cache_version() function associated to at least one of \"\n \"those Ops.\",\n BoolParam(False),\n in_c_key=False)\n\nAddConfigVar('cmodule.remove_gxx_opt',\n \"If True, will remove the -O* parameter passed to g++.\"\n \"This is useful to debug in gdb modules compiled by Theano.\"\n \"The parameter -g is passed by default to g++\",\n BoolParam(False),\n # TODO: change so that this isn't needed.\n # This can be done by handing this in compile_args()\n in_c_key=True)\n\nAddConfigVar('cmodule.compilation_warning',\n \"If True, will print compilation warnings.\",\n BoolParam(False),\n in_c_key=False)\n\n\nAddConfigVar('cmodule.preload_cache',\n \"If set to True, will preload the C module cache at import time\",\n BoolParam(False, allow_override=False),\n in_c_key=False)\n\n\ndef default_blas_ldflags():\n global numpy\n try:\n if (hasattr(numpy.distutils, '__config__') and\n numpy.distutils.__config__):\n # If the old private interface is available use it as it\n # don't print information to the user.\n blas_info = numpy.distutils.__config__.blas_opt_info\n else:\n # We do this import only here, as in some setup, if we\n # just import theano and exit, with the import at global\n # scope, we get this error at exit: \"Exception TypeError:\n # \"'NoneType' object is not callable\" in <bound method\n # Popen.__del__ of <subprocess.Popen object at 0x21359d0>>\n # ignored\"\n\n # This happen with Python 2.7.3 |EPD 7.3-1 and numpy 1.8.1\n import numpy.distutils.system_info # noqa\n\n # We need to catch warnings as in some cases NumPy print\n # stuff that we don't want the user to see.\n # I'm not able to remove all printed stuff\n with warnings.catch_warnings(record=True):\n numpy.distutils.system_info.system_info.verbosity = 0\n blas_info = numpy.distutils.system_info.get_info(\"blas_opt\")\n\n # If we are in a EPD installation, mkl is available\n if \"EPD\" in sys.version:\n use_unix_epd = True\n if sys.platform == 'win32':\n return ' '.join(\n ['-L%s' % os.path.join(sys.prefix, \"Scripts\")] +\n # Why on Windows, the library used are not the\n # same as what is in\n # blas_info['libraries']?\n ['-l%s' % l for l in [\"mk2_core\", \"mk2_intel_thread\",\n \"mk2_rt\"]])\n elif sys.platform == 'darwin':\n # The env variable is needed to link with mkl\n new_path = os.path.join(sys.prefix, \"lib\")\n v = os.getenv(\"DYLD_FALLBACK_LIBRARY_PATH\", None)\n if v is not None:\n # Explicit version could be replaced by a symbolic\n # link called 'Current' created by EPD installer\n # This will resolve symbolic links\n v = os.path.realpath(v)\n\n # The python __import__ don't seam to take into account\n # the new env variable \"DYLD_FALLBACK_LIBRARY_PATH\"\n # when we set with os.environ['...'] = X or os.putenv()\n # So we warn the user and tell him what todo.\n if v is None or new_path not in v.split(\":\"):\n _logger.warning(\n \"The environment variable \"\n \"'DYLD_FALLBACK_LIBRARY_PATH' does not contain \"\n \"the '%s' path in its value. This will make \"\n \"Theano use a slow version of BLAS. Update \"\n \"'DYLD_FALLBACK_LIBRARY_PATH' to contain the \"\n \"said value, this will disable this warning.\"\n % new_path)\n\n use_unix_epd = False\n if use_unix_epd:\n return ' '.join(\n ['-L%s' % os.path.join(sys.prefix, \"lib\")] +\n ['-l%s' % l for l in blas_info['libraries']])\n\n # Canopy\n if \"Canopy\" in sys.prefix:\n subsub = 'lib'\n if sys.platform == 'win32':\n subsub = 'Scripts'\n lib_path = os.path.join(sys.base_prefix, subsub)\n if not os.path.exists(lib_path):\n # Old logic to find the path. I don't think we still\n # need it, but I don't have the time to test all\n # installation configuration. So I keep this as a fall\n # back in case the current expectation don't work.\n\n # This old logic don't work when multiple version of\n # Canopy is installed.\n p = os.path.join(sys.base_prefix, \"..\", \"..\", \"appdata\")\n assert os.path.exists(p), \"Canopy changed the location of MKL\"\n lib_paths = os.listdir(p)\n # Try to remove subdir that can't contain MKL\n for sub in lib_paths:\n if not os.path.exists(os.path.join(p, sub, subsub)):\n lib_paths.remove(sub)\n assert len(lib_paths) == 1, (\n \"Unexpected case when looking for Canopy MKL libraries\",\n p, lib_paths, [os.listdir(os.path.join(p, sub))\n for sub in lib_paths])\n lib_path = os.path.join(p, lib_paths[0], subsub)\n assert os.path.exists(lib_path), \"Canopy changed the location of MKL\"\n\n if sys.platform == \"linux2\" or sys.platform == \"darwin\":\n return ' '.join(\n ['-L%s' % lib_path] +\n ['-l%s' % l for l in blas_info['libraries']])\n elif sys.platform == 'win32':\n return ' '.join(\n ['-L%s' % lib_path] +\n # Why on Windows, the library used are not the\n # same as what is in blas_info['libraries']?\n ['-l%s' % l for l in [\"mk2_core\", \"mk2_intel_thread\",\n \"mk2_rt\"]])\n\n # Anaconda\n if \"Anaconda\" in sys.version and sys.platform == \"win32\":\n # If the \"mkl-service\" conda package (available\n # through Python package \"mkl\") is installed and\n # importable, then the libraries (installed by conda\n # package \"mkl-rt\") are actually available. Using\n # \"conda install mkl\" will install both, as well as\n # optimized versions of numpy and scipy.\n try:\n import mkl # noqa\n except ImportError as e:\n _logger.info('Conda mkl is not available: %s', e)\n else:\n # This branch is executed if no exception was raised\n lib_path = os.path.join(sys.prefix, 'DLLs')\n flags = ['-L%s' % lib_path]\n flags += ['-l%s' % l for l in [\"mkl_core\",\n \"mkl_intel_thread\",\n \"mkl_rt\"]]\n res = try_blas_flag(flags)\n if res:\n return res\n\n ret = (\n # TODO: the Gemm op below should separate the\n # -L and -l arguments into the two callbacks\n # that CLinker uses for that stuff. for now,\n # we just pass the whole ldflags as the -l\n # options part.\n ['-L%s' % l for l in blas_info.get('library_dirs', [])] +\n ['-l%s' % l for l in blas_info.get('libraries', [])] +\n blas_info.get('extra_link_args', []))\n # For some very strange reason, we need to specify -lm twice\n # to get mkl to link correctly. I have no idea why.\n if any('mkl' in fl for fl in ret):\n ret.extend(['-lm', '-lm'])\n res = try_blas_flag(ret)\n if res:\n return res\n\n # Some environment don't have the lib dir in LD_LIBRARY_PATH.\n # So add it.\n ret.extend(['-Wl,-rpath,' + l for l in\n blas_info.get('library_dirs', [])])\n res = try_blas_flag(ret)\n if res:\n return res\n\n # Try to add the anaconda lib directory to runtime loading of lib.\n # This fix some case with Anaconda 2.3 on Linux.\n # Newer Anaconda still have this problem but only have\n # Continuum in sys.version.\n if ((\"Anaconda\" in sys.version or\n \"Continuum\" in sys.version) and\n \"linux\" in sys.platform):\n lib_path = os.path.join(sys.prefix, 'lib')\n ret.append('-Wl,-rpath,' + lib_path)\n res = try_blas_flag(ret)\n if res:\n return res\n\n except KeyError:\n pass\n\n # Even if we could not detect what was used for numpy, or if these\n # libraries are not found, most Linux systems have a libblas.so\n # readily available. We try to see if that's the case, rather\n # than disable blas. To test it correctly, we must load a program.\n # Otherwise, there could be problem in the LD_LIBRARY_PATH.\n return try_blas_flag(['-lblas'])\n\n\ndef try_blas_flag(flags):\n from theano.gof.cmodule import GCC_compiler\n test_code = textwrap.dedent(\"\"\"\\\n extern \"C\" double ddot_(int*, double*, int*, double*, int*);\n int main(int argc, char** argv)\n {\n int Nx = 5;\n int Sx = 1;\n double x[5] = {0, 1, 2, 3, 4};\n double r = ddot_(&Nx, x, &Sx, x, &Sx);\n\n if ((r - 30.) > 1e-6 || (r - 30.) < -1e-6)\n {\n return -1;\n }\n return 0;\n }\n \"\"\")\n cflags = flags + ['-L' + d for d in theano.gof.cmodule.std_lib_dirs()]\n res = GCC_compiler.try_compile_tmp(\n test_code, tmp_prefix='try_blas_',\n flags=cflags, try_run=True)\n # res[0]: shows successful compilation\n # res[1]: shows successful execution\n if res and res[0] and res[1]:\n return ' '.join(flags)\n else:\n return \"\"\n\nAddConfigVar('blas.ldflags',\n \"lib[s] to include for [Fortran] level-3 blas implementation\",\n StrParam(default_blas_ldflags),\n # Added elsewhere in the c key only when needed.\n in_c_key=False)\n\nAddConfigVar(\n 'metaopt.verbose',\n \"Enable verbose output for meta optimizers\",\n theano.configparser.BoolParam(False),\n in_c_key=False)\n\nAddConfigVar('profile',\n \"If VM should collect profile information\",\n BoolParam(False),\n in_c_key=False)\n\nAddConfigVar('profile_optimizer',\n \"If VM should collect optimizer profile information\",\n BoolParam(False),\n in_c_key=False)\n\nAddConfigVar('profile_memory',\n \"If VM should collect memory profile information and print it\",\n BoolParam(False),\n in_c_key=False)\n\n\ndef filter_vm_lazy(val):\n if val == 'False' or val is False:\n return False\n elif val == 'True' or val is True:\n return True\n elif val == 'None' or val is None:\n return None\n else:\n raise ValueError('Valid values for an vm.lazy parameter '\n 'should be None, False or True, not `%s`.' % val)\n\nAddConfigVar('vm.lazy',\n \"Useful only for the vm linkers. When lazy is None,\"\n \" auto detect if lazy evaluation is needed and use the apropriate\"\n \" version. If lazy is True/False, force the version used between\"\n \" Loop/LoopGC and Stack.\",\n ConfigParam('None', filter_vm_lazy),\n in_c_key=False)\n\nAddConfigVar(\n 'warn.identify_1pexp_bug',\n 'Warn if Theano versions prior to 7987b51 (2011-12-18) could have '\n 'yielded a wrong result due to a bug in the is_1pexp function',\n BoolParam(warn_default('0.4.1')),\n in_c_key=False)\n\nAddConfigVar('on_shape_error',\n \"warn: print a warning and use the default\"\n \" value. raise: raise an error\",\n theano.configparser.EnumStr(\"warn\", \"raise\"),\n in_c_key=False)\n\nAddConfigVar(\n 'tensor.insert_inplace_optimizer_validate_nb',\n \"-1: auto, if graph have less then 500 nodes 1, else 10\",\n theano.configparser.IntParam(-1),\n in_c_key=False)\n\nAddConfigVar('experimental.local_alloc_elemwise',\n \"DEPRECATED: If True, enable the experimental\"\n \" optimization local_alloc_elemwise.\"\n \" Generates error if not True. Use\"\n \" optimizer_excluding=local_alloc_elemwise\"\n \" to dsiable.\",\n theano.configparser.BoolParam(\n True,\n is_valid=lambda x: x\n ),\n in_c_key=False)\n\n# False could make the graph faster but not as safe.\nAddConfigVar(\n 'experimental.local_alloc_elemwise_assert',\n \"When the local_alloc_elemwise is applied, add\"\n \" an assert to highlight shape errors.\",\n theano.configparser.BoolParam(True),\n in_c_key=False)\n\nAddConfigVar('scan.allow_gc',\n \"Allow/disallow gc inside of Scan (default: False)\",\n BoolParam(False),\n in_c_key=False)\n\nAddConfigVar('scan.allow_output_prealloc',\n \"Allow/disallow memory preallocation for outputs inside of scan \"\n \"(default: True)\",\n BoolParam(True),\n in_c_key=False)\n\nAddConfigVar('scan.debug',\n \"If True, enable extra verbose output related to scan\",\n BoolParam(False),\n in_c_key=False)\n\nAddConfigVar('pycuda.init',\n \"\"\"If True, always initialize PyCUDA when Theano want to\n initilize the GPU. Currently, we must always initialize\n PyCUDA before Theano do it. Setting this flag to True,\n ensure that, but always import PyCUDA. It can be done\n manually by importing theano.misc.pycuda_init before theano\n initialize the GPU device.\n \"\"\",\n BoolParam(False),\n in_c_key=False)\n\nAddConfigVar('cublas.lib',\n \"\"\"Name of the cuda blas library for the linker.\"\"\",\n StrParam('cublas'),\n # Added elsewhere in the c key only when needed.\n in_c_key=False)\n\nAddConfigVar('lib.cnmem',\n \"\"\"Do we enable CNMeM or not (a faster CUDA memory allocator).\n\n The parameter represent the start size (in MB or % of\n total GPU memory) of the memory pool.\n\n 0: not enabled.\n 0 < N <= 1: % of the total GPU memory (clipped to .985 for driver memory)\n > 0: use that number of MB of memory.\n\n \"\"\",\n # We should not mix both allocator, so we can't override\n FloatParam(0, lambda i: i >= 0, allow_override=False),\n in_c_key=False)\n\nAddConfigVar('compile.wait',\n \"\"\"Time to wait before retrying to aquire the compile lock.\"\"\",\n IntParam(5, lambda i: i > 0, allow_override=False),\n in_c_key=False)\n\n\ndef _timeout_default():\n return theano.config.compile.wait * 24\n\nAddConfigVar('compile.timeout',\n \"\"\"In seconds, time that a process will wait before deciding to\noverride an existing lock. An override only happens when the existing\nlock is held by the same owner *and* has not been 'refreshed' by this\nowner for more than this period. Refreshes are done every half timeout\nperiod for running processes.\"\"\",\n IntParam(_timeout_default, lambda i: i >= 0,\n allow_override=False),\n in_c_key=False)\n\n\ntry:\n p_out = output_subprocess_Popen([config.cxx, '-dumpversion'])\n gcc_version_str = p_out[0].strip().decode()\nexcept OSError:\n # Typically means gcc cannot be found.\n gcc_version_str = 'GCC_NOT_FOUND'\n\n\ndef local_bitwidth():\n \"\"\"\n Return 32 for 32bit arch, 64 for 64bit arch.\n\n By \"architecture\", we mean the size of memory pointers (size_t in C),\n *not* the size of long int, as it can be different.\n\n \"\"\"\n # Note that according to Python documentation, `platform.architecture()` is\n # not reliable on OS X with universal binaries.\n # Also, sys.maxsize does not exist in Python < 2.6.\n # 'P' denotes a void*, and the size is expressed in bytes.\n return struct.calcsize('P') * 8\n\n\ndef python_int_bitwidth():\n \"\"\"\n Return the bit width of Python int (C long int).\n\n Note that it can be different from the size of a memory pointer.\n\n \"\"\"\n # 'l' denotes a C long int, and the size is expressed in bytes.\n return struct.calcsize('l') * 8\n\n\ncompiledir_format_dict = {\n \"platform\": platform.platform(),\n \"processor\": platform.processor(),\n \"python_version\": platform.python_version(),\n \"python_bitwidth\": local_bitwidth(),\n \"python_int_bitwidth\": python_int_bitwidth(),\n \"theano_version\": theano.__version__,\n \"numpy_version\": numpy.__version__,\n \"gxx_version\": gcc_version_str.replace(\" \", \"_\"),\n \"hostname\": socket.gethostname()}\n\n\ndef short_platform(r=None, p=None):\n \"\"\"\n Return a safe shorter version of platform.platform().\n\n The old default Theano compiledir used platform.platform in\n it. This use the platform.version() as a substring. This is too\n specific as it contain the full kernel number and package\n version. This cause the compiledir to change each time there is a\n new linux kernel update. This function remove the part of platform\n that are too precise.\n\n If we have something else then expected, we do nothing. So this\n should be safe on other OS.\n\n Some example if we use platform.platform() direction. On the same\n OS, with just some kernel updates.\n\n compiledir_Linux-2.6.32-504.el6.x86_64-x86_64-with-redhat-6.6-Santiago-x86_64-2.6.6-64\n compiledir_Linux-2.6.32-431.29.2.el6.x86_64-x86_64-with-redhat-6.5-Santiago-x86_64-2.6.6-64\n compiledir_Linux-2.6.32-431.23.3.el6.x86_64-x86_64-with-redhat-6.5-Santiago-x86_64-2.6.6-64\n compiledir_Linux-2.6.32-431.20.3.el6.x86_64-x86_64-with-redhat-6.5-Santiago-x86_64-2.6.6-64\n compiledir_Linux-2.6.32-431.17.1.el6.x86_64-x86_64-with-redhat-6.5-Santiago-x86_64-2.6.6-64\n compiledir_Linux-2.6.32-431.11.2.el6.x86_64-x86_64-with-redhat-6.5-Santiago-x86_64-2.6.6-64\n compiledir_Linux-2.6.32-431.el6.x86_64-x86_64-with-redhat-6.5-Santiago-x86_64-2.6.6-64\n compiledir_Linux-2.6.32-358.23.2.el6.x86_64-x86_64-with-redhat-6.4-Santiago-x86_64-2.6.6-64\n compiledir_Linux-2.6.32-358.6.2.el6.x86_64-x86_64-with-redhat-6.4-Santiago-x86_64-2.6.6-64\n compiledir_Linux-2.6.32-358.6.1.el6.x86_64-x86_64-with-redhat-6.4-Santiago-x86_64-2.6.6-64\n compiledir_Linux-2.6.32-358.2.1.el6.x86_64-x86_64-with-redhat-6.4-Santiago-x86_64-2.6.6-64\n compiledir_Linux-2.6.32-358.el6.x86_64-x86_64-with-redhat-6.4-Santiago-x86_64-2.6.6-64\n compiledir_Linux-2.6.32-358.el6.x86_64-x86_64-with-redhat-6.4-Santiago-x86_64-2.6.6\n compiledir_Linux-2.6.32-279.14.1.el6.x86_64-x86_64-with-redhat-6.4-Santiago-x86_64-2.6.6\n compiledir_Linux-2.6.32-279.14.1.el6.x86_64-x86_64-with-redhat-6.3-Santiago-x86_64-2.6.6\n compiledir_Linux-2.6.32-279.5.2.el6.x86_64-x86_64-with-redhat-6.3-Santiago-x86_64-2.6.6\n compiledir_Linux-2.6.32-220.13.1.el6.x86_64-x86_64-with-redhat-6.3-Santiago-x86_64-2.6.6\n compiledir_Linux-2.6.32-220.13.1.el6.x86_64-x86_64-with-redhat-6.2-Santiago-x86_64-2.6.6\n compiledir_Linux-2.6.32-220.7.1.el6.x86_64-x86_64-with-redhat-6.2-Santiago-x86_64-2.6.6\n compiledir_Linux-2.6.32-220.4.1.el6.x86_64-x86_64-with-redhat-6.2-Santiago-x86_64-2.6.6\n\n We suppose the version are ``X.Y[.*]-(digit)*(anything)*``. We keep ``X.Y``\n and don't keep less important digit in the part before ``-`` and we remove\n the leading digit after the first ``-``.\n\n If the information don't fit that pattern, we do not modify platform.\n\n \"\"\"\n if r is None:\n r = platform.release()\n if p is None:\n p = platform.platform()\n sp = r.split('-')\n if len(sp) < 2:\n return p\n\n # For the split before the first -, we remove all learning digit:\n kernel_version = sp[0].split('.')\n if len(kernel_version) <= 2:\n # kernel version should always have at least 3 number.\n # If not, it use another semantic, so don't change it.\n return p\n sp[0] = '.'.join(kernel_version[:2])\n\n # For the split after the first -, we remove leading non-digit value.\n rest = sp[1].split('.')\n while len(rest):\n if rest[0].isdigit():\n del rest[0]\n else:\n break\n sp[1] = '.'.join(rest)\n\n # For sp[2:], we don't change anything.\n sr = '-'.join(sp)\n p = p.replace(r, sr)\n\n return p\ncompiledir_format_dict['short_platform'] = short_platform()\ncompiledir_format_keys = \", \".join(sorted(compiledir_format_dict.keys()))\ndefault_compiledir_format = (\"compiledir_%(short_platform)s-%(processor)s-\"\n \"%(python_version)s-%(python_bitwidth)s\")\n\nAddConfigVar(\"compiledir_format\",\n textwrap.fill(textwrap.dedent(\"\"\"\\\n Format string for platform-dependent compiled\n module subdirectory (relative to base_compiledir).\n Available keys: %s. Defaults to %r.\n \"\"\" % (compiledir_format_keys, default_compiledir_format))),\n StrParam(default_compiledir_format, allow_override=False),\n in_c_key=False)\n\n\ndef default_compiledirname():\n formatted = theano.config.compiledir_format % compiledir_format_dict\n safe = re.sub(\"[\\(\\)\\s,]+\", \"_\", formatted)\n return safe\n\n\ndef filter_base_compiledir(path):\n # Expand '~' in path\n return os.path.expanduser(str(path))\n\n\ndef filter_compiledir(path):\n # Expand '~' in path\n path = os.path.expanduser(path)\n # Turn path into the 'real' path. This ensures that:\n # 1. There is no relative path, which would fail e.g. when trying to\n # import modules from the compile dir.\n # 2. The path is stable w.r.t. e.g. symlinks (which makes it easier\n # to re-use compiled modules).\n path = os.path.realpath(path)\n if os.access(path, os.F_OK): # Do it exist?\n if not os.access(path, os.R_OK | os.W_OK | os.X_OK):\n # If it exist we need read, write and listing access\n raise ValueError(\n \"compiledir '%s' exists but you don't have read, write\"\n \" or listing permissions.\" % path)\n else:\n try:\n os.makedirs(path, 0o770) # read-write-execute for user and group\n except OSError as e:\n # Maybe another parallel execution of theano was trying to create\n # the same directory at the same time.\n if e.errno != errno.EEXIST:\n raise ValueError(\n \"Unable to create the compiledir directory\"\n \" '%s'. Check the permissions.\" % path)\n\n # PROBLEM: sometimes the initial approach based on\n # os.system('touch') returned -1 for an unknown reason; the\n # alternate approach here worked in all cases... it was weird.\n # No error should happen as we checked the permissions.\n init_file = os.path.join(path, '__init__.py')\n if not os.path.exists(init_file):\n try:\n open(init_file, 'w').close()\n except IOError as e:\n if os.path.exists(init_file):\n pass # has already been created\n else:\n e.args += ('%s exist? %s' % (path, os.path.exists(path)),)\n raise\n return path\n\n\ndef get_home_dir():\n \"\"\"\n Return location of the user's home directory.\n\n \"\"\"\n home = os.getenv('HOME')\n if home is None:\n # This expanduser usually works on Windows (see discussion on\n # theano-users, July 13 2010).\n home = os.path.expanduser('~')\n if home == '~':\n # This might happen when expanduser fails. Although the cause of\n # failure is a mystery, it has been seen on some Windows system.\n home = os.getenv('USERPROFILE')\n assert home is not None\n return home\n\n\n# On Windows we should avoid writing temporary files to a directory that is\n# part of the roaming part of the user profile. Instead we use the local part\n# of the user profile, when available.\nif sys.platform == 'win32' and os.getenv('LOCALAPPDATA') is not None:\n default_base_compiledir = os.path.join(os.getenv('LOCALAPPDATA'), 'Theano')\nelse:\n default_base_compiledir = os.path.join(get_home_dir(), '.theano')\n\n\nAddConfigVar(\n 'base_compiledir',\n \"platform-independent root directory for compiled modules\",\n ConfigParam(\n default_base_compiledir,\n filter=filter_base_compiledir,\n allow_override=False),\n in_c_key=False)\n\n\ndef default_compiledir():\n return os.path.join(\n theano.config.base_compiledir,\n default_compiledirname())\n\nAddConfigVar(\n 'compiledir',\n \"platform-dependent cache directory for compiled modules\",\n\n ConfigParam(\n default_compiledir,\n filter=filter_compiledir,\n allow_override=False),\n in_c_key=False)\n\n# Check if there are remaining flags provided by the user through THEANO_FLAGS.\nfor key in THEANO_FLAGS_DICT.keys():\n warnings.warn('Theano does not recognise this flag: {0}'.format(key))\n" ]
[ [ "numpy.product", "numpy.random.random", "numpy.asarray", "numpy.arange", "numpy.random.normal", "numpy.random.randn", "numpy.random.rand", "numpy.exp", "numpy.array", "numpy.zeros" ], [ "numpy.distutils.system_info.get_info" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
Babelscape/crocodile
[ "424ae33c68fdf22eb305e75b2f498831526d87f8" ]
[ "add_filter_relations.py" ]
[ "import jsonlines\nimport re\nimport transformers\nimport torch\nfrom tqdm import trange, tqdm\nimport argparse\nimport os, sys\n\ndef get_case_insensitive_key_value(input_dict, key):\n return next((value for dict_key, value in input_dict.items() if dict_key.lower() == key.lower()), None)\n\ndef filter_triples(model, tokenizer, texts):\n if max([len(text) for text in texts])>256:\n range_length = 12\n else:\n range_length = 64\n result = []\n for batch in range(0,len(texts),range_length):\n encoded_input = tokenizer(\n [ex[0] for ex in texts[batch: batch + range_length]], [ex[1] for ex in texts[batch: batch + range_length]],\n return_tensors=\"pt\",\n add_special_tokens=True,\n max_length=256,\n padding='longest',\n return_token_type_ids=False,\n truncation_strategy='only_first')\n for tensor in encoded_input:\n encoded_input[tensor] = encoded_input[tensor].cuda()\n with torch.no_grad(): # remove this if you need gradients.\n outputs = model(**encoded_input, return_dict=True, output_attentions=False, output_hidden_states = False)\n result.append(outputs['logits'].softmax(dim=1))\n del outputs\n logits = torch.cat(result)\n # if language == 'ko':\n # return logits.argmax(1) == get_case_insensitive_key_value(model.config.label2id, 'entailment')# [:,get_case_insensitive_key_value(model.config.label2id, 'entailment')]>0.75\n return logits[:,get_case_insensitive_key_value(model.config.label2id, 'entailment')]#>0.75\n\ndef prepare_triplet(subject_entity, object_entity, article_text, predicate):\n text_triplet = ''\n text_triplet += re.compile(\"(?<!\\d)\\.(?!\\d)\").split(article_text[:min(subject_entity['boundaries'][0], object_entity['boundaries'][0])])[-1]\n text_triplet += article_text[min(subject_entity['boundaries'][0], object_entity['boundaries'][0]):max(subject_entity['boundaries'][1], object_entity['boundaries'][1])]\n text_triplet += re.compile(\"(?<!\\d)\\.(?!\\d)\").split(article_text[max(subject_entity['boundaries'][1], object_entity['boundaries'][1]):])[0]\n if language == 'ko' or language == 'kosource':\n return (text_triplet.strip('\\n'), ' '.join([str(subject_entity['surfaceform']), str(object_entity['surfaceform']), str(predicate['surfaceform'])]))\n # return (text_triplet.strip('\\n'), ' '.join([str(object_entity['surfaceform']), str(predicate['surfaceform']), str(subject_entity['surfaceform'])]))\n return (text_triplet.strip('\\n'), ' '.join([str(subject_entity['surfaceform']), str(predicate['surfaceform']), str(object_entity['surfaceform'])]))\n\ndef main(folder_input = 'out/ko'):\n global language \n language = folder_input.split('/')[1]\n if language == 'ko' or language == 'kosource':\n model_name_or_path = '/home/huguetcabot/sentence_transformers/test-glue/XNLI'\n # model_name_or_path = '/home/huguetcabot/sentence_transformers/test-glue/run-1/checkpoint-3910'\n else:\n model_name_or_path = 'joeddav/xlm-roberta-large-xnli'\n\n tokenizer = transformers.AutoTokenizer.from_pretrained(\n model_name_or_path)\n model_config = transformers.AutoConfig.from_pretrained(\n model_name_or_path,\n # num_labels=2,\n output_hidden_states=True,\n output_attentions=True,\n )\n model = transformers.AutoModelForSequenceClassification.from_pretrained(model_name_or_path, config = model_config)\n model.cuda()\n model.eval()\n model.half()\n with jsonlines.open(f'out_clean/{\"/\".join(folder_input.split(\"/\")[1:])}.jsonl', mode='w') as writer:\n for k,j,y in os.walk(folder_input):\n for file_name in y:\n with jsonlines.open(k + '/' + file_name) as reader:\n for i, article in tqdm(enumerate(reader)):\n previous = []\n triples_list = []\n texts = []\n for triple in article['triples']:\n if triple['subject']['boundaries'] != None and triple['object']['boundaries'] != None and (triple['subject']['boundaries'], triple['object']['boundaries']) not in previous:\n previous.append((triple['subject']['boundaries'], triple['object']['boundaries']))\n triples_list.append(triple)\n texts.append(prepare_triplet(triple['subject'], triple['object'], article['text'], triple[\"predicate\"]))\n elif (triple['subject']['boundaries'], triple['object']['boundaries']) not in previous:\n distance = 1000000\n for entity in article['entities']:\n if entity['uri'] == triple['subject']['uri']:\n if abs(min(triple['object']['boundaries'])-min(entity['boundaries'])) < distance:\n subject_entity = entity\n distance = abs(min(triple['object']['boundaries'])-min(entity['boundaries']))\n triple['subject'] = subject_entity\n previous.append((triple['subject']['boundaries'], triple['object']['boundaries']))\n triples_list.append(triple)\n texts.append(prepare_triplet(subject_entity, triple['object'], article['text'], triple[\"predicate\"]))\n indexes = filter_triples(model, tokenizer, texts)\n if len(indexes) == 0:\n continue\n for pred, trip in zip(indexes, triples_list):\n trip['confidence'] = pred.item()\n # article['triples'] = [x for i,x in zip(indexes, triples_list) if (i == True) or x[\"predicate\"][\"uri\"] in [\"P569\", \"P570\"]]\n article['triples'] = triples_list\n writer.write(article)\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]),\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=__doc__)\n parser.add_argument(\"--folder_input\", \n help=\"input file\")\n args = parser.parse_args()\n\n main(args.folder_input)\n" ]
[ [ "torch.no_grad", "torch.cat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
panchiittp/pyross
[ "d5a455ae36a61e2fba29b30f1da774f1b284f1e2" ]
[ "tests/quick_test.py" ]
[ "#!python\n\"\"\"Unittesting for the pyross module. Run as python -m unittest pyross.test.\"\"\"\nimport sys\n#remove pwd from path that tries to import .pyx files\nfor i in sys.path:\n if 'pyross' in i or i == '':\n sys.path.remove(i)\n# print(sys.path)\nimport pyross\nimport unittest\nimport inspect\nimport numpy as np\nimport scipy as sp\n\n\nclass DeterministicTest(unittest.TestCase):\n \"\"\"testing deterministic.pyx.\"\"\"\n N = np.asarray([10000], dtype=np.float64)\n M = 1\n alpha = 0\n beta = 0.0071\n gIa = 0.008\n gIs = 0.008\n gI = 0.008\n gE = 0.007\n gIc = 0.1\n gIhp= 0.1\n gIsp= 0.1\n gIcp= 0.1\n gIh = 0.1\n gA = 0\n tE = 0\n tIa = 0\n tIs = 0\n Tf = 100\n Nf = 1000\n fsa = 0\n fh = 1\n sa = 0\n iaa = 0\n hh = 0\n cc = 0\n mm = 0\n tE = 0\n tA = 0\n tIa = 0\n tIs = 0\n kI = 1\n kE = 1\n k = 1\n ep = 0\n parameters = {'N': N, 'M': M, 'alpha': alpha,\n 'beta': beta, 'gIa': gIa, 'gIs': gIs,\n 'gIsp':gIsp,'gIhp':gIhp,'gIcp':gIcp,\n 'gI': gI, 'iaa': iaa,\n 'gE': gE, 'gA': gA, 'tE': tE,\n 'gIc': gIc, 'gIh': gIh, 'fh': fh,\n 'tIa': tIa, 'tIs': tIs, 'fsa': fsa,\n 'sa': sa, 'hh': hh, 'cc': cc,\n 'mm': mm, 'tA': tA, 'tE': tE,\n 'tIa': tIa, 'tIs': tIs, 'kI': kI,\n 'kE': kE, 'ep': ep, 'k': k}\n\n\n def __init__(self, *args, **kwargs):\n super(DeterministicTest, self).__init__(*args, **kwargs)\n # self.parameters = self.parameters\n\n def contactMatrix(self, t): return np.identity(self.M)\n\n def test_decay(self):\n \"\"\"\n Exponential decay from infected to recovered. Paths agree within .1%.\n \"\"\"\n SIR = pyross.deterministic.SIR(self.parameters, self.M, self.N)\n sim = SIR.simulate(np.zeros(1), np.zeros(1), self.N,\n self.contactMatrix, self.Tf,\n self.Nf, integrator='solve_ivp')\n time_points = np.linspace(0, self.Tf, self.Nf)\n exp_decay = sp.integrate.solve_ivp(lambda t, y: -self.gIs * y,\n (0, self.Tf), self.N,\n t_eval=time_points)\n diff = (sim['X'][:, 2] - exp_decay.y)/self.N\n self.assertTrue((diff < 0.001).all(), msg=\"paths differ > .1%\")\n\n def test_integrators(self):\n \"\"\"\n All integration methods produce paths which agree within .1%\n \"\"\"\n integrators = ['solve_ivp', 'odeint', 'odespy',\n 'odespy-rkf45', 'odespy-rk4']\n paths = []\n model = pyross.deterministic.SIR(self.parameters, self.M, self.N)\n for integrator in integrators:\n try:\n data = model.simulate(np.zeros(1), np.zeros(1), self.N,\n self.contactMatrix, self.Tf,\n self.Nf, integrator=integrator)\n except ImportError:\n print(f\"{integrator} is not installed, skipping...\")\n pass\n paths.append(data['X'])\n for i in range(len(paths)):\n for j in range(len(paths)):\n if i != j:\n diff = (paths[i]-paths[j])/self.N\n self.assertTrue((np.asarray(diff) < 0.001).all(),\n msg=f\"path {i} not equal to path {j}\")\n\n def test_SIRS(self):\n \"\"\"Test to make sure SIRS collapses down to SIR\"\"\"\n self.parameters['ep'] = 0\n self.parameters['sa'] = 0\n self.parameters['iaa'] = 0\n SIR = pyross.deterministic.SIR(self.parameters, self.M, self.N)\n SIRS = pyross.deterministic.SIRS(self.parameters, self.M, self.N)\n SIRdata = SIR.simulate(self.N, np.ones(1), np.zeros(1),\n self.contactMatrix, self.Tf,\n self.Nf)['X']\n SIRSdata = SIRS.simulate(self.N, np.ones(1), np.zeros(1),\n self.contactMatrix, self.Tf,\n self.Nf)['X']\n self.assertTrue((SIRdata-SIRSdata[:, 0:3] < 0.001).all(),\n msg=\"paths differ > .1%\")\n\n def test_init_models(self):\n \"\"\"Test initialisation of deterministic models\"\"\"\n deterministic_models = dict(inspect.getmembers(pyross.deterministic,\n inspect.isclass))\n for name, model in deterministic_models.items():\n if name.startswith('S') and not 'Spp':\n m = model(self.parameters, self.M, self.N)\n\n def test_run_models(self):\n \"\"\"Runs all deterministic models\"\"\"\n deterministic_models = dict(inspect.getmembers(pyross.deterministic,\n inspect.isclass))\n traj_dict={}\n for name, model in deterministic_models.items():\n if name.startswith('S') and not 'Spp':\n m = model(self.parameters, self.M, self.N)\n x0 = np.array([*self.N, *np.ones(self.M),\n *np.zeros(m.nClass -2)], dtype=np.float64).reshape((m.nClass,1))\n traj_dict[name] = m.simulate(*x0, self.contactMatrix, 100, 100)\n\n\nclass StochasticTest(unittest.TestCase):\n \"\"\"testing stochastic.pyx\"\"\"\n nloops=10\n iinfec = 3000\n Tf = 10\n\n def __init__(self, *args, **kwargs):\n super(StochasticTest, self).__init__(*args, **kwargs)\n self.parameters = DeterministicTest.parameters\n self.stochastic_models = dict(inspect.getmembers(pyross.stochastic,\n inspect.isclass))\n\n def contactMatrix(self, t): return np.identity(self.parameters['M'])\n\n def test_init_models(self):\n \"\"\"Initializes all stochastic models\"\"\"\n traj_dict={}\n for name, model in self.stochastic_models.items():\n if name.startswith('S'):\n params, M, N = self.parameters, self.parameters['M'], self.parameters['N']\n m = model(params, M, N)\n # x0 = np.array([*self.N, *np.ones(self.M),\n # *np.zeros(m.nClass -2)], dtype=np.float64).reshape((m.nClass,1))\n # traj_dict[name] = m.simulate(*x0, self.contactMatrix, 100, 100)\n\n def test_run_models(self):\n \"\"\"Runs all stochastic models\"\"\"\n traj_dict={}\n for name, model in self.stochastic_models.items():\n \n if name.startswith('S'):\n params, M, N = self.parameters, self.parameters['M'], self.parameters['N']\n m = model(params, M, N + M*10)\n x0 = np.array([*self.parameters['N'],\n *np.ones(self.parameters['M'])*10,\n *np.zeros(m.nClass -2)],\n dtype=np.float64).reshape((m.nClass,1))\n traj_dict[name] = m.simulate(*x0, self.contactMatrix, 100, 100)\n \n def test_stochastic_mean_gillespie(self):\n \"\"\"Runs stochastic models a few times and compares mean to \n deterministic\"\"\"\n deterministic_models = dict(inspect.getmembers(pyross.deterministic,\n inspect.isclass))\n params, M, N = self.parameters, self.parameters['M'], self.parameters['N']\n for name, model in self.stochastic_models.items():\n if name.startswith('S'):\n mS = model(params, M, N + M*self.iinfec)\n # print(mS.kk)\n mD = deterministic_models[name](params, M, N + M*self.iinfec)\n x0 = np.array([*self.parameters['N'],\n *np.ones(self.parameters['M'])*self.iinfec,\n *np.zeros(mS.nClass -2)],\n dtype=np.float64).reshape((mS.nClass,1))\n trajectories = []\n for i in range(self.nloops):\n traj = mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf)['X']\n trajectories.append(traj)\n traj_mean = np.mean(trajectories, axis=0)[:-1]\n mean = mD.simulate(*x0, self.contactMatrix, self.Tf, self.Tf)['X']\n absdiff = np.abs(traj_mean -mean)/(N*self.Tf)\n # print(name, np.sum(absdiff[:,:-1]))\n self.assertTrue(np.sum(absdiff[:,:-1])<0.01, \n msg=f\"{name} model disagreement\")\n\n def test_stochastic_mean_tau(self):\n \"\"\"Runs stochastic models a few times and compares mean to \n deterministic using tau leaping\"\"\"\n deterministic_models = dict(inspect.getmembers(pyross.deterministic,\n inspect.isclass))\n params, M, N = self.parameters, self.parameters['M'], self.parameters['N']\n for name, model in self.stochastic_models.items():\n if name.startswith('S'):\n mS = model(params, M, N + M*self.iinfec)\n # print(mS.kk)\n mD = deterministic_models[name](params, M, N + M*self.iinfec)\n x0 = np.array([*self.parameters['N'],\n *np.ones(self.parameters['M'])*self.iinfec,\n *np.zeros(mS.nClass -2)],\n dtype=np.float64).reshape((mS.nClass,1))\n trajectories = []\n for i in range(self.nloops):\n traj = mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf,\n method='tau_leaping')['X']\n trajectories.append(traj)\n traj_mean = np.mean(trajectories, axis=0)[:-1]\n mean = mD.simulate(*x0, self.contactMatrix, self.Tf, self.Tf)['X']\n absdiff = np.abs(traj_mean -mean)/(N*self.Tf)\n # print(name, np.sum(absdiff[:,:-1]))\n self.assertTrue(np.sum(absdiff[:,:-1])<0.01, \n msg=f\"{name} model disagreement\")\n\n def test_stochastic_integrators(self):\n \"\"\"Compare tau leaping to Gillespie.\n This will fail because there is a problem with SIkR\n Also, difference is an order of magnitude greater than\n Gillespie from the mean.\n \"\"\"\n self.nloops=10\n params, M, N = self.parameters, self.parameters['M'], self.parameters['N']\n for name, model in self.stochastic_models.items():\n if name.startswith('S'):\n mS = model(params, M, N + M*self.iinfec)\n x0 = np.array([*self.parameters['N'],\n *np.ones(self.parameters['M'])*self.iinfec,\n *np.zeros(mS.nClass -2)],\n dtype=np.float64).reshape((mS.nClass,1))\n gtraj = []\n tautraj = []\n for i in range(self.nloops):\n gtraj.append(mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf, \n method='gillespie')['X'])\n tautraj.append(mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf, \n method='tau_leaping', epsilon=1E-3)['X'])\n gmean = np.sum(gtraj, axis=0)\n taumean= np.sum(tautraj, axis=0)\n absdiff = np.abs(gmean - taumean)/(N*self.Tf)\n # print(name, np.sum(absdiff), np.shape(gmean), np.shape(taumean))\n self.assertTrue(np.sum(absdiff)<.1, msg=f\"{name} model disagreement\")\n\n\nclass ControlTest(unittest.TestCase):\n \"\"\"testing control.pyx\"\"\"\n \n def __init__(self, *args, **kwargs):\n super(ControlTest, self).__init__(*args, **kwargs)\n self.parameters = DeterministicTest.parameters\n self.control_models = dict(inspect.getmembers(pyross.control,\n inspect.isclass))\n\n def contactMatrix(self, t): return np.identity(self.parameters['M'])\n\n def test_init_models(self):\n \"\"\"Initializes all control models\"\"\"\n for name, model in self.control_models.items():\n if name.startswith('S'):\n params, M, N = self.parameters, self.parameters['M'], self.parameters['N']\n m = model(params, M, N)\n\n\nclass InferenceTest(unittest.TestCase):\n \"\"\"testing inference.pyx\"\"\"\n \n def __init__(self, *args, **kwargs):\n super(InferenceTest, self).__init__(*args, **kwargs)\n self.parameters = DeterministicTest.parameters\n self.control_models = dict(inspect.getmembers(pyross.inference,\n inspect.isclass))\n \n def contactMatrix(self, t): return np.identity(self.parameters['M'])\n\n def test_init_models(self):\n \"\"\"Initializes all inference models\"\"\"\n for name, model in self.control_models.items():\n if name.startswith('S') and name != \"SIR_type\":\n params, M, Ni = self.parameters, self.parameters['M'], self.parameters['N']\n N = int(np.sum(Ni))\n fi = Ni/N\n steps = 1\n m = model(params, M, fi, N, steps)\n\n\nclass ForecastTest(unittest.TestCase):\n \"\"\"testing forcast.pyx\"\"\"\n \n def __init__(self, *args, **kwargs):\n super(ForecastTest, self).__init__(*args, **kwargs)\n self.parameters = DeterministicTest.parameters\n self.control_models = dict(inspect.getmembers(pyross.forecast,\n inspect.isclass))\n self.parameters['cov'] = np.identity(2)\n \n def contactMatrix(self, t): return np.identity(self.parameters['M'])\n\n def test_init_models(self):\n \"\"\"Initializes all forcast models\"\"\"\n for name, model in self.control_models.items():\n if name.startswith('S') and name != \"SIR_type\":\n params, M, Ni = self.parameters, self.parameters['M'], self.parameters['N']\n N = int(np.sum(Ni))\n fi = Ni/N\n steps = 1\n m = model(params, M, Ni)\n\n\nclass UtilsPythonTest(unittest.TestCase):\n \"\"\"Testing the minimization function in utils_python.py\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(UtilsPythonTest, self).__init__(*args, **kwargs)\n\n def test_minimization(self):\n \"\"\"Test the minimization(...) function in utils_python.py with a few simple examples\"\"\"\n\n # A simple example\n f1 = lambda x, grad=0: 1 + np.linalg.norm(x)**2 \n # A multi-modal example\n f2 = lambda x, grad=0: 1 + np.linalg.norm(x)**2 + 0.1*np.abs(np.sin(4*np.pi*np.linalg.norm(x)))\n\n # Test global optimisation\n guess = np.array([1.0, 1.0])\n bounds = np.array([[-2.0, 2.0], [-2.0, 2.0]])\n x, y = pyross.utils_python.minimization(f1, guess, bounds, enable_global=True, enable_local=False,\n ftol=1e-4, cma_random_seed=1, verbose=False)\n self.assertTrue(np.abs(y - 1.0) < 1e-3)\n\n x, y = pyross.utils_python.minimization(f2, guess, bounds, enable_global=True, enable_local=False,\n ftol=1e-4, verbose=False, cma_random_seed=2)\n self.assertTrue(np.abs(y - 1.0) < 1e-3)\n\n # Test local optimisation\n guess = np.array([2.0, 2.0])\n bounds = np.array([[-5.0, 5.0], [-5.0, 5.0]])\n x, y = pyross.utils_python.minimization(f1, guess, bounds, enable_global=False, enable_local=True,\n ftol=1e-5, verbose=False)\n self.assertTrue(np.abs(y - 1.0) < 1e-4)\n\n # And now combined\n x, y = pyross.utils_python.minimization(f2, guess, bounds, enable_global=True, enable_local=True,\n ftol=1e-5, global_ftol_factor=100, verbose=False, cma_random_seed=4)\n self.assertTrue(np.abs(y - 1.0) < 1e-4)\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.abs", "numpy.linspace", "numpy.asarray", "scipy.integrate.solve_ivp", "numpy.linalg.norm", "numpy.ones", "numpy.identity", "numpy.mean", "numpy.array", "numpy.zeros", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.10", "1.4", "1.9", "1.5", "1.2", "1.7", "1.0", "1.3", "1.8" ], "tensorflow": [] } ]
jhong93/vpd
[ "1ed3e8631c46e078ecb9a7756dba1f1c14aead5b", "1ed3e8631c46e078ecb9a7756dba1f1c14aead5b" ]
[ "dummy_2d_features.py", "vipe_dataset/keypoint.py" ]
[ "#!/usr/bin/env python3\n\n\"\"\"\nConvert COCO17 2D poses to dummy embeddings for 2D-VPD.\n\"\"\"\n\nimport os\nimport argparse\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom util.io import store_pickle, load_gz_json\nfrom vipe_dataset.dataset_base import normalize_2d_skeleton\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('pose_dir', type=str)\n parser.add_argument('-o', '--out_dir', type=str)\n parser.add_argument('--no_flip', action='store_true')\n return parser.parse_args()\n\n\ndef main(pose_dir, out_dir, no_flip):\n for video_name in tqdm(sorted(os.listdir(pose_dir))):\n if video_name.endswith('.json.gz'):\n # Flat case\n video_pose_path = os.path.join(pose_dir, video_name)\n video_name = video_name.split('.json.gz')[0]\n else:\n # Nested case\n video_pose_path = os.path.join(\n pose_dir, video_name, 'coco_keypoints.json.gz')\n\n if not os.path.exists(video_pose_path):\n print('Not found:', video_pose_path)\n continue\n\n embs = []\n for frame_num, pose_data in load_gz_json(video_pose_path):\n raw_2d = np.array(pose_data[0][-1])\n pose_2d = normalize_2d_skeleton(raw_2d, False, to_tensor=False)\n emb = pose_2d[:, :2].flatten() # drop confidence column\n meta = {'is_2d': True, 'kp_score': np.mean(pose_2d[:, 2] + 0.5).item()}\n if not no_flip:\n emb2 = normalize_2d_skeleton(\n raw_2d, True, to_tensor=False)[:, :2].flatten()\n emb = np.stack([emb, emb2])\n embs.append((frame_num, emb, meta))\n\n if out_dir is not None:\n os.makedirs(out_dir, exist_ok=True)\n store_pickle(os.path.join(out_dir, video_name + '.emb.pkl'), embs)\n print('Done!')\n\n\nif __name__ == '__main__':\n main(**vars(get_args()))", "import os\nimport math\nimport random\nfrom collections import Counter, defaultdict\nimport torch\nfrom torch.utils.data import Dataset\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom . import human36m, people3d, nba2k, amass\nfrom .util import flip_skeleton_offsets\nfrom .dataset_base import (\n D3KeypointDataset, MAX_NEG_SAMPLE_TRIES, is_good_3d_neg_sample,\n normalize_3d_offsets, normalize_2d_skeleton, get_3d_features,\n NUM_COCO_KEYPOINTS_ORIG)\nfrom util.io import load_pickle, load_gz_json\n\n\nUSE_EXTREMITIES = True\nUSE_ROOT_DIRECTIONS = True\n\nCAMERA_AUG_ELEVATION_RANGE = (-np.pi / 6, np.pi / 6)\nCAMERA_AUG_ROLL_RANGE = (-np.pi / 6, np.pi / 6)\n\n\ndef _random_project_3d(coco_xyz, elevation=None, roll=None):\n # Point the camera at the torso\n # coco_xyz -= np.mean([\n # skl.left_arm, skl.right_arm, skl.left_up_leg, skl.right_up_leg],\n # axis=0)\n\n # Rotate around z\n a = np.random.uniform(-np.pi, np.pi)\n cos_a = math.cos(a)\n sin_a = math.sin(a)\n rot_z_t = np.array([\n [cos_a, sin_a, 0],\n [-sin_a, cos_a, 0],\n [0, 0, 1]\n ])\n coco_xyz = coco_xyz.dot(rot_z_t)\n\n if elevation is not None:\n # Rotate around x\n b = np.random.uniform(*elevation)\n cos_b = math.cos(b)\n sin_b = math.sin(b)\n rot_x_t = np.array([\n [1, 0, 0],\n [0, cos_b, sin_b],\n [0, -sin_b, cos_b],\n ])\n coco_xyz = coco_xyz.dot(rot_x_t)\n\n if roll is not None:\n # Rotate around y\n c = np.random.uniform(*roll)\n cos_c = math.cos(c)\n sin_c = math.sin(c)\n rot_y_t = np.array([\n [cos_c, 0, sin_c],\n [0, 1, 0],\n [-sin_c, 0, cos_c],\n ])\n coco_xyz = coco_xyz.dot(rot_y_t)\n\n # Randomize confidence scores\n conf = np.random.uniform(0.5, 1, size=NUM_COCO_KEYPOINTS_ORIG)\n conf[1:5] = 0\n\n # Project into 2D\n coco_xzc = np.hstack((coco_xyz[:, [0, 2]], conf[:, None]))\n\n # Invert z to convert to pixel coordinates\n coco_xzc[:, 1] *= -1\n\n assert coco_xzc.shape == (NUM_COCO_KEYPOINTS_ORIG, 3)\n return coco_xzc\n\n\ndef _sample_camera_pair(all_cameras_and_2d_poses):\n if len(all_cameras_and_2d_poses) > 1:\n views = np.random.choice(\n range(len(all_cameras_and_2d_poses)), 2, replace=False)\n else:\n views = (0, 0)\n camera1, pose_2d1 = all_cameras_and_2d_poses[views[0]]\n camera2, pose_2d2 = all_cameras_and_2d_poses[views[1]]\n return camera1, camera2, pose_2d1, pose_2d2\n\n\nclass Human36MDataset(D3KeypointDataset):\n\n def get_sequence(self, index, camera=None, stride=25):\n (person, action), frames = self.get(index)\n seq_poses = self.poses_3d[(person, action)]\n\n sequence = []\n for i, (frame_num, all_cameras_and_2d_poses) in enumerate(frames):\n if i % stride != 0:\n continue\n\n if camera is None:\n # Choose a random camera\n camera, pose2d = random.choice(all_cameras_and_2d_poses)\n else:\n for camera2, pose2d in all_cameras_and_2d_poses:\n if camera2 == camera:\n break\n else:\n continue\n\n # Load 3d ground truth\n if frame_num >= len(seq_poses):\n print('Invalid frame: {} > {} (max_frame: {})'.format(\n frame_num, len(seq_poses), frames[-1][0]))\n break\n _, rotation, abs_kp_offsets = seq_poses[frame_num]\n norm_kp_offsets, kp_dists = normalize_3d_offsets(abs_kp_offsets)\n\n sequence.append({\n 'person': person,\n 'action': action,\n 'frame': frame_num,\n 'rotation': rotation,\n 'kp_offsets': norm_kp_offsets,\n 'kp_offset_norms': kp_dists,\n 'camera': camera,\n 'pose': normalize_2d_skeleton(\n pose2d, False, include_bone_features=self.embed_bones)\n })\n return sequence\n\n @staticmethod\n def _random_project_3d(raw_kp_offsets):\n skl = human36m.decode_skeleton_from_offsets(raw_kp_offsets)\n coco_xyz = np.stack([\n skl.nose,\n skl.nose, # No eyes in h36m\n skl.nose,\n skl.nose, # No ears in h36m\n skl.nose,\n skl.left_arm,\n skl.right_arm,\n skl.left_forearm,\n skl.right_forearm,\n skl.left_hand,\n skl.right_hand,\n skl.left_up_leg,\n skl.right_up_leg,\n skl.left_leg,\n skl.right_leg,\n skl.left_foot,\n skl.right_foot,\n ])\n return _random_project_3d(\n coco_xyz, elevation=CAMERA_AUG_ELEVATION_RANGE,\n roll=CAMERA_AUG_ROLL_RANGE)\n\n def _get_negative_sample(self, frames, seq_poses, norm_kp_offsets):\n # Try to find a pose in the same sequence that differs the current one\n neg_flip = False\n for _ in range(MAX_NEG_SAMPLE_TRIES):\n neg_frame_num, neg_cameras_and_2d_poses = random.choice(frames)\n if neg_frame_num >= len(seq_poses):\n continue\n neg_raw_offsets = seq_poses[neg_frame_num][-1]\n neg_flip = self._should_flip()\n if is_good_3d_neg_sample(\n normalize_3d_offsets(\n flip_skeleton_offsets(neg_raw_offsets, human36m.XFLIP_ROWS)\n if neg_flip else neg_raw_offsets\n )[0],\n norm_kp_offsets,\n ignore=None if USE_EXTREMITIES else human36m.EXTREMITY_ROWS\n ):\n if self._should_project():\n # Need to project with 3d before flipping\n neg_pose2d = Human36MDataset._random_project_3d(neg_raw_offsets)\n else:\n neg_pose2d = random.choice(neg_cameras_and_2d_poses)[1]\n break\n else:\n neg_pose2d = None\n self._log_neg_sample_fail()\n return neg_pose2d, neg_flip\n\n def __getitem__(self, index):\n self.sample_count += 1\n\n (person, action), frames = self.get(index)\n seq_poses = self.poses_3d[(person, action)]\n flip = self._should_flip()\n\n while True:\n frame_num, all_cameras_and_2d_poses = random.choice(frames)\n if frame_num < len(seq_poses):\n break\n assert len(all_cameras_and_2d_poses) > 0\n\n # Load 3d ground truth\n _, rotation, raw_kp_offsets = seq_poses[frame_num]\n\n # Flip and normalize 3D\n abs_kp_offsets = raw_kp_offsets\n if flip:\n rotation = -rotation\n abs_kp_offsets = flip_skeleton_offsets(\n abs_kp_offsets, human36m.XFLIP_ROWS)\n\n # Sample two random cameras\n camera1, camera2, pose_2d1, pose_2d2 = _sample_camera_pair(\n all_cameras_and_2d_poses)\n\n # Replace with random projections if enabled\n if self._should_project():\n camera1 = ''\n pose_2d1 = Human36MDataset._random_project_3d(raw_kp_offsets)\n if self._should_project():\n camera2 = ''\n pose_2d2 = Human36MDataset._random_project_3d(raw_kp_offsets)\n\n # Negative sample\n neg_pose2d, neg_flip = self._get_negative_sample(\n frames, seq_poses, normalize_3d_offsets(abs_kp_offsets)[0])\n\n norm_pose1 = normalize_2d_skeleton(\n pose_2d1, flip, include_bone_features=self.embed_bones)\n ret = {\n 'kp_features': get_3d_features(\n abs_kp_offsets, human36m, include_extremities=USE_EXTREMITIES,\n include_root_directions=USE_ROOT_DIRECTIONS),\n 'pose1': norm_pose1,\n 'pose2': normalize_2d_skeleton(\n pose_2d2, flip, include_bone_features=self.embed_bones),\n 'pose_neg': torch.zeros_like(norm_pose1) if neg_pose2d is None\n else normalize_2d_skeleton(\n neg_pose2d, neg_flip,\n include_bone_features=self.embed_bones),\n 'pose_neg_is_valid': int(neg_pose2d is not None)\n }\n if self.debug_info:\n ret.update({\n 'person': person,\n 'action': action,\n 'frame': frame_num,\n 'rotation': rotation,\n 'camera1': camera1,\n 'camera2': camera2,\n 'is_flip': flip\n })\n return ret\n\n @staticmethod\n def load_default(pose_2d_dir, pose_3d_file, embed_bones, augment_camera):\n # These do not have 3d poses\n exclude_actions = {'_ALL', '_ALL 1'}\n\n pose_2d = defaultdict(lambda: defaultdict(list))\n for pose_2d_file in tqdm(\n os.listdir(pose_2d_dir), desc='Loading human3.6m'\n ):\n person, action, camera, _ = pose_2d_file.split('.', 3)\n if action in exclude_actions:\n continue\n seq_pose = load_gz_json(os.path.join(pose_2d_dir, pose_2d_file))\n for frame, pose_data in seq_pose:\n if len(pose_data) > 0:\n kp = np.array(pose_data[0][-1], dtype=np.float32)\n pose_2d[(person, action)][frame].append((camera, kp))\n pose_2d = [(k, list(v.items())) for k, v in pose_2d.items()]\n pose_3d = load_pickle(pose_3d_file)\n\n all_people = {x[0][0] for x in pose_2d}\n val_people = {'S9', 'S11'}\n print('{} / {} people reserved for validation'.format(\n len(val_people), len(all_people)))\n assert val_people <= all_people\n\n train_2d = [x for x in pose_2d if x[0][0] not in val_people]\n train_2d.sort()\n train_dataset = Human36MDataset(\n train_2d, pose_3d, True, augment_camera, embed_bones, 20000)\n\n val_2d = [x for x in pose_2d if x[0][0] in val_people]\n val_2d.sort()\n val_dataset = Human36MDataset(\n val_2d, pose_3d, True, augment_camera, embed_bones, 2000)\n return train_dataset, val_dataset\n\n# Common format for amass, 3dpeople, and nba2k\ndef _load_person_poses(pose_2d_dir, pose_2d_file):\n person_pose = []\n for frame, all_camera_pose_data in sorted(\n load_gz_json(os.path.join(pose_2d_dir, pose_2d_file))\n ):\n frame_camera_pose = []\n for camera, pose_data in all_camera_pose_data:\n assert len(pose_data) > 0\n if len(pose_data) > 0:\n kp = np.array(pose_data[-1], dtype=np.float32)\n frame_camera_pose.append((camera, kp))\n person_pose.append((frame, frame_camera_pose))\n assert len(person_pose) > 0\n return person_pose\n\n\nclass NBA2kDataset(D3KeypointDataset):\n\n CAMERA_AUG_PROB = 0.5\n CAMERA_AUG_ELEVATION_RANGE = (-np.pi / 6, np.pi / 6)\n\n @staticmethod\n def _random_project_3d(raw_kp_offsets):\n skl = nba2k.decode_skeleton_from_offsets(raw_kp_offsets)\n coco_xyz = np.stack([\n skl.nose,\n skl.leye,\n skl.reye,\n skl.lear,\n skl.rear,\n skl.lshoulder,\n skl.rshoulder,\n skl.lelbow,\n skl.relbow,\n skl.lwrist,\n skl.rwrist,\n skl.lhip,\n skl.rhip,\n skl.lknee,\n skl.rknee,\n skl.lankle,\n skl.rankle,\n ])\n return _random_project_3d(\n coco_xyz, elevation=CAMERA_AUG_ELEVATION_RANGE,\n roll=CAMERA_AUG_ROLL_RANGE)\n\n def get_sequence(self, index, camera=None, stride=4):\n person_key, frame_data = self.get(index)\n person_3d_poses = self.poses_3d[person_key]\n\n sequence = []\n for i, (frame_num, all_cameras_and_poses) in enumerate(frame_data):\n if i % stride != 0:\n continue\n\n # Load 3d ground truth\n _, rotation, abs_kp_offsets = person_3d_poses[frame_num]\n norm_kp_offsets, kp_dists = normalize_3d_offsets(abs_kp_offsets)\n\n sequence.append({\n 'person': person_key[0],\n 'action': '',\n 'camera': '',\n 'frame': frame_num,\n 'rotation': rotation,\n 'kp_offsets': norm_kp_offsets,\n 'kp_offset_norms': kp_dists,\n 'pose': normalize_2d_skeleton(\n all_cameras_and_poses[0][-1], False,\n include_bone_features=self.embed_bones)\n })\n return sequence\n\n def _get_negative_sample(self, frame_data, seq_poses, norm_kp_offsets):\n # Try to find a pose in the same sequence that differs the current one\n neg_flip = False\n for _ in range(MAX_NEG_SAMPLE_TRIES):\n neg_frame_num, _ = random.choice(frame_data)\n neg_raw_offsets = seq_poses[neg_frame_num][-1]\n neg_flip = self._should_flip()\n if is_good_3d_neg_sample(\n normalize_3d_offsets(\n flip_skeleton_offsets(neg_raw_offsets, nba2k.XFLIP_ROWS)\n if neg_flip else neg_raw_offsets\n )[0],\n norm_kp_offsets,\n ignore=None if USE_EXTREMITIES else nba2k.EXTREMITY_ROWS\n ):\n neg_pose2d = NBA2kDataset._random_project_3d(neg_raw_offsets)\n break\n else:\n neg_pose2d = None\n self._log_neg_sample_fail()\n return neg_pose2d, neg_flip\n\n def __getitem__(self, index):\n self.sample_count += 1\n\n person_key, frame_data = self.get(index)\n person_3d_poses = self.poses_3d[person_key]\n frame_num, all_cameras_and_poses = random.choice(frame_data)\n pose_2d = all_cameras_and_poses[0][-1]\n flip = self._should_flip()\n\n # Load 3d ground truth\n _, rotation, raw_kp_offsets = person_3d_poses[frame_num]\n\n # Flip and normalize 3D\n abs_kp_offsets = raw_kp_offsets\n if flip:\n rotation = -rotation\n abs_kp_offsets = flip_skeleton_offsets(\n abs_kp_offsets, nba2k.XFLIP_ROWS)\n\n if self._should_project():\n pose_2d = NBA2kDataset._random_project_3d(raw_kp_offsets)\n\n ret = {'kp_features': get_3d_features(\n abs_kp_offsets, nba2k, include_extremities=USE_EXTREMITIES,\n include_root_directions=USE_ROOT_DIRECTIONS),\n 'pose1': normalize_2d_skeleton(\n pose_2d, flip, include_bone_features=self.embed_bones)}\n\n if self.augment_camera:\n pose_2d2 = NBA2kDataset._random_project_3d(raw_kp_offsets)\n ret['pose2'] = normalize_2d_skeleton(\n pose_2d2, flip, include_bone_features=self.embed_bones)\n\n neg_pose2d, neg_flip = self._get_negative_sample(\n frame_data, person_3d_poses,\n normalize_3d_offsets(abs_kp_offsets)[0])\n ret['pose_neg'] = (\n torch.zeros_like(pose_2d) if neg_pose2d is None else\n normalize_2d_skeleton(neg_pose2d, neg_flip,\n include_bone_features=self.embed_bones))\n ret['pose_neg_is_valid'] = int(neg_pose2d is not None)\n\n if self.debug_info:\n ret.update({\n 'person': person_key[0],\n 'action': '',\n 'frame': frame_num,\n 'rotation': rotation,\n 'camera1': '', 'camera2': '',\n 'is_flip': flip\n })\n return ret\n\n @staticmethod\n def load_default(pose_2d_dir, pose_3d_file, embed_bones):\n pose_3d = load_pickle(pose_3d_file)\n pose_2d = []\n for pose_2d_file in tqdm(os.listdir(pose_2d_dir), desc='Loading NBA2K'):\n person = pose_2d_file.split('.', 1)[0]\n pose_2d.append((\n (person,), _load_person_poses(pose_2d_dir, pose_2d_file)))\n\n all_people = {x[0][0] for x in pose_2d}\n val_people = {'alfred', 'allen', 'barney', 'bradley'}\n print('{} / {} people reserved for validation'.format(\n len(val_people), len(all_people)))\n assert val_people <= all_people\n\n train_2d = [x for x in pose_2d if x[0][0] not in val_people]\n train_2d.sort()\n train_dataset = NBA2kDataset(\n train_2d, pose_3d, True, True, embed_bones, 5000)\n\n val_2d = [x for x in pose_2d if x[0][0] in val_people]\n val_2d.sort()\n val_dataset = NBA2kDataset(\n val_2d, pose_3d, True, True, embed_bones, 500)\n return train_dataset, val_dataset\n\n\nclass People3dDataset(D3KeypointDataset):\n\n def get_sequence(self, index, camera=None, stride=2):\n (person, action), frame_data = self.get(index)\n seq_poses = self.poses_3d[(person, action)]\n\n sequence = []\n for i, (frame_num, all_cameras_and_2d_poses) in enumerate(frame_data):\n if i % stride != 0:\n continue\n\n if camera is None:\n # Choose a random camera\n camera, pose2d = random.choice(all_cameras_and_2d_poses)\n else:\n for camera2, pose2d in all_cameras_and_2d_poses:\n if camera2 == camera:\n break\n else:\n continue\n\n # Load 3d ground truth\n _, rotation, abs_kp_offsets = seq_poses[frame_num - 1]\n norm_kp_offsets, kp_dists = normalize_3d_offsets(abs_kp_offsets)\n\n sequence.append({\n 'person': person,\n 'action': action,\n 'frame': frame_num,\n 'rotation': rotation,\n 'kp_offsets': norm_kp_offsets,\n 'kp_offset_norms': kp_dists,\n 'camera': camera,\n 'pose': normalize_2d_skeleton(\n pose2d, False, include_bone_features=self.embed_bones)\n })\n return sequence\n\n @staticmethod\n def _random_project_3d(raw_kp_offsets):\n skl = people3d.decode_skeleton_from_offsets(raw_kp_offsets)\n coco_xyz = np.stack([\n (skl.head + skl.left_eye + skl.right_eye) / 3,\n skl.left_eye,\n skl.right_eye,\n skl.left_eye, # No ears in 3dpeople\n skl.right_eye,\n skl.left_arm,\n skl.right_arm,\n skl.left_forearm,\n skl.right_forearm,\n skl.left_hand,\n skl.right_hand,\n skl.left_up_leg,\n skl.right_up_leg,\n skl.left_leg,\n skl.right_leg,\n skl.left_foot,\n skl.right_foot,\n ])\n return _random_project_3d(\n coco_xyz, elevation=CAMERA_AUG_ELEVATION_RANGE,\n roll=CAMERA_AUG_ROLL_RANGE)\n\n def _get_negative_sample(self, frame_data, seq_poses, norm_kp_offsets):\n # Try to find a pose in the same sequence that differs the current one\n neg_flip = False\n for _ in range(MAX_NEG_SAMPLE_TRIES):\n neg_frame_num, neg_cameras_and_2d_poses = random.choice(frame_data)\n neg_raw_offsets = seq_poses[neg_frame_num - 1][-1]\n neg_flip = self._should_flip()\n if is_good_3d_neg_sample(\n normalize_3d_offsets(\n flip_skeleton_offsets(neg_raw_offsets, people3d.XFLIP_ROWS)\n if neg_flip else neg_raw_offsets\n )[0],\n norm_kp_offsets,\n ignore=None if USE_EXTREMITIES else people3d.EXTREMITY_ROWS\n ):\n if self._should_project():\n neg_pose2d = People3dDataset._random_project_3d(neg_raw_offsets)\n else:\n neg_pose2d = random.choice(neg_cameras_and_2d_poses)[1]\n break\n else:\n neg_pose2d = None\n self._log_neg_sample_fail()\n return neg_pose2d, neg_flip\n\n def __getitem__(self, index):\n self.sample_count += 1\n\n (person, action), frame_data = self.get(index)\n seq_poses = self.poses_3d[(person, action)]\n flip = self._should_flip()\n\n frame_num, all_cameras_and_2d_poses = random.choice(frame_data)\n assert len(all_cameras_and_2d_poses) > 0\n\n # Load 3d ground truth\n _, rotation, raw_kp_offsets = seq_poses[frame_num - 1]\n\n # Flip and normalize 3D\n abs_kp_offsets = raw_kp_offsets\n if flip:\n rotation = -rotation\n abs_kp_offsets = flip_skeleton_offsets(\n abs_kp_offsets, people3d.XFLIP_ROWS)\n\n # Sample two random cameras\n camera1, camera2, pose_2d1, pose_2d2 = _sample_camera_pair(\n all_cameras_and_2d_poses)\n\n # Replace with projections if needed\n if self._should_project():\n camera1 = ''\n pose_2d1 = People3dDataset._random_project_3d(raw_kp_offsets)\n if self._should_project():\n camera2 = ''\n pose_2d2 = People3dDataset._random_project_3d(raw_kp_offsets)\n\n # Get negative sample\n neg_pose2d, neg_flip = self._get_negative_sample(\n frame_data, seq_poses, normalize_3d_offsets(abs_kp_offsets)[0])\n\n norm_pose1 = normalize_2d_skeleton(\n pose_2d1, flip, include_bone_features=self.embed_bones)\n ret = {\n 'kp_features': get_3d_features(\n abs_kp_offsets, people3d, include_extremities=USE_EXTREMITIES,\n include_root_directions=USE_ROOT_DIRECTIONS),\n 'pose1': norm_pose1,\n 'pose2': normalize_2d_skeleton(\n pose_2d2, flip, include_bone_features=self.embed_bones),\n 'pose_neg': torch.zeros_like(norm_pose1) if neg_pose2d is None\n else normalize_2d_skeleton(\n neg_pose2d, neg_flip,\n include_bone_features=self.embed_bones),\n 'pose_neg_is_valid': int(neg_pose2d is not None)\n }\n if self.debug_info:\n ret.update({\n 'person': person,\n 'action': action,\n 'frame': frame_num,\n 'rotation': rotation,\n 'camera1': camera1,\n 'camera2': camera2,\n 'is_flip': flip\n })\n return ret\n\n @staticmethod\n def load_default(pose_2d_dir, pose_3d_file, embed_bones, augment_camera):\n pose_2d = []\n for pose_2d_file in tqdm(\n os.listdir(pose_2d_dir), desc='Loading 3D people'\n ):\n person, action = pose_2d_file.split('.', 1)[0].split('__', 1)\n pose_2d.append(((person, action),\n _load_person_poses(pose_2d_dir, pose_2d_file)))\n pose_3d = load_pickle(pose_3d_file)\n\n all_people = {x[0][0] for x in pose_2d}\n val_people = set()\n for s in ['man', 'woman']:\n val_people.update(['{}{:02d}'.format(s, i + 1) for i in range(4)])\n print('{} / {} people reserved for validation'.format(\n len(val_people), len(all_people)))\n assert val_people <= all_people\n\n train_2d = [x for x in pose_2d if x[0][0] not in val_people]\n train_2d.sort()\n train_dataset = People3dDataset(\n train_2d, pose_3d, True, augment_camera, embed_bones, 5000)\n\n val_2d = [x for x in pose_2d if x[0][0] in val_people]\n val_2d.sort()\n val_dataset = People3dDataset(\n val_2d, pose_3d, True, augment_camera, embed_bones, 500)\n return train_dataset, val_dataset\n\n\nclass AmassDataset(D3KeypointDataset):\n\n CAMERA_AUG_ELEVATION_RANGE = (-np.pi / 6, np.pi / 6)\n\n idx_stride = 25\n\n sample_weights = {\n 'ACCAD': 1,\n 'BMLhandball': 1,\n 'BMLmovi': 1,\n 'BMLrub': 1,\n 'CMU': 1,\n 'DFaust67': 1,\n 'EKUT': 1,\n 'EyesJapanDataset': 1,\n 'HumanEva': 1,\n 'KIT': 1,\n 'MPIHDM05': 10,\n 'MPILimits': 10,\n 'MPImosh': 10,\n 'SFU': 1,\n 'SSMsynced': 1,\n 'TCDhandMocap': 1,\n 'TotalCapture': 1,\n 'Transitionsmocap': 1\n }\n\n @staticmethod\n def _idx(frame_num):\n return frame_num // AmassDataset.idx_stride\n\n def get_sequence(self, index, camera=None, stride=25):\n (dataset, action), frame_data = self.get(index)\n seq_poses = self.poses_3d[(dataset, action)]\n\n sequence = []\n for i, (frame_num, all_cameras_and_2d_poses) in enumerate(frame_data):\n if i % stride != 0:\n continue\n\n camera, pose2d = random.choice(all_cameras_and_2d_poses)\n\n # Load 3d ground truth\n _, rotation, abs_kp_offsets = seq_poses[AmassDataset._idx(frame_num)]\n norm_kp_offsets, kp_dists = normalize_3d_offsets(abs_kp_offsets)\n\n sequence.append({\n 'person': dataset,\n 'action': action,\n 'frame': frame_num,\n 'rotation': rotation,\n 'kp_offsets': norm_kp_offsets,\n 'kp_offset_norms': kp_dists,\n 'camera': camera,\n 'pose': normalize_2d_skeleton(\n pose2d, False, include_bone_features=self.embed_bones)\n })\n return sequence\n\n @staticmethod\n def _random_project_3d(raw_kp_offsets):\n skl = amass.decode_skeleton_from_offsets(raw_kp_offsets)\n nose = (skl.head_top + skl.head) / 2\n coco_xyz = np.stack([\n nose,\n nose, # No eyes in amass\n nose,\n nose, # No ears in amass\n nose,\n skl.l_shoulder,\n skl.r_shoulder,\n skl.l_elbow,\n skl.r_elbow,\n skl.l_wrist,\n skl.r_wrist,\n skl.l_hip,\n skl.r_hip,\n skl.l_knee,\n skl.r_knee,\n skl.l_ankle,\n skl.r_ankle,\n ])\n return _random_project_3d(\n coco_xyz, elevation=CAMERA_AUG_ELEVATION_RANGE,\n roll=CAMERA_AUG_ROLL_RANGE)\n\n def _get_negative_sample(self, frame_data, seq_poses, norm_kp_offsets):\n # Try to find a pose in the same sequence that differs the current one\n neg_flip = False\n for _ in range(MAX_NEG_SAMPLE_TRIES):\n neg_frame_num, neg_cameras_and_2d_poses = random.choice(frame_data)\n neg_raw_offsets = seq_poses[AmassDataset._idx(neg_frame_num)][-1]\n neg_flip = self._should_flip()\n if is_good_3d_neg_sample(\n normalize_3d_offsets(\n flip_skeleton_offsets(neg_raw_offsets, amass.XFLIP_ROWS)\n if neg_flip else neg_raw_offsets\n )[0],\n norm_kp_offsets,\n ignore=None if USE_EXTREMITIES else amass.EXTREMITY_ROWS\n ):\n if self._should_project():\n neg_pose2d = AmassDataset._random_project_3d(neg_raw_offsets)\n else:\n neg_pose2d = random.choice(neg_cameras_and_2d_poses)[1]\n break\n else:\n neg_pose2d = None\n self._log_neg_sample_fail()\n return neg_pose2d, neg_flip\n\n def __getitem__(self, index):\n self.sample_count += 1\n\n (dataset, action), frame_data = self.get(index)\n seq_poses = self.poses_3d[(dataset, action)]\n flip = self._should_flip()\n\n frame_num, all_cameras_and_2d_poses = random.choice(frame_data)\n assert len(all_cameras_and_2d_poses) > 0\n\n # Load 3d ground truth\n _, rotation, raw_kp_offsets = seq_poses[AmassDataset._idx(frame_num)]\n\n # Flip and normalize 3D\n abs_kp_offsets = raw_kp_offsets\n if flip:\n rotation = -rotation\n abs_kp_offsets = flip_skeleton_offsets(\n abs_kp_offsets, amass.XFLIP_ROWS)\n\n # Sample two random cameras\n camera1, camera2, pose_2d1, pose_2d2 = _sample_camera_pair(\n all_cameras_and_2d_poses)\n\n # Replace with projections if needed\n if self._should_project():\n camera1 = ''\n pose_2d1 = AmassDataset._random_project_3d(raw_kp_offsets)\n if self._should_project():\n camera2 = ''\n pose_2d2 = AmassDataset._random_project_3d(raw_kp_offsets)\n\n # Get negative sample\n neg_pose2d, neg_flip = self._get_negative_sample(\n frame_data, seq_poses, normalize_3d_offsets(abs_kp_offsets)[0])\n\n norm_pose1 = normalize_2d_skeleton(\n pose_2d1, flip, include_bone_features=self.embed_bones)\n ret = {\n 'kp_features': get_3d_features(\n abs_kp_offsets, amass, include_extremities=USE_EXTREMITIES,\n include_root_directions=USE_ROOT_DIRECTIONS),\n 'pose1': norm_pose1,\n 'pose2': normalize_2d_skeleton(\n pose_2d2, flip, include_bone_features=self.embed_bones),\n 'pose_neg': torch.zeros_like(norm_pose1) if neg_pose2d is None\n else normalize_2d_skeleton(\n neg_pose2d, neg_flip,\n include_bone_features=self.embed_bones),\n 'pose_neg_is_valid': int(neg_pose2d is not None)\n }\n if self.debug_info:\n ret.update({\n 'person': dataset,\n 'action': action,\n 'frame': frame_num,\n 'rotation': rotation,\n 'camera1': camera1,\n 'camera2': camera2,\n 'is_flip': flip\n })\n return ret\n\n @staticmethod\n def load_default(pose_2d_dir, pose_3d_file, embed_bones, augment_camera):\n pose_2d = []\n for pose_2d_file in tqdm(\n os.listdir(pose_2d_dir), desc='Loading AMASS'\n ):\n dataset, action = pose_2d_file.split('.', 1)[0].split('_', 1)\n pose_2d.append(((dataset, action),\n _load_person_poses(pose_2d_dir, pose_2d_file)))\n pose_3d = load_pickle(pose_3d_file)\n\n # Stride over subsampled datasets\n dataset_counter = Counter()\n\n all_datasets = set()\n all_sequences = []\n for item in pose_2d:\n dataset = item[0][0]\n dataset_weight = AmassDataset.sample_weights[dataset]\n if dataset_weight >= 1:\n for _ in range(round(dataset_weight)):\n all_sequences.append(item)\n else:\n if dataset_counter[dataset] % round(1 / dataset_weight) == 0:\n all_sequences.append(item)\n dataset_counter[dataset] += 1\n all_datasets.add(dataset)\n\n val_datasets = {'EyesJapanDataset'}\n print('{} / {} datasets reserved for validation'.format(\n len(val_datasets), len(all_datasets)))\n assert val_datasets <= all_datasets\n\n train_2d = [x for x in pose_2d if x[0][0] not in val_datasets]\n train_2d.sort()\n train_dataset = AmassDataset(\n train_2d, pose_3d, True, augment_camera, embed_bones, 20000)\n\n val_2d = [x for x in pose_2d if x[0][0] in val_datasets]\n val_2d.sort()\n val_dataset = AmassDataset(\n val_2d, pose_3d, True, augment_camera, embed_bones, 2000)\n return train_dataset, val_dataset\n\n\nclass Pairwise_People3dDataset(Dataset):\n\n def __init__(self, pose_2d, scale, embed_bones, random_hflip=True):\n super().__init__()\n self.random_hflip = random_hflip\n self.embed_bones = embed_bones\n\n # (person, action) -> frames\n self.point_dict = {\n tuple(a): (\n [x[0] for x in b], # Frame list\n dict(b) # Frame to cameras\n ) for a, b in pose_2d\n }\n self.people = list(set(x[0] for x in self.point_dict))\n self.actions = list(set(x[1] for x in self.point_dict))\n self.scale = scale\n\n def __len__(self):\n return len(self.actions) * self.scale\n\n def _should_flip(self):\n return self.random_hflip and random.getrandbits(1) > 0\n\n def __getitem__(self, index):\n action = self.actions[index % len(self.actions)]\n person1, person2 = np.random.choice(\n self.people, 2, replace=False).tolist()\n\n frames1, frame_to_cameras1 = self.point_dict[(person1, action)]\n _, frame_to_cameras2 = self.point_dict[(person2, action)]\n for i in range(1000):\n if i == 10:\n print('Why is this taking so many tries?',\n person1, person2, action)\n frame_num = random.choice(frames1)\n\n # No camera is available for person2; try again\n all_cameras2 = frame_to_cameras2.get(frame_num)\n if all_cameras2 is None:\n continue\n\n # Sample the cameras\n pose_2d1 = random.choice(frame_to_cameras1[frame_num])[1]\n pose_2d2 = random.choice(all_cameras2)[1]\n break\n else:\n raise RuntimeError('This dataset is really borked...')\n\n flip = self._should_flip()\n return {\n 'pose1': normalize_2d_skeleton(\n pose_2d1, flip, include_bone_features=self.embed_bones),\n 'pose2': normalize_2d_skeleton(\n pose_2d2, flip, include_bone_features=self.embed_bones),\n 'is_same': True, 'is_flip': flip\n }\n\n @staticmethod\n def load_default(pose_2d_dir, scale, embed_bones):\n pose_2d = []\n for pose_2d_file in tqdm(\n os.listdir(pose_2d_dir), desc='Loading 3D people (Pairs)'\n ):\n person, action = pose_2d_file.split('.', 1)[0].split('__', 1)\n pose_2d.append(((person, action),\n _load_person_poses(pose_2d_dir, pose_2d_file)))\n\n all_people = {x[0][0] for x in pose_2d}\n val_people = set()\n for s in ['man', 'woman']:\n val_people.update(['{}{:02d}'.format(s, i + 1) for i in range(4)])\n print('{} / {} people reserved for validation'.format(\n len(val_people), len(all_people)))\n assert val_people <= all_people\n\n train_2d = [x for x in pose_2d if x[0][0] not in val_people]\n train_2d.sort()\n train_dataset = Pairwise_People3dDataset(train_2d, scale, embed_bones)\n\n val_2d = [x for x in pose_2d if x[0][0] in val_people]\n val_2d.sort()\n val_dataset = Pairwise_People3dDataset(\n val_2d, int(scale * 0.2), embed_bones)\n return train_dataset, val_dataset" ]
[ [ "numpy.array", "numpy.mean", "numpy.stack" ], [ "numpy.hstack", "numpy.random.choice", "torch.zeros_like", "numpy.stack", "numpy.random.uniform", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JPompeus/Stone-Soup
[ "030c60aaf5ff92d7bb53f06e350c0bf58c9af037", "030c60aaf5ff92d7bb53f06e350c0bf58c9af037", "030c60aaf5ff92d7bb53f06e350c0bf58c9af037" ]
[ "stonesoup/simulator/simple.py", "stonesoup/predictor/kalman.py", "stonesoup/models/measurement/nonlinear.py" ]
[ "# -*- coding: utf-8 -*-\nimport datetime\n\nimport numpy as np\n\nfrom ..base import Property\nfrom ..models.measurement import MeasurementModel\nfrom ..models.transition import TransitionModel\nfrom ..reader import GroundTruthReader\nfrom ..types.detection import TrueDetection, Clutter\nfrom ..types.groundtruth import GroundTruthPath, GroundTruthState\nfrom ..types.numeric import Probability\nfrom ..types.state import GaussianState, State\nfrom .base import DetectionSimulator, GroundTruthSimulator\nfrom stonesoup.buffered_generator import BufferedGenerator\n\n\nclass SingleTargetGroundTruthSimulator(GroundTruthSimulator):\n \"\"\"Target simulator that produces a single target\"\"\"\n transition_model = Property(\n TransitionModel, doc=\"Transition Model used as propagator for track.\")\n initial_state = Property(\n State,\n doc=\"Initial state to use to generate ground truth\")\n timestep = Property(\n datetime.timedelta,\n default=datetime.timedelta(seconds=1),\n doc=\"Time step between each state. Default one second.\")\n number_steps = Property(\n int, default=100, doc=\"Number of time steps to run for\")\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.index = 0\n\n @BufferedGenerator.generator_method\n def groundtruth_paths_gen(self):\n time = self.initial_state.timestamp or datetime.datetime.now()\n\n gttrack = GroundTruthPath([\n GroundTruthState(self.initial_state.state_vector, timestamp=time,\n metadata={\"index\": self.index})])\n yield time, {gttrack}\n\n for _ in range(self.number_steps - 1):\n time += self.timestep\n # Move track forward\n trans_state_vector = self.transition_model.function(\n gttrack[-1].state_vector,\n time_interval=self.timestep)\n gttrack.append(GroundTruthState(\n trans_state_vector, timestamp=time,\n metadata={\"index\": self.index}))\n yield time, {gttrack}\n\n\nclass SwitchOneTargetGroundTruthSimulator(SingleTargetGroundTruthSimulator):\n \"\"\"Target simulator that produces a single target. This target switches\n between multiple transition models based on a markov matrix\n (:attr:`model_probs`)\"\"\"\n transition_models = Property(\n [TransitionModel], doc=\"List of transition models to be used, ensure\\\n that they all have the same dimensions.\")\n model_probs = Property([float], doc=\"A matrix of probabilities.\\\n The element in the ith row and the jth column is the probability of\\\n switching from the ith transition model in :attr:`transition_models`\\\n to the jth\")\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.index = 0\n\n @property\n def transition_model(self):\n self.index = np.random.choice(range(0, len(self.transition_models)),\n p=self.model_probs[self.index])\n return self.transition_models[self.index]\n\n\nclass MultiTargetGroundTruthSimulator(SingleTargetGroundTruthSimulator):\n \"\"\"Target simulator that produces multiple targets.\n\n Targets are created and destroyed randomly, as defined by the birth rate\n and death probability.\"\"\"\n transition_model = Property(\n TransitionModel, doc=\"Transition Model used as propagator for track.\")\n\n initial_state = Property(\n GaussianState,\n doc=\"Initial state to use to generate states\")\n birth_rate = Property(\n float, default=1.0, doc=\"Rate at which tracks are born. Expected \"\n \"number of occurrences (λ) in Poisson distribution. Default 1.0.\")\n death_probability = Property(\n Probability, default=0.1,\n doc=\"Probability of track dying in each time step. Default 0.1.\")\n\n @BufferedGenerator.generator_method\n def groundtruth_paths_gen(self):\n groundtruth_paths = set()\n time = self.initial_state.timestamp or datetime.datetime.now()\n\n for _ in range(self.number_steps):\n # Random drop tracks\n groundtruth_paths.difference_update(\n gttrack\n for gttrack in groundtruth_paths.copy()\n if np.random.rand() <= self.death_probability)\n\n # Move tracks forward\n for gttrack in groundtruth_paths:\n self.index = gttrack[-1].metadata.get(\"index\")\n trans_state_vector = self.transition_model.function(\n gttrack[-1].state_vector,\n time_interval=self.timestep)\n gttrack.append(GroundTruthState(\n trans_state_vector, timestamp=time,\n metadata={\"index\": self.index}))\n\n # Random create\n for _ in range(np.random.poisson(self.birth_rate)):\n self.index = 0\n gttrack = GroundTruthPath()\n gttrack.append(GroundTruthState(\n self.initial_state.state_vector +\n np.sqrt(self.initial_state.covar) @\n np.random.randn(self.initial_state.ndim, 1),\n timestamp=time, metadata={\"index\": self.index}))\n groundtruth_paths.add(gttrack)\n\n yield time, groundtruth_paths\n time += self.timestep\n\n\nclass SwitchMultiTargetGroundTruthSimulator(MultiTargetGroundTruthSimulator):\n \"\"\"Functions identically to :class:`~.MultiTargetGroundTruthSimulator`,\n but has the transition model switching ability from\n :class:`.SwitchOneTargetGroundTruthSimulator`\"\"\"\n transition_models = Property(\n [TransitionModel], doc=\"List of transition models to be used, ensure\\\n that they all have the same dimensions.\")\n model_probs = Property([float], doc=\"A matrix of probabilities.\\\n The element in the ith row and the jth column is the probability of\\\n switching from the ith transition model in :attr:`transition_models`\\\n to the jth\")\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.index = 0\n\n @property\n def transition_model(self):\n self.index = np.random.choice(range(0, len(self.transition_models)),\n p=self.model_probs[self.index])\n return self.transition_models[self.index]\n\n\nclass SimpleDetectionSimulator(DetectionSimulator):\n \"\"\"A simple detection simulator.\n\n Parameters\n ----------\n groundtruth : GroundTruthReader\n Source of ground truth tracks used to generate detections for.\n measurement_model : MeasurementModel\n Measurement model used in generating detections.\n \"\"\"\n groundtruth = Property(GroundTruthReader)\n measurement_model = Property(MeasurementModel)\n meas_range = Property(np.ndarray)\n detection_probability = Property(Probability, default=0.9)\n clutter_rate = Property(float, default=2.0)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.real_detections = set()\n self.clutter_detections = set()\n self.index = 0\n\n @property\n def clutter_spatial_density(self):\n \"\"\"returns the clutter spatial density of the measurement space - num\n clutter detections per unit volume per timestep\"\"\"\n return self.clutter_rate/np.prod(np.diff(self.meas_range))\n\n @BufferedGenerator.generator_method\n def detections_gen(self):\n for time, tracks in self.groundtruth:\n self.real_detections.clear()\n self.clutter_detections.clear()\n\n for track in tracks:\n self.index = track[-1].metadata.get(\"index\")\n if np.random.rand() < self.detection_probability:\n detection = TrueDetection(\n self.measurement_model.function(\n track[-1].state_vector),\n timestamp=track[-1].timestamp,\n groundtruth_path=track)\n detection.clutter = False\n self.real_detections.add(detection)\n\n # generate clutter\n for _ in range(np.random.poisson(self.clutter_rate)):\n detection = Clutter(\n np.random.rand(self.measurement_model.ndim_meas, 1) *\n np.diff(self.meas_range) + self.meas_range[:, :1],\n timestamp=time)\n self.clutter_detections.add(detection)\n\n yield time, self.real_detections | self.clutter_detections\n\n\nclass SwitchDetectionSimulator(SimpleDetectionSimulator):\n\n \"\"\"Functions identically as the :class:`SimpleDetectionSimulator`, but for\n ground truth paths formed using multiple transition models it allows the\n user to assign a detection probability to each transition models.\n For example, if you wanted a higher detection probability when the\n simulated object makes a turn\"\"\"\n\n detection_probabilities = Property([Probability], doc=\"List of\\\n probabilities that correspond to the detection probability of the\\\n simulated object while undergoing each transition model\")\n\n @property\n def detection_probability(self):\n return self.detection_probabilities[self.index]\n", "# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom functools import lru_cache, partial\n\nfrom ..base import Property\nfrom .base import Predictor\nfrom ..types.prediction import GaussianStatePrediction\nfrom ..models.base import LinearModel\nfrom ..models.transition import TransitionModel\nfrom ..models.transition.linear import LinearGaussianTransitionModel\nfrom ..models.control import ControlModel\nfrom ..models.control.linear import LinearControlModel\nfrom ..functions import gauss2sigma, unscented_transform\n\n\nclass KalmanPredictor(Predictor):\n r\"\"\"A predictor class which forms the basis for the family of Kalman\n predictors. This class also serves as the (specific) Kalman Filter\n :class:`~.Predictor` class. Here\n\n .. math::\n\n f_k( \\mathbf{x}_{k-1}) = F_k \\mathbf{x}_{k-1}, \\ b_k( \\mathbf{x}_k) =\n B_k \\mathbf{x}_k \\ \\mathrm{and} \\ \\mathbf{\\nu}_k \\sim \\mathcal{N}(0,Q_k)\n\n\n Notes\n -----\n In the Kalman filter, transition and control models must be linear.\n\n\n Raises\n ------\n ValueError\n If no :class:`~.TransitionModel` is specified.\n\n\n \"\"\"\n\n transition_model = Property(\n LinearGaussianTransitionModel,\n doc=\"The transition model to be used.\")\n control_model = Property(\n LinearControlModel,\n default=None,\n doc=\"The control model to be used. Default `None` where the predictor \"\n \"will create a zero-effect linear :class:`~.ControlModel`.\")\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # If no control model insert a linear zero-effect one\n # TODO: Think about whether it's more efficient to leave this out\n if self.control_model is None:\n ndims = self.transition_model.ndim_state\n self.control_model = LinearControlModel(ndims, [],\n np.zeros([ndims, 1]),\n np.zeros([ndims, ndims]),\n np.zeros([ndims, ndims]))\n\n def _transition_matrix(self, **kwargs):\n \"\"\"Return the transition matrix\n\n Parameters\n ----------\n **kwargs : various, optional\n These are passed to :meth:`~.LinearGaussianTransitionModel.matrix`\n\n Returns\n -------\n : :class:`numpy.ndarray`\n The transition matrix, :math:`F_k`\n\n \"\"\"\n return self.transition_model.matrix(**kwargs)\n\n def _transition_function(self, prior, **kwargs):\n r\"\"\"Applies the linear transition function to a single vector in the\n absence of a control input, returns a single predicted state.\n\n Parameters\n ----------\n prior : :class:`~.State`\n The prior state, :math:`\\mathbf{x}_{k-1}`\n\n **kwargs : various, optional\n These are passed to :meth:`~.LinearGaussianTransitionModel.matrix`\n\n Returns\n -------\n : :class:`~.State`\n The predicted state\n\n \"\"\"\n return self.transition_model.matrix(**kwargs) @ prior.state_vector\n\n @property\n def _control_matrix(self):\n r\"\"\"Convenience function which returns the control matrix\n\n Returns\n -------\n : :class:`numpy.ndarray`\n control matrix, :math:`B_k`\n\n \"\"\"\n return self.control_model.matrix()\n\n def _predict_over_interval(self, prior, timestamp):\n \"\"\"Private function to get the prediction interval (or None)\n\n Parameters\n ----------\n prior : :class:`~.State`\n The prior state\n\n timestamp : :class:`datetime.datetime`, optional\n The (current) timestamp\n\n Returns\n -------\n : :class:`datetime.timedelta`\n time interval to predict over\n\n \"\"\"\n\n # Deal with undefined timestamps\n if timestamp is None or prior.timestamp is None:\n predict_over_interval = None\n else:\n predict_over_interval = timestamp - prior.timestamp\n\n return predict_over_interval\n\n @lru_cache()\n def predict(self, prior, timestamp=None, **kwargs):\n r\"\"\"The predict function\n\n Parameters\n ----------\n prior : :class:`~.State`\n :math:`\\mathbf{x}_{k-1}`\n timestamp : :class:`datetime.datetime`, optional\n :math:`k`\n **kwargs :\n These are passed, via :meth:`~.KalmanFilter.transition_function` to\n :meth:`~.LinearGaussianTransitionModel.matrix`\n\n Returns\n -------\n : :class:`~.State`\n :math:`\\mathbf{x}_{k|k-1}`, the predicted state and the predicted\n state covariance :math:`P_{k|k-1}`\n\n \"\"\"\n\n # Get the prediction interval\n predict_over_interval = self._predict_over_interval(prior, timestamp)\n\n # Prediction of the mean\n x_pred = self._transition_function(\n prior, time_interval=predict_over_interval, **kwargs) \\\n + self.control_model.control_input()\n\n # As this is Kalman-like, the control model must be capable of\n # returning a control matrix (B)\n\n transition_matrix = self._transition_matrix(\n prior=prior, time_interval=predict_over_interval, **kwargs)\n transition_covar = self.transition_model.covar(\n time_interval=predict_over_interval, **kwargs)\n\n control_matrix = self._control_matrix\n control_noise = self.control_model.control_noise\n\n p_pred = transition_matrix @ prior.covar @ transition_matrix.T \\\n + transition_covar \\\n + control_matrix @ control_noise @ control_matrix.T\n\n return GaussianStatePrediction(x_pred, p_pred, timestamp=timestamp)\n\n\nclass ExtendedKalmanPredictor(KalmanPredictor):\n \"\"\"ExtendedKalmanPredictor class\n\n An implementation of the Extended Kalman Filter predictor. Here the\n transition and control functions may be non-linear, their transition and\n control matrices are approximated via Jacobian matrices. To this end the\n transition and control models, if non-linear, must be able to return the\n :attr:`jacobian()` function.\n\n \"\"\"\n\n # In this version the models can be non-linear, but must have access to the\n # :attr:`jacobian()` function\n # TODO: Enforce the presence of :attr:`jacobian()`\n transition_model = Property(\n TransitionModel,\n doc=\"The transition model to be used.\")\n control_model = Property(\n ControlModel,\n default=None,\n doc=\"The control model to be used. Default `None` where the predictor \"\n \"will create a zero-effect linear :class:`~.ControlModel`.\")\n\n def _transition_matrix(self, prior, **kwargs):\n r\"\"\"Returns the transition matrix, a matrix if the model is linear, or\n approximated as Jacobian otherwise.\n\n Parameters\n ----------\n prior : :class:`~.State`\n :math:`\\mathbf{x}_{k-1}`\n **kwargs : various, optional\n These are passed to :meth:`~.TransitionModel.matrix` or\n :meth:`~.TransitionModel.jacobian`\n\n Returns\n -------\n : :class:`numpy.ndarray`\n The transition matrix, :math:`F_k`, if linear (i.e.\n :meth:`TransitionModel.matrix` exists, or\n :meth:`~.TransitionModel.jacobian` if not)\n \"\"\"\n if isinstance(self.transition_model, LinearModel):\n return self.transition_model.matrix(**kwargs)\n else:\n return self.transition_model.jacobian(prior.state_vector, **kwargs)\n\n def _transition_function(self, prior, **kwargs):\n r\"\"\"This is the application of :math:`f_k(\\mathbf{x}_{k-1})`, the\n transition function, non-linear in general, in the absence of a control\n input\n\n Parameters\n ----------\n prior : :class:`~.State`\n The prior state, :math:`\\mathbf{x}_{k-1}`\n **kwargs : various, optional\n These are passed to :meth:`~.TransitionModel.function`\n\n Returns\n -------\n : :class:`~.State`\n The predicted state\n\n \"\"\"\n return self.transition_model.function(prior.state_vector, noise=0,\n **kwargs)\n\n @property\n def _control_matrix(self):\n r\"\"\"Returns the control input model matrix, :math:`B_k`, or its linear\n approximation via a Jacobian. The :class:`~.ControlModel`, if\n non-linear must therefore be capable of returning a\n :meth:`~.ControlModel.jacobian`,\n\n Returns\n -------\n : :class:`numpy.ndarray`\n The control model matrix, or its linear approximation\n \"\"\"\n if isinstance(self.control_model, LinearModel):\n return self.control_model.matrix()\n else:\n return self.control_model.jacobian(\n self.control_model.control_vector)\n\n\nclass UnscentedKalmanPredictor(KalmanPredictor):\n \"\"\"UnscentedKalmanFilter class\n\n The predict is accomplished by calculating the sigma points from the\n Gaussian mean and covariance, then putting these through the (in general\n non-linear) transition function, then reconstructing the Gaussian.\n \"\"\"\n transition_model = Property(\n TransitionModel,\n doc=\"The transition model to be used.\")\n control_model = Property(\n ControlModel,\n default=None,\n doc=\"The control model to be used. Default `None` where the predictor \"\n \"will create a zero-effect linear :class:`~.ControlModel`.\")\n alpha = Property(\n float,\n default=0.5,\n doc=\"Primary sigma point spread scaling parameter. Default is 0.5.\")\n beta = Property(\n float,\n default=2,\n doc=\"Used to incorporate prior knowledge of the distribution. If the \"\n \"true distribution is Gaussian, the value of 2 is optimal. \"\n \"Default is 2\")\n kappa = Property(\n float,\n default=0,\n doc=\"Secondary spread scaling parameter. Default is calculated as \"\n \"3-Ns\")\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self._time_interval = None\n\n def _transition_and_control_function(self, prior_state_vector, **kwargs):\n r\"\"\"Returns the result of applying the transition and control functions\n for the unscented transform\n\n Parameters\n ----------\n prior_state_vector : :class:`~.State`\n Prior state vector\n **kwargs : various, optional\n These are passed to :meth:`~.TransitionModel.function`\n\n Returns\n -------\n : :class:`numpy.ndarray`\n The combined, noiseless, effect of applying the transition and\n control\n \"\"\"\n\n return \\\n self.transition_model.function(\n prior_state_vector, noise=0, **kwargs) \\\n + self.control_model.control_input()\n\n @lru_cache()\n def predict(self, prior, timestamp=None, **kwargs):\n r\"\"\"The unscented version of the predict step\n\n Parameters\n ----------\n prior : :class:`~.State`\n Prior state, :math:`\\mathbf{x}_{k-1}`\n timestamp : :class:`datetime.datetime`\n Time to transit to (:math:`k`)\n **kwargs : various, optional\n These are passed to :meth:`~.TransitionModel.covar`\n\n Returns\n -------\n : :class:`~.GaussianStatePrediction`\n The predicted state :math:`\\mathbf{x}_{k|k-1}` and the predicted\n state covariance :math:`P_{k|k-1}`\n \"\"\"\n\n # Get the prediction interval\n predict_over_interval = self._predict_over_interval(prior, timestamp)\n\n # The covariance on the transition model + the control model\n # TODO: Note that I'm not sure you can actually do this with the\n # TODO: covariances, i.e. sum them before calculating\n # TODO: the sigma points and then just sticking them into the\n # TODO: unscented transform, and I haven't checked the statistics.\n total_noise_covar = \\\n self.transition_model.covar(\n time_interval=predict_over_interval, **kwargs) \\\n + self.control_model.control_noise\n\n # Get the sigma points from the prior mean and covariance.\n sigma_points, mean_weights, covar_weights = gauss2sigma(\n prior.state_vector, prior.covar, self.alpha, self.beta, self.kappa)\n\n # This ensures that function passed to unscented transform has the\n # correct time interval\n transition_and_control_function = partial(\n self._transition_and_control_function,\n time_interval=predict_over_interval)\n\n # Put these through the unscented transform, together with the total\n # covariance to get the parameters of the Gaussian\n x_pred, p_pred, _, _, _, _ = unscented_transform(\n sigma_points, mean_weights, covar_weights,\n transition_and_control_function, covar_noise=total_noise_covar\n )\n\n # and return a Gaussian state based on these parameters\n return GaussianStatePrediction(x_pred, p_pred, timestamp=timestamp)\n", "# -*- coding: utf-8 -*-\n\nimport scipy as sp\nfrom numpy.linalg import inv\n\nfrom ...base import Property\n\nfrom ...functions import cart2pol, pol2cart, \\\n cart2sphere, sphere2cart, cart2angles, \\\n rotx, roty, rotz\nfrom ...types.array import StateVector, CovarianceMatrix\nfrom ...types.angle import Bearing, Elevation\nfrom ..base import NonLinearModel, GaussianModel, ReversibleModel\nfrom .base import MeasurementModel\n\n\nclass NonLinearGaussianMeasurement(MeasurementModel,\n NonLinearModel,\n GaussianModel):\n r\"\"\"This class combines the MeasurementModel, NonLinearModel and \\\n GaussianModel classes. It is not meant to be instantiated directly \\\n but subclasses should be derived from this class.\n \"\"\"\n noise_covar = Property(CovarianceMatrix, doc=\"Noise covariance\")\n rotation_offset = Property(\n StateVector, default=StateVector(sp.array([[0], [0], [0]])),\n doc=\"A 3x1 array of angles (rad), specifying the clockwise rotation\\\n around each Cartesian axis in the order :math:`x,y,z`.\\\n The rotation angles are positive if the rotation is in the \\\n counter-clockwise direction when viewed by an observer looking\\\n along the respective rotation axis, towards the origin.\")\n\n def covar(self, **kwargs):\n \"\"\"Returns the measurement model noise covariance matrix.\n\n Returns\n -------\n :class:`~.CovarianceMatrix` of shape\\\n (:py:attr:`~ndim_meas`, :py:attr:`~ndim_meas`)\n The measurement noise covariance.\n \"\"\"\n\n return self.noise_covar\n\n @property\n def _rotation_matrix(self):\n \"\"\"_rotation_matrix getter method\n\n Calculates and returns the (3D) axis rotation matrix.\n\n Returns\n -------\n :class:`numpy.ndarray` of shape (3, 3)\n The model (3D) rotation matrix.\n \"\"\"\n\n theta_x = -self.rotation_offset[0, 0]\n theta_y = -self.rotation_offset[1, 0]\n theta_z = -self.rotation_offset[2, 0]\n\n return rotz(theta_z)@roty(theta_y)@rotx(theta_x)\n\n\nclass CartesianToElevationBearingRange(\n NonLinearGaussianMeasurement, ReversibleModel):\n r\"\"\"This is a class implementation of a time-invariant measurement model, \\\n where measurements are assumed to be received in the form of bearing \\\n (:math:`\\phi`), elevation (:math:`\\theta`) and range (:math:`r`), with \\\n Gaussian noise in each dimension.\n\n The model is described by the following equations:\n\n .. math::\n\n \\vec{y}_t = h(\\vec{x}_t, \\vec{v}_t)\n\n where:\n\n * :math:`\\vec{y}_t` is a measurement vector of the form:\n\n .. math::\n\n \\vec{y}_t = \\begin{bmatrix}\n \\theta \\\\\n \\phi \\\\\n r\n \\end{bmatrix}\n\n * :math:`h` is a non-linear model function of the form:\n\n .. math::\n\n h(\\vec{x}_t,\\vec{v}_t) = \\begin{bmatrix}\n asin(\\mathcal{z}/\\sqrt{\\mathcal{x}^2 + \\mathcal{y}^2 +\\mathcal{z}^2}) \\\\\n atan2(\\mathcal{y},\\mathcal{x}) \\\\\n \\sqrt{\\mathcal{x}^2 + \\mathcal{y}^2 + \\mathcal{z}^2}\n \\end{bmatrix} + \\vec{v}_t\n\n * :math:`\\vec{v}_t` is Gaussian distributed with covariance :math:`R`, i.e.:\n\n .. math::\n\n \\vec{v}_t \\sim \\mathcal{N}(0,R)\n\n .. math::\n\n R = \\begin{bmatrix}\n \\sigma_{\\theta}^2 & 0 & 0 \\\\\n 0 & \\sigma_{\\phi}^2 & 0 \\\\\n 0 & 0 & \\sigma_{r}^2\n \\end{bmatrix}\n\n The :py:attr:`mapping` property of the model is a 3 element vector, \\\n whose first (i.e. :py:attr:`mapping[0]`), second (i.e. \\\n :py:attr:`mapping[1]`) and third (i.e. :py:attr:`mapping[2`) elements \\\n contain the state index of the :math:`x`, :math:`y` and :math:`z` \\\n coordinates, respectively.\n\n Note\n ----\n The current implementation of this class assumes a 3D Cartesian plane.\n\n \"\"\" # noqa:E501\n\n translation_offset = Property(\n StateVector, default=StateVector(sp.array([[0], [0], [0]])),\n doc=\"A 3x1 array specifying the Cartesian origin offset in terms of :math:`x,y,z`\\\n coordinates.\")\n\n @property\n def ndim_meas(self):\n \"\"\"ndim_meas getter method\n\n Returns\n -------\n :class:`int`\n The number of measurement dimensions\n \"\"\"\n\n return 3\n\n def function(self, state_vector, noise=None, **kwargs):\n r\"\"\"Model function :math:`h(\\vec{x}_t,\\vec{v}_t)`\n\n Parameters\n ----------\n state_vector: :class:`~.StateVector`\n An input state vector\n noise: :class:`numpy.ndarray`\n An externally generated random process noise sample (the default in\n `None`, in which case process noise will be generated internally)\n\n Returns\n -------\n :class:`numpy.ndarray` of shape (:py:attr:`~ndim_state`, 1)\n The model function evaluated given the provided time interval.\n \"\"\"\n\n if noise is None:\n noise = self.rvs()\n\n # Account for origin offset\n xyz = state_vector[self.mapping] - self.translation_offset\n\n # Rotate coordinates\n xyz_rot = self._rotation_matrix @ xyz\n\n # Convert to Spherical\n rho, phi, theta = cart2sphere(*xyz_rot[:, 0])\n\n return sp.array([[Elevation(theta)],\n [Bearing(phi)],\n [rho]]) + noise\n\n def inverse_function(self, state_vector, **kwargs):\n\n theta, phi, rho = state_vector[:, 0]\n x, y, z = sphere2cart(rho, phi, theta)\n\n xyz = [[x], [y], [z]]\n inv_rotation_matrix = inv(self._rotation_matrix)\n xyz_rot = inv_rotation_matrix @ xyz\n xyz = [xyz_rot[0][0], xyz_rot[1][0], xyz_rot[2][0]]\n x, y, z = xyz + self.translation_offset[:, 0]\n\n res = sp.zeros((self.ndim_state, 1))\n res[self.mapping, 0] = x, y, z\n\n return res\n\n def rvs(self, num_samples=1, **kwargs):\n out = super().rvs(num_samples, **kwargs)\n out = sp.array([[Elevation(0.)], [Bearing(0.)], [0.]]) + out\n return out\n\n\nclass CartesianToBearingRange(\n NonLinearGaussianMeasurement, ReversibleModel):\n r\"\"\"This is a class implementation of a time-invariant measurement model, \\\n where measurements are assumed to be received in the form of bearing \\\n (:math:`\\phi`) and range (:math:`r`), with Gaussian noise in each dimension.\n\n The model is described by the following equations:\n\n .. math::\n\n \\vec{y}_t = h(\\vec{x}_t, \\vec{v}_t)\n\n where:\n\n * :math:`\\vec{y}_t` is a measurement vector of the form:\n\n .. math::\n\n \\vec{y}_t = \\begin{bmatrix}\n \\phi \\\\\n r\n \\end{bmatrix}\n\n * :math:`h` is a non-linear model function of the form:\n\n .. math::\n\n h(\\vec{x}_t,\\vec{v}_t) = \\begin{bmatrix}\n atan2(\\mathcal{y},\\mathcal{x}) \\\\\n \\sqrt{\\mathcal{x}^2 + \\mathcal{y}^2}\n \\end{bmatrix} + \\vec{v}_t\n\n * :math:`\\vec{v}_t` is Gaussian distributed with covariance :math:`R`, i.e.:\n\n .. math::\n\n \\vec{v}_t \\sim \\mathcal{N}(0,R)\n\n .. math::\n\n R = \\begin{bmatrix}\n \\sigma_{\\phi}^2 & 0 \\\\\n 0 & \\sigma_{r}^2\n \\end{bmatrix}\n\n The :py:attr:`mapping` property of the model is a 2 element vector, \\\n whose first (i.e. :py:attr:`mapping[0]`) and second (i.e. \\\n :py:attr:`mapping[0]`) elements contain the state index of the \\\n :math:`x` and :math:`y` coordinates, respectively.\n\n Note\n ----\n The current implementation of this class assumes a 2D Cartesian plane.\n\n \"\"\" # noqa:E501\n\n translation_offset = Property(\n StateVector, default=StateVector(sp.array([[0], [0]])),\n doc=\"A 2x1 array specifying the origin offset in terms of :math:`x,y`\\\n coordinates.\")\n\n @property\n def ndim_meas(self):\n \"\"\"ndim_meas getter method\n\n Returns\n -------\n :class:`int`\n The number of measurement dimensions\n \"\"\"\n\n return 2\n\n def inverse_function(self, state_vector, **kwargs):\n if not ((self.rotation_offset[0][0] == 0)\n and (self.rotation_offset[1][0] == 0)):\n raise RuntimeError(\n \"Measurement model assumes 2D space. \\\n Rotation in 3D space is unsupported at this time.\")\n\n phi, rho = state_vector[:, 0]\n x, y = pol2cart(rho, phi)\n\n xyz = [[x], [y], [0]]\n inv_rotation_matrix = inv(self._rotation_matrix)\n xyz_rot = inv_rotation_matrix @ xyz\n xy = [xyz_rot[0][0], xyz_rot[1][0]]\n x, y = xy + self.translation_offset[:, 0]\n\n res = sp.zeros((self.ndim_state, 1))\n res[self.mapping, 0] = x, y\n\n return res\n\n def function(self, state_vector, noise=None, **kwargs):\n r\"\"\"Model function :math:`h(\\vec{x}_t,\\vec{v}_t)`\n\n Parameters\n ----------\n state_vector: :class:`~.StateVector`\n An input state vector\n noise: :class:`numpy.ndarray`\n An externally generated random process noise sample (the default in\n `None`, in which case process noise will be generated internally)\n\n Returns\n -------\n :class:`numpy.ndarray` of shape (:py:attr:`~ndim_meas`, 1)\n The model function evaluated given the provided time interval.\n \"\"\"\n\n if noise is None:\n noise = self.rvs()\n\n # Account for origin offset\n xyz = [[state_vector[self.mapping[0], 0]\n - self.translation_offset[0, 0]],\n [state_vector[self.mapping[1], 0]\n - self.translation_offset[1, 0]],\n [0]]\n\n # Rotate coordinates\n xyz_rot = self._rotation_matrix @ xyz\n\n # Covert to polar\n rho, phi = cart2pol(*xyz_rot[:2, 0])\n\n return sp.array([[Bearing(phi)], [rho]]) + noise\n\n def rvs(self, num_samples=1, **kwargs):\n out = super().rvs(num_samples, **kwargs)\n out = sp.array([[Bearing(0)], [0.]]) + out\n return out\n\n\nclass CartesianToElevationBearing(NonLinearGaussianMeasurement):\n r\"\"\"This is a class implementation of a time-invariant measurement model, \\\n where measurements are assumed to be received in the form of bearing \\\n (:math:`\\phi`) and elevation (:math:`\\theta`) and with \\\n Gaussian noise in each dimension.\n\n The model is described by the following equations:\n\n .. math::\n\n \\vec{y}_t = h(\\vec{x}_t, \\vec{v}_t)\n\n where:\n\n * :math:`\\vec{y}_t` is a measurement vector of the form:\n\n .. math::\n\n \\vec{y}_t = \\begin{bmatrix}\n \\theta \\\\\n \\phi\n \\end{bmatrix}\n\n * :math:`h` is a non-linear model function of the form:\n\n .. math::\n\n h(\\vec{x}_t,\\vec{v}_t) = \\begin{bmatrix}\n asin(\\mathcal{z}/\\sqrt{\\mathcal{x}^2 + \\mathcal{y}^2 +\\mathcal{z}^2}) \\\\\n atan2(\\mathcal{y},\\mathcal{x}) \\\\\n \\end{bmatrix} + \\vec{v}_t\n\n * :math:`\\vec{v}_t` is Gaussian distributed with covariance :math:`R`, i.e.:\n\n .. math::\n\n \\vec{v}_t \\sim \\mathcal{N}(0,R)\n\n .. math::\n\n R = \\begin{bmatrix}\n \\sigma_{\\theta}^2 & 0 \\\\\n 0 & \\sigma_{\\phi}^2\\\\\n \\end{bmatrix}\n\n The :py:attr:`mapping` property of the model is a 3 element vector, \\\n whose first (i.e. :py:attr:`mapping[0]`), second (i.e. \\\n :py:attr:`mapping[1]`) and third (i.e. :py:attr:`mapping[2]`) elements \\\n contain the state index of the :math:`x`, :math:`y` and :math:`z` \\\n coordinates, respectively.\n\n Note\n ----\n The current implementation of this class assumes a 3D Cartesian plane.\n\n \"\"\" # noqa:E501\n\n translation_offset = Property(\n StateVector, default=StateVector(sp.array([[0], [0], [0]])),\n doc=\"A 3x1 array specifying the origin offset in terms of :math:`x,y,z`\\\n coordinates.\")\n\n @property\n def ndim_meas(self):\n \"\"\"ndim_meas getter method\n\n Returns\n -------\n :class:`int`\n The number of measurement dimensions\n \"\"\"\n\n return 2\n\n def function(self, state_vector, noise=None, **kwargs):\n r\"\"\"Model function :math:`h(\\vec{x}_t,\\vec{v}_t)`\n\n Parameters\n ----------\n state_vector: :class:`~.StateVector`\n An input state vector\n noise: :class:`numpy.ndarray`\n An externally generated random process noise sample (the default in\n `None`, in which case process noise will be generated internally)\n\n Returns\n -------\n :class:`numpy.ndarray` of shape (:py:attr:`~ndim_state`, 1)\n The model function evaluated given the provided time interval.\n \"\"\"\n\n if noise is None:\n noise = self.rvs()\n\n # Account for origin offset\n xyz = state_vector[self.mapping] - self.translation_offset\n\n # Rotate coordinates\n xyz_rot = self._rotation_matrix @ xyz\n\n # Convert to Angles\n phi, theta = cart2angles(*xyz_rot[:, 0])\n\n return sp.array([[Elevation(theta)],\n [Bearing(phi)]]) + noise\n\n def rvs(self, num_samples=1, **kwargs):\n out = super().rvs(num_samples, **kwargs)\n out = sp.array([[Elevation(0.)], [Bearing(0.)]]) + out\n return out\n" ]
[ [ "numpy.sqrt", "numpy.random.poisson", "numpy.diff", "numpy.random.rand", "numpy.random.randn" ], [ "numpy.zeros" ], [ "numpy.linalg.inv", "scipy.zeros", "scipy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
hello-ag/stretch_body
[ "4d9a1f10617b8f7155b8498c5333821818ce24ab" ]
[ "body/test/test_dxl_comms.py" ]
[ "# Logging level must be set before importing any stretch_body class\nimport stretch_body.robot_params\n#stretch_body.robot_params.RobotParams.set_logging_level(\"DEBUG\")\n\nimport unittest\nimport stretch_body.device\nimport stretch_body.robot as robot\nimport numpy as np\n\nclass TestTimingStats(unittest.TestCase):\n def test_thread_starvation_group_sync_read(self):\n robot = stretch_body.robot.Robot()\n robot.end_of_arm.params['use_group_sync_read']=1\n print(robot.end_of_arm.joints)\n print('Starting test_thread_starvation')\n print('Latency timer of %f'%robot.end_of_arm.params['dxl_latency_timer'])\n print('Testing on tool %s'%robot.params['tool'])\n robot.startup()\n try:\n for itr in range(100): #Make large CPU load\n x = np.random.rand(3, 1000, 1000)\n x.tolist()\n except (IndexError, IOError) as e:\n self.fail(\"IndexError or IOError failure in comms\")\n self.assertTrue(robot.end_of_arm.comm_errors.status['n_rx']<2)\n robot.end_of_arm.comm_errors.pretty_print()\n robot.stop()\n" ]
[ [ "numpy.random.rand" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jsun94/nimble
[ "e5c899a69677818b1becc58100577441e15ede13", "e5c899a69677818b1becc58100577441e15ede13", "e5c899a69677818b1becc58100577441e15ede13", "e5c899a69677818b1becc58100577441e15ede13", "e5c899a69677818b1becc58100577441e15ede13", "e5c899a69677818b1becc58100577441e15ede13" ]
[ "benchmarks/operator_benchmark/pt/qbatchnorm_test.py", "torch/utils/data/dataloader.py", "torch/distributed/distributed_c10d.py", "test/jit/test_type_sharing.py", "torch/optim/_multi_tensor/adam.py", "test/jit/test_with.py" ]
[ "\nimport operator_benchmark as op_bench\nimport torch\n\n\n\"\"\"Microbenchmarks for quantized batchnorm operator.\"\"\"\n\nbatchnorm_configs_short = op_bench.config_list(\n attr_names=[\"M\", \"N\", \"K\"],\n attrs=[\n [1, 256, 3136],\n ],\n cross_product_configs={\n 'device': ['cpu'],\n 'dtype': (torch.qint8,),\n },\n tags=[\"short\"]\n)\n\n\nclass QBatchNormBenchmark(op_bench.TorchBenchmarkBase):\n def init(self, M, N, K, device, dtype):\n self._init(M, N, K, device)\n x_scale = 0.1\n x_zero_point = 0\n self.q_input_one = torch.quantize_per_tensor(\n self.input_one, scale=x_scale, zero_point=x_zero_point, dtype=dtype)\n self.mean = torch.rand(N)\n self.var = torch.rand(N)\n self.weight = torch.rand(N)\n self.bias = torch.rand(N)\n self.eps = 1e-5\n self.Y_scale = 0.1\n self.Y_zero_point = 0\n\n def _init(self, M, N, K, device):\n pass\n\n def forward(self):\n pass\n\n\nclass QBatchNorm1dBenchmark(QBatchNormBenchmark):\n def _init(self, M, N, K, device):\n self.set_module_name(\"QBatchNorm1d\")\n self.input_one = torch.rand(M, N, K, device=device, requires_grad=self.auto_set())\n\n def forward(self):\n return torch.ops.quantized.batch_norm1d(\n self.q_input_one, self.weight, self.bias, self.mean, self.var, self.eps,\n self.Y_scale, self.Y_zero_point)\n\n\nclass QBatchNorm2dBenchmark(QBatchNormBenchmark):\n def _init(self, M, N, K, device):\n self.set_module_name(\"QBatchNorm2d\")\n # Note: quantized implementation requires rank 4, which is why we\n # add a 1 as the last dimension\n self.input_one = torch.rand(M, N, K, 1, device=device, requires_grad=self.auto_set())\n\n def forward(self):\n return torch.ops.quantized.batch_norm2d(\n self.q_input_one, self.weight, self.bias, self.mean, self.var, self.eps,\n self.Y_scale, self.Y_zero_point)\n\n\nop_bench.generate_pt_test(batchnorm_configs_short, QBatchNorm1dBenchmark)\nop_bench.generate_pt_test(batchnorm_configs_short, QBatchNorm2dBenchmark)\n\nif __name__ == \"__main__\":\n op_bench.benchmark_runner.main()\n", "r\"\"\"Definition of the DataLoader and associated iterators that subclass _BaseDataLoaderIter\n\nTo support these two classes, in `./_utils` we define many utility methods and\nfunctions to be run in multiprocessing. E.g., the data loading worker loop is\nin `./_utils/worker.py`.\n\"\"\"\n\nimport threading\nimport itertools\nimport warnings\nfrom typing import Any, Callable, TypeVar, Generic, Sequence, List, Optional\n\nimport multiprocessing as python_multiprocessing\nimport torch\nimport torch.multiprocessing as multiprocessing\nfrom torch._utils import ExceptionWrapper\nfrom torch._six import queue, string_classes\n\nfrom . import IterableDataset, Sampler, SequentialSampler, RandomSampler, BatchSampler, Dataset\nfrom . import _utils\n\nT_co = TypeVar('T_co', covariant=True)\nT = TypeVar('T')\n_worker_init_fn_t = Callable[[int], None]\n\n# Ideally we would parameterize `DataLoader` by the return type of `collate_fn`, but there is currently no way to have that\n# type parameter set to a default value if the user doesn't pass in a custom 'collate_fn'.\n# See https://github.com/python/mypy/issues/3737.\n_collate_fn_t = Callable[[List[T]], Any]\n\n\n# This function used to be defined in this file. However, it was moved to\n# _utils/collate.py. Although it is rather hard to access this from user land\n# (one has to explicitly directly `import torch.utils.data.dataloader`), there\n# probably is user code out there using it. This aliasing maintains BC in this\n# aspect.\ndefault_collate: _collate_fn_t = _utils.collate.default_collate\n\nget_worker_info = _utils.worker.get_worker_info\n\nclass _DatasetKind(object):\n Map = 0\n Iterable = 1\n\n @staticmethod\n def create_fetcher(kind, dataset, auto_collation, collate_fn, drop_last):\n if kind == _DatasetKind.Map:\n return _utils.fetch._MapDatasetFetcher(dataset, auto_collation, collate_fn, drop_last)\n else:\n return _utils.fetch._IterableDatasetFetcher(dataset, auto_collation, collate_fn, drop_last)\n\n\nclass _InfiniteConstantSampler(Sampler):\n r\"\"\"Analogous to ``itertools.repeat(None, None)``.\n Used as sampler for :class:`~torch.utils.data.IterableDataset`.\n\n Arguments:\n data_source (Dataset): dataset to sample from\n \"\"\"\n\n def __init__(self):\n super(_InfiniteConstantSampler, self).__init__(None)\n\n def __iter__(self):\n while True:\n yield None\n\n\nclass DataLoader(Generic[T_co]):\n r\"\"\"\n Data loader. Combines a dataset and a sampler, and provides an iterable over\n the given dataset.\n\n The :class:`~torch.utils.data.DataLoader` supports both map-style and\n iterable-style datasets with single- or multi-process loading, customizing\n loading order and optional automatic batching (collation) and memory pinning.\n\n See :py:mod:`torch.utils.data` documentation page for more details.\n\n Arguments:\n dataset (Dataset): dataset from which to load the data.\n batch_size (int, optional): how many samples per batch to load\n (default: ``1``).\n shuffle (bool, optional): set to ``True`` to have the data reshuffled\n at every epoch (default: ``False``).\n sampler (Sampler or Iterable, optional): defines the strategy to draw\n samples from the dataset. Can be any ``Iterable`` with ``__len__``\n implemented. If specified, :attr:`shuffle` must not be specified.\n batch_sampler (Sampler or Iterable, optional): like :attr:`sampler`, but\n returns a batch of indices at a time. Mutually exclusive with\n :attr:`batch_size`, :attr:`shuffle`, :attr:`sampler`,\n and :attr:`drop_last`.\n num_workers (int, optional): how many subprocesses to use for data\n loading. ``0`` means that the data will be loaded in the main process.\n (default: ``0``)\n collate_fn (callable, optional): merges a list of samples to form a\n mini-batch of Tensor(s). Used when using batched loading from a\n map-style dataset.\n pin_memory (bool, optional): If ``True``, the data loader will copy Tensors\n into CUDA pinned memory before returning them. If your data elements\n are a custom type, or your :attr:`collate_fn` returns a batch that is a custom type,\n see the example below.\n drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,\n if the dataset size is not divisible by the batch size. If ``False`` and\n the size of dataset is not divisible by the batch size, then the last batch\n will be smaller. (default: ``False``)\n timeout (numeric, optional): if positive, the timeout value for collecting a batch\n from workers. Should always be non-negative. (default: ``0``)\n worker_init_fn (callable, optional): If not ``None``, this will be called on each\n worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as\n input, after seeding and before data loading. (default: ``None``)\n prefetch_factor (int, optional, keyword-only arg): Number of sample loaded\n in advance by each worker. ``2`` means there will be a total of\n 2 * num_workers samples prefetched across all workers. (default: ``2``)\n persistent_workers (bool, optional): If ``True``, the data loader will not shutdown\n the worker processes after a dataset has been consumed once. This allows to \n maintain the workers `Dataset` instances alive. (default: ``False``)\n\n\n .. warning:: If the ``spawn`` start method is used, :attr:`worker_init_fn`\n cannot be an unpicklable object, e.g., a lambda function. See\n :ref:`multiprocessing-best-practices` on more details related\n to multiprocessing in PyTorch.\n\n .. warning:: ``len(dataloader)`` heuristic is based on the length of the sampler used.\n When :attr:`dataset` is an :class:`~torch.utils.data.IterableDataset`,\n it instead returns an estimate based on ``len(dataset) / batch_size``, with proper\n rounding depending on :attr:`drop_last`, regardless of multi-process loading\n configurations. This represents the best guess PyTorch can make because PyTorch\n trusts user :attr:`dataset` code in correctly handling multi-process\n loading to avoid duplicate data.\n\n However, if sharding results in multiple workers having incomplete last batches,\n this estimate can still be inaccurate, because (1) an otherwise complete batch can\n be broken into multiple ones and (2) more than one batch worth of samples can be\n dropped when :attr:`drop_last` is set. Unfortunately, PyTorch can not detect such\n cases in general.\n\n See `Dataset Types`_ for more details on these two types of datasets and how\n :class:`~torch.utils.data.IterableDataset` interacts with\n `Multi-process data loading`_.\n \"\"\"\n dataset: Dataset[T_co]\n batch_size: Optional[int]\n num_workers: int\n pin_memory: bool\n drop_last: bool\n timeout: float\n sampler: Sampler\n prefetch_factor: int\n _iterator : Optional['_BaseDataLoaderIter']\n __initialized = False\n\n def __init__(self, dataset: Dataset[T_co], batch_size: Optional[int] = 1,\n shuffle: bool = False, sampler: Optional[Sampler[int]] = None,\n batch_sampler: Optional[Sampler[Sequence[int]]] = None,\n num_workers: int = 0, collate_fn: _collate_fn_t = None,\n pin_memory: bool = False, drop_last: bool = False,\n timeout: float = 0, worker_init_fn: _worker_init_fn_t = None,\n multiprocessing_context=None, generator=None,\n *, prefetch_factor: int = 2,\n persistent_workers: bool = False):\n torch._C._log_api_usage_once(\"python.data_loader\") # type: ignore\n\n if num_workers < 0:\n raise ValueError('num_workers option should be non-negative; '\n 'use num_workers=0 to disable multiprocessing.')\n\n if timeout < 0:\n raise ValueError('timeout option should be non-negative')\n\n if num_workers == 0 and prefetch_factor != 2:\n raise ValueError('prefetch_factor option could only be specified in multiprocessing.'\n 'let num_workers > 0 to enable multiprocessing.')\n assert prefetch_factor > 0\n\n if persistent_workers and num_workers == 0:\n raise ValueError('persistent_workers option needs num_workers > 0')\n\n self.dataset = dataset\n self.num_workers = num_workers\n self.prefetch_factor = prefetch_factor\n self.pin_memory = pin_memory\n self.timeout = timeout\n self.worker_init_fn = worker_init_fn\n self.multiprocessing_context = multiprocessing_context\n\n # Arg-check dataset related before checking samplers because we want to\n # tell users that iterable-style datasets are incompatible with custom\n # samplers first, so that they don't learn that this combo doesn't work\n # after spending time fixing the custom sampler errors.\n if isinstance(dataset, IterableDataset):\n self._dataset_kind = _DatasetKind.Iterable\n # NOTE [ Custom Samplers and IterableDataset ]\n #\n # `IterableDataset` does not support custom `batch_sampler` or\n # `sampler` since the key is irrelevant (unless we support\n # generator-style dataset one day...).\n #\n # For `sampler`, we always create a dummy sampler. This is an\n # infinite sampler even when the dataset may have an implemented\n # finite `__len__` because in multi-process data loading, naive\n # settings will return duplicated data (which may be desired), and\n # thus using a sampler with length matching that of dataset will\n # cause data lost (you may have duplicates of the first couple\n # batches, but never see anything afterwards). Therefore,\n # `Iterabledataset` always uses an infinite sampler, an instance of\n # `_InfiniteConstantSampler` defined above.\n #\n # A custom `batch_sampler` essentially only controls the batch size.\n # However, it is unclear how useful it would be since an iterable-style\n # dataset can handle that within itself. Moreover, it is pointless\n # in multi-process data loading as the assignment order of batches\n # to workers is an implementation detail so users can not control\n # how to batchify each worker's iterable. Thus, we disable this\n # option. If this turns out to be useful in future, we can re-enable\n # this, and support custom samplers that specify the assignments to\n # specific workers.\n if shuffle is not False:\n raise ValueError(\n \"DataLoader with IterableDataset: expected unspecified \"\n \"shuffle option, but got shuffle={}\".format(shuffle))\n elif sampler is not None:\n # See NOTE [ Custom Samplers and IterableDataset ]\n raise ValueError(\n \"DataLoader with IterableDataset: expected unspecified \"\n \"sampler option, but got sampler={}\".format(sampler))\n elif batch_sampler is not None:\n # See NOTE [ Custom Samplers and IterableDataset ]\n raise ValueError(\n \"DataLoader with IterableDataset: expected unspecified \"\n \"batch_sampler option, but got batch_sampler={}\".format(batch_sampler))\n else:\n self._dataset_kind = _DatasetKind.Map\n\n if sampler is not None and shuffle:\n raise ValueError('sampler option is mutually exclusive with '\n 'shuffle')\n\n if batch_sampler is not None:\n # auto_collation with custom batch_sampler\n if batch_size != 1 or shuffle or sampler is not None or drop_last:\n raise ValueError('batch_sampler option is mutually exclusive '\n 'with batch_size, shuffle, sampler, and '\n 'drop_last')\n batch_size = None\n drop_last = False\n elif batch_size is None:\n # no auto_collation\n if drop_last:\n raise ValueError('batch_size=None option disables auto-batching '\n 'and is mutually exclusive with drop_last')\n\n if sampler is None: # give default samplers\n if self._dataset_kind == _DatasetKind.Iterable:\n # See NOTE [ Custom Samplers and IterableDataset ]\n sampler = _InfiniteConstantSampler()\n else: # map-style\n if shuffle:\n # Cannot statically verify that dataset is Sized\n # Somewhat related: see NOTE [ Lack of Default `__len__` in Python Abstract Base Classes ]\n sampler = RandomSampler(dataset, generator=generator) # type: ignore\n else:\n sampler = SequentialSampler(dataset)\n\n if batch_size is not None and batch_sampler is None:\n # auto_collation without custom batch_sampler\n batch_sampler = BatchSampler(sampler, batch_size, drop_last)\n\n self.batch_size = batch_size\n self.drop_last = drop_last\n self.sampler = sampler\n self.batch_sampler = batch_sampler\n self.generator = generator\n\n if collate_fn is None:\n if self._auto_collation:\n collate_fn = _utils.collate.default_collate\n else:\n collate_fn = _utils.collate.default_convert\n\n self.collate_fn = collate_fn\n self.persistent_workers = persistent_workers\n\n self.__initialized = True\n self._IterableDataset_len_called = None # See NOTE [ IterableDataset and __len__ ]\n\n self._iterator = None\n\n def _get_iterator(self) -> '_BaseDataLoaderIter':\n if self.num_workers == 0:\n return _SingleProcessDataLoaderIter(self)\n else:\n return _MultiProcessingDataLoaderIter(self)\n\n @property\n def multiprocessing_context(self):\n return self.__multiprocessing_context\n\n @multiprocessing_context.setter\n def multiprocessing_context(self, multiprocessing_context):\n if multiprocessing_context is not None:\n if self.num_workers > 0:\n if not multiprocessing._supports_context:\n raise ValueError('multiprocessing_context relies on Python >= 3.4, with '\n 'support for different start methods')\n\n if isinstance(multiprocessing_context, string_classes):\n valid_start_methods = multiprocessing.get_all_start_methods()\n if multiprocessing_context not in valid_start_methods:\n raise ValueError(\n ('multiprocessing_context option '\n 'should specify a valid start method in {!r}, but got '\n 'multiprocessing_context={!r}').format(valid_start_methods, multiprocessing_context))\n # error: Argument 1 to \"get_context\" has incompatible type \"Union[str, bytes]\"; expected \"str\" [arg-type]\n multiprocessing_context = multiprocessing.get_context(multiprocessing_context) # type: ignore\n\n if not isinstance(multiprocessing_context, python_multiprocessing.context.BaseContext):\n raise TypeError(('multiprocessing_context option should be a valid context '\n 'object or a string specifying the start method, but got '\n 'multiprocessing_context={}').format(multiprocessing_context))\n else:\n raise ValueError(('multiprocessing_context can only be used with '\n 'multi-process loading (num_workers > 0), but got '\n 'num_workers={}').format(self.num_workers))\n\n self.__multiprocessing_context = multiprocessing_context\n\n def __setattr__(self, attr, val):\n if self.__initialized and attr in (\n 'batch_size', 'batch_sampler', 'sampler', 'drop_last', 'dataset', 'persistent_workers'):\n raise ValueError('{} attribute should not be set after {} is '\n 'initialized'.format(attr, self.__class__.__name__))\n\n super(DataLoader, self).__setattr__(attr, val)\n\n # We quote '_BaseDataLoaderIter' since it isn't defined yet and the definition can't be moved up\n # since '_BaseDataLoaderIter' references 'DataLoader'.\n def __iter__(self) -> '_BaseDataLoaderIter':\n # When using a single worker the returned iterator should be\n # created everytime to avoid reseting its state\n # However, in the case of a multiple workers iterator\n # the iterator is only created once in the lifetime of the\n # DataLoader object so that workers can be reused\n if self.persistent_workers and self.num_workers > 0:\n if self._iterator is None:\n self._iterator = self._get_iterator()\n else:\n self._iterator._reset(self)\n return self._iterator\n else:\n return self._get_iterator()\n\n @property\n def _auto_collation(self):\n return self.batch_sampler is not None\n\n @property\n def _index_sampler(self):\n # The actual sampler used for generating indices for `_DatasetFetcher`\n # (see _utils/fetch.py) to read data at each time. This would be\n # `.batch_sampler` if in auto-collation mode, and `.sampler` otherwise.\n # We can't change `.sampler` and `.batch_sampler` attributes for BC\n # reasons.\n if self._auto_collation:\n return self.batch_sampler\n else:\n return self.sampler\n\n def __len__(self) -> int:\n if self._dataset_kind == _DatasetKind.Iterable:\n # NOTE [ IterableDataset and __len__ ]\n #\n # For `IterableDataset`, `__len__` could be inaccurate when one naively\n # does multi-processing data loading, since the samples will be duplicated.\n # However, no real use case should be actually using that behavior, so\n # it should count as a user error. We should generally trust user\n # code to do the proper thing (e.g., configure each replica differently\n # in `__iter__`), and give us the correct `__len__` if they choose to\n # implement it (this will still throw if the dataset does not implement\n # a `__len__`).\n #\n # To provide a further warning, we track if `__len__` was called on the\n # `DataLoader`, save the returned value in `self._len_called`, and warn\n # if the iterator ends up yielding more than this number of samples.\n\n # Cannot statically verify that dataset is Sized\n length = self._IterableDataset_len_called = len(self.dataset) # type: ignore\n if self.batch_size is not None: # IterableDataset doesn't allow custom sampler or batch_sampler\n from math import ceil\n if self.drop_last:\n length = length // self.batch_size\n else:\n length = ceil(length / self.batch_size)\n return length\n else:\n return len(self._index_sampler)\n\n\nclass _BaseDataLoaderIter(object):\n def __init__(self, loader: DataLoader) -> None:\n self._dataset = loader.dataset\n self._dataset_kind = loader._dataset_kind\n self._IterableDataset_len_called = loader._IterableDataset_len_called\n self._auto_collation = loader._auto_collation\n self._drop_last = loader.drop_last\n self._index_sampler = loader._index_sampler\n self._num_workers = loader.num_workers\n self._prefetch_factor = loader.prefetch_factor\n self._pin_memory = loader.pin_memory and torch.cuda.is_available()\n self._timeout = loader.timeout\n self._collate_fn = loader.collate_fn\n self._sampler_iter = iter(self._index_sampler)\n self._base_seed = torch.empty((), dtype=torch.int64).random_(generator=loader.generator).item()\n self._persistent_workers = loader.persistent_workers\n self._num_yielded = 0\n\n def __iter__(self) -> '_BaseDataLoaderIter':\n return self\n\n def _reset(self, loader, first_iter=False):\n self._sampler_iter = iter(self._index_sampler)\n self._num_yielded = 0\n self._IterableDataset_len_called = loader._IterableDataset_len_called\n\n def _next_index(self):\n return next(self._sampler_iter) # may raise StopIteration\n\n def _next_data(self):\n raise NotImplementedError\n\n def __next__(self) -> Any:\n if self._sampler_iter is None:\n self._reset()\n data = self._next_data()\n self._num_yielded += 1\n if self._dataset_kind == _DatasetKind.Iterable and \\\n self._IterableDataset_len_called is not None and \\\n self._num_yielded > self._IterableDataset_len_called:\n warn_msg = (\"Length of IterableDataset {} was reported to be {} (when accessing len(dataloader)), but {} \"\n \"samples have been fetched. \").format(self._dataset, self._IterableDataset_len_called,\n self._num_yielded)\n if self._num_workers > 0:\n warn_msg += (\"For multiprocessing data-loading, this could be caused by not properly configuring the \"\n \"IterableDataset replica at each worker. Please see \"\n \"https://pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset for examples.\")\n warnings.warn(warn_msg)\n return data\n\n next = __next__ # Python 2 compatibility\n\n def __len__(self) -> int:\n return len(self._index_sampler)\n\n def __getstate__(self):\n # TODO: add limited pickling support for sharing an iterator\n # across multiple threads for HOGWILD.\n # Probably the best way to do this is by moving the sample pushing\n # to a separate thread and then just sharing the data queue\n # but signalling the end is tricky without a non-blocking API\n raise NotImplementedError(\"{} cannot be pickled\", self.__class__.__name__)\n\n\nclass _SingleProcessDataLoaderIter(_BaseDataLoaderIter):\n def __init__(self, loader):\n super(_SingleProcessDataLoaderIter, self).__init__(loader)\n assert self._timeout == 0\n assert self._num_workers == 0\n\n self._dataset_fetcher = _DatasetKind.create_fetcher(\n self._dataset_kind, self._dataset, self._auto_collation, self._collate_fn, self._drop_last)\n\n def _next_data(self):\n index = self._next_index() # may raise StopIteration\n data = self._dataset_fetcher.fetch(index) # may raise StopIteration\n if self._pin_memory:\n data = _utils.pin_memory.pin_memory(data)\n return data\n\n\nclass _MultiProcessingDataLoaderIter(_BaseDataLoaderIter):\n r\"\"\"Iterates once over the DataLoader's dataset, as specified by the sampler\"\"\"\n\n # NOTE [ Data Loader Multiprocessing Shutdown Logic ]\n #\n # Preliminary:\n #\n # Our data model looks like this (queues are indicated with curly brackets):\n #\n # main process ||\n # | ||\n # {index_queue} ||\n # | ||\n # worker processes || DATA\n # | ||\n # {worker_result_queue} || FLOW\n # | ||\n # pin_memory_thread of main process || DIRECTION\n # | ||\n # {data_queue} ||\n # | ||\n # data output \\/\n #\n # P.S. `worker_result_queue` and `pin_memory_thread` part may be omitted if\n # `pin_memory=False`.\n #\n #\n # Terminating multiprocessing logic requires very careful design. In\n # particular, we need to make sure that\n #\n # 1. The iterator gracefully exits the workers when its last reference is\n # gone or it is depleted.\n #\n # In this case, the workers should be gracefully exited because the\n # main process may still need to continue to run, and we want cleaning\n # up code in the workers to be executed (e.g., releasing GPU memory).\n # Naturally, we implement the shutdown logic in `__del__` of\n # DataLoaderIterator.\n #\n # We delay the discussion on the logic in this case until later.\n #\n # 2. The iterator exits the workers when the loader process and/or worker\n # processes exits normally or with error.\n #\n # We set all workers and `pin_memory_thread` to have `daemon=True`.\n #\n # You may ask, why can't we make the workers non-daemonic, and\n # gracefully exit using the same logic as we have in `__del__` when the\n # iterator gets deleted (see 1 above)?\n #\n # First of all, `__del__` is **not** guaranteed to be called when\n # interpreter exits. Even if it is called, by the time it executes,\n # many Python core library resources may alreay be freed, and even\n # simple things like acquiring an internal lock of a queue may hang.\n # Therefore, in this case, we actually need to prevent `__del__` from\n # being executed, and rely on the automatic termination of daemonic\n # children. Thus, we register an `atexit` hook that sets a global flag\n # `_utils.python_exit_status`. Since `atexit` hooks are executed in the\n # reverse order of registration, we are guaranteed that this flag is\n # set before library resources we use are freed. (Hooks freeing those\n # resources are registered at importing the Python core libraries at\n # the top of this file.) So in `__del__`, we check if\n # `_utils.python_exit_status` is set or `None` (freed), and perform\n # no-op if so.\n #\n # Another problem with `__del__` is also related to the library cleanup\n # calls. When a process ends, it shuts the all its daemonic children\n # down with a SIGTERM (instead of joining them without a timeout).\n # Simiarly for threads, but by a different mechanism. This fact,\n # together with a few implementation details of multiprocessing, forces\n # us to make workers daemonic. All of our problems arise when a\n # DataLoader is used in a subprocess, and are caused by multiprocessing\n # code which looks more or less like this:\n #\n # try:\n # your_function_using_a_dataloader()\n # finally:\n # multiprocessing.util._exit_function()\n #\n # The joining/termination mentioned above happens inside\n # `_exit_function()`. Now, if `your_function_using_a_dataloader()`\n # throws, the stack trace stored in the exception will prevent the\n # frame which uses `DataLoaderIter` to be freed. If the frame has any\n # reference to the `DataLoaderIter` (e.g., in a method of the iter),\n # its `__del__`, which starts the shutdown procedure, will not be\n # called. That, in turn, means that workers aren't notified. Attempting\n # to join in `_exit_function` will then result in a hang.\n #\n # For context, `_exit_function` is also registered as an `atexit` call.\n # So it is unclear to me (@ssnl) why this is needed in a finally block.\n # The code dates back to 2008 and there is no comment on the original\n # PEP 371 or patch https://bugs.python.org/issue3050 (containing both\n # the finally block and the `atexit` registration) that explains this.\n #\n # Another choice is to just shutdown workers with logic in 1 above\n # whenever we see an error in `next`. This isn't ideal because\n # a. It prevents users from using try-catch to resume data loading.\n # b. It doesn't prevent hanging if users have references to the\n # iterator.\n #\n # 3. All processes exit if any of them die unexpectedly by fatal signals.\n #\n # As shown above, the workers are set as daemonic children of the main\n # process. However, automatic cleaning-up of such child processes only\n # happens if the parent process exits gracefully (e.g., not via fatal\n # signals like SIGKILL). So we must ensure that each process will exit\n # even the process that should send/receive data to/from it were\n # killed, i.e.,\n #\n # a. A process won't hang when getting from a queue.\n #\n # Even with carefully designed data dependencies (i.e., a `put()`\n # always corresponding to a `get()`), hanging on `get()` can still\n # happen when data in queue is corrupted (e.g., due to\n # `cancel_join_thread` or unexpected exit).\n #\n # For child exit, we set a timeout whenever we try to get data\n # from `data_queue`, and check the workers' status on each timeout\n # and error.\n # See `_DataLoaderiter._get_batch()` and\n # `_DataLoaderiter._try_get_data()` for details.\n #\n # Additionally, for child exit on non-Windows platforms, we also\n # register a SIGCHLD handler (which is supported on Windows) on\n # the main process, which checks if any of the workers fail in the\n # (Python) handler. This is more efficient and faster in detecting\n # worker failures, compared to only using the above mechanism.\n # See `DataLoader.cpp` and `_utils/signal_handling.py` for details.\n #\n # For `.get()` calls where the sender(s) is not the workers, we\n # guard them with timeouts, and check the status of the sender\n # when timeout happens:\n # + in the workers, the `_utils.worker.ManagerWatchdog` class\n # checks the status of the main process.\n # + if `pin_memory=True`, when getting from `pin_memory_thread`,\n # check `pin_memory_thread` status periodically until `.get()`\n # returns or see that `pin_memory_thread` died.\n #\n # b. A process won't hang when putting into a queue;\n #\n # We use `mp.Queue` which has a separate background thread to put\n # objects from an unbounded buffer array. The background thread is\n # daemonic and usually automatically joined when the process\n # exits.\n #\n # However, in case that the receiver has ended abruptly while\n # reading from the pipe, the join will hang forever. Therefore,\n # for both `worker_result_queue` (worker -> main process/pin_memory_thread)\n # and each `index_queue` (main process -> worker), we use\n # `q.cancel_join_thread()` in sender process before any `q.put` to\n # prevent this automatic join.\n #\n # Moreover, having all queues called `cancel_join_thread` makes\n # implementing graceful shutdown logic in `__del__` much easier.\n # It won't need to get from any queue, which would also need to be\n # guarded by periodic status checks.\n #\n # Nonetheless, `cancel_join_thread` must only be called when the\n # queue is **not** going to be read from or write into by another\n # process, because it may hold onto a lock or leave corrupted data\n # in the queue, leading other readers/writers to hang.\n #\n # `pin_memory_thread`'s `data_queue` is a `queue.Queue` that does\n # a blocking `put` if the queue is full. So there is no above\n # problem, but we do need to wrap the `put` in a loop that breaks\n # not only upon success, but also when the main process stops\n # reading, i.e., is shutting down.\n #\n #\n # Now let's get back to 1:\n # how we gracefully exit the workers when the last reference to the\n # iterator is gone.\n #\n # To achieve this, we implement the following logic along with the design\n # choices mentioned above:\n #\n # `workers_done_event`:\n # A `multiprocessing.Event` shared among the main process and all worker\n # processes. This is used to signal the workers that the iterator is\n # shutting down. After it is set, they will not send processed data to\n # queues anymore, and only wait for the final `None` before exiting.\n # `done_event` isn't strictly needed. I.e., we can just check for `None`\n # from the input queue, but it allows us to skip wasting resources\n # processing data if we are already shutting down.\n #\n # `pin_memory_thread_done_event`:\n # A `threading.Event` for a similar purpose to that of\n # `workers_done_event`, but is for the `pin_memory_thread`. The reason\n # that separate events are needed is that `pin_memory_thread` reads from\n # the output queue of the workers. But the workers, upon seeing that\n # `workers_done_event` is set, only wants to see the final `None`, and is\n # not required to flush all data in the output queue (e.g., it may call\n # `cancel_join_thread` on that queue if its `IterableDataset` iterator\n # happens to exhaust coincidentally, which is out of the control of the\n # main process). Thus, since we will exit `pin_memory_thread` before the\n # workers (see below), two separete events are used.\n #\n # NOTE: In short, the protocol is that the main process will set these\n # `done_event`s and then the corresponding processes/threads a `None`,\n # and that they may exit at any time after receiving the `None`.\n #\n # NOTE: Using `None` as the final signal is valid, since normal data will\n # always be a 2-tuple with the 1st element being the index of the data\n # transferred (different from dataset index/key), and the 2nd being\n # either the dataset key or the data sample (depending on which part\n # of the data model the queue is at).\n #\n # [ worker processes ]\n # While loader process is alive:\n # Get from `index_queue`.\n # If get anything else,\n # Check `workers_done_event`.\n # If set, continue to next iteration\n # i.e., keep getting until see the `None`, then exit.\n # Otherwise, process data:\n # If is fetching from an `IterableDataset` and the iterator\n # is exhausted, send an `_IterableDatasetStopIteration`\n # object to signal iteration end. The main process, upon\n # receiving such an object, will send `None` to this\n # worker and not use the corresponding `index_queue`\n # anymore.\n # If timed out,\n # No matter `workers_done_event` is set (still need to see `None`)\n # or not, must continue to next iteration.\n # (outside loop)\n # If `workers_done_event` is set, (this can be False with `IterableDataset`)\n # `data_queue.cancel_join_thread()`. (Everything is ending here:\n # main process won't read from it;\n # other workers will also call\n # `cancel_join_thread`.)\n #\n # [ pin_memory_thread ]\n # # No need to check main thread. If this thread is alive, the main loader\n # # thread must be alive, because this thread is set as daemonic.\n # While `pin_memory_thread_done_event` is not set:\n # Get from `index_queue`.\n # If timed out, continue to get in the next iteration.\n # Otherwise, process data.\n # While `pin_memory_thread_done_event` is not set:\n # Put processed data to `data_queue` (a `queue.Queue` with blocking put)\n # If timed out, continue to put in the next iteration.\n # Otherwise, break, i.e., continuing to the out loop.\n #\n # NOTE: we don't check the status of the main thread because\n # 1. if the process is killed by fatal signal, `pin_memory_thread`\n # ends.\n # 2. in other cases, either the cleaning-up in __del__ or the\n # automatic exit of daemonic thread will take care of it.\n # This won't busy-wait either because `.get(timeout)` does not\n # busy-wait.\n #\n # [ main process ]\n # In the DataLoader Iter's `__del__`\n # b. Exit `pin_memory_thread`\n # i. Set `pin_memory_thread_done_event`.\n # ii Put `None` in `worker_result_queue`.\n # iii. Join the `pin_memory_thread`.\n # iv. `worker_result_queue.cancel_join_thread()`.\n #\n # c. Exit the workers.\n # i. Set `workers_done_event`.\n # ii. Put `None` in each worker's `index_queue`.\n # iii. Join the workers.\n # iv. Call `.cancel_join_thread()` on each worker's `index_queue`.\n #\n # NOTE: (c) is better placed after (b) because it may leave corrupted\n # data in `worker_result_queue`, which `pin_memory_thread`\n # reads from, in which case the `pin_memory_thread` can only\n # happen at timeing out, which is slow. Nonetheless, same thing\n # happens if a worker is killed by signal at unfortunate times,\n # but in other cases, we are better off having a non-corrupted\n # `worker_result_queue` for `pin_memory_thread`.\n #\n # NOTE: If `pin_memory=False`, there is no `pin_memory_thread` and (b)\n # can be omitted\n #\n # NB: `done_event`s isn't strictly needed. E.g., we can just check for\n # `None` from `index_queue`, but it allows us to skip wasting resources\n # processing indices already in `index_queue` if we are already shutting\n # down.\n\n def __init__(self, loader):\n super(_MultiProcessingDataLoaderIter, self).__init__(loader)\n\n assert self._num_workers > 0\n assert self._prefetch_factor > 0\n\n if loader.multiprocessing_context is None:\n multiprocessing_context = multiprocessing\n else:\n multiprocessing_context = loader.multiprocessing_context\n\n self._worker_init_fn = loader.worker_init_fn\n self._worker_queue_idx_cycle = itertools.cycle(range(self._num_workers))\n # No certainty which module multiprocessing_context is\n self._worker_result_queue = multiprocessing_context.Queue() # type: ignore\n self._worker_pids_set = False\n self._shutdown = False\n self._workers_done_event = multiprocessing_context.Event()\n\n self._index_queues = []\n self._workers = []\n for i in range(self._num_workers):\n # No certainty which module multiprocessing_context is\n index_queue = multiprocessing_context.Queue() # type: ignore\n # index_queue.cancel_join_thread()\n w = multiprocessing_context.Process(\n target=_utils.worker._worker_loop,\n args=(self._dataset_kind, self._dataset, index_queue,\n self._worker_result_queue, self._workers_done_event,\n self._auto_collation, self._collate_fn, self._drop_last,\n self._base_seed + i, self._worker_init_fn, i, self._num_workers,\n self._persistent_workers))\n w.daemon = True\n # NB: Process.start() actually take some time as it needs to\n # start a process and pass the arguments over via a pipe.\n # Therefore, we only add a worker to self._workers list after\n # it started, so that we do not call .join() if program dies\n # before it starts, and __del__ tries to join but will get:\n # AssertionError: can only join a started process.\n w.start()\n self._index_queues.append(index_queue)\n self._workers.append(w)\n\n if self._pin_memory:\n self._pin_memory_thread_done_event = threading.Event()\n\n # Queue is not type-annotated\n self._data_queue = queue.Queue() # type: ignore\n pin_memory_thread = threading.Thread(\n target=_utils.pin_memory._pin_memory_loop,\n args=(self._worker_result_queue, self._data_queue,\n torch.cuda.current_device(),\n self._pin_memory_thread_done_event))\n pin_memory_thread.daemon = True\n pin_memory_thread.start()\n # Similar to workers (see comment above), we only register\n # pin_memory_thread once it is started.\n self._pin_memory_thread = pin_memory_thread\n else:\n self._data_queue = self._worker_result_queue\n\n # .pid can be None only before process is spawned (not the case, so ignore)\n _utils.signal_handling._set_worker_pids(id(self), tuple(w.pid for w in self._workers)) # type: ignore\n _utils.signal_handling._set_SIGCHLD_handler()\n self._worker_pids_set = True\n self._reset(loader, first_iter=True)\n\n def _reset(self, loader, first_iter=False):\n super()._reset(loader, first_iter)\n self._send_idx = 0 # idx of the next task to be sent to workers\n self._rcvd_idx = 0 # idx of the next task to be returned in __next__\n # information about data not yet yielded, i.e., tasks w/ indices in range [rcvd_idx, send_idx).\n # map: task idx => - (worker_id,) if data isn't fetched (outstanding)\n # \\ (worker_id, data) if data is already fetched (out-of-order)\n self._task_info = {}\n self._tasks_outstanding = 0 # always equal to count(v for v in task_info.values() if len(v) == 1)\n # A list of booleans representing whether each worker still has work to\n # do, i.e., not having exhausted its iterable dataset object. It always\n # contains all `True`s if not using an iterable-style dataset\n # (i.e., if kind != Iterable).\n # Not that this indicates that a worker still has work to do *for this epoch*.\n # It does not mean that a worker is dead. In case of `_persistent_workers`, \n # the worker will be reset to available in the next epoch.\n self._workers_status = [True for i in range(self._num_workers)]\n # We resume the prefetching in case it was enabled\n if not first_iter:\n for idx in range(self._num_workers):\n self._index_queues[idx].put(_utils.worker._ResumeIteration())\n resume_iteration_cnt = self._num_workers\n while resume_iteration_cnt > 0:\n data = self._get_data()\n if isinstance(data, _utils.worker._ResumeIteration):\n resume_iteration_cnt -= 1\n # prime the prefetch loop\n for _ in range(self._prefetch_factor * self._num_workers):\n self._try_put_index()\n\n def _try_get_data(self, timeout=_utils.MP_STATUS_CHECK_INTERVAL):\n # Tries to fetch data from `self._data_queue` once for a given timeout.\n # This can also be used as inner loop of fetching without timeout, with\n # the sender status as the loop condition.\n #\n # This raises a `RuntimeError` if any worker died expectedly. This error\n # can come from either the SIGCHLD handler in `_utils/signal_handling.py`\n # (only for non-Windows platforms), or the manual check below on errors\n # and timeouts.\n #\n # Returns a 2-tuple:\n # (bool: whether successfully get data, any: data if successful else None)\n try:\n data = self._data_queue.get(timeout=timeout)\n return (True, data)\n except Exception as e:\n # At timeout and error, we manually check whether any worker has\n # failed. Note that this is the only mechanism for Windows to detect\n # worker failures.\n failed_workers = []\n for worker_id, w in enumerate(self._workers):\n if self._workers_status[worker_id] and not w.is_alive():\n failed_workers.append(w)\n self._mark_worker_as_unavailable(worker_id)\n if len(failed_workers) > 0:\n pids_str = ', '.join(str(w.pid) for w in failed_workers)\n raise RuntimeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(pids_str)) from e\n if isinstance(e, queue.Empty):\n return (False, None)\n import tempfile\n import errno\n try:\n # Raise an exception if we are this close to the FDs limit.\n # Apparently, trying to open only one file is not a sufficient\n # test.\n # See NOTE [ DataLoader on Linux and open files limit ]\n fds_limit_margin = 10\n fs = [tempfile.NamedTemporaryFile() for i in range(fds_limit_margin)]\n except OSError as e:\n if e.errno == errno.EMFILE:\n raise RuntimeError(\n \"Too many open files. Communication with the\"\n \" workers is no longer possible. Please increase the\"\n \" limit using `ulimit -n` in the shell or change the\"\n \" sharing strategy by calling\"\n \" `torch.multiprocessing.set_sharing_strategy('file_system')`\"\n \" at the beginning of your code\") from None\n raise\n\n# NOTE [ DataLoader on Linux and open files limit ]\n#\n# On Linux when DataLoader is used with multiprocessing we pass the data between\n# the root process and the workers through SHM files. We remove those files from\n# the filesystem as soon as they are created and keep them alive by\n# passing around their file descriptors through AF_UNIX sockets. (See\n# docs/source/multiprocessing.rst and 'Multiprocessing Technical Notes` in\n# the wiki (https://github.com/pytorch/pytorch/wiki).)\n#\n# This sometimes leads us to exceeding the open files limit. When that happens,\n# and the offending file descriptor is coming over a socket, the `socket` Python\n# package silently strips the file descriptor from the message, setting only the\n# `MSG_CTRUNC` flag (which might be a bit misleading since the manpage says that\n# it _indicates that some control data were discarded due to lack of space in\n# the buffer for ancillary data_). This might reflect the C implementation of\n# AF_UNIX sockets.\n#\n# This behaviour can be reproduced with the script and instructions at the\n# bottom of this note.\n#\n# When that happens, the standard Python `multiprocessing` (and not\n# `torch.multiprocessing`) raises a `RuntimeError: received 0 items of ancdata`\n#\n# Sometimes, instead of the FD being stripped, you may get an `OSError:\n# Too many open files`, both in the script below and in DataLoader. However,\n# this is rare and seems to be nondeterministic.\n#\n#\n# #!/usr/bin/env python3\n# import sys\n# import socket\n# import os\n# import array\n# import shutil\n# import socket\n#\n#\n# if len(sys.argv) != 4:\n# print(\"Usage: \", sys.argv[0], \" tmp_dirname iteration (send|recv)\")\n# sys.exit(1)\n#\n# if __name__ == '__main__':\n# dirname = sys.argv[1]\n# sock_path = dirname + \"/sock\"\n# iterations = int(sys.argv[2])\n# def dummy_path(i):\n# return dirname + \"/\" + str(i) + \".dummy\"\n#\n#\n# if sys.argv[3] == 'send':\n# while not os.path.exists(sock_path):\n# pass\n# client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)\n# client.connect(sock_path)\n# for i in range(iterations):\n# fd = os.open(dummy_path(i), os.O_WRONLY | os.O_CREAT)\n# ancdata = array.array('i', [fd])\n# msg = bytes([i % 256])\n# print(\"Sending fd \", fd, \" (iteration #\", i, \")\")\n# client.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, ancdata)])\n#\n#\n# else:\n# assert sys.argv[3] == 'recv'\n#\n# if os.path.exists(dirname):\n# raise Exception(\"Directory exists\")\n#\n# os.mkdir(dirname)\n#\n# print(\"Opening socket...\")\n# server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)\n# server.bind(sock_path)\n#\n# print(\"Listening...\")\n# for i in range(iterations):\n# a = array.array('i')\n# msg, ancdata, flags, addr = server.recvmsg(1, socket.CMSG_SPACE(a.itemsize))\n# assert(len(ancdata) == 1)\n# cmsg_level, cmsg_type, cmsg_data = ancdata[0]\n# a.frombytes(cmsg_data)\n# print(\"Received fd \", a[0], \" (iteration #\", i, \")\")\n#\n# shutil.rmtree(dirname)\n#\n# Steps to reproduce:\n#\n# 1. Run two shells and set lower file descriptor limit in the receiving one:\n# (shell1) ulimit -n 1020\n# (shell2) ulimit -n 1022\n#\n# 2. Run the script above with the `recv` option in the first shell\n# (shell1) ./test_socket.py sock_tmp 1017 recv\n#\n# 3. Run the script with the `send` option in the second shell:\n# (shell2) ./test_socket.py sock_tmp 1017 send\n\n def _get_data(self):\n # Fetches data from `self._data_queue`.\n #\n # We check workers' status every `MP_STATUS_CHECK_INTERVAL` seconds,\n # which we achieve by running `self._try_get_data(timeout=MP_STATUS_CHECK_INTERVAL)`\n # in a loop. This is the only mechanism to detect worker failures for\n # Windows. For other platforms, a SIGCHLD handler is also used for\n # worker failure detection.\n #\n # If `pin_memory=True`, we also need check if `pin_memory_thread` had\n # died at timeouts.\n if self._timeout > 0:\n success, data = self._try_get_data(self._timeout)\n if success:\n return data\n else:\n raise RuntimeError('DataLoader timed out after {} seconds'.format(self._timeout))\n elif self._pin_memory:\n while self._pin_memory_thread.is_alive():\n success, data = self._try_get_data()\n if success:\n return data\n else:\n # while condition is false, i.e., pin_memory_thread died.\n raise RuntimeError('Pin memory thread exited unexpectedly')\n # In this case, `self._data_queue` is a `queue.Queue`,. But we don't\n # need to call `.task_done()` because we don't use `.join()`.\n else:\n while True:\n success, data = self._try_get_data()\n if success:\n return data\n\n def _next_data(self):\n while True:\n # If the worker responsible for `self._rcvd_idx` has already ended\n # and was unable to fulfill this task (due to exhausting an `IterableDataset`),\n # we try to advance `self._rcvd_idx` to find the next valid index.\n #\n # This part needs to run in the loop because both the `self._get_data()`\n # call and `_IterableDatasetStopIteration` check below can mark\n # extra worker(s) as dead.\n while self._rcvd_idx < self._send_idx:\n info = self._task_info[self._rcvd_idx]\n worker_id = info[0]\n if len(info) == 2 or self._workers_status[worker_id]: # has data or is still active\n break\n del self._task_info[self._rcvd_idx]\n self._rcvd_idx += 1\n else:\n # no valid `self._rcvd_idx` is found (i.e., didn't break)\n if not self._persistent_workers:\n self._shutdown_workers()\n raise StopIteration\n\n # Now `self._rcvd_idx` is the batch index we want to fetch\n\n # Check if the next sample has already been generated\n if len(self._task_info[self._rcvd_idx]) == 2:\n data = self._task_info.pop(self._rcvd_idx)[1]\n return self._process_data(data)\n\n assert not self._shutdown and self._tasks_outstanding > 0\n idx, data = self._get_data()\n self._tasks_outstanding -= 1\n if self._dataset_kind == _DatasetKind.Iterable:\n # Check for _IterableDatasetStopIteration\n if isinstance(data, _utils.worker._IterableDatasetStopIteration):\n if self._persistent_workers:\n self._workers_status[data.worker_id] = False\n else:\n self._mark_worker_as_unavailable(data.worker_id)\n self._try_put_index()\n continue\n\n if idx != self._rcvd_idx:\n # store out-of-order samples\n self._task_info[idx] += (data,)\n else:\n del self._task_info[idx]\n return self._process_data(data)\n\n def _try_put_index(self):\n assert self._tasks_outstanding < self._prefetch_factor * self._num_workers\n\n try:\n index = self._next_index()\n except StopIteration:\n return\n for _ in range(self._num_workers): # find the next active worker, if any\n worker_queue_idx = next(self._worker_queue_idx_cycle)\n if self._workers_status[worker_queue_idx]:\n break\n else:\n # not found (i.e., didn't break)\n return\n\n self._index_queues[worker_queue_idx].put((self._send_idx, index))\n self._task_info[self._send_idx] = (worker_queue_idx,)\n self._tasks_outstanding += 1\n self._send_idx += 1\n\n def _process_data(self, data):\n self._rcvd_idx += 1\n self._try_put_index()\n if isinstance(data, ExceptionWrapper):\n data.reraise()\n return data\n\n def _mark_worker_as_unavailable(self, worker_id, shutdown=False):\n # Mark a worker as having finished its work e.g., due to\n # exhausting an `IterableDataset`. This should be used only when this\n # `_MultiProcessingDataLoaderIter` is going to continue running.\n\n assert self._workers_status[worker_id] or (self._persistent_workers and shutdown)\n\n # Signal termination to that specific worker.\n q = self._index_queues[worker_id]\n # Indicate that no more data will be put on this queue by the current\n # process.\n q.put(None)\n\n # Note that we don't actually join the worker here, nor do we remove the\n # worker's pid from C side struct because (1) joining may be slow, and\n # (2) since we don't join, the worker may still raise error, and we\n # prefer capturing those, rather than ignoring them, even though they\n # are raised after the worker has finished its job.\n # Joinning is deferred to `_shutdown_workers`, which it is called when\n # all workers finish their jobs (e.g., `IterableDataset` replicas) or\n # when this iterator is garbage collected.\n\n self._workers_status[worker_id] = False\n\n assert self._workers_done_event.is_set() == shutdown\n\n def _shutdown_workers(self):\n # Called when shutting down this `_MultiProcessingDataLoaderIter`.\n # See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on\n # the logic of this function.\n python_exit_status = _utils.python_exit_status\n if python_exit_status is True or python_exit_status is None:\n # See (2) of the note. If Python is shutting down, do no-op.\n return\n # Normal exit when last reference is gone / iterator is depleted.\n # See (1) and the second half of the note.\n if not self._shutdown:\n self._shutdown = True\n try:\n # Exit `pin_memory_thread` first because exiting workers may leave\n # corrupted data in `worker_result_queue` which `pin_memory_thread`\n # reads from.\n if hasattr(self, '_pin_memory_thread'):\n # Use hasattr in case error happens before we set the attribute.\n self._pin_memory_thread_done_event.set()\n # Send something to pin_memory_thread in case it is waiting\n # so that it can wake up and check `pin_memory_thread_done_event`\n self._worker_result_queue.put((None, None))\n self._pin_memory_thread.join()\n self._worker_result_queue.cancel_join_thread()\n self._worker_result_queue.close()\n\n # Exit workers now.\n self._workers_done_event.set()\n for worker_id in range(len(self._workers)):\n # Get number of workers from `len(self._workers)` instead of\n # `self._num_workers` in case we error before starting all\n # workers.\n # If we are using workers_status with persistent_workers\n # we have to shut it down because the worker is paused\n if self._persistent_workers or self._workers_status[worker_id]:\n self._mark_worker_as_unavailable(worker_id, shutdown=True)\n for w in self._workers:\n w.join(timeout=_utils.MP_STATUS_CHECK_INTERVAL)\n if w.is_alive():\n # Existing mechanisms try to make the workers exit\n # peacefully, but in case that we unfortunately reach\n # here, which we shouldn't, (e.g., pytorch/pytorch#39570),\n # we kill the worker.\n w.terminate()\n for q in self._index_queues:\n q.cancel_join_thread()\n q.close()\n finally:\n # Even though all this function does is putting into queues that\n # we have called `cancel_join_thread` on, weird things can\n # happen when a worker is killed by a signal, e.g., hanging in\n # `Event.set()`. So we need to guard this with SIGCHLD handler,\n # and remove pids from the C side data structure only at the\n # end.\n #\n # FIXME: Unfortunately, for Windows, we are missing a worker\n # error detection mechanism here in this function, as it\n # doesn't provide a SIGCHLD handler.\n if self._worker_pids_set:\n _utils.signal_handling._remove_worker_pids(id(self))\n self._worker_pids_set = False\n\n def __del__(self):\n self._shutdown_workers()\n", "import pickle\nimport torch\nimport warnings\nfrom torch._six import string_classes\nfrom datetime import timedelta\n\n# This module is wildcard imported from torch.distributed.\n# TODO: specify __all__\n\nfrom .constants import default_pg_timeout\nfrom .rendezvous import rendezvous, register_rendezvous_handler # noqa: F401\nfrom . import (\n AllreduceOptions,\n AllreduceCoalescedOptions,\n AllToAllOptions,\n BroadcastOptions,\n GatherOptions,\n ReduceOptions,\n ReduceScatterOptions,\n ScatterOptions,\n)\nfrom . import ReduceOp\nfrom . import PrefixStore\n\n\n_MPI_AVAILABLE = True\n_NCCL_AVAILABLE = True\n_GLOO_AVAILABLE = True\n\n\ntry:\n from. import ProcessGroupMPI\nexcept ImportError:\n _MPI_AVAILABLE = False\n\ntry:\n from. import ProcessGroupNCCL\nexcept ImportError:\n _NCCL_AVAILABLE = False\n\ntry:\n from. import ProcessGroupGloo\nexcept ImportError:\n _GLOO_AVAILABLE = False\n\n\nclass Backend(object):\n \"\"\"\n An enum-like class of available backends: GLOO, NCCL, MPI, and other registered\n backends.\n\n The values of this class are lowercase strings, e.g., ``\"gloo\"``. They can\n be accessed as attributes, e.g., ``Backend.NCCL``.\n\n This class can be directly called to parse the string, e.g.,\n ``Backend(backend_str)`` will check if ``backend_str`` is valid, and\n return the parsed lowercase string if so. It also accepts uppercase strings,\n e.g., ``Backend(\"GLOO\")`` returns ``\"gloo\"``.\n\n .. note:: The entry ``Backend.UNDEFINED`` is present but only used as\n initial value of some fields. Users should neither use it directly\n nor assume its existence.\n \"\"\"\n UNDEFINED = \"undefined\"\n GLOO = \"gloo\"\n NCCL = \"nccl\"\n MPI = \"mpi\"\n TCP = \"tcp\"\n\n def __new__(cls, name):\n if not isinstance(name, string_classes):\n raise ValueError(\"Backend name must be a string, but got: {}\".format(name))\n value = getattr(Backend, name.upper(), Backend.UNDEFINED)\n\n if value == Backend.TCP:\n raise ValueError(\"TCP backend has been deprecated. Please use \"\n \"Gloo or MPI backend for collective operations \"\n \"on CPU tensors.\")\n elif value == Backend.UNDEFINED:\n raise ValueError(\"Invalid backend: '{}'\".format(name))\n elif value != Backend.GLOO and value != Backend.NCCL and value != Backend.MPI:\n value = name\n return value\n\n @classmethod\n def register_backend(cls, name, func):\n \"\"\"\n Registers a new backend.\n\n This class method is used by 3rd party cpp extension to register new backend.\n\n Arguments:\n name (str): Backend name matching with the one in `init_process_group()`.\n func (function): Function handler that instantiates the backend.\n The function should be implemented in the backend cpp extension\n and takes four arguments, including prefix_store, rank,\n world_size, and timeout.\n\n .. note:: This support of 3rd party backend is experimental and subject to change.\n\n \"\"\"\n setattr(Backend, name.upper(), func)\n\n# `_backend`, `dist_backend`, and `reduce_op` are here to maintain backward\n# compatibility with pre-c10d distributed package.\n# TODO: remove them when users are ready to take a hard dependency on PyTorch 1.\n_backend = Backend.UNDEFINED\ndist_backend = Backend\n\n\nclass reduce_op(object):\n r\"\"\"\n Deprecated enum-like class for reduction operations: ``SUM``, ``PRODUCT``,\n ``MIN``, and ``MAX``.\n\n :class:`~torch.distributed.ReduceOp` is recommended to use instead.\n \"\"\"\n\n def __init__(self):\n # __members__ is a dict storing key-value pairs for enum classes\n for k, v in ReduceOp.__members__.items():\n setattr(self, k, v)\n self.__members__ = ReduceOp.__members__\n\n def __getattribute__(self, key):\n warnings.warn(\"torch.distributed.reduce_op is deprecated, please use \"\n \"torch.distributed.ReduceOp instead\")\n return object.__getattribute__(self, key)\n\nreduce_op = reduce_op()\n\n\nclass group(object):\n WORLD = object()\n\n\nclass GroupMember(object):\n # Alias to group.WORLD for backward compatibility\n WORLD = group.WORLD\n NON_GROUP_MEMBER = object()\n\n\n# Cached process groups\n# For NCCL and GLOO pg, it is a map from ProcessGroup to (Backend, Store)\n# For MPI pg, it is a map from ProcessGroup to (Backend, None)\n_pg_map = {}\n# Process group's names, map from ProcessGroup to str\n_pg_names = {}\n# Process group's global rank to local rank mapping\n_pg_group_ranks = {}\n\n# Default process group state\n_default_pg = None\n_default_pg_init_method = None\n\n# Process group count for default naming\n_group_count = 0\n\n\ndef _rank_not_in_group(group):\n \"\"\"\n Helper that checks if the current process's rank is not in a given group\n\n \"\"\"\n if group == GroupMember.WORLD:\n return False\n return group == GroupMember.NON_GROUP_MEMBER\n\n\ndef _get_group_rank(group, rank):\n \"\"\"\n Helper that gets a given group's local rank in the group from a given global\n rank\n\n \"\"\"\n if group is GroupMember.WORLD:\n raise RuntimeError(\"group.WORLD does not have local rank to global \"\n \"rank mapping\")\n if group not in _pg_group_ranks:\n raise RuntimeError(\"The given group does not exist\")\n try:\n group_rank = _pg_group_ranks[group][rank]\n except KeyError:\n raise RuntimeError(f\"The global rank {rank} is not part of the group {group}\") from None\n return group_rank\n\n\ndef _get_global_rank(group, group_rank):\n \"\"\"\n Helper that gets a given group's global rank from a given local rank in the\n group\n\n \"\"\"\n if group is GroupMember.WORLD:\n raise RuntimeError(\"group.WORLD does not have local rank to global \"\n \"rank mapping\")\n group_rank_map = _pg_group_ranks[group]\n for rank, grp_rank in group_rank_map.items():\n if grp_rank == group_rank:\n return rank\n raise RuntimeError(\"The group rank is not part of the group\")\n\n\ndef _check_default_pg():\n \"\"\"\n Helper that checks if the default ProcessGroup has been initialized, with\n assertion\n\n \"\"\"\n assert _default_pg is not None, \\\n \"Default process group is not initialized\"\n\n\ndef _get_group_size(group):\n \"\"\"\n Helper that gets a given group's world size\n\n \"\"\"\n if group is GroupMember.WORLD:\n _check_default_pg()\n return _default_pg.size()\n if group not in _pg_group_ranks:\n raise RuntimeError(\"The given group does not exist\")\n return len(_pg_group_ranks[group])\n\n\ndef _check_single_tensor(param, param_name):\n \"\"\"\n Helper to check that the parameter ``param_name`` is a single tensor.\n\n \"\"\"\n if not isinstance(param, torch.Tensor):\n raise RuntimeError(\"Invalid function argument. Expected parameter `{}` \"\n \"to be of type torch.Tensor.\".format(param_name))\n\n\ndef _check_tensor_list(param, param_name):\n \"\"\"\n Helper to check that the parameter ``param_name`` is a list of tensors.\n\n \"\"\"\n if not isinstance(param, list) or \\\n not all(isinstance(p, torch.Tensor) for p in param):\n raise RuntimeError(\"Invalid function argument. Expected parameter `{}` \"\n \"to be of type List[torch.Tensor].\".format(param_name))\n\n\ndef is_mpi_available():\n \"\"\"\n Checks if the MPI backend is available.\n\n \"\"\"\n return _MPI_AVAILABLE\n\n\ndef is_nccl_available():\n \"\"\"\n Checks if the NCCL backend is available.\n\n \"\"\"\n return _NCCL_AVAILABLE\n\n\ndef is_gloo_available():\n \"\"\"\n Checks if the Gloo backend is available.\n\n \"\"\"\n return _GLOO_AVAILABLE\n\n\ndef is_initialized():\n \"\"\"\n Checking if the default process group has been initialized\n\n \"\"\"\n return _default_pg is not None\n\n\ndef _get_default_group():\n \"\"\"\n Getting the default process group created by init_process_group\n\n \"\"\"\n if not is_initialized():\n raise RuntimeError(\"Default process group has not been initialized, \"\n \"please make sure to call init_process_group.\")\n return _default_pg\n\n\ndef _get_default_store():\n \"\"\"\n Getting the default store created by init_process_group\n\n \"\"\"\n if not is_initialized():\n raise RuntimeError(\"Default process group has not been initialized, \"\n \"please make sure to call init_process_group.\")\n _, default_store = _pg_map[_default_pg]\n return default_store\n\n\ndef get_backend(group=group.WORLD):\n \"\"\"\n Returns the backend of the given process group.\n\n Arguments:\n group (ProcessGroup, optional): The process group to work on. The\n default is the general main process group. If another specific group\n is specified, the calling process must be part of :attr:`group`.\n\n Returns:\n The backend of the given process group as a lower case string.\n\n \"\"\"\n _check_default_pg()\n\n if group == GroupMember.WORLD:\n pg = _default_pg\n else:\n pg = group\n if _rank_not_in_group(pg):\n raise RuntimeError(\"Invalid process group specified\")\n return _pg_map.get(pg, None)[0]\n\n\ndef init_process_group(backend,\n init_method=None,\n timeout=default_pg_timeout,\n world_size=-1,\n rank=-1,\n store=None,\n group_name=''):\n \"\"\"\n Initializes the default distributed process group, and this will also\n initialize the distributed package.\n\n There are 2 main ways to initialize a process group:\n 1. Specify ``store``, ``rank``, and ``world_size`` explicitly.\n 2. Specify ``init_method`` (a URL string) which indicates where/how\n to discover peers. Optionally specify ``rank`` and ``world_size``,\n or encode all required parameters in the URL and omit them.\n\n If neither is specified, ``init_method`` is assumed to be \"env://\".\n\n\n Arguments:\n backend (str or Backend): The backend to use. Depending on\n build-time configurations, valid values include ``mpi``, ``gloo``,\n and ``nccl``. This field should be given as a lowercase string\n (e.g., ``\"gloo\"``), which can also be accessed via\n :class:`Backend` attributes (e.g., ``Backend.GLOO``). If using\n multiple processes per machine with ``nccl`` backend, each process\n must have exclusive access to every GPU it uses, as sharing GPUs\n between processes can result in deadlocks.\n init_method (str, optional): URL specifying how to initialize the\n process group. Default is \"env://\" if no\n ``init_method`` or ``store`` is specified.\n Mutually exclusive with ``store``.\n world_size (int, optional): Number of processes participating in\n the job. Required if ``store`` is specified.\n rank (int, optional): Rank of the current process.\n Required if ``store`` is specified.\n store(Store, optional): Key/value store accessible to all workers, used\n to exchange connection/address information.\n Mutually exclusive with ``init_method``.\n timeout (timedelta, optional): Timeout for operations executed against\n the process group. Default value equals 30 minutes.\n This is applicable for the ``gloo`` backend. For ``nccl``, this is\n applicable only if the environment variable ``NCCL_BLOCKING_WAIT``\n or ``NCCL_ASYNC_ERROR_HANDLING`` is set to 1. When\n ``NCCL_BLOCKING_WAIT`` is set, this is the duration for which the\n process will block and wait for collectives to complete before\n throwing an exception. When ``NCCL_ASYNC_ERROR_HANDLING`` is set,\n this is the duration after which collectives will be aborted\n asynchronously and the process will crash. ``NCCL_BLOCKING_WAIT``\n will provide errors to the user which can be caught and handled,\n but due to its blocking nature, it has a performance overhead. On\n the other hand, ``NCCL_ASYNC_ERROR_HANDLING`` has little\n performance overhead, but crashes the process on errors. This is\n done since CUDA execution is async and it is no longer safe to\n continue executing user code since failed async NCCL operations\n might result in subsequent CUDA operations to run on corrupted\n data. Only one of these two environment variables should be set.\n group_name (str, optional, deprecated): Group name.\n\n To enable ``backend == Backend.MPI``, PyTorch needs to be built from source\n on a system that supports MPI.\n\n \"\"\"\n global _pg_group_ranks\n global _backend\n global _default_pg\n global _default_pg_init_method\n\n if not isinstance(timeout, timedelta):\n raise RuntimeError(\"Expected timeout argument to be of type\"\n \"datetime.timedelta\")\n\n if _default_pg is not None:\n raise RuntimeError(\"trying to initialize the default process group \"\n \"twice!\")\n\n assert (store is None) or (init_method is None), \\\n \"Cannot specify both init_method and store.\"\n\n if store is not None:\n assert world_size > 0, 'world_size must be positive if using store'\n assert rank >= 0, 'rank must be non-negative if using store'\n elif init_method is None:\n init_method = \"env://\"\n\n backend = Backend(backend)\n\n if backend == Backend.MPI:\n if world_size != -1 or rank != -1:\n warnings.warn(\n \"For MPI backend, world_size ({}) and rank ({}) \"\n \"are ignored since they are assigned by the \"\n \"MPI runtime.\".format(world_size, rank))\n\n _default_pg = _new_process_group_helper(\n -1,\n -1,\n [],\n Backend.MPI,\n None,\n group_name=group_name,\n timeout=timeout)\n else:\n # backward compatible API\n if store is None:\n rendezvous_iterator = rendezvous(\n init_method, rank, world_size, timeout=timeout\n )\n store, rank, world_size = next(rendezvous_iterator)\n store.set_timeout(timeout)\n\n _default_pg = _new_process_group_helper(\n world_size,\n rank,\n [],\n backend,\n store,\n group_name=group_name,\n timeout=timeout)\n\n _pg_group_ranks[_default_pg] = {i: i for i in range(_default_pg.size())}\n _backend = _pg_map[_default_pg][0]\n _default_pg_init_method = init_method\n\n # barrier at the end to ensure that once we return from this method, all\n # process groups including global variables are updated correctly on all\n # ranks.\n barrier()\n\ndef _new_process_group_helper(world_size,\n rank,\n group_ranks,\n backend,\n store,\n group_name=None,\n timeout=default_pg_timeout):\n \"\"\"\n Create a new distributed process group.\n\n This function must be called by ALL processes in the global group, even if\n the calling process is not part of the newly created group. In that case,\n this function returns GroupMember.NON_GROUP_MEMBER.\n\n This function is called with ``group_ranks == []`` for the default group.\n \"\"\"\n global _pg_map\n global _group_count\n global _pg_names\n\n if not group_name:\n group_name = str(_group_count)\n _group_count += 1\n\n if group_name in _pg_names.values():\n raise RuntimeError(\"The specified group name has already been \"\n \"created, please use a different group name\")\n\n if not isinstance(timeout, timedelta):\n raise RuntimeError(\"Expected timeout argument to be of type\"\n \"datetime.timedelta\")\n\n # The list of group ranks is empty if we're creating the default group.\n is_default_group = (len(group_ranks) == 0)\n\n backend = Backend(backend)\n if backend == Backend.MPI:\n if not is_mpi_available():\n raise RuntimeError(\n \"Distributed package doesn't have MPI built in.\"\n \" MPI is only included if you build PyTorch from\"\n \" source on a host that has MPI installed.\")\n pg = ProcessGroupMPI.create(group_ranks)\n if not pg:\n return GroupMember.NON_GROUP_MEMBER\n _pg_map[pg] = (Backend.MPI, None)\n _pg_names[pg] = group_name\n else:\n # If this is a subgroup (which means group_ranks is specified),\n # we check if the current process is a member of the new group.\n if not is_default_group:\n global_rank = _default_pg.rank()\n if global_rank not in group_ranks:\n return GroupMember.NON_GROUP_MEMBER\n\n # Use the group name as prefix in the default store, such that\n # a single store can be reused by multiple groups.\n prefix_store = PrefixStore(group_name, store)\n\n if backend == Backend.GLOO:\n pg = ProcessGroupGloo(\n prefix_store,\n rank,\n world_size,\n timeout=timeout)\n _pg_map[pg] = (Backend.GLOO, store)\n _pg_names[pg] = group_name\n elif backend == Backend.NCCL:\n if not is_nccl_available():\n raise RuntimeError(\"Distributed package doesn't have NCCL \"\n \"built in\")\n pg = ProcessGroupNCCL(\n prefix_store,\n rank,\n world_size,\n timeout)\n _pg_map[pg] = (Backend.NCCL, store)\n _pg_names[pg] = group_name\n else:\n pg = getattr(Backend, backend.upper())(\n prefix_store,\n rank,\n world_size,\n timeout)\n _pg_map[pg] = (backend, store)\n _pg_names[pg] = group_name\n\n return pg\n\n\ndef destroy_process_group(group=group.WORLD):\n \"\"\"\n Destroy a given process group, and deinitialize the distributed package\n\n Arguments:\n group (ProcessGroup, optional): The process group to be destroyed, if\n group.WORLD is given, all process\n groups including the default one will\n be destroyed.\n \"\"\"\n global _pg_map\n global _pg_names\n global _pg_group_ranks\n global _default_pg\n global _default_pg_init_method\n global _group_count\n\n if group == GroupMember.NON_GROUP_MEMBER:\n return\n\n if group == GroupMember.WORLD:\n pg = _default_pg\n else:\n pg = group\n\n if _pg_map.get(pg, None) is None:\n raise RuntimeError(\"Invalid process group specified\")\n\n if group == GroupMember.WORLD:\n _default_pg = None\n _default_pg_init_method = None\n _pg_map.clear()\n _pg_names.clear()\n _pg_group_ranks.clear()\n\n # when process group doesn't have an explicit name (only WORLD (default)\n # process group can have an explicit name), we use global _group_counter\n # to generate the name. We need to reset the counter on destruction to\n # allow consistent value to be generated when we re-create process\n # groups after some trainers recover from failure\n #\n # We only reset this when WORLD is being destroyed because if this\n # process group is in good state, we aren't dealing with failures.\n _group_count = 0\n else:\n del _pg_map[pg]\n del _pg_names[pg]\n del _pg_group_ranks[pg]\n\n\ndef get_rank(group=group.WORLD):\n \"\"\"\n Returns the rank of current process group\n\n Rank is a unique identifier assigned to each process within a distributed\n process group. They are always consecutive integers ranging from 0 to\n ``world_size``.\n\n Arguments:\n group (ProcessGroup, optional): The process group to work on\n\n Returns:\n The rank of the process group\n -1, if not part of the group\n\n \"\"\"\n if _rank_not_in_group(group):\n return -1\n\n _check_default_pg()\n if group == GroupMember.WORLD:\n return _default_pg.rank()\n\n return _get_group_rank(group, _default_pg.rank())\n\n\ndef get_world_size(group=group.WORLD):\n \"\"\"\n Returns the number of processes in the current process group\n\n Arguments:\n group (ProcessGroup, optional): The process group to work on\n\n Returns:\n The world size of the process group\n -1, if not part of the group\n\n \"\"\"\n if _rank_not_in_group(group):\n return -1\n\n return _get_group_size(group)\n\n\ndef isend(tensor,\n dst,\n group=group.WORLD,\n tag=0):\n \"\"\"\n Sends a tensor asynchronously.\n\n Arguments:\n tensor (Tensor): Tensor to send.\n dst (int): Destination rank.\n group (ProcessGroup, optional): The process group to work on\n tag (int, optional): Tag to match send with remote recv\n\n Returns:\n A distributed request object.\n None, if not part of the group\n\n \"\"\"\n _check_single_tensor(tensor, \"tensor\")\n if _rank_not_in_group(group):\n return\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n return _default_pg.send([tensor], dst, tag)\n else:\n group_dst_rank = _get_group_rank(group, dst)\n return group.send([tensor], group_dst_rank, tag)\n\n\ndef irecv(tensor,\n src,\n group=group.WORLD,\n tag=0):\n \"\"\"\n Receives a tensor asynchronously.\n\n Arguments:\n tensor (Tensor): Tensor to fill with received data.\n src (int): Source rank.\n group (ProcessGroup, optional): The process group to work on\n tag (int, optional): Tag to match recv with remote send\n\n Returns:\n A distributed request object.\n None, if not part of the group\n\n \"\"\"\n _check_single_tensor(tensor, \"tensor\")\n if _rank_not_in_group(group):\n return\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n return _default_pg.recv([tensor], src, tag)\n else:\n group_src_rank = _get_group_rank(group, src)\n return group.recv([tensor], group_src_rank, tag)\n\n\ndef send(tensor,\n dst,\n group=group.WORLD,\n tag=0):\n \"\"\"\n Sends a tensor synchronously.\n\n Arguments:\n tensor (Tensor): Tensor to send.\n dst (int): Destination rank.\n group (ProcessGroup, optional): The process group to work on\n tag (int, optional): Tag to match send with remote recv\n\n \"\"\"\n _check_single_tensor(tensor, \"tensor\")\n if _rank_not_in_group(group):\n return\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n _default_pg.send([tensor], dst, tag).wait()\n else:\n group_dst_rank = _get_group_rank(group, dst)\n group.send([tensor], group_dst_rank, tag).wait()\n\n\ndef recv(tensor,\n src=None,\n group=group.WORLD,\n tag=0):\n \"\"\"\n Receives a tensor synchronously.\n\n Arguments:\n tensor (Tensor): Tensor to fill with received data.\n src (int, optional): Source rank. Will receive from any\n process if unspecified.\n group (ProcessGroup, optional): The process group to work on\n tag (int, optional): Tag to match recv with remote send\n\n Returns:\n Sender rank\n -1, if not part of the group\n\n \"\"\"\n _check_single_tensor(tensor, \"tensor\")\n if _rank_not_in_group(group):\n return -1\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n pg = _default_pg\n else:\n pg = group\n\n if src is None:\n work = pg.recv_anysource([tensor], tag)\n work.wait()\n src_rank = work._source_rank()\n if group == GroupMember.WORLD:\n return src_rank\n else:\n return _get_global_rank(pg, src_rank)\n else:\n if group == GroupMember.WORLD:\n pg.recv([tensor], src, tag).wait()\n else:\n group_src_rank = _get_group_rank(pg, src)\n pg.recv([tensor], group_src_rank, tag).wait()\n return src\n\n\ndef broadcast_multigpu(tensor_list,\n src,\n group=group.WORLD,\n async_op=False,\n src_tensor=0):\n \"\"\"\n Broadcasts the tensor to the whole group with multiple GPU tensors\n per node.\n\n ``tensor`` must have the same number of elements in all the GPUs from\n all processes participating in the collective. each tensor in the list must\n be on a different GPU\n\n Only nccl and gloo backend are currently supported\n tensors should only be GPU tensors\n\n Arguments:\n tensor_list (List[Tensor]): Tensors that participate in the collective\n operation. If ``src`` is the rank, then the specified ``src_tensor``\n element of ``tensor_list`` (``tensor_list[src_tensor]``) will be\n broadcast to all other tensors (on different GPUs) in the src process\n and all tensors in ``tensor_list`` of other non-src processes.\n You also need to make sure that ``len(tensor_list)`` is the same\n for all the distributed processes calling this function.\n\n src (int): Source rank.\n group (ProcessGroup, optional): The process group to work on\n async_op (bool, optional): Whether this op should be an async op\n src_tensor (int, optional): Source tensor rank within ``tensor_list``\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group\n\n \"\"\"\n if _rank_not_in_group(group):\n return\n\n opts = BroadcastOptions()\n opts.rootRank = src\n opts.rootTensor = src_tensor\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.broadcast(tensor_list, opts)\n else:\n group_src_rank = _get_group_rank(group, src)\n opts.rootRank = group_src_rank\n work = group.broadcast(tensor_list, opts)\n if async_op:\n return work\n else:\n work.wait()\n\n\ndef broadcast(tensor,\n src,\n group=group.WORLD,\n async_op=False):\n \"\"\"\n Broadcasts the tensor to the whole group.\n\n ``tensor`` must have the same number of elements in all processes\n participating in the collective.\n\n Arguments:\n tensor (Tensor): Data to be sent if ``src`` is the rank of current\n process, and tensor to be used to save received data otherwise.\n src (int): Source rank.\n group (ProcessGroup, optional): The process group to work on\n async_op (bool, optional): Whether this op should be an async op\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group\n\n \"\"\"\n _check_single_tensor(tensor, \"tensor\")\n if _rank_not_in_group(group):\n return\n\n opts = BroadcastOptions()\n opts.rootRank = src\n opts.rootTensor = 0\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.broadcast([tensor], opts)\n else:\n group_src_rank = _get_group_rank(group, src)\n opts.rootRank = group_src_rank\n work = group.broadcast([tensor], opts)\n if async_op:\n return work\n else:\n work.wait()\n\n\ndef all_reduce_multigpu(tensor_list,\n op=ReduceOp.SUM,\n group=group.WORLD,\n async_op=False):\n r\"\"\"\n Reduces the tensor data across all machines in such a way that all get\n the final result. This function reduces a number of tensors on every node,\n while each tensor resides on different GPUs.\n Therefore, the input tensor in the tensor list needs to be GPU tensors.\n Also, each tensor in the tensor list needs to reside on a different GPU.\n\n After the call, all ``tensor`` in ``tensor_list`` is going to be bitwise\n identical in all processes.\n\n Only nccl and gloo backend is currently supported\n tensors should only be GPU tensors\n\n Arguments:\n tensor list (List[Tensor]): List of input and output tensors of\n the collective. The function operates in-place and requires that\n each tensor to be a GPU tensor on different GPUs.\n You also need to make sure that ``len(tensor_list)`` is the same for\n all the distributed processes calling this function.\n op (optional): One of the values from\n ``torch.distributed.ReduceOp``\n enum. Specifies an operation used for element-wise reductions.\n group (ProcessGroup, optional): The process group to work on\n async_op (bool, optional): Whether this op should be an async op\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group\n\n \"\"\"\n if _rank_not_in_group(group):\n return\n\n opts = AllreduceOptions()\n opts.reduceOp = op\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.allreduce(tensor_list, opts)\n else:\n work = group.allreduce(tensor_list, opts)\n\n if async_op:\n return work\n else:\n work.wait()\n\n\ndef all_reduce(tensor,\n op=ReduceOp.SUM,\n group=group.WORLD,\n async_op=False):\n \"\"\"\n Reduces the tensor data across all machines in such a way that all get\n the final result.\n\n After the call ``tensor`` is going to be bitwise identical in all processes.\n\n Arguments:\n tensor (Tensor): Input and output of the collective. The function\n operates in-place.\n op (optional): One of the values from\n ``torch.distributed.ReduceOp``\n enum. Specifies an operation used for element-wise reductions.\n group (ProcessGroup, optional): The process group to work on\n async_op (bool, optional): Whether this op should be an async op\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group\n\n \"\"\"\n _check_single_tensor(tensor, \"tensor\")\n if _rank_not_in_group(group):\n return\n\n opts = AllreduceOptions()\n opts.reduceOp = op\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.allreduce([tensor], opts)\n else:\n work = group.allreduce([tensor], opts)\n\n if async_op:\n return work\n else:\n work.wait()\n\n\ndef all_reduce_coalesced(tensors,\n op=ReduceOp.SUM,\n group=group.WORLD,\n async_op=False):\n \"\"\"\n WARNING: at this time individual shape checking is not implemented across nodes.\n For example, if the rank 0 node passes [torch.rand(4), torch.rand(2)] and the\n rank 1 node passes [torch.rand(2), torch.rand(2), torch.rand(2)], the allreduce\n operation will proceed without complaint and return erroneous outputs. This lack\n of shape checking results in significant performance improvements but users of this\n function should take extra care to ensure that each node passes in tensors whose\n shapes match across nodes.\n\n Reduces each tensor in tensors (residing on the same device) across all machines\n in such a way that all get the final result.\n\n After the call each tensor in tensors is going to bitwise identical\n in all processes.\n\n Arguments:\n tensors (List[Tensor]): Input and output of the collective. The function\n operates in-place.\n op (Optional[ReduceOp]): One of the values from\n ``torch.distributed.ReduceOp`` enum. Specifies an operation used for\n element-wise reductions.\n group (Optional[ProcessGroup]): The process group to work on.\n async_op (Optional[bool]): Whether this op should be an async op.\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group.\n\n \"\"\"\n _check_tensor_list(tensors, \"tensor\")\n if _rank_not_in_group(group):\n return\n\n opts = AllreduceCoalescedOptions()\n opts.reduceOp = op\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.allreduce_coalesced(tensors, opts)\n else:\n work = group.allreduce_coalesced(tensors, opts)\n\n if async_op:\n return work\n else:\n work.wait()\n\n\ndef reduce_multigpu(tensor_list,\n dst,\n op=ReduceOp.SUM,\n group=group.WORLD,\n async_op=False,\n dst_tensor=0):\n \"\"\"\n Reduces the tensor data on multiple GPUs across all machines. Each tensor\n in ``tensor_list`` should reside on a separate GPU\n\n Only the GPU of ``tensor_list[dst_tensor]`` on the process with rank ``dst``\n is going to receive the final result.\n\n Only nccl backend is currently supported\n tensors should only be GPU tensors\n\n Arguments:\n tensor_list (List[Tensor]): Input and output GPU tensors of the\n collective. The function operates in-place.\n You also need to make sure that ``len(tensor_list)`` is the same for\n all the distributed processes calling this function.\n dst (int): Destination rank\n op (optional): One of the values from\n ``torch.distributed.ReduceOp``\n enum. Specifies an operation used for element-wise reductions.\n group (ProcessGroup, optional): The process group to work on\n async_op (bool, optional): Whether this op should be an async op\n dst_tensor (int, optional): Destination tensor rank within\n ``tensor_list``\n\n Returns:\n Async work handle, if async_op is set to True.\n None, otherwise\n\n \"\"\"\n if _rank_not_in_group(group):\n return\n\n opts = ReduceOptions()\n opts.reduceOp = op\n opts.rootRank = dst\n opts.rootTensor = dst_tensor\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.reduce(tensor_list, opts)\n else:\n group_dst_rank = _get_group_rank(group, dst)\n opts.rootRank = group_dst_rank\n work = group.reduce(tensor_list, opts)\n\n if async_op:\n return work\n else:\n work.wait()\n\n\ndef reduce(tensor,\n dst,\n op=ReduceOp.SUM,\n group=group.WORLD,\n async_op=False):\n \"\"\"\n Reduces the tensor data across all machines.\n\n Only the process with rank ``dst`` is going to receive the final result.\n\n Arguments:\n tensor (Tensor): Input and output of the collective. The function\n operates in-place.\n dst (int): Destination rank\n op (optional): One of the values from\n ``torch.distributed.ReduceOp``\n enum. Specifies an operation used for element-wise reductions.\n group (ProcessGroup, optional): The process group to work on\n async_op (bool, optional): Whether this op should be an async op\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group\n\n \"\"\"\n _check_single_tensor(tensor, \"tensor\")\n if _rank_not_in_group(group):\n return\n\n opts = ReduceOptions()\n opts.reduceOp = op\n opts.rootRank = dst\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.reduce([tensor], opts)\n else:\n group_dst_rank = _get_group_rank(group, dst)\n opts.rootRank = group_dst_rank\n work = group.reduce([tensor], opts)\n\n if async_op:\n return work\n else:\n work.wait()\n\n\ndef all_gather_multigpu(output_tensor_lists,\n input_tensor_list,\n group=group.WORLD,\n async_op=False):\n \"\"\"\n Gathers tensors from the whole group in a list.\n Each tensor in ``tensor_list`` should reside on a separate GPU\n\n Only nccl backend is currently supported\n tensors should only be GPU tensors\n\n Arguments:\n output_tensor_lists (List[List[Tensor]]): Output lists. It should\n contain correctly-sized tensors on each GPU to be used for output\n of the collective, e.g. ``output_tensor_lists[i]`` contains the\n all_gather result that resides on the GPU of\n ``input_tensor_list[i]``.\n\n Note that each element of ``output_tensor_lists`` has the size of\n ``world_size * len(input_tensor_list)``, since the function all\n gathers the result from every single GPU in the group. To interpret\n each element of ``output_tensor_lists[i]``, note that\n ``input_tensor_list[j]`` of rank k will be appear in\n ``output_tensor_lists[i][k * world_size + j]``\n\n Also note that ``len(output_tensor_lists)``, and the size of each\n element in ``output_tensor_lists`` (each element is a list,\n therefore ``len(output_tensor_lists[i])``) need to be the same\n for all the distributed processes calling this function.\n\n input_tensor_list (List[Tensor]): List of tensors(on different GPUs) to\n be broadcast from current process.\n Note that ``len(input_tensor_list)`` needs to be the same for\n all the distributed processes calling this function.\n\n group (ProcessGroup, optional): The process group to work on\n async_op (bool, optional): Whether this op should be an async op\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group\n\n \"\"\"\n if _rank_not_in_group(group):\n return\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.allgather(output_tensor_lists, input_tensor_list)\n else:\n work = group.allgather(output_tensor_lists, input_tensor_list)\n\n if async_op:\n return work\n else:\n work.wait()\n\n\ndef _object_to_tensor(obj):\n buffer = pickle.dumps(obj)\n byte_storage = torch.ByteStorage.from_buffer(buffer)\n byte_tensor = torch.ByteTensor(byte_storage)\n local_size = torch.LongTensor([byte_tensor.numel()])\n return byte_tensor, local_size\n\n\ndef _tensor_to_object(tensor, tensor_size):\n buf = tensor.numpy().tobytes()[:tensor_size]\n out = pickle.loads(buf)\n return out\n\n\ndef all_gather_object(object_list, obj, group=group.WORLD):\n \"\"\"\n Gathers picklable objects from the whole group into a list. Similar to\n :func:`all_gather`, but Python objects can be passed in. Note that the object\n must be picklable in order to be gathered.\n\n Arguments:\n object_list (list[Any]): Output list. It should be correctly sized as the\n size of the group for this collective and will contain the output.\n object (Any): Pickable Python object to be broadcast from current process.\n group (ProcessGroup, optional): The process group to work on\n\n Returns:\n None. If the calling rank is part of this group, the output of the\n collective will be populated into the input ``object_list``. If the\n calling rank is not part of the group, the passed in ``object_list`` will\n be unmodified.\n\n .. note:: Note that this API differs slightly from the :func:`all_gather`\n collective since it does not provide an ``async_op`` handle and thus\n will be a blocking call.\n\n .. warning::\n :func:`all_gather_object` uses ``pickle`` module implicitly, which is\n known to be insecure. It is possible to construct malicious pickle data\n which will execute arbitrary code during unpickling. Only call this\n function with data you trust.\n \"\"\"\n if _rank_not_in_group(group):\n return\n\n input_tensor, local_size = _object_to_tensor(obj)\n group_backend = get_backend(group)\n my_rank = get_rank()\n is_nccl_backend = group_backend == Backend.NCCL\n if is_nccl_backend:\n input_tensor, local_size = input_tensor.to(my_rank), local_size.to(my_rank)\n # Gather all local sizes. This is so that we can find the max size, and index\n # until the correct size when deserializing the tensors.\n group_size = get_world_size(group=group)\n object_sizes_tensor = torch.zeros(group_size, dtype=int).to(\n my_rank if is_nccl_backend else \"cpu\"\n )\n object_size_list = [\n object_sizes_tensor[i].unsqueeze(dim=0) for i in range(group_size)\n ]\n # Allgather tensor sizes\n all_gather(object_size_list, local_size, group=group)\n max_object_size = max(object_size_list)\n # Resize tensor to max size across all ranks.\n input_tensor.resize_(max_object_size)\n coalesced_output_tensor = torch.empty(\n max_object_size * group_size, dtype=torch.uint8\n ).to(my_rank if is_nccl_backend else \"cpu\")\n # Output tensors are nonoverlapping views of coalesced_output_tensor\n output_tensors = [\n coalesced_output_tensor[max_object_size * i : max_object_size * (i + 1)]\n for i in range(group_size)\n ]\n all_gather(output_tensors, input_tensor, group=group)\n # Deserialize outputs back to object.\n for i, tensor in enumerate(output_tensors):\n tensor = tensor.type(torch.ByteTensor)\n tensor_size = object_size_list[i]\n object_list[i] = _tensor_to_object(tensor, tensor_size)\n\n\ndef gather_object(obj, object_gather_list=None, dst=0, group=group.WORLD):\n \"\"\"\n Gathers picklable objects from the whole group in a single process.\n Similar to :func:`gather`, but Python objects can be passed in. Note that the\n object must be picklable in order to be gathered.\n\n Arguments:\n obj (Any): Input object. Must be picklable.\n object_gather_list (list[Any]): Output list. On the ``dst`` rank, it\n should be correctly sized as the size of the group for this\n collective and will contain the output. Must be ``None`` on non-dst\n ranks. (default is ``None``)\n dst (int, optional): Destination rank. (default is 0)\n group: (ProcessGroup, optional): The process group to work on.\n\n Returns:\n None. On the ``dst`` rank, ``object_gather_list`` will contain the\n output of the collective.\n\n .. note:: Note that this API differs slightly from the gather collective\n since it does not provide an async_op handle and thus will be a blocking\n call.\n\n .. note:: Note that this API is not supported when using the NCCL backend.\n\n .. warning::\n :func:`gather_object` uses ``pickle`` module implicitly, which is\n known to be insecure. It is possible to construct malicious pickle data\n which will execute arbitrary code during unpickling. Only call this\n function with data you trust.\n \"\"\"\n if _rank_not_in_group(group):\n return\n\n # Ensure object_gather_list is specified appopriately.\n my_rank = get_rank()\n _validate_output_list_for_rank(my_rank, dst, object_gather_list)\n input_tensor, local_size = _object_to_tensor(obj)\n group_backend = get_backend(group)\n is_nccl_backend = group_backend == Backend.NCCL\n if is_nccl_backend:\n input_tensor, local_size = input_tensor.to(my_rank), local_size.to(my_rank)\n # Gather all local sizes. This is so that we can find the max size, and index\n # until the correct size when deserializing the tensors.\n group_size = get_world_size(group=group)\n object_sizes_tensor = torch.zeros(group_size, dtype=int).to(\n my_rank if is_nccl_backend else \"cpu\"\n )\n object_size_list = [\n object_sizes_tensor[i].unsqueeze(dim=0) for i in range(group_size)\n ]\n # Allgather tensor sizes. An all-gather is needed here despite this being a gather,\n # since each rank needs to broadcast a tensor of the same (maximal) size.\n all_gather(object_size_list, local_size, group=group)\n max_object_size = max(object_size_list)\n # Resize tensor to max size across all ranks.\n input_tensor.resize_(max_object_size)\n # Avoid populating output tensors if the result won't be gathered on this rank.\n if my_rank == dst:\n coalesced_output_tensor = torch.empty(\n max_object_size * group_size, dtype=torch.uint8\n ).to(my_rank if is_nccl_backend else \"cpu\")\n # Output tensors are nonoverlapping views of coalesced_output_tensor\n output_tensors = [\n coalesced_output_tensor[max_object_size * i : max_object_size * (i + 1)]\n for i in range(group_size)\n ]\n # All ranks call gather with equal-sized tensors.\n gather(\n input_tensor,\n gather_list=output_tensors if my_rank == dst else None,\n dst=dst,\n group=group,\n )\n if my_rank != dst:\n return\n for i, tensor in enumerate(output_tensors):\n tensor = tensor.type(torch.ByteTensor)\n tensor_size = object_size_list[i]\n object_gather_list[i] = _tensor_to_object(tensor, tensor_size)\n\n\ndef broadcast_object_list(object_list, src, group=group.WORLD):\n \"\"\"\n Broadcasts picklable objects in ``object_list`` to the whole group. Similar\n to :func:`broadcast`, but Python objects can be passed in.\n Note that all objects in ``object_list`` must be picklable in order to be\n broadcasted.\n\n Arguments:\n object_list (List[Any]): List of input objects to broadcast.\n Each object must be picklable. Only objects on the ``src`` rank will\n be broadcast, but each rank must provide lists of equal sizes.\n src (int): Source rank from which to broadcast ``object_list``.\n group: (ProcessGroup, optional): The process group to work on.\n\n Returns:\n ``None``. If rank is part of the group, ``object_list`` will contain the\n broadcasted objects from ``src`` rank.\n\n .. note:: Note that this API differs slightly from the broadcast collective\n since it does not provide an ``async_op`` handle and thus will be a\n blocking call.\n\n .. warning::\n :func:`broadcast_object_list` uses ``pickle`` module implicitly, which\n is known to be insecure. It is possible to construct malicious pickle\n data which will execute arbitrary code during unpickling. Only call this\n function with data you trust.\n \"\"\"\n if _rank_not_in_group(group):\n return\n\n my_rank = get_rank()\n # Serialize object_list elements to tensors on src rank.\n if my_rank == src:\n tensor_list, size_list = zip(*[_object_to_tensor(obj) for obj in object_list])\n object_sizes_tensor = torch.cat(size_list)\n else:\n object_sizes_tensor = torch.LongTensor(len(object_list))\n\n group_backend = get_backend(group)\n is_nccl_backend = group_backend == Backend.NCCL\n if is_nccl_backend:\n object_sizes_tensor = object_sizes_tensor.to(my_rank)\n\n # Broadcast object sizes\n broadcast(object_sizes_tensor, src=src, group=group)\n\n # Concatenate and broadcast serialized object tensors\n if my_rank == src:\n object_tensor = torch.cat(tensor_list)\n else:\n object_tensor = torch.ByteTensor(torch.sum(object_sizes_tensor).item())\n\n if is_nccl_backend:\n object_tensor = object_tensor.to(my_rank)\n broadcast(object_tensor, src=src, group=group)\n # Deserialize objects using their stored sizes.\n offset = 0\n if my_rank != src:\n for i, obj_size in enumerate(object_sizes_tensor):\n obj_view = object_tensor[offset : offset + obj_size]\n obj_view = obj_view.type(torch.ByteTensor)\n offset += obj_size\n object_list[i] = _tensor_to_object(obj_view, obj_size)\n\n\ndef all_gather(tensor_list,\n tensor,\n group=group.WORLD,\n async_op=False):\n \"\"\"\n Gathers tensors from the whole group in a list.\n\n Arguments:\n tensor_list (list[Tensor]): Output list. It should contain\n correctly-sized tensors to be used for output of the collective.\n tensor (Tensor): Tensor to be broadcast from current process.\n group (ProcessGroup, optional): The process group to work on\n async_op (bool, optional): Whether this op should be an async op\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group\n\n \"\"\"\n _check_tensor_list(tensor_list, \"tensor_list\")\n _check_single_tensor(tensor, \"tensor\")\n if _rank_not_in_group(group):\n return\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.allgather([tensor_list], [tensor])\n else:\n work = group.allgather([tensor_list], [tensor])\n\n if async_op:\n return work\n else:\n work.wait()\n\ndef all_gather_coalesced(output_tensor_lists,\n input_tensor_list,\n group=group.WORLD,\n async_op=False):\n \"\"\"\n Gathers input tensors from the whole group in a list in a coalesced manner.\n\n Arguments:\n output_tensor_lists (list[list[Tensor]]): Output list. It should contain\n correctly-sized tensors to be used for output of the collective.\n input_tensor_list (list[Tensor]): Tensors to be broadcast from\n current process. At least one tensor has to be non empty.\n group (ProcessGroup, optional): The process group to work on\n async_op (bool, optional): Whether this op should be an async op.\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group\n\n Example:\n we have 2 process groups, 2 ranks.\n rank 0 passes:\n input_tensor_list = [[[1, 1], [1, 1]], [2], [3, 3]]\n output_tensor_lists =\n [[[[-1, -1], [-1, -1]], [-1], [-1, -1]],\n [[[-1, -1], [-1, -1]], [-1], [-1, -1]]]\n rank 1 passes:\n input_tensor_list = [[[3, 3], [3, 3]], [5], [1, 1]]\n output_tensor_lists =\n [[[[-1, -1], [-1, -1]], [-1], [-1, -1]],\n [[[-1, -1], [-1, -1]], [-1], [-1, -1]]]\n both rank 0 and 1 get:\n output_tensor_lists =\n [[[1, 1], [1, 1]], [2], [3, 3]],\n [[3, 3], [3, 3]], [5], [1, 1]]].\n\n WARNING: at this time individual shape checking is not implemented across nodes.\n For example, if the rank 0 node passes [torch.rand(4), torch.rand(2)] and the\n rank 1 node passes [torch.rand(2), torch.rand(2), torch.rand(2)], the\n all_gather_coalesced operation will proceed without complaint and return\n erroneous outputs. This lack of shape checking results in significant\n performance improvements but users of this function should take extra care\n to ensure that each node passes in tensors whose shapes match across nodes.\n \"\"\"\n # We only check basic compatibility with C++ params here, C++ code will\n # do shape and type checking.\n if _rank_not_in_group(group):\n return\n _check_tensor_list(input_tensor_list, \"tensor_list\")\n if not isinstance(output_tensor_lists, list):\n raise RuntimeError(\"Invalid function argument: \"\n \"output_tensor_lists should be a list\")\n for output_tensor_list in output_tensor_lists:\n _check_tensor_list(output_tensor_list, \"output_tensor_lists\")\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.allgather_coalesced(\n output_tensor_lists, input_tensor_list)\n else:\n work = group.allgather_coalesced(output_tensor_lists, input_tensor_list)\n\n if async_op:\n return work\n else:\n work.wait()\n\ndef _validate_output_list_for_rank(my_rank, dst, gather_list):\n if dst == my_rank:\n if not gather_list:\n raise ValueError(\n \"Argument ``gather_list`` must be specified on destination rank.\"\n )\n elif gather_list:\n raise ValueError(\n \"Argument ``gather_list`` must NOT be specified \"\n \"on non-destination ranks.\"\n )\n\n\ndef gather(tensor,\n gather_list=None,\n dst=0,\n group=group.WORLD,\n async_op=False):\n \"\"\"\n Gathers a list of tensors in a single process.\n\n Arguments:\n tensor (Tensor): Input tensor.\n gather_list (list[Tensor], optional): List of appropriately-sized\n tensors to use for gathered data (default is None, must be specified\n on the destination rank)\n dst (int, optional): Destination rank (default is 0)\n group (ProcessGroup, optional): The process group to work on\n async_op (bool, optional): Whether this op should be an async op\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group\n\n \"\"\"\n _check_single_tensor(tensor, \"tensor\")\n\n # Parameter ``gather_list`` may be left unspecified on non-dst ranks.\n if gather_list:\n _check_tensor_list(gather_list, \"gather_list\")\n else:\n gather_list = []\n\n if _rank_not_in_group(group):\n return\n\n my_rank = get_rank()\n _validate_output_list_for_rank(my_rank, dst, gather_list)\n output_tensors = [gather_list] if dst == my_rank else []\n input_tensors = [tensor]\n\n opts = GatherOptions()\n opts.rootRank = dst\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.gather(output_tensors, input_tensors, opts)\n else:\n group_dst_rank = _get_group_rank(group, dst)\n opts.rootRank = group_dst_rank\n work = group.gather(output_tensors, input_tensors, opts)\n\n if async_op:\n return work\n else:\n work.wait()\n\n\ndef scatter(tensor,\n scatter_list=None,\n src=0,\n group=group.WORLD,\n async_op=False):\n \"\"\"\n Scatters a list of tensors to all processes in a group.\n\n Each process will receive exactly one tensor and store its data in the\n ``tensor`` argument.\n\n Arguments:\n tensor (Tensor): Output tensor.\n scatter_list (list[Tensor]): List of tensors to scatter (default is\n None, must be specified on the source rank)\n src (int): Source rank (default is 0)\n group (ProcessGroup, optional): The process group to work on\n async_op (bool, optional): Whether this op should be an async op\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group\n\n \"\"\"\n _check_single_tensor(tensor, \"tensor\")\n\n # Parameter ``scatter_list`` may be left unspecified on non-src ranks.\n if scatter_list:\n _check_tensor_list(scatter_list, \"scatter_list\")\n else:\n scatter_list = []\n\n if _rank_not_in_group(group):\n return\n\n my_rank = get_rank()\n if src == my_rank:\n if not scatter_list:\n raise ValueError(\"Argument ``scatter_list`` must be specified \"\n \"on source rank.\")\n input_tensors = [scatter_list]\n output_tensors = [tensor]\n else:\n if scatter_list:\n raise ValueError(\"Argument ``scatter_list`` must NOT be specified \"\n \"on non-source ranks.\")\n input_tensors = []\n output_tensors = [tensor]\n\n opts = ScatterOptions()\n opts.rootRank = src\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.scatter(output_tensors, input_tensors, opts)\n else:\n group_src_rank = _get_group_rank(group, src)\n opts.rootRank = group_src_rank\n work = group.scatter(output_tensors, input_tensors, opts)\n\n if async_op:\n return work\n else:\n work.wait()\n\n\ndef reduce_scatter_multigpu(output_tensor_list,\n input_tensor_lists,\n op=ReduceOp.SUM,\n group=group.WORLD,\n async_op=False):\n \"\"\"\n Reduce and scatter a list of tensors to the whole group. Only nccl backend\n is currently supported.\n\n Each tensor in ``output_tensor_list`` should reside on a separate GPU, as\n should each list of tensors in ``input_tensor_lists``.\n\n Arguments:\n output_tensor_list (List[Tensor]): Output tensors (on different GPUs)\n to receive the result of the operation.\n\n Note that ``len(output_tensor_list)`` needs to be the same for all\n the distributed processes calling this function.\n\n input_tensor_lists (List[List[Tensor]]): Input lists. It should\n contain correctly-sized tensors on each GPU to be used for input of\n the collective, e.g. ``input_tensor_lists[i]`` contains the\n reduce_scatter input that resides on the GPU of\n ``output_tensor_list[i]``.\n\n Note that each element of ``input_tensor_lists`` has the size of\n ``world_size * len(output_tensor_list)``, since the function\n scatters the result from every single GPU in the group. To\n interpret each element of ``input_tensor_lists[i]``, note that\n ``output_tensor_list[j]`` of rank k receives the reduce-scattered\n result from ``input_tensor_lists[i][k * world_size + j]``\n\n Also note that ``len(input_tensor_lists)``, and the size of each\n element in ``input_tensor_lists`` (each element is a list,\n therefore ``len(input_tensor_lists[i])``) need to be the same for\n all the distributed processes calling this function.\n\n group (ProcessGroup, optional): The process group to work on.\n async_op (bool, optional): Whether this op should be an async op.\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group.\n\n \"\"\"\n if _rank_not_in_group(group):\n return\n\n opts = ReduceScatterOptions()\n opts.reduceOp = op\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.reduce_scatter(\n output_tensor_list,\n input_tensor_lists,\n opts\n )\n else:\n work = group.reduce_scatter(\n output_tensor_list,\n input_tensor_lists,\n opts\n )\n\n if async_op:\n return work\n else:\n work.wait()\n\n\ndef reduce_scatter(output,\n input_list,\n op=ReduceOp.SUM,\n group=group.WORLD,\n async_op=False):\n \"\"\"\n Reduces, then scatters a list of tensors to all processes in a group.\n\n Arguments:\n output (Tensor): Output tensor.\n input_list (list[Tensor]): List of tensors to reduce and scatter.\n group (ProcessGroup, optional): The process group to work on.\n async_op (bool, optional): Whether this op should be an async op.\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group.\n\n \"\"\"\n _check_single_tensor(output, \"output\")\n _check_tensor_list(input_list, \"input_list\")\n if _rank_not_in_group(group):\n return\n\n opts = ReduceScatterOptions()\n opts.reduceOp = op\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.reduce_scatter([output], [input_list], opts)\n else:\n work = group.reduce_scatter([output], [input_list], opts)\n\n if async_op:\n return work\n else:\n work.wait()\n\n\ndef all_to_all_single(output,\n input,\n output_split_sizes=None,\n input_split_sizes=None,\n group=group.WORLD,\n async_op=False):\n \"\"\"\n Each process splits input tensor and then scatters the split list\n to all processes in a group. Then concatenate the received tensors from all\n the processes in the group and return single output tensor.\n\n Arguments:\n output (Tensor): Gathered cancatenated output tensor.\n input (Tensor): Input tensor to scatter.\n output_split_sizes: (list[Int], optional): Output split sizes for dim 0\n if specified None or empty, dim 0 of ``output`` tensor must divide\n equally by ``world_size``.\n input_split_sizes: (list[Int], optional): Input split sizes for dim 0\n if specified None or empty, dim 0 of ``input`` tensor must divide\n equally by ``world_size``.\n group (ProcessGroup, optional): The process group to work on.\n async_op (bool, optional): Whether this op should be an async op.\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group.\n\n .. warning::\n `all_to_all_single` is experimental and subject to change.\n\n Examples:\n >>> input = torch.arange(4) + rank * 4\n >>> input\n tensor([0, 1, 2, 3]) # Rank 0\n tensor([4, 5, 6, 7]) # Rank 1\n tensor([8, 9, 10, 11]) # Rank 2\n tensor([12, 13, 14, 15]) # Rank 3\n >>> output = torch.empty([4], dtype=torch.int64)\n >>> dist.all_to_all_single(output, input)\n >>> output\n tensor([0, 4, 8, 12]) # Rank 0\n tensor([1, 5, 9, 13]) # Rank 1\n tensor([2, 6, 10, 14]) # Rank 2\n tensor([3, 7, 11, 15]) # Rank 3\n\n >>> # Essentially, it is similar to following operation:\n >>> scatter_list = list(input.chunk(world_size))\n >>> gather_list = list(output.chunk(world_size))\n >>> for i in range(world_size):\n >>> dist.scatter(gather_list[i], scatter_list if i == rank else [], src = i)\n\n >>> # Another example with uneven split\n >>> input\n tensor([0, 1, 2, 3, 4, 5]) # Rank 0\n tensor([10, 11, 12, 13, 14, 15, 16, 17, 18]) # Rank 1\n tensor([20, 21, 22, 23, 24]) # Rank 2\n tensor([30, 31, 32, 33, 34, 35, 36]) # Rank 3\n >>> input_splits\n [2, 2, 1, 1] # Rank 0\n [3, 2, 2, 2] # Rank 1\n [2, 1, 1, 1] # Rank 2\n [2, 2, 2, 1] # Rank 3\n >>> output_splits\n [2, 3, 2, 2] # Rank 0\n [2, 2, 1, 2] # Rank 1\n [1, 2, 1, 2] # Rank 2\n [1, 2, 1, 1] # Rank 3\n >>> output = ...\n >>> dist.all_to_all_single(output, input, output_splits, input_splits)\n >>> output\n tensor([ 0, 1, 10, 11, 12, 20, 21, 30, 31]) # Rank 0\n tensor([ 2, 3, 13, 14, 22, 32, 33]) # Rank 1\n tensor([ 4, 15, 16, 23, 34, 35]) # Rank 2\n tensor([ 5, 17, 18, 24, 36]) # Rank 3\n \"\"\"\n if _rank_not_in_group(group):\n return\n\n opts = AllToAllOptions()\n _check_single_tensor(output, \"output\")\n _check_single_tensor(input, \"input\")\n output_split_sizes = [] if output_split_sizes is None else output_split_sizes\n input_split_sizes = [] if input_split_sizes is None else input_split_sizes\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.alltoall_base(output, input, output_split_sizes, input_split_sizes, opts)\n else:\n work = group.alltoall_base(output, input, output_split_sizes, input_split_sizes, opts)\n\n if async_op:\n return work\n else:\n work.wait()\n\ndef all_to_all(output_tensor_list,\n input_tensor_list,\n group=group.WORLD,\n async_op=False):\n \"\"\"\n Each process scatters list of input tensors to all processes in a group and\n return gathered list of tensors in output list.\n\n Arguments:\n output_tensor_list (list[Tensor]): List of tensors to be gathered one\n per rank.\n input_tensor_list (list[Tensor]): List of tensors to scatter one per rank.\n group (ProcessGroup, optional): The process group to work on.\n async_op (bool, optional): Whether this op should be an async op.\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group.\n\n .. warning::\n `all_to_all` is experimental and subject to change.\n\n Examples:\n >>> input = torch.arange(4) + rank * 4\n >>> input = list(input.chunk(4))\n >>> input\n [tensor([0]), tensor([1]), tensor([2]), tensor([3])] # Rank 0\n [tensor([4]), tensor([5]), tensor([6]), tensor([7])] # Rank 1\n [tensor([8]), tensor([9]), tensor([10]), tensor([11])] # Rank 2\n [tensor([12]), tensor([13]), tensor([14]), tensor([15])] # Rank 3\n >>> output = list(torch.empty([4], dtype=torch.int64).chunk(4))\n >>> dist.all_to_all(output, input)\n >>> output\n [tensor([0]), tensor([4]), tensor([8]), tensor([12])] # Rank 0\n [tensor([1]), tensor([5]), tensor([9]), tensor([13])] # Rank 1\n [tensor([2]), tensor([6]), tensor([10]), tensor([14])] # Rank 2\n [tensor([3]), tensor([7]), tensor([11]), tensor([15])] # Rank 3\n\n >>> # Essentially, it is similar to following operation:\n >>> scatter_list = input\n >>> gather_list = output\n >>> for i in range(world_size):\n >>> dist.scatter(gather_list[i], scatter_list if i == rank else [], src = i)\n\n >>> input\n tensor([0, 1, 2, 3, 4, 5]) # Rank 0\n tensor([10, 11, 12, 13, 14, 15, 16, 17, 18]) # Rank 1\n tensor([20, 21, 22, 23, 24]) # Rank 2\n tensor([30, 31, 32, 33, 34, 35, 36]) # Rank 3\n >>> input_splits\n [2, 2, 1, 1] # Rank 0\n [3, 2, 2, 2] # Rank 1\n [2, 1, 1, 1] # Rank 2\n [2, 2, 2, 1] # Rank 3\n >>> output_splits\n [2, 3, 2, 2] # Rank 0\n [2, 2, 1, 2] # Rank 1\n [1, 2, 1, 2] # Rank 2\n [1, 2, 1, 1] # Rank 3\n >>> input = list(input.split(input_splits))\n >>> input\n [tensor([0, 1]), tensor([2, 3]), tensor([4]), tensor([5])] # Rank 0\n [tensor([10, 11, 12]), tensor([13, 14]), tensor([15, 16]), tensor([17, 18])] # Rank 1\n [tensor([20, 21]), tensor([22]), tensor([23]), tensor([24])] # Rank 2\n [tensor([30, 31]), tensor([32, 33]), tensor([34, 35]), tensor([36])] # Rank 3\n >>> output = ...\n >>> dist.all_to_all(output, input)\n >>> output\n [tensor([0, 1]), tensor([10, 11, 12]), tensor([20, 21]), tensor([30, 31])] # Rank 0\n [tensor([2, 3]), tensor([13, 14]), tensor([22]), tensor([32, 33])] # Rank 1\n [tensor([4]), tensor([15, 16]), tensor([23]), tensor([34, 35])] # Rank 2\n [tensor([5]), tensor([17, 18]), tensor([24]), tensor([36])] # Rank 3\n \"\"\"\n if _rank_not_in_group(group):\n return\n\n opts = AllToAllOptions()\n _check_tensor_list(output_tensor_list, \"output_tensor_list\")\n _check_tensor_list(input_tensor_list, \"input_tensor_list\")\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.alltoall(output_tensor_list, input_tensor_list, opts)\n else:\n work = group.alltoall(output_tensor_list, input_tensor_list, opts)\n\n if async_op:\n return work\n else:\n work.wait()\n\n\ndef barrier(group=group.WORLD,\n async_op=False):\n \"\"\"\n Synchronizes all processes.\n\n This collective blocks processes until the whole group enters this function,\n if async_op is False, or if async work handle is called on wait().\n\n Arguments:\n group (ProcessGroup, optional): The process group to work on\n async_op (bool, optional): Whether this op should be an async op\n\n Returns:\n Async work handle, if async_op is set to True.\n None, if not async_op or if not part of the group\n \"\"\"\n if _rank_not_in_group(group):\n return\n\n if group == GroupMember.WORLD:\n _check_default_pg()\n work = _default_pg.barrier()\n else:\n work = group.barrier()\n\n if async_op:\n return work\n else:\n work.wait()\n\n\ndef new_group(ranks=None, timeout=default_pg_timeout, backend=None):\n \"\"\"\n Creates a new distributed group.\n\n This function requires that all processes in the main group (i.e. all\n processes that are part of the distributed job) enter this function, even\n if they are not going to be members of the group. Additionally, groups\n should be created in the same order in all processes.\n\n Arguments:\n ranks (list[int]): List of ranks of group members. If ``None``, will be\n set to all ranks. Default is ``None``.\n timeout (timedelta, optional): Timeout for operations executed against\n the process group. Default value equals 30 minutes.\n This is only applicable for the ``gloo`` backend.\n backend (str or Backend, optional): The backend to use. Depending on\n build-time configurations, valid values are ``gloo`` and ``nccl``.\n By default uses the same backend as the global group. This field\n should be given as a lowercase string (e.g., ``\"gloo\"``), which can\n also be accessed via :class:`Backend` attributes (e.g.,\n ``Backend.GLOO``).\n\n Returns:\n A handle of distributed group that can be given to collective calls.\n \"\"\"\n\n _check_default_pg()\n\n global _pg_group_ranks\n\n default_backend, default_store = _pg_map[_default_pg]\n global_rank = _default_pg.rank()\n global_world_size = _default_pg.size()\n\n # Default to the same backend as the global process group\n # if the backend is not specified.\n if not backend:\n backend = default_backend\n\n # checks the input ranks\n if ranks is not None:\n ranks = sorted(ranks)\n group_world_size = len(ranks)\n if group_world_size > global_world_size:\n raise RuntimeError(\"the new group's world size should be less or \"\n \"equal to the world size set by \"\n \"init_process_group\")\n # check ranks' sanity\n for rank in ranks:\n if rank < 0 or rank >= global_world_size:\n raise RuntimeError(\"The new group's rank should be within the \"\n \"the world_size set by init_process_group\")\n if global_rank in ranks:\n group_rank = ranks.index(global_rank)\n else:\n group_rank = None\n else:\n ranks = list(range(global_world_size))\n group_world_size = global_world_size\n group_rank = global_rank\n\n backend = Backend(backend)\n pg = _new_process_group_helper(group_world_size,\n group_rank,\n ranks,\n backend,\n default_store,\n timeout=timeout)\n\n # Create the global rank to group rank mapping\n _pg_group_ranks[pg] = {\n global_rank: group_rank\n for group_rank, global_rank in enumerate(ranks)\n }\n\n # barrier at the end to ensure that once we return from this method, all\n # process groups including global variables are updated correctly on all\n # ranks.\n barrier()\n\n return pg\n", "import os\nimport sys\nimport io\n\nimport torch\n\n# Make the helper files in test/ importable\npytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\nsys.path.append(pytorch_test_dir)\nfrom torch.testing._internal.jit_utils import JitTestCase\nfrom torch.testing._internal.common_utils import suppress_warnings\n\nif __name__ == '__main__':\n raise RuntimeError(\"This test file is not meant to be run directly, use:\\n\\n\"\n \"\\tpython test/test_jit.py TESTNAME\\n\\n\"\n \"instead.\")\n\nclass TestTypeSharing(JitTestCase):\n def assertSameType(self, m1, m2):\n if not isinstance(m1, torch.jit.ScriptModule):\n m1 = torch.jit.script(m1)\n if not isinstance(m2, torch.jit.ScriptModule):\n m2 = torch.jit.script(m2)\n self.assertEqual(m1._c._type(), m2._c._type())\n\n def assertDifferentType(self, m1, m2):\n if not isinstance(m1, torch.jit.ScriptModule):\n m1 = torch.jit.script(m1)\n if not isinstance(m2, torch.jit.ScriptModule):\n m2 = torch.jit.script(m2)\n self.assertNotEqual(m1._c._type(), m2._c._type())\n\n def test_basic(self):\n class M(torch.nn.Module):\n def __init__(self, a, b, c):\n super(M, self).__init__()\n self.a = a\n self.b = b\n self.c = c\n\n def forward(self, x):\n return x\n a = torch.rand(2, 3)\n b = torch.rand(2, 3)\n c = torch.rand(2, 3)\n m1 = M(a, b, c)\n m2 = M(a, b, c)\n self.assertSameType(m1, m2)\n\n def test_diff_attr_values(self):\n \"\"\"\n Types should be shared even if attribute values differ\n \"\"\"\n class M(torch.nn.Module):\n def __init__(self, a, b, c):\n super(M, self).__init__()\n self.a = a\n self.b = b\n self.c = c\n\n def forward(self, x):\n return x\n a = torch.rand(2, 3)\n b = torch.rand(2, 3)\n c = torch.rand(2, 3)\n m1 = M(a, b, c)\n m2 = M(a * 2, b * 3, c * 4)\n self.assertSameType(m1, m2)\n\n def test_constants(self):\n \"\"\"\n Types should be shared for identical constant values, and different for different constant values\n \"\"\"\n class M(torch.nn.Module):\n __constants__ = [\"const\"]\n\n def __init__(self, attr, const):\n super(M, self).__init__()\n self.attr = attr\n self.const = const\n\n def forward(self):\n return self.const\n\n attr = torch.rand(2, 3)\n m1 = M(attr, 1)\n m2 = M(attr, 1)\n self.assertSameType(m1, m2)\n\n # a different constant value\n m3 = M(attr, 2)\n self.assertDifferentType(m1, m3)\n\n def test_linear(self):\n \"\"\"\n Simple example with a real nn Module\n \"\"\"\n a = torch.nn.Linear(5, 5)\n b = torch.nn.Linear(5, 5)\n c = torch.nn.Linear(10, 10)\n a = torch.jit.script(a)\n b = torch.jit.script(b)\n c = torch.jit.script(c)\n\n self.assertSameType(a, b)\n self.assertDifferentType(a, c)\n\n def test_submodules(self):\n \"\"\"\n If submodules differ, the types should differ.\n \"\"\"\n class M(torch.nn.Module):\n def __init__(self, in1, out1, in2, out2):\n super(M, self).__init__()\n self.submod1 = torch.nn.Linear(in1, out1)\n self.submod2 = torch.nn.Linear(in2, out2)\n\n def forward(self, x):\n x = self.submod1(x)\n x = self.submod2(x)\n return x\n\n a = M(1, 1, 2, 2)\n b = M(1, 1, 2, 2)\n self.assertSameType(a, b)\n self.assertSameType(a.submod1, b.submod1)\n c = M(2, 2, 2, 2)\n self.assertDifferentType(a, c)\n\n self.assertSameType(b.submod2, c.submod1)\n self.assertDifferentType(a.submod1, b.submod2)\n\n def test_param_vs_attribute(self):\n \"\"\"\n The same module with an `foo` as a parameter vs. attribute shouldn't\n share types\n \"\"\"\n class M(torch.nn.Module):\n def __init__(self, foo):\n super(M, self).__init__()\n self.foo = foo\n\n def forward(self, x):\n return x + self.foo\n\n as_param = torch.nn.Parameter(torch.ones(2, 2))\n as_attr = torch.ones(2, 2)\n param_mod = M(as_param)\n attr_mod = M(as_attr)\n self.assertDifferentType(attr_mod, param_mod)\n\n def test_same_but_different_classes(self):\n \"\"\"\n Even if everything about the module is the same, different originating\n classes should prevent type sharing.\n \"\"\"\n class A(torch.nn.Module):\n __constants__ = [\"const\"]\n\n def __init__(self, in1, out1, in2, out2):\n super(A, self).__init__()\n self.submod1 = torch.nn.Linear(in1, out1)\n self.submod2 = torch.nn.Linear(in2, out2)\n self.const = 5\n\n def forward(self, x):\n x = self.submod1(x)\n x = self.submod2(x)\n return x * self.const\n\n class B(torch.nn.Module):\n __constants__ = [\"const\"]\n\n def __init__(self, in1, out1, in2, out2):\n super(B, self).__init__()\n self.submod1 = torch.nn.Linear(in1, out1)\n self.submod2 = torch.nn.Linear(in2, out2)\n self.const = 5\n\n def forward(self, x):\n x = self.submod1(x)\n x = self.submod2(x)\n return x * self.const\n\n a = A(1, 1, 2, 2)\n b = B(1, 1, 2, 2)\n self.assertDifferentType(a, b)\n\n def test_mutate_attr_value(self):\n \"\"\"\n Mutating the value of an attribute should not change type sharing\n \"\"\"\n class M(torch.nn.Module):\n def __init__(self, in1, out1, in2, out2):\n super(M, self).__init__()\n self.submod1 = torch.nn.Linear(in1, out1)\n self.submod2 = torch.nn.Linear(in2, out2)\n self.foo = torch.ones(in1, in1)\n\n def forward(self, x):\n x = self.submod1(x)\n x = self.submod2(x)\n return x + self.foo\n\n a = M(1, 1, 2, 2)\n b = M(1, 1, 2, 2)\n a.foo = torch.ones(2, 2)\n b.foo = torch.rand(2, 2)\n self.assertSameType(a, b)\n\n def test_assign_python_attr(self):\n \"\"\"\n Assigning a new (python-only) attribute should not change type sharing\n \"\"\"\n class M(torch.nn.Module):\n def __init__(self, in1, out1, in2, out2):\n super(M, self).__init__()\n self.submod1 = torch.nn.Linear(in1, out1)\n self.submod2 = torch.nn.Linear(in2, out2)\n self.foo = torch.ones(in1, in1)\n\n def forward(self, x):\n x = self.submod1(x)\n x = self.submod2(x)\n return x + self.foo\n\n # explicitly call script() to freeze the type\n a = torch.jit.script(M(1, 1, 2, 2))\n b = torch.jit.script(M(1, 1, 2, 2))\n a.new_attr = \"foo bar baz\"\n self.assertSameType(a, b)\n\n # but if we assign attributes *before* calling script(), the types\n # should be different, since `new_attr` should be turned into a Script\n # attribute\n a = M(1, 1, 2, 2)\n b = M(1, 1, 2, 2)\n a.new_attr = \"foo bar baz\"\n self.assertDifferentType(a, b)\n\n def test_failed_attribute_compilation(self):\n \"\"\"\n Attributes whose type cannot be inferred should fail cleanly with nice hints\n \"\"\"\n class NotScriptable(object):\n pass\n\n class M(torch.nn.Module):\n def __init__(self):\n super(M, self).__init__()\n # assign a type we know can't be converted to TorchScript\n self.foo = NotScriptable()\n\n def forward(self):\n # try to use it in forward\n return self.foo\n\n m = M()\n with self.assertRaisesRegex(RuntimeError, \"failed to convert Python type\"):\n torch.jit.script(m)\n\n def test_script_function_attribute_different(self):\n \"\"\"\n Different functions passed in should lead to different types\n \"\"\"\n @torch.jit.script\n def fn1(x):\n return x + x\n\n @torch.jit.script\n def fn2(x):\n return x - x\n\n class M(torch.nn.Module):\n def __init__(self, fn):\n super(M, self).__init__()\n self.fn = fn\n\n def forward(self, x):\n return self.fn(x)\n\n fn1_mod = M(fn1)\n fn2_mod = M(fn2)\n\n self.assertDifferentType(fn1_mod, fn2_mod)\n\n def test_builtin_function_same(self):\n class Caller(torch.nn.Module):\n def __init__(self, fn):\n super(Caller, self).__init__()\n self.fn = fn\n\n def forward(self, input):\n return self.fn(input, input)\n\n c1 = Caller(torch.add)\n c2 = Caller(torch.add)\n\n self.assertSameType(c1, c2)\n\n def test_builtin_function_different(self):\n class Caller(torch.nn.Module):\n def __init__(self, fn):\n super(Caller, self).__init__()\n self.fn = fn\n\n def forward(self, input):\n return self.fn(input, input)\n\n c1 = Caller(torch.add)\n c2 = Caller(torch.sub)\n\n self.assertDifferentType(c1, c2)\n\n def test_script_function_attribute_same(self):\n \"\"\"\n Same functions passed in should lead to same types\n \"\"\"\n @torch.jit.script\n def fn(x):\n return x + x\n\n class M(torch.nn.Module):\n def __init__(self, fn):\n super(M, self).__init__()\n self.fn = fn\n\n def forward(self, x):\n return self.fn(x)\n\n fn1_mod = M(fn)\n fn2_mod = M(fn)\n\n self.assertSameType(fn1_mod, fn2_mod)\n\n def test_python_function_attribute_different(self):\n \"\"\"\n Different functions passed in should lead to different types\n \"\"\"\n def fn1(x):\n return x + x\n\n def fn2(x):\n return x - x\n\n class M(torch.nn.Module):\n def __init__(self, fn):\n super(M, self).__init__()\n self.fn = fn\n\n def forward(self, x):\n return self.fn(x)\n\n fn1_mod = M(fn1)\n fn2_mod = M(fn2)\n\n self.assertDifferentType(fn1_mod, fn2_mod)\n\n def test_python_function_attribute_same(self):\n \"\"\"\n Same functions passed in should lead to same types\n \"\"\"\n def fn(x):\n return x + x\n\n class M(torch.nn.Module):\n def __init__(self, fn):\n super(M, self).__init__()\n self.fn = fn\n\n def forward(self, x):\n return self.fn(x)\n\n fn1_mod = M(fn)\n fn2_mod = M(fn)\n\n self.assertSameType(fn1_mod, fn2_mod)\n\n @suppress_warnings\n def test_tracing_gives_different_types(self):\n \"\"\"\n Since we can't guarantee that methods are the same between different\n trace runs, tracing must always generate a unique type.\n \"\"\"\n class M(torch.nn.Module):\n def __init__(self):\n super(M, self).__init__()\n\n def forward(self, x, y):\n if x.sum() > y.sum():\n return x\n else:\n return y\n\n a = torch.jit.trace(M(), (torch.zeros(1, 1), torch.ones(1, 1)))\n b = torch.jit.trace(M(), (torch.ones(1, 1), torch.zeros(1, 1)))\n self.assertDifferentType(a, b)\n\n def test_ignored_fns(self):\n class M(torch.nn.Module):\n def __init__(self, foo):\n super(M, self).__init__()\n self.foo = foo\n\n @torch.jit.ignore\n def ignored(self):\n return self.foo\n\n def forward(self):\n return self.ignored()\n\n a = torch.jit.script(M(torch.ones(1)))\n b = torch.jit.script(M(torch.ones(2)))\n self.assertSameType(a, b)\n self.assertNotEqual(a(), b())\n\n @suppress_warnings\n def test_script_module_containing_traced_module(self):\n class Traced(torch.nn.Module):\n def __init__(self):\n super(Traced, self).__init__()\n\n def forward(self, x):\n if x.sum() > 0:\n return x\n else:\n return x + x\n\n class M(torch.nn.Module):\n def __init__(self, input):\n super(M, self).__init__()\n self.traced = torch.jit.trace(Traced(), input)\n\n def forward(self, x):\n return self.traced(x)\n\n a = M((torch.ones(1), ))\n b = M((torch.zeros(1), ))\n self.assertDifferentType(a, b)\n\n def test_loaded_modules_work(self):\n class AB(torch.nn.Module):\n def __init__(self):\n super(AB, self).__init__()\n self.a = 1\n self.b = 1\n\n def forward(self):\n return self.a + self.b\n\n class A(torch.nn.Module):\n def __init__(self):\n super(A, self).__init__()\n self.a = 1\n\n def forward(self):\n return self.a\n\n class Wrapper(torch.nn.Module):\n def __init__(self, sub):\n super(Wrapper, self).__init__()\n self.sub = sub\n\n def forward(self):\n return self.sub()\n\n def package(x):\n buffer = io.BytesIO()\n torch.jit.save(torch.jit.script(x), buffer)\n buffer.seek(0)\n return torch.jit.script(Wrapper(torch.jit.load(buffer)))\n\n\n a = package(AB())\n a()\n b = package(A())\n b()\n\n def test_module_dict_same_type_different_name(self):\n \"\"\"\n We should be able to differentiate between two ModuleDict instances\n that have different keys but the same value types.\n \"\"\"\n class A(torch.nn.Module):\n def __init__(self):\n super(A, self).__init__()\n\n def forward(self, x):\n return x\n\n class Foo(torch.nn.Module):\n def __init__(self, s):\n super(Foo, self).__init__()\n self.dict = torch.nn.ModuleDict(s)\n\n def forward(self, x):\n return x\n\n a = Foo({'foo': A()})\n b = Foo({'bar': A()})\n c = Foo({'bar': A()})\n self.assertDifferentType(a, b)\n self.assertSameType(b, c)\n\n def test_type_sharing_define_in_init(self):\n \"\"\"\n Tests that types between instances of a ScriptModule\n subclass that defines methods in its __init__ are not\n shared.\n \"\"\"\n class A(torch.jit.ScriptModule):\n def __init__(self, val):\n super().__init__()\n self.define(f\"\"\"\n def forward(self) -> int:\n return {val}\n \"\"\")\n\n one = A(1)\n two = A(2)\n\n self.assertEqual(one(), 1)\n self.assertEqual(two(), 2)\n\n def test_type_sharing_disabled(self):\n \"\"\"\n Test that type sharing can be disabled.\n \"\"\"\n class A(torch.nn.Module):\n def __init__(self, sub):\n super().__init__()\n self.sub = sub\n\n def forward(self, x):\n return x\n\n class B(torch.nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, x):\n return x\n\n top1 = A(A(B()))\n top2 = A(A(B()))\n\n top1_s = torch.jit._recursive.create_script_module(\n top1,\n torch.jit._recursive.infer_methods_to_compile,\n share_types=False,\n )\n top2_s = torch.jit._recursive.create_script_module(\n top2,\n torch.jit._recursive.infer_methods_to_compile,\n share_types=False,\n )\n\n self.assertDifferentType(top1_s, top2_s)\n self.assertDifferentType(top1_s, top1_s.sub)\n self.assertDifferentType(top1_s, top2_s.sub)\n self.assertDifferentType(top2_s, top2_s.sub)\n self.assertDifferentType(top2_s, top1_s.sub)\n", "import math\nimport torch\nfrom ..optimizer import Optimizer\n\nclass Adam(Optimizer):\n r\"\"\"Implements Adam algorithm with multi tensor APIs.\n\n It has been proposed in `Adam: A Method for Stochastic Optimization`_.\n The implementation of the L2 penalty follows changes proposed in\n `Decoupled Weight Decay Regularization`_.\n\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default: 1e-3)\n betas (Tuple[float, float], optional): coefficients used for computing\n running averages of gradient and its square (default: (0.9, 0.999))\n eps (float, optional): term added to the denominator to improve\n numerical stability (default: 1e-8)\n weight_decay (float, optional): weight decay (L2 penalty) (default: 0)\n amsgrad (boolean, optional): whether to use the AMSGrad variant of this\n algorithm from the paper `On the Convergence of Adam and Beyond`_\n (default: False)\n\n .. _Adam\\: A Method for Stochastic Optimization:\n https://arxiv.org/abs/1412.6980\n .. _Decoupled Weight Decay Regularization:\n https://arxiv.org/abs/1711.05101\n .. _On the Convergence of Adam and Beyond:\n https://openreview.net/forum?id=ryQu7f-RZ\n \"\"\"\n\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,\n weight_decay=0, amsgrad=False):\n if not 0.0 <= lr:\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\n if not 0.0 <= eps:\n raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n if not 0.0 <= weight_decay:\n raise ValueError(\"Invalid weight_decay value: {}\".format(weight_decay))\n defaults = dict(lr=lr, betas=betas, eps=eps,\n weight_decay=weight_decay, amsgrad=amsgrad)\n super(Adam, self).__init__(params, defaults)\n\n def __setstate__(self, state):\n super(Adam, self).__setstate__(state)\n for group in self.param_groups:\n group.setdefault('amsgrad', False)\n\n @torch.no_grad()\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n with torch.enable_grad():\n loss = closure()\n\n for group in self.param_groups:\n amsgrad = group['amsgrad']\n\n grads = []\n states = []\n exp_avg = []\n exp_avg_sq = []\n max_exp_avg_sq = []\n params_with_grad = []\n\n for p in group['params']:\n if p.grad is not None:\n if p.grad.is_sparse:\n raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')\n params_with_grad.append(p)\n grads.append(p.grad)\n\n for p in params_with_grad:\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format)\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format)\n if amsgrad:\n # Maintains max of all exp. moving avg. of sq. grad. values\n state['max_exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format)\n\n exp_avg.append(state['exp_avg'])\n exp_avg_sq.append(state['exp_avg_sq'])\n\n if amsgrad:\n max_exp_avg_sq.append(state['max_exp_avg_sq'])\n\n state['step'] += 1\n states.append(state)\n\n beta1, beta2 = group['betas']\n\n bias_correction1 = [1 - beta1 ** state['step'] for state in states] \n bias_correction2 = [1 - beta2 ** state['step'] for state in states] \n if group['weight_decay'] != 0:\n grads = torch._foreach_add(grads, params_with_grad, alpha=group['weight_decay'])\n\n #\n # Decay the first and second moment running average coefficient\n #\n torch._foreach_mul_(exp_avg, beta1)\n torch._foreach_add_(exp_avg, grads, alpha=1 - beta1)\n\n torch._foreach_mul_(exp_avg_sq, beta2)\n torch._foreach_addcmul_(exp_avg_sq, grads, grads, 1 - beta2)\n\n if amsgrad:\n # Maintains the maximum of all 2nd moment running avg. till now\n [torch.max(a, b, out=a) for a, b in zip(max_exp_avg_sq, exp_avg_sq)]\n # Use the max. for normalizing running avg. of gradient\n max_exp_avg_sq_sqrt = torch._foreach_sqrt(max_exp_avg_sq)\n bias_correction_sqrt = [math.sqrt(bc) for bc in bias_correction2]\n torch._foreach_div_scalar_list_(max_exp_avg_sq_sqrt, bias_correction_sqrt)\n denom = torch._foreach_add(max_exp_avg_sq_sqrt, group['eps'])\n else:\n exp_avg_sq_sqrt = torch._foreach_sqrt(exp_avg_sq)\n bias_correction_sqrt = [math.sqrt(bc) for bc in bias_correction2]\n torch._foreach_div_scalar_list_(exp_avg_sq_sqrt, bias_correction_sqrt)\n denom = torch._foreach_add(exp_avg_sq_sqrt, group['eps'])\n\n step_size = [group['lr'] / bc for bc in bias_correction1]\n\n for i in range(len(step_size)):\n params_with_grad[i].addcdiv_(exp_avg[i], denom[i], value=-step_size[i])\n\n return loss\n", "import os\nimport sys\n\nfrom typing import Any\n\nimport torch\nfrom torch.testing._internal.jit_utils import JitTestCase\n\n\n# Make the helper files in test/ importable\npytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\nsys.path.append(pytorch_test_dir)\n\nif __name__ == \"__main__\":\n raise RuntimeError(\n \"This test file is not meant to be run directly, use:\\n\\n\"\n \"\\tpython test/test_jit.py TESTNAME\\n\\n\"\n \"instead.\"\n )\n\n\nclass TestWith(JitTestCase):\n \"\"\"\n A suite of tests for with statements.\n \"\"\"\n\n def test_with_as(self):\n \"\"\"\n Check that with statements that use the 'as' keyword to bind expressions\n to targets work as expected.\n \"\"\"\n global Context\n\n @torch.jit.script\n class Context(object):\n \"\"\"\n This class implements a basic context manager interface for use in\n the unit tests. Unlike Context, the stateful part of this class\n is a Tensor that is mutated in-place so that modifications made in the\n JIT interpreter are visible outside of it.\n \"\"\"\n\n def __init__(self, start: int):\n self.count = torch.tensor([start], dtype=torch.double)\n\n def __enter__(self):\n self.count.add_(0.3)\n return self.count\n\n def __exit__(self, type: Any, value: Any, tb: Any):\n self.count.sub_(0.3)\n\n def test_basic(x):\n # type: (Tensor) -> Tensor\n \"\"\"Basic test with one with-statement.\"\"\"\n\n c = Context(1)\n\n with c as mult:\n y = x + mult\n\n y *= c.count\n return y\n\n def test_pass(x):\n # type: (Tensor) -> Tensor\n \"\"\"\n Test with a pass statement inside a with-statement. Although\n the body of the with is empty, __enter__ and __exit__ should\n still be called.\n \"\"\"\n c = Context(1)\n\n with c as mult:\n pass\n\n x *= c.count\n return x\n\n def test_early_return(x, c):\n # type: (Tensor, Context) -> Tensor\n \"\"\"\n Test that returning early from inside a with-statement works\n as expected.\n \"\"\"\n with c as mult:\n y = x + mult\n return y\n\n x = y + y\n return x\n\n def test_conditional_early_return(x, c):\n # type: (Tensor, Context) -> Tensor\n \"\"\"\n Test that conditionally returning early from inside a with-statement works\n as expected.\n \"\"\"\n with c as mult:\n y = x + mult\n if mult > 0:\n return y\n\n x = y + y\n return x\n\n def test_break(x, c, l):\n # type: (Tensor, Context, List[int]) -> Tensor\n \"\"\"\n Test that breaking early from inside a with-statement works\n as expected.\n \"\"\"\n with c as mult:\n for a in l:\n if a == 0:\n break\n x += a * mult\n\n return x\n\n def test_continue(x, c, l):\n # type: (Tensor, Context, List[int]) -> Tensor\n \"\"\"\n Test that using continue inside a with-statement works\n as expected.\n \"\"\"\n with c as mult:\n for a in l:\n if a == 0:\n continue\n x += a * mult\n\n return x\n\n def test_serial(x):\n # type: (Tensor) -> Tensor\n \"\"\"\n Test two with-statements in a row.\n \"\"\"\n c = Context(1)\n\n with c as mult:\n y = x + mult\n\n with c as mult:\n y *= mult\n\n return y\n\n def test_nested(x):\n # type: (Tensor) -> Tensor\n \"\"\"\n Test nested with-statements.\n \"\"\"\n c = Context(1)\n\n with c as m:\n with c as n:\n y = x + n\n\n y *= m\n\n return y\n\n def test_combined(x):\n # type: (Tensor) -> Tensor\n \"\"\"\n Test a with-statement with multiple with items.\n \"\"\"\n c = Context(1)\n d = Context(2)\n\n with c as m, d as n:\n y = x + (m + n)\n\n return y\n\n test_input = torch.randn(2, 2)\n test_context = Context(2)\n test_list = [2, 0, 1, 3, 0, 2]\n\n self.checkScript(test_basic, (test_input,))\n self.checkScript(test_pass, (test_input,))\n self.checkScript(test_early_return, (test_input, test_context))\n self.checkScript(test_break, (test_input, test_context, test_list))\n self.checkScript(test_continue, (test_input, test_context, test_list))\n self.assertEqual(test_context.count, 2)\n self.checkScript(test_serial, (test_input,))\n self.checkScript(test_nested, (test_input,))\n self.checkScript(test_combined, (test_input,))\n\n def test_with_no_as(self):\n \"\"\"\n Check that with statements that do not use the 'as' keyword to bind expressions\n to targets work as expected.\n \"\"\"\n global Context\n\n @torch.jit.script\n class Context(object):\n \"\"\"\n This class implements a basic context manager interface for use in\n the unit tests. Unlike Context, the stateful part of this class\n is a Tensor that is mutated in-place so that modifications made in the\n JIT interpreter are visible outside of it.\n \"\"\"\n\n def __init__(self, start: int):\n self.count = torch.tensor([start], dtype=torch.double)\n\n def __enter__(self):\n self.count.add_(0.3)\n return self.count\n\n def __exit__(self, type: Any, value: Any, tb: Any):\n self.count.sub_(0.3)\n\n def test_basic(x):\n # type: (Tensor) -> Tensor\n \"\"\"Basic test with one with-statement.\"\"\"\n\n c = Context(1)\n\n with c:\n y = x + c.count\n\n y *= c.count\n return y\n\n def test_pass(x):\n # type: (Tensor) -> Tensor\n \"\"\"\n Test with a pass statement inside a with-statement. Although\n the body of the with is empty, __enter__ and __exit__ should\n still be called.\n \"\"\"\n c = Context(1)\n\n with c:\n pass\n\n x *= c.count\n return x\n\n def test_early_return(x, c):\n # type: (Tensor, Context) -> Tensor\n \"\"\"\n Test that returning early from inside a with-statement works\n as expected.\n \"\"\"\n with c:\n y = x + c.count\n return y\n\n x = y + y\n return x\n\n def test_conditional_early_return(x, c):\n # type: (Tensor, Context) -> Tensor\n \"\"\"\n Test that conditionally returning early from inside a with-statement works\n as expected.\n \"\"\"\n with c:\n y = x + c.count\n if c.count > 0:\n return y\n\n x = y + y\n return x\n\n def test_break(x, c, l):\n # type: (Tensor, Context, List[int]) -> Tensor\n \"\"\"\n Test that breaking early from inside a with-statement works\n as expected.\n \"\"\"\n with c:\n for a in l:\n if a == 0:\n break\n x += a * c.count\n\n return x\n\n def test_continue(x, c, l):\n # type: (Tensor, Context, List[int]) -> Tensor\n \"\"\"\n Test that using continue inside a with-statement works\n as expected.\n \"\"\"\n with c:\n for a in l:\n if a == 0:\n continue\n x += a * c.count\n\n return x\n\n def test_serial(x):\n # type: (Tensor) -> Tensor\n \"\"\"\n Test two with-statements in a row.\n \"\"\"\n c = Context(1)\n\n with c:\n y = x + c.count\n\n with c:\n y *= c.count\n\n return y\n\n def test_nested(x):\n # type: (Tensor) -> Tensor\n \"\"\"\n Test nested with-statements.\n \"\"\"\n c = Context(1)\n\n with c:\n with c:\n y = x + c.count\n\n y *= c.count\n\n return y\n\n def test_combined(x):\n # type: (Tensor) -> Tensor\n \"\"\"\n Test a with-statement with multiple with items.\n \"\"\"\n c = Context(1)\n d = Context(2)\n\n with c, d:\n y = x + (c.count + d.count)\n\n return y\n\n test_input = torch.randn(2, 2)\n test_context = Context(2)\n test_list = [2, 0, 1, 3, 0, 2]\n\n self.checkScript(test_basic, (test_input,))\n self.checkScript(test_pass, (test_input,))\n self.checkScript(test_early_return, (test_input, test_context))\n self.checkScript(test_break, (test_input, test_context, test_list))\n self.checkScript(test_continue, (test_input, test_context, test_list))\n self.assertEqual(test_context.count, 2)\n self.checkScript(test_serial, (test_input,))\n self.checkScript(test_nested, (test_input,))\n self.checkScript(test_combined, (test_input,))\n\n def test_with_exceptions(self):\n \"\"\"\n Check that exceptions thrown in the bodies of with-statements are\n handled correctly.\n \"\"\"\n global Context\n\n @torch.jit.script\n class Context(object):\n \"\"\"\n This class implements a basic context manager interface for use in\n the unit tests. Unlike Context, the stateful part of this class\n is a Tensor that is mutated in-place so that modifications made in the\n JIT interpreter are visible outside of it.\n \"\"\"\n\n def __init__(self, start: int):\n self.count = torch.tensor([start], dtype=torch.double)\n\n def __enter__(self):\n self.count.add_(0.3)\n return self.count\n\n def __exit__(self, type: Any, value: Any, tb: Any):\n self.count.sub_(0.3)\n\n @torch.jit.script\n def method_that_raises():\n # type: () -> Tensor\n raise Exception(\"raised exception\")\n\n @torch.jit.script\n def test_exception(x, c):\n # type: (Tensor, Context) -> Tensor\n \"\"\"\n Test the case in which an exception is thrown while executing the body of a with-statement.\n \"\"\"\n with c as _:\n x += method_that_raises()\n\n return x\n\n @torch.jit.script\n def test_exception_nested(x, c):\n # type: (Tensor, Context) -> Tensor\n \"\"\"\n Test the case in which an exception is thrown while executing the body of a nested with-statement.\n \"\"\"\n with c as _:\n with c as _:\n x += method_that_raises()\n\n return x\n\n @torch.jit.script\n def with_that_raises(c):\n # type: (Context) -> Tensor\n a = torch.tensor([1])\n\n with c as _:\n a += method_that_raises()\n\n return a\n\n @torch.jit.script\n def test_exception_fn_call(x, c):\n # type: (Tensor, Context) -> Tensor\n \"\"\"\n Test the case in which an exception is thrown while there are active with-statements in two different\n frames.\n \"\"\"\n with c as _:\n x += with_that_raises(c)\n\n return x\n\n c = Context(1)\n\n # checkScript and checkScriptRaisesRegex cannot be used because the string frontend will\n # not compile class types (of which Context, the context manager being used for this test\n # is one).\n with self.assertRaisesRegex(Exception, r\"raised exception\"):\n test_exception(torch.randn(2), c)\n self.assertEqual(c.count, 1)\n\n with self.assertRaisesRegex(Exception, r\"raised exception\"):\n test_exception_nested(torch.randn(2), c)\n self.assertEqual(c.count, 1)\n\n with self.assertRaisesRegex(Exception, r\"raised exception\"):\n test_exception_fn_call(torch.randn(2), c)\n self.assertEqual(c.count, 1)\n\n def test_with_errors(self):\n \"\"\"\n Check that errors related to with-statements are detected and reported correctly.\n \"\"\"\n\n @torch.jit.script\n class NoEnterNoExit(object):\n \"\"\"\n This class is missing __enter__ and __exit__ methods.\n \"\"\"\n\n def __init__(self):\n self.count = 1\n\n @torch.jit.script\n class BadEnter(object):\n \"\"\"\n This class is has an __enter__ method with an incorrect signature.\n \"\"\"\n\n def __init__(self):\n self.count = 1\n\n def __enter__(self, incr: int):\n self.count += incr\n\n def __exit__(self, type: Any, value: Any, tb: Any):\n pass\n\n @torch.jit.script\n class BadExit(object):\n \"\"\"\n This class is has an __exit__ method with an incorrect signature.\n \"\"\"\n\n def __init__(self):\n self.count = 1\n\n def __enter__(self):\n self.count += 1\n\n def __exit__(self, type: Any, value: Any):\n pass\n\n @torch.jit.script\n class ExitIncorrectTypes(object):\n \"\"\"\n This class is has an __exit__ method with unsupported argument types.\n \"\"\"\n\n def __init__(self):\n self.count = 1\n\n def __enter__(self):\n self.count += 1\n\n def __exit__(self, type: Any, value: int, tb: int):\n pass\n\n def test_no_enter_no_exit(x, c):\n # type: (Tensor, NoEnterNoExit) -> Tensor\n with c as _:\n pass\n\n return x\n\n def test_bad_enter(x, c):\n # type: (Tensor, BadEnter) -> Tensor\n with c as _:\n pass\n\n return x\n\n def test_bad_exit(x, c):\n # type: (Tensor, BadExit) -> Tensor\n with c as _:\n pass\n\n return x\n\n def test_exit_incorrect_types(x, c):\n # type: (Tensor, ExitIncorrectTypes) -> Tensor\n with c as _:\n pass\n\n return x\n\n test_tensor = torch.randn(5, dtype=torch.double)\n\n with self.assertRaisesRegex(\n RuntimeError, r\"does not define __enter__ and __exit__ methods\"\n ):\n self.checkScript(test_no_enter_no_exit, (test_tensor, NoEnterNoExit()))\n\n with self.assertRaisesRegex(\n RuntimeError, r\"__enter__ must have only one argument and one return value\"\n ):\n self.checkScript(test_bad_enter, (test_tensor, BadEnter()))\n\n with self.assertRaisesRegex(\n RuntimeError, r\"__exit__ must have four arguments and no return value\"\n ):\n self.checkScript(test_bad_exit, (test_tensor, BadExit()))\n\n with self.assertRaisesRegex(\n RuntimeError, r\"argument 2 of __exit__ must have Any type\"\n ):\n self.checkScript(\n test_exit_incorrect_types, (test_tensor, ExitIncorrectTypes())\n )\n\n def test_with_no_grad(self):\n \"\"\"\n Check that torch.no_grad() works. Most of these are adapted from\n corresponding tests for eager-mode no_grad.\n \"\"\"\n\n # Basic no_grad test.\n def test_no_grad(x, y):\n # type: (Tensor, Tensor) -> Tensor\n with torch.no_grad():\n w = x + y\n\n return w\n\n s = torch.jit.script(test_no_grad)\n x = torch.ones(5, 5, requires_grad=True)\n y = torch.ones(5, 5) * 4\n w = s(x, y)\n\n self.assertFalse(w.requires_grad)\n self.assertRaises(RuntimeError, lambda: w.backward(torch.ones(5, 5)))\n self.assertIsNone(w.grad_fn)\n\n # Test assignment of a grad-less Tensor to a Tensor with gradients\n # in a no_grad block.\n def test_no_grad_assignment(x, y):\n # type: (Tensor, Tensor) -> Tensor\n with torch.no_grad():\n x[0] = y\n\n return x\n\n s = torch.jit.script(test_no_grad_assignment)\n z = torch.randn(5)\n w = s(x, z)\n self.assertTrue(w.requires_grad)\n self.assertIsNone(w.grad_fn)\n\n # Check that @torch.jit.ignored functions respect no_grad when it is\n # called in JIT mode.\n class NoGradModule(torch.nn.Module):\n def __init__(self):\n super().__init__()\n\n @torch.jit.ignore\n def adder(self, x, y):\n # type: (Tensor, Tensor) -> Tensor\n w = x + y\n return w\n\n def forward(self, x, y):\n # type: (Tensor, Tensor) -> Tensor\n with torch.no_grad():\n w = self.adder(x, y)\n\n return w\n\n s = torch.jit.script(NoGradModule())\n w = s(x, y)\n\n self.assertFalse(w.requires_grad)\n\n def test_with_record_function(self):\n \"\"\"\n Check that torch.autograd.profiler.record_function context manager is\n torchscriptable.\n \"\"\"\n def with_rf(x, y):\n # type: (Tensor, Tensor) -> Tensor\n with torch.autograd.profiler.record_function(\"foo\"):\n # Nested record_function.\n with torch.autograd.profiler.record_function(\"nested\"):\n a = x + y\n return a\n\n scripted = torch.jit.script(with_rf)\n x, y = torch.ones(2), torch.ones(2)\n with torch.autograd.profiler.profile() as p:\n scripted(x, y)\n\n # Need to call below to populate CPU children.\n p.key_averages()\n function_events = p.function_events\n # Event with name \"foo\" should be recorded.\n rf_events = [evt for evt in function_events if evt.name == \"foo\"]\n self.assertTrue(len(rf_events), 1)\n rf_event = rf_events[0]\n child_events = rf_event.cpu_children\n # Ensure we find nested record_function event\n self.assertTrue(\"nested\" in (child.name for child in child_events))\n nested_function_event = [\n evt for evt in function_events if evt.name == \"nested\"\n ][0]\n # Nested record function should have child \"aten::add\"\n nested_child_events = nested_function_event.cpu_children\n self.assertTrue(\"aten::add\" in (child.name for child in nested_child_events))\n" ]
[ [ "torch.ops.quantized.batch_norm1d", "torch.ops.quantized.batch_norm2d", "torch.quantize_per_tensor", "torch.rand" ], [ "torch.empty", "torch.cuda.current_device", "torch.multiprocessing.get_all_start_methods", "torch._six.queue.Queue", "torch._C._log_api_usage_once", "torch.multiprocessing.get_context", "torch.cuda.is_available" ], [ "torch.ByteTensor", "torch.empty", "torch.zeros", "torch.cat", "torch.sum", "torch.ByteStorage.from_buffer" ], [ "torch.jit.script", "torch.jit.load", "torch.ones", "torch.zeros", "torch.nn.ModuleDict", "torch.nn.Linear", "torch.rand", "torch.jit._recursive.create_script_module" ], [ "torch._foreach_add", "torch.enable_grad", "torch.max", "torch._foreach_addcmul_", "torch._foreach_mul_", "torch.zeros_like", "torch.no_grad", "torch._foreach_div_scalar_list_", "torch._foreach_add_", "torch._foreach_sqrt" ], [ "torch.jit.script", "torch.autograd.profiler.record_function", "torch.ones", "torch.randn", "torch.tensor", "torch.no_grad", "torch.autograd.profiler.profile" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
silverriver/Stylized_Dialog
[ "559dd97c4ec9c91e94deb048f789684ef3f1f9fa" ]
[ "TCFC/eval/bert_eval_acc.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\"\"\" Finetuning the library models for sequence classification on GLUE (Bert, XLM, XLNet, RoBERTa, Albert, XLM-RoBERTa).\"\"\"\n\n\nimport argparse\nimport glob\nimport json\nimport logging\nimport os\nimport random\nimport shutil\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset\nfrom torch.utils.data.distributed import DistributedSampler\nfrom tqdm import tqdm, trange\n\nfrom transformers import (\n WEIGHTS_NAME,\n AdamW,\n AlbertConfig,\n AlbertForSequenceClassification,\n AlbertTokenizer,\n BertConfig,\n BertForSequenceClassification,\n BertTokenizer,\n DistilBertConfig,\n DistilBertForSequenceClassification,\n DistilBertTokenizer,\n FlaubertConfig,\n FlaubertForSequenceClassification,\n FlaubertTokenizer,\n RobertaConfig,\n RobertaForSequenceClassification,\n RobertaTokenizer,\n XLMConfig,\n XLMForSequenceClassification,\n XLMRobertaConfig,\n XLMRobertaForSequenceClassification,\n XLMRobertaTokenizer,\n XLMTokenizer,\n XLNetConfig,\n XLNetForSequenceClassification,\n XLNetTokenizer,\n get_linear_schedule_with_warmup,\n)\nfrom transformers import glue_compute_metrics as compute_metrics\nfrom transformers import glue_convert_examples_to_features as convert_examples_to_features\nfrom transformers import glue_output_modes as output_modes\nfrom transformers import glue_processors as processors\n\n\nfrom torch.utils.tensorboard import SummaryWriter\n\n\nlogger = logging.getLogger(__name__)\n\nALL_MODELS = sum(\n (\n tuple(conf.pretrained_config_archive_map.keys())\n for conf in (\n BertConfig,\n XLNetConfig,\n XLMConfig,\n RobertaConfig,\n DistilBertConfig,\n AlbertConfig,\n XLMRobertaConfig,\n FlaubertConfig,\n )\n ),\n (),\n)\n\nMODEL_CLASSES = {\n \"bert\": (BertConfig, BertForSequenceClassification, BertTokenizer),\n \"xlnet\": (XLNetConfig, XLNetForSequenceClassification, XLNetTokenizer),\n \"xlm\": (XLMConfig, XLMForSequenceClassification, XLMTokenizer),\n \"roberta\": (RobertaConfig, RobertaForSequenceClassification, RobertaTokenizer),\n \"distilbert\": (DistilBertConfig, DistilBertForSequenceClassification, DistilBertTokenizer),\n \"albert\": (AlbertConfig, AlbertForSequenceClassification, AlbertTokenizer),\n \"xlmroberta\": (XLMRobertaConfig, XLMRobertaForSequenceClassification, XLMRobertaTokenizer),\n \"flaubert\": (FlaubertConfig, FlaubertForSequenceClassification, FlaubertTokenizer),\n}\n\n\ndef set_seed(args):\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if args.n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n\ndef softmax(x):\n x_row_max = x.max(axis=-1)\n x_row_max = x_row_max.reshape(list(x.shape)[:-1]+[1])\n x = x - x_row_max\n x_exp = np.exp(x)\n x_exp_row_sum = x_exp.sum(axis=-1).reshape(list(x.shape)[:-1]+[1])\n softmax = x_exp / x_exp_row_sum\n return softmax\n\n\ndef train(args, train_dataset, model, tokenizer):\n \"\"\" Train the model \"\"\"\n if args.local_rank in [-1, 0]:\n tb_writer = SummaryWriter()\n\n args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)\n train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset)\n train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size)\n\n if args.max_steps > 0:\n t_total = args.max_steps\n args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1\n else:\n t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs\n\n # Prepare optimizer and schedule (linear warmup and decay)\n no_decay = [\"bias\", \"LayerNorm.weight\"]\n optimizer_grouped_parameters = [\n {\n \"params\": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],\n \"weight_decay\": args.weight_decay,\n },\n {\"params\": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], \"weight_decay\": 0.0},\n ]\n\n optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)\n scheduler = get_linear_schedule_with_warmup(\n optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total\n )\n\n # Check if saved optimizer or scheduler states exist\n if os.path.isfile(os.path.join(args.model_name_or_path, \"optimizer.pt\")) and os.path.isfile(\n os.path.join(args.model_name_or_path, \"scheduler.pt\")\n ):\n # Load in optimizer and scheduler states\n optimizer.load_state_dict(torch.load(os.path.join(args.model_name_or_path, \"optimizer.pt\")))\n scheduler.load_state_dict(torch.load(os.path.join(args.model_name_or_path, \"scheduler.pt\")))\n\n if args.fp16:\n try:\n from apex import amp\n except ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to use fp16 training.\")\n model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level)\n\n # multi-gpu training (should be after apex fp16 initialization)\n if args.n_gpu > 1:\n model = torch.nn.DataParallel(model)\n\n # Distributed training (should be after apex fp16 initialization)\n if args.local_rank != -1:\n model = torch.nn.parallel.DistributedDataParallel(\n model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True,\n )\n\n # Train!\n logger.info(\"***** Running training *****\")\n logger.info(\" Num examples = %d\", len(train_dataset))\n logger.info(\" Num Epochs = %d\", args.num_train_epochs)\n logger.info(\" Instantaneous batch size per GPU = %d\", args.per_gpu_train_batch_size)\n logger.info(\n \" Total train batch size (w. parallel, distributed & accumulation) = %d\",\n args.train_batch_size\n * args.gradient_accumulation_steps\n * (torch.distributed.get_world_size() if args.local_rank != -1 else 1),\n )\n logger.info(\" Gradient Accumulation steps = %d\", args.gradient_accumulation_steps)\n logger.info(\" Total optimization steps = %d\", t_total)\n\n global_step = 0\n epochs_trained = 0\n steps_trained_in_current_epoch = 0\n # Check if continuing training from a checkpoint\n if os.path.exists(args.model_name_or_path):\n # set global_step to global_step of last saved checkpoint from model path\n try:\n global_step = int(args.model_name_or_path.split(\"-\")[-1].split(\"/\")[0])\n except ValueError:\n global_step = 0\n epochs_trained = global_step // (len(train_dataloader) // args.gradient_accumulation_steps)\n steps_trained_in_current_epoch = global_step % (len(train_dataloader) // args.gradient_accumulation_steps)\n\n logger.info(\" Continuing training from checkpoint, will skip to saved global_step\")\n logger.info(\" Continuing training from epoch %d\", epochs_trained)\n logger.info(\" Continuing training from global step %d\", global_step)\n logger.info(\" Will skip the first %d steps in the first epoch\", steps_trained_in_current_epoch)\n\n tr_loss, logging_loss = 0.0, 0.0\n model.zero_grad()\n train_iterator = trange(\n epochs_trained, int(args.num_train_epochs), desc=\"Epoch\", disable=args.local_rank not in [-1, 0],\n )\n set_seed(args) # Added here for reproductibility\n for _ in train_iterator:\n epoch_iterator = tqdm(train_dataloader, desc=\"Iteration\", disable=args.local_rank not in [-1, 0])\n for step, batch in enumerate(epoch_iterator):\n\n # Skip past any already trained steps if resuming training\n if steps_trained_in_current_epoch > 0:\n steps_trained_in_current_epoch -= 1\n continue\n\n model.train()\n batch = tuple(t.to(args.device) for t in batch)\n inputs = {\"input_ids\": batch[0], \"attention_mask\": batch[1], \"labels\": batch[3]}\n if args.model_type != \"distilbert\":\n inputs[\"token_type_ids\"] = (\n batch[2] if args.model_type in [\"bert\", \"xlnet\", \"albert\"] else None\n ) # XLM, DistilBERT, RoBERTa, and XLM-RoBERTa don't use segment_ids\n outputs = model(**inputs)\n loss = outputs[0] # model outputs are always tuple in transformers (see doc)\n\n if args.n_gpu > 1:\n loss = loss.mean() # mean() to average on multi-gpu parallel training\n if args.gradient_accumulation_steps > 1:\n loss = loss / args.gradient_accumulation_steps\n\n if args.fp16:\n with amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n else:\n loss.backward()\n\n tr_loss += loss.item()\n if (step + 1) % args.gradient_accumulation_steps == 0:\n if args.fp16:\n torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)\n else:\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)\n\n optimizer.step()\n scheduler.step() # Update learning rate schedule\n model.zero_grad()\n global_step += 1\n\n if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0:\n logs = {}\n if (\n args.local_rank == -1 and args.evaluate_during_training\n ): # Only evaluate when single GPU otherwise metrics may not average well\n results = evaluate(args, model, tokenizer)\n for key, value in results.items():\n eval_key = \"eval_{}\".format(key)\n logs[eval_key] = value\n\n loss_scalar = (tr_loss - logging_loss) / args.logging_steps\n learning_rate_scalar = scheduler.get_lr()[0]\n logs[\"learning_rate\"] = learning_rate_scalar\n logs[\"loss\"] = loss_scalar\n logging_loss = tr_loss\n\n for key, value in logs.items():\n tb_writer.add_scalar(key, value, global_step)\n print(json.dumps({**logs, **{\"step\": global_step}}))\n\n if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0:\n # Save model checkpoint\n output_dir = os.path.join(args.output_dir, \"checkpoint-{}\".format(global_step))\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n model_to_save = (\n model.module if hasattr(model, \"module\") else model\n ) # Take care of distributed/parallel training\n model_to_save.save_pretrained(output_dir)\n tokenizer.save_pretrained(output_dir)\n\n torch.save(args, os.path.join(output_dir, \"training_args.bin\"))\n logger.info(\"Saving model checkpoint to %s\", output_dir)\n\n torch.save(optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\"))\n torch.save(scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\"))\n logger.info(\"Saving optimizer and scheduler states to %s\", output_dir)\n\n if args.max_steps > 0 and global_step > args.max_steps:\n epoch_iterator.close()\n break\n if args.max_steps > 0 and global_step > args.max_steps:\n train_iterator.close()\n break\n\n if args.local_rank in [-1, 0]:\n tb_writer.close()\n\n return global_step, tr_loss / global_step\n\n\ndef evaluate(args, model, tokenizer, prefix=\"\"):\n # Loop to handle MNLI double evaluation (matched, mis-matched)\n eval_task_names = (\"mnli\", \"mnli-mm\") if args.task_name == \"mnli\" else (args.task_name,)\n eval_outputs_dirs = (args.output_dir, args.output_dir + \"-MM\") if args.task_name == \"mnli\" else (args.output_dir,)\n\n results = {}\n for eval_task, eval_output_dir in zip(eval_task_names, eval_outputs_dirs):\n eval_dataset = load_and_cache_examples(args, eval_task, tokenizer, evaluate=True)\n\n if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]:\n os.makedirs(eval_output_dir)\n\n args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)\n # Note that DistributedSampler samples randomly\n eval_sampler = SequentialSampler(eval_dataset)\n eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)\n\n # multi-gpu eval\n if args.n_gpu > 1 and not isinstance(model, torch.nn.DataParallel):\n model = torch.nn.DataParallel(model)\n\n # Eval!\n logger.info(\"***** Running evaluation {} *****\".format(prefix))\n logger.info(\" Num examples = %d\", len(eval_dataset))\n logger.info(\" Batch size = %d\", args.eval_batch_size)\n eval_loss = 0.0\n nb_eval_steps = 0\n preds = None\n out_label_ids = None\n for batch in tqdm(eval_dataloader, desc=\"Evaluating\"):\n model.eval()\n batch = tuple(t.to(args.device) for t in batch)\n\n with torch.no_grad():\n inputs = {\"input_ids\": batch[0], \"attention_mask\": batch[1], \"labels\": batch[3]}\n if args.model_type != \"distilbert\":\n inputs[\"token_type_ids\"] = (\n batch[2] if args.model_type in [\"bert\", \"xlnet\", \"albert\"] else None\n ) # XLM, DistilBERT, RoBERTa, and XLM-RoBERTa don't use segment_ids\n outputs = model(**inputs)\n tmp_eval_loss, logits = outputs[:2]\n\n eval_loss += tmp_eval_loss.mean().item()\n nb_eval_steps += 1\n if preds is None:\n preds = logits.detach().cpu().numpy()\n out_label_ids = inputs[\"labels\"].detach().cpu().numpy()\n else:\n preds = np.append(preds, logits.detach().cpu().numpy(), axis=0)\n out_label_ids = np.append(out_label_ids, inputs[\"labels\"].detach().cpu().numpy(), axis=0)\n\n eval_loss = eval_loss / nb_eval_steps\n if args.output_mode == \"classification\":\n preds = np.argmax(preds, axis=1)\n elif args.output_mode == \"regression\":\n preds = np.squeeze(preds)\n result = compute_metrics(eval_task, preds, out_label_ids)\n results.update(result)\n\n output_eval_file = os.path.join(eval_output_dir, prefix, \"eval_results.txt\")\n with open(output_eval_file, \"w\") as writer:\n logger.info(\"***** Eval results {} *****\".format(prefix))\n for key in sorted(result.keys()):\n logger.info(\" %s = %s\", key, str(result[key]))\n writer.write(\"%s = %s\\n\" % (key, str(result[key])))\n\n return results\n\n\ndef pred_prob(args, model, tokenizer, prefix=\"\"):\n # Loop to handle MNLI double evaluation (matched, mis-matched)\n eval_task_names = (\"mnli\", \"mnli-mm\") if args.task_name == \"mnli\" else (args.task_name,)\n eval_outputs_dirs = (args.output_dir, args.output_dir + \"-MM\") if args.task_name == \"mnli\" else (args.output_dir,)\n\n for eval_task, eval_output_dir in zip(eval_task_names, eval_outputs_dirs):\n eval_dataset = load_and_cache_examples(args, eval_task, tokenizer, evaluate=True)\n\n if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]:\n os.makedirs(eval_output_dir)\n\n args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)\n # Note that DistributedSampler samples randomly\n eval_sampler = SequentialSampler(eval_dataset)\n eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)\n\n # multi-gpu eval\n if args.n_gpu > 1 and not isinstance(model, torch.nn.DataParallel):\n model = torch.nn.DataParallel(model)\n\n # Eval!\n logger.info(\"***** Running evaluation {} *****\".format(prefix))\n logger.info(\" Num examples = %d\", len(eval_dataset))\n logger.info(\" Batch size = %d\", args.eval_batch_size)\n all_logits = None\n for batch in tqdm(eval_dataloader, desc=\"Evaluating\"):\n model.eval()\n batch = tuple(t.to(args.device) for t in batch)\n\n with torch.no_grad():\n inputs = {\"input_ids\": batch[0], \"attention_mask\": batch[1], \"labels\": batch[3]}\n if args.model_type != \"distilbert\":\n inputs[\"token_type_ids\"] = (\n batch[2] if args.model_type in [\"bert\", \"xlnet\", \"albert\"] else None\n ) # XLM, DistilBERT, RoBERTa, and XLM-RoBERTa don't use segment_ids\n outputs = model(**inputs)\n tmp_eval_loss, logits = outputs[:2]\n logits = logits.detach().cpu().numpy()\n if all_logits is None:\n all_logits = logits\n else:\n all_logits = np.concatenate((all_logits, logits), 0)\n\n all_logits = softmax(all_logits)\n results = all_logits[:, 1].reshape(-1)\n\n return results\n\n\ndef load_and_cache_examples(args, task, tokenizer, evaluate=False):\n if args.local_rank not in [-1, 0] and not evaluate:\n torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache\n\n processor = processors[task]()\n output_mode = output_modes[task]\n # Load data features from cache or dataset file\n cached_features_file = os.path.join(\n args.data_dir,\n \"cached_{}_{}_{}_{}\".format(\n \"dev\" if evaluate else \"train\",\n list(filter(None, args.model_name_or_path.split(\"/\"))).pop(),\n str(args.max_seq_length),\n str(task),\n ),\n )\n if os.path.exists(cached_features_file) and not args.overwrite_cache:\n logger.info(\"Loading features from cached file %s\", cached_features_file)\n features = torch.load(cached_features_file)\n else:\n logger.info(\"Creating features from dataset file at %s\", args.data_dir)\n label_list = processor.get_labels()\n if task in [\"mnli\", \"mnli-mm\"] and args.model_type in [\"roberta\", \"xlmroberta\"]:\n # HACK(label indices are swapped in RoBERTa pretrained model)\n label_list[1], label_list[2] = label_list[2], label_list[1]\n examples = (\n processor.get_dev_examples(args.data_dir) if evaluate else processor.get_train_examples(args.data_dir)\n )\n features = convert_examples_to_features(\n examples,\n tokenizer,\n label_list=label_list,\n max_length=args.max_seq_length,\n output_mode=output_mode,\n pad_on_left=bool(args.model_type in [\"xlnet\"]), # pad on the left for xlnet\n pad_token=tokenizer.convert_tokens_to_ids([tokenizer.pad_token])[0],\n pad_token_segment_id=4 if args.model_type in [\"xlnet\"] else 0,\n )\n if args.local_rank in [-1, 0]:\n logger.info(\"Saving features into cached file %s\", cached_features_file)\n torch.save(features, cached_features_file)\n\n if args.local_rank == 0 and not evaluate:\n torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache\n\n # Convert to Tensors and build dataset\n all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)\n all_attention_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long)\n all_token_type_ids = torch.tensor([f.token_type_ids for f in features], dtype=torch.long)\n if output_mode == \"classification\":\n all_labels = torch.tensor([f.label for f in features], dtype=torch.long)\n elif output_mode == \"regression\":\n all_labels = torch.tensor([f.label for f in features], dtype=torch.float)\n\n dataset = TensorDataset(all_input_ids, all_attention_mask, all_token_type_ids, all_labels)\n return dataset\n\n\ndef main(file_path):\n parser = argparse.ArgumentParser()\n\n # Required parameters\n parser.add_argument('--eval_file_path', help='path of the eval file')\n parser.add_argument(\n \"--data_dir\",\n default=\"tmp\",\n type=str,\n help=\"The input data dir. Should contain the .tsv files (or other data files) for the task.\",\n )\n parser.add_argument(\n \"--model_type\",\n default=\"bert\",\n type=str,\n help=\"Model type selected in the list: \" + \", \".join(MODEL_CLASSES.keys()),\n )\n parser.add_argument(\n \"--model_name_or_path\",\n default=\"bert-base-cased\",\n type=str,\n help=\"Path to pre-trained model or shortcut name selected in the list: \" + \", \".join(ALL_MODELS),\n )\n parser.add_argument(\n \"--task_name\",\n default=\"sst-2\",\n type=str,\n help=\"The name of the task to train selected in the list: \" + \", \".join(processors.keys()),\n )\n parser.add_argument(\n \"--output_dir\",\n default=\"../data/out_cased\",\n type=str,\n help=\"The output directory where the model predictions and checkpoints will be written.\",\n )\n\n # Other parameters\n parser.add_argument(\n \"--config_name\", default=\"\", type=str, help=\"Pretrained config name or path if not the same as model_name\",\n )\n parser.add_argument(\n \"--tokenizer_name\",\n default=\"\",\n type=str,\n help=\"Pretrained tokenizer name or path if not the same as model_name\",\n )\n parser.add_argument(\n \"--cache_dir\",\n default=\"../data/cache\",\n type=str,\n help=\"Where do you want to store the pre-trained models downloaded from s3\",\n )\n parser.add_argument(\n \"--max_seq_length\",\n default=128,\n type=int,\n help=\"The maximum total input sequence length after tokenization. Sequences longer \"\n \"than this will be truncated, sequences shorter will be padded.\",\n )\n parser.add_argument(\n \"--evaluate_during_training\", action=\"store_true\", help=\"Run evaluation during training at each logging step.\",\n )\n parser.add_argument(\n \"--do_lower_case\", action=\"store_true\", help=\"Set this flag if you are using an uncased model.\",\n )\n\n parser.add_argument(\n \"--per_gpu_train_batch_size\", default=8, type=int, help=\"Batch size per GPU/CPU for training.\",\n )\n parser.add_argument(\n \"--per_gpu_eval_batch_size\", default=8, type=int, help=\"Batch size per GPU/CPU for evaluation.\",\n )\n parser.add_argument(\n \"--gradient_accumulation_steps\",\n type=int,\n default=1,\n help=\"Number of updates steps to accumulate before performing a backward/update pass.\",\n )\n parser.add_argument(\"--learning_rate\", default=2e-5, type=float, help=\"The initial learning rate for Adam.\")\n parser.add_argument(\"--weight_decay\", default=0.0, type=float, help=\"Weight decay if we apply some.\")\n parser.add_argument(\"--adam_epsilon\", default=1e-8, type=float, help=\"Epsilon for Adam optimizer.\")\n parser.add_argument(\"--max_grad_norm\", default=1.0, type=float, help=\"Max gradient norm.\")\n parser.add_argument(\n \"--num_train_epochs\", default=3.0, type=float, help=\"Total number of training epochs to perform.\",\n )\n parser.add_argument(\n \"--max_steps\",\n default=-1,\n type=int,\n help=\"If > 0: set total number of training steps to perform. Override num_train_epochs.\",\n )\n parser.add_argument(\"--warmup_steps\", default=0, type=int, help=\"Linear warmup over warmup_steps.\")\n\n parser.add_argument(\"--logging_steps\", type=int, default=500, help=\"Log every X updates steps.\")\n parser.add_argument(\"--save_steps\", type=int, default=500, help=\"Save checkpoint every X updates steps.\")\n parser.add_argument(\n \"--eval_all_checkpoints\",\n action=\"store_true\",\n help=\"Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number\",\n )\n parser.add_argument(\"--no_cuda\", action=\"store_true\", help=\"Avoid using CUDA when available\")\n parser.add_argument(\n \"--overwrite_output_dir\", action=\"store_true\", help=\"Overwrite the content of the output directory\",\n )\n parser.add_argument(\n \"--overwrite_cache\", action=\"store_true\", help=\"Overwrite the cached training and evaluation sets\",\n )\n parser.add_argument(\"--seed\", type=int, default=42, help=\"random seed for initialization\")\n\n parser.add_argument(\n \"--fp16\",\n action=\"store_true\",\n help=\"Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit\",\n )\n parser.add_argument(\n \"--fp16_opt_level\",\n type=str,\n default=\"O1\",\n help=\"For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].\"\n \"See details at https://nvidia.github.io/apex/amp.html\",\n )\n parser.add_argument(\"--local_rank\", type=int, default=-1, help=\"For distributed training: local_rank\")\n parser.add_argument(\"--server_ip\", type=str, default=\"\", help=\"For distant debugging.\")\n parser.add_argument(\"--server_port\", type=str, default=\"\", help=\"For distant debugging.\")\n args = parser.parse_args()\n args.no_cuda = True\n\n # Setup distant debugging if needed\n if args.server_ip and args.server_port:\n # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script\n import ptvsd\n\n print(\"Waiting for debugger attach\")\n ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)\n ptvsd.wait_for_attach()\n\n # Setup CUDA, GPU & distributed training\n if args.local_rank == -1 or args.no_cuda:\n device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\")\n args.n_gpu = 0 if args.no_cuda else torch.cuda.device_count()\n else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs\n torch.cuda.set_device(args.local_rank)\n device = torch.device(\"cuda\", args.local_rank)\n torch.distributed.init_process_group(backend=\"nccl\")\n args.n_gpu = 1\n args.device = device\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.ERROR\n )\n logger.warning(\n \"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s\",\n args.local_rank,\n device,\n args.n_gpu,\n bool(args.local_rank != -1),\n args.fp16,\n )\n\n # Set seed\n set_seed(args)\n\n # Prepare GLUE task\n args.task_name = args.task_name.lower()\n if args.task_name not in processors:\n raise ValueError(\"Task not found: %s\" % (args.task_name))\n processor = processors[args.task_name]()\n args.output_mode = output_modes[args.task_name]\n label_list = processor.get_labels()\n num_labels = len(label_list)\n\n # Load pretrained model and tokenizer\n if args.local_rank not in [-1, 0]:\n torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab\n\n args.model_type = args.model_type.lower()\n config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type]\n config = config_class.from_pretrained(\n args.config_name if args.config_name else args.model_name_or_path,\n num_labels=num_labels,\n finetuning_task=args.task_name,\n cache_dir=args.cache_dir if args.cache_dir else None,\n )\n tokenizer = tokenizer_class.from_pretrained(\n args.tokenizer_name if args.tokenizer_name else args.model_name_or_path,\n do_lower_case=args.do_lower_case,\n cache_dir=args.cache_dir if args.cache_dir else None,\n )\n model = model_class.from_pretrained(\n args.model_name_or_path,\n from_tf=bool(\".ckpt\" in args.model_name_or_path),\n config=config,\n cache_dir=args.cache_dir if args.cache_dir else None,\n )\n\n if args.local_rank == 0:\n torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab\n\n model.to(args.device)\n\n logger.info(\"Evaluation parameters %s\", args)\n\n # Evaluation\n if args.local_rank in [-1, 0]:\n tokenizer = tokenizer_class.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case)\n checkpoints = [args.output_dir]\n if args.eval_all_checkpoints:\n checkpoints = list(\n os.path.dirname(c) for c in sorted(glob.glob(args.output_dir + \"/**/\" + WEIGHTS_NAME, recursive=True))\n )\n logging.getLogger(\"transformers.modeling_utils\").setLevel(logging.WARN) # Reduce logging\n logger.info(\"Evaluate the following checkpoints: %s\", checkpoints)\n for checkpoint in checkpoints:\n global_step = checkpoint.split(\"-\")[-1] if len(checkpoints) > 1 else \"\"\n prefix = checkpoint.split(\"/\")[-1] if checkpoint.find(\"checkpoint\") != -1 else \"\"\n\n model = model_class.from_pretrained(checkpoint)\n model.to(args.device)\n\n data_folder = args.data_dir\n dev_file_path = os.path.join(data_folder, 'dev.tsv')\n\n preds = []\n with open(file_path, encoding='utf8') as f:\n d = f.read().strip().split('\\n')\n for s in d:\n j = json.loads(s)\n preds += j['pred_style0']\n preds = '\\n'.join([s + '\\t0' for s in preds]) + '\\n'\n\n if os.path.exists(data_folder):\n shutil.rmtree(data_folder)\n os.makedirs(data_folder)\n with open(dev_file_path, 'w', encoding='utf8') as f:\n f.write(preds)\n\n result = evaluate(args, model, tokenizer, prefix=prefix)\n acc0 = result['acc']\n\n preds = []\n with open(file_path, encoding='utf8') as f:\n d = f.read().strip().split('\\n')\n for s in d:\n j = json.loads(s)\n preds += j['pred_style1']\n preds = '\\n'.join([s + '\\t1' for s in preds]) + '\\n'\n\n if os.path.exists(data_folder):\n shutil.rmtree(data_folder)\n os.makedirs(data_folder)\n with open(dev_file_path, 'w', encoding='utf8') as f:\n f.write(preds)\n\n result = evaluate(args, model, tokenizer, prefix=prefix)\n acc1 = result['acc']\n\n print('BERT:', 's0', acc0 * 100, 's1', acc1 * 100, 'mean', (acc0 + acc1) / 2 * 100)\n\n" ]
[ [ "torch.load", "numpy.squeeze", "torch.utils.data.DataLoader", "numpy.concatenate", "torch.no_grad", "torch.utils.tensorboard.SummaryWriter", "torch.cuda.manual_seed_all", "torch.cuda.is_available", "torch.device", "numpy.exp", "torch.save", "torch.distributed.init_process_group", "torch.utils.data.distributed.DistributedSampler", "torch.utils.data.TensorDataset", "torch.distributed.barrier", "torch.tensor", "numpy.argmax", "torch.cuda.device_count", "torch.distributed.get_world_size", "torch.nn.parallel.DistributedDataParallel", "numpy.random.seed", "torch.cuda.set_device", "torch.manual_seed", "torch.utils.data.SequentialSampler", "torch.utils.data.RandomSampler", "torch.nn.DataParallel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
earthinversion/Fnet_IRIS_data_automated_download
[ "09a6e0c992662feac95744935e038d1c68539fa1", "09a6e0c992662feac95744935e038d1c68539fa1" ]
[ "IRIS_data_download/IRIS_download_support/obspy/clients/fdsn/mass_downloader/download_helpers.py", "IRIS_data_download/IRIS_download_support/obspy/signal/tests/test_invsim.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nHelpers for the mass downloader.\n\nIntended to simplify and stabilize the logic of the mass downloader and make\nit understandable in the first place.\n\n:copyright:\n Lion Krischer ([email protected]), 2014-2015\n:license:\n GNU Lesser General Public License, Version 3\n (https://www.gnu.org/copyleft/lesser.html)\n\"\"\"\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\nfrom future.builtins import * # NOQA\n\nimport collections\nimport copy\nimport fnmatch\nimport itertools\nimport sys\nfrom multiprocessing.pool import ThreadPool\nimport os\nimport time\nimport timeit\n\nif sys.version_info.major == 2:\n from itertools import ifilterfalse as filterfalse\nelse:\n from itertools import filterfalse\n\nimport numpy as np\n\nfrom lxml.etree import XMLSyntaxError\n\nimport obspy\nfrom obspy.core.util import Enum\n\nfrom . import utils\n\n# The current status of an entity.\nSTATUS = Enum([\"none\", \"needs_downloading\", \"downloaded\", \"ignore\", \"exists\",\n \"download_failed\", \"download_rejected\",\n \"download_partially_failed\"])\n\n\nclass _SlotsEqualityComparisionObject(object):\n \"\"\"\n Helper object with an equality comparision method simply comparing all\n slotted attributes.\n \"\"\"\n __slots__ = []\n\n def __eq__(self, other):\n if type(self) != type(other):\n return False\n return all([getattr(self, _i) == getattr(other, _i)\n for _i in self.__slots__])\n\n\nclass Station(_SlotsEqualityComparisionObject):\n \"\"\"\n Object representing a seismic station within the download helper classes.\n\n It knows the coordinates of the station to perform the filtering,\n its channels and the filename and status of the StationXML files.\n\n :param network: The network code.\n :type network: str\n :param station: The station code.\n :type station: str\n :param latitude: The latitude of the station.\n :type latitude: float\n :param longitude: The longitude of the station.\n :type longitude: float\n :param channels: The channels of the station.\n :type channels: list of :class:`~.Channel` objects\n :param stationxml_filename: The filename of the StationXML file.\n :type stationxml_filename: str\n :param stationxml_status: The current status of the station.\n :type stationxml_filename:\n :class:`~.STATUS`\n \"\"\"\n __slots__ = [\"network\", \"station\", \"latitude\", \"longitude\", \"channels\",\n \"_stationxml_filename\", \"want_station_information\",\n \"miss_station_information\", \"have_station_information\",\n \"stationxml_status\"]\n\n def __init__(self, network, station, latitude, longitude, channels,\n stationxml_filename=None, stationxml_status=None):\n # Station attributes.\n self.network = network\n self.station = station\n self.latitude = latitude\n self.longitude = longitude\n self.channels = channels\n # Station information settings.\n self.stationxml_filename = stationxml_filename\n self.stationxml_status = stationxml_status and STATUS.NONE\n\n # Internally keep track of which channels and time interval want\n # station information, which miss station information and which\n # already have some. want_station_information should always be the\n # union of miss and have.\n self.want_station_information = {}\n self.miss_station_information = {}\n self.have_station_information = {}\n\n @property\n def has_existing_or_downloaded_time_intervals(self):\n \"\"\"\n Returns true if any of the station's time intervals have status\n \"DOWNLOADED\" or \"EXISTS\". Otherwise it returns False meaning it does\n not have to be considered anymore.\n \"\"\"\n status = set()\n for chan in self.channels:\n for ti in chan.intervals:\n status.add(ti.status)\n if STATUS.EXISTS in status or STATUS.DOWNLOADED in status:\n return True\n return False\n\n @property\n def has_existing_time_intervals(self):\n \"\"\"\n Returns True if any of the station's time intervals already exist.\n \"\"\"\n for chan in self.channels:\n for ti in chan.intervals:\n if ti.status == STATUS.EXISTS:\n return True\n return False\n\n def remove_files(self, logger, reason):\n \"\"\"\n Delete all files under it. Only delete stuff that actually has been\n downloaded!\n \"\"\"\n for chan in self.channels:\n for ti in chan.intervals:\n if ti.status != STATUS.DOWNLOADED or not ti.filename:\n continue\n if os.path.exists(ti.filename):\n logger.info(\"Deleting MiniSEED file '%s'. Reason: %s\" % (\n ti.filename, reason))\n utils.safe_delete(ti.filename)\n\n if self.stationxml_status == STATUS.DOWNLOADED and \\\n self.stationxml_filename and \\\n os.path.exists(self.stationxml_filename):\n logger.info(\"Deleting StationXMl file '%s'. Reason: %s\" %\n (self.stationxml_filename, reason))\n utils.safe_delete(self.stationxml_filename)\n\n @property\n def stationxml_filename(self):\n return self._stationxml_filename\n\n @stationxml_filename.setter\n def stationxml_filename(self, value):\n \"\"\"\n Setter creating the directory for the file if it does not already\n exist.\n \"\"\"\n self._stationxml_filename = value\n if not value:\n return\n dirname = os.path.dirname(value)\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n\n @property\n def temporal_bounds(self):\n \"\"\"\n Return the temporal bounds for the station.\n \"\"\"\n starttimes = []\n endtimes = []\n for channel in self.channels:\n s, e = channel.temporal_bounds\n starttimes.append(s)\n endtimes.append(e)\n return min(starttimes), max(endtimes)\n\n def __str__(self):\n channels = \"\\n\".join(str(i) for i in self.channels)\n channels = \"\\n\\t\".join(channels.splitlines())\n return (\n \"Station '{network}.{station}' [Lat: {lat:.2f}, Lng: {lng:.2f}]\\n\"\n \"\\t-> Filename: {filename} ({status})\\n\"\n \"\\t-> Wants station information for channels: {want}\\n\"\n \"\\t-> Has station information for channels: {has}\\n\"\n \"\\t-> Misses station information for channels: {miss}\\n\"\n \"\\t{channels}\"\n ).format(\n network=self.network,\n station=self.station,\n lat=self.latitude,\n lng=self.longitude,\n filename=self.stationxml_filename,\n status=\"exists\" if (self.stationxml_filename and os.path.exists(\n self.stationxml_filename)) else \"does not yet exist\",\n want=\", \".join([\"%s.%s\" % (_i[0], _i[1]) for _i in\n self.want_station_information.keys()]),\n has=\", \".join([\"%s.%s\" % (_i[0], _i[1]) for _i in\n self.have_station_information.keys()]),\n miss=\", \".join([\"%s.%s\" % (_i[0], _i[1]) for _i in\n self.miss_station_information.keys()]),\n channels=channels)\n\n def prepare_stationxml_download(self, stationxml_storage, logger):\n \"\"\"\n Figure out what to download.\n\n :param stationxml_storage:\n \"\"\"\n # Determine what channels actually want to have station information.\n # This will be a tuple of location code, channel code, starttime,\n # and endtime.\n self.want_station_information = {}\n for channel in self.channels:\n if channel.needs_station_file is False:\n continue\n self.want_station_information[\n (channel.location, channel.channel)] = channel.temporal_bounds\n\n # No channel has any data, thus nothing will happen.\n if not self.want_station_information:\n self.stationxml_status = STATUS.NONE\n return\n\n # Only those channels that now actually want station information\n # will be treated in the following.\n s, e = self.temporal_bounds\n storage = utils.get_stationxml_filename(\n stationxml_storage, self.network, self.station,\n list(self.want_station_information.keys()),\n starttime=s, endtime=e)\n\n # The simplest case. The function returns a string. Now two things\n # can happen.\n if isinstance(storage, (str, bytes)):\n filename = storage\n self.stationxml_filename = filename\n # 1. The file does not yet exist. Thus all channels must be\n # downloaded.\n if not os.path.exists(filename):\n self.miss_station_information = \\\n copy.deepcopy(self.want_station_information)\n self.have_station_information = {}\n self.stationxml_status = STATUS.NEEDS_DOWNLOADING\n return\n # 2. The file does exist. It will be parsed. If it contains ALL\n # necessary information, nothing will happen. Otherwise it will\n # be overwritten.\n else:\n info = utils.get_stationxml_contents(filename)\n for c_id, times in self.want_station_information.items():\n # Get the temporal range of information in the file.\n c_info = [_i for _i in info if\n _i.network == self.network and\n _i.station == self.station and\n _i.location == c_id[0] and\n _i.channel == c_id[1]]\n if not c_info:\n break\n starttime = min([_i.starttime for _i in c_info])\n endtime = max([_i.endtime for _i in c_info])\n if starttime > times[0] or endtime < times[1]:\n break\n # All good if no break is called.\n else:\n self.have_station_information = \\\n copy.deepcopy(self.want_station_information)\n self.miss_station_information = {}\n self.stationxml_status = STATUS.EXISTS\n return\n # Otherwise everything will be downloaded.\n self.miss_station_information = \\\n copy.deepcopy(self.want_station_information)\n self.have_station_information = {}\n self.stationxml_status = STATUS.NEEDS_DOWNLOADING\n return\n # The other possibility is that a dictionary is returned.\n else:\n # The types are already checked by the get_stationxml_filename()\n # function.\n missing_channels = storage[\"missing_channels\"]\n available_channels = storage[\"available_channels\"]\n\n # Get the channels wanting station information and filter them.\n channels_wanting_station_information = copy.deepcopy(\n self.want_station_information\n )\n\n # Figure out what channels are missing and will be downloaded.\n self.miss_station_information = {}\n for channel in missing_channels:\n if channel not in channels_wanting_station_information:\n continue\n self.miss_station_information[channel] = \\\n channels_wanting_station_information[channel]\n\n # Same thing but with the already available channels.\n self.have_station_information = {}\n for channel in available_channels:\n if channel not in channels_wanting_station_information:\n continue\n self.have_station_information[channel] = \\\n channels_wanting_station_information[channel]\n\n self.stationxml_filename = storage[\"filename\"]\n\n # Raise a warning if something is missing, but do not raise an\n # exception or halt the program at this point.\n have_channels = set(self.have_station_information.keys())\n miss_channels = set(self.miss_station_information.keys())\n want_channels = set(self.want_station_information.keys())\n if have_channels.union(miss_channels) != want_channels:\n logger.warning(\n \"The custom `stationxml_storage` did not return \"\n \"information about channels %s\" %\n str(want_channels.difference(have_channels.union(\n miss_channels))))\n\n if self.miss_station_information:\n self.stationxml_status = STATUS.NEEDS_DOWNLOADING\n elif not self.miss_station_information and \\\n self.have_station_information:\n self.stationxml_status = STATUS.EXISTS\n else:\n self.stationxml_status = STATUS.IGNORE\n\n def prepare_mseed_download(self, mseed_storage):\n \"\"\"\n Loop through all channels of the station and distribute filenames\n and the current status of the channel.\n\n A MiniSEED interval will be ignored, if the `mseed_storage` function\n returns `True`.\n Possible statuses after method execution are IGNORE, EXISTS, and\n NEEDS_DOWNLOADING.\n\n :param mseed_storage:\n \"\"\"\n for channel in self.channels:\n for interval in channel.intervals:\n interval.filename = utils.get_mseed_filename(\n mseed_storage, self.network, self.station,\n channel.location, channel.channel, interval.start,\n interval.end)\n if interval.filename is True:\n interval.status = STATUS.IGNORE\n elif os.path.exists(interval.filename):\n interval.status = STATUS.EXISTS\n else:\n if not os.path.exists(os.path.dirname(interval.filename)):\n os.makedirs(os.path.dirname(interval.filename))\n interval.status = STATUS.NEEDS_DOWNLOADING\n\n def sanitize_downloads(self, logger):\n \"\"\"\n Should be run after the MiniSEED and StationXML downloads finished.\n It will make sure that every MiniSEED file also has a corresponding\n StationXML file.\n\n It will delete MiniSEED files but never a StationXML file. The logic\n of the download helpers does not allow for a StationXML file with no\n data.\n \"\"\"\n from obspy.io.mseed.util import get_start_and_end_time\n # All or nothing for each channel.\n for id in self.miss_station_information.keys():\n logger.warning(\"Station information could not be downloaded for \"\n \"%s.%s.%s.%s. MiniSEED files outside of the \"\n \"station information period \"\n \"will be deleted!\" % (\n self.network, self.station, id[0], id[1]))\n channel = [_i for _i in self.channels if\n (_i.location, _i.channel) == id][0]\n for time_interval in channel.intervals:\n # Check that file exists before proceeding\n if not time_interval.filename or \\\n not os.path.isfile(time_interval.filename):\n continue\n # Check that the time_interval.start and end are correct!\n time_interval.start, time_interval.end = \\\n get_start_and_end_time(time_interval.filename)\n # Only delete downloaded things!\n if time_interval.status == STATUS.DOWNLOADED:\n # Only delete if the station data are actually missing\n # for this time\n miss_start, miss_end = self.miss_station_information[id]\n if miss_start <= time_interval.start <= miss_end and \\\n miss_start <= time_interval.end <= miss_end:\n utils.safe_delete(time_interval.filename)\n time_interval.status = STATUS.DOWNLOAD_REJECTED\n\n\nclass Channel(_SlotsEqualityComparisionObject):\n \"\"\"\n Object representing a Channel. Each time interval should end up in one\n MiniSEED file.\n \"\"\"\n __slots__ = [\"location\", \"channel\", \"intervals\"]\n\n def __init__(self, location, channel, intervals):\n self.location = location\n self.channel = channel\n self.intervals = intervals\n\n @property\n def needs_station_file(self):\n \"\"\"\n Determine if the channel requires any station information.\n\n As soon as the status of at least one interval is either\n ``DOWNLOADED`` or ``EXISTS`` the whole channel will be thought of as\n requiring station information. This does not yet mean that station\n information will be downloaded. That is decided at a later stage.\n \"\"\"\n status = set([_i.status for _i in self.intervals])\n if STATUS.DOWNLOADED in status or STATUS.EXISTS in status:\n return True\n return False\n\n @property\n def temporal_bounds(self):\n \"\"\"\n Returns a tuple of the minimum start time and the maximum end time.\n \"\"\"\n return (min([_i.start for _i in self.intervals]),\n max([_i.end for _i in self.intervals]))\n\n def __str__(self):\n return \"Channel '{location}.{channel}':\\n\\t{intervals}\".format(\n location=self.location, channel=self.channel,\n intervals=\"\\n\\t\".join([str(i) for i in self.intervals]))\n\n\nclass TimeInterval(_SlotsEqualityComparisionObject):\n \"\"\"\n Simple object representing a time interval of a channel.\n\n It knows the temporal bounds of the interval, the (desired) filename,\n and the current status of the interval.\n\n :param start: The start of the interval.\n :type start: :class:`~obspy.core.utcdatetime.UTCDateTime`\n :param end: The end of the interval.\n :type end: :class:`~obspy.core.utcdatetime.UTCDateTime`\n :param filename: The filename of the interval.\n :type filename: str\n :param status: The status of the time interval.\n :param status: :class:`~.STATUS`\n \"\"\"\n __slots__ = [\"start\", \"end\", \"filename\", \"status\"]\n\n def __init__(self, start, end, filename=None, status=None):\n self.start = start\n self.end = end\n self.filename = filename\n self.status = status if status is not None else STATUS.NONE\n\n def __repr__(self):\n return \"TimeInterval(start={start}, end={end}, filename={filename}, \" \\\n \"status='{status}')\".format(\n start=repr(self.start),\n end=repr(self.end),\n filename=\"'%s'\" % self.filename\n if self.filename is not None else \"None\",\n status=str(self.status))\n\n\nclass ClientDownloadHelper(object):\n \"\"\"\n :type client: :class:`obspy.fdsn.client.Client`\n :param client: An initialized FDSN client.\n :type client_name: str\n :param client_name: The name of the client. Only used for logging.\n :type restrictions: :class:`~.restrictions.Restrictions`\n :param restrictions: The non-domain related restrictions for the query.\n :type domain: :class:`~.domain.Domain` subclass\n :param domain: The domain definition.\n :param mseed_storage: The MiniSEED storage settings.\n :param stationxml_storage: The StationXML storage settings.\n :param logger: An active logger instance.\n \"\"\"\n def __init__(self, client, client_name, restrictions, domain,\n mseed_storage, stationxml_storage, logger):\n self.client = client\n self.client_name = client_name\n self.restrictions = restrictions\n self.domain = domain\n self.mseed_storage = mseed_storage\n self.stationxml_storage = stationxml_storage\n self.logger = logger\n self.stations = {}\n self.is_availability_reliable = None\n\n def __bool__(self):\n return bool(len(self))\n\n def __str__(self):\n avail_map = {\n None: \"Unknown reliability of availability information\",\n True: \"Reliable availability information\",\n False: \"Non-reliable availability information\"\n }\n reliability = avail_map[self.is_availability_reliable]\n return (\n \"ClientDownloadHelper object for client '{client}' ({url})\\n\"\n \"-> {reliability}\\n\"\n \"-> Manages {station_count} stations.\\n{stations}\").format(\n client=self.client_name,\n url=self.client.base_url,\n reliability=reliability,\n station_count=len(self),\n stations=\"\\n\".join([str(_i) for _i in self.stations.values()]))\n\n def __len__(self):\n return len(self.stations)\n\n def prepare_mseed_download(self):\n \"\"\"\n Prepare each Station for the MiniSEED downloading stage.\n\n This will distribute filenames and identify files that require\n downloading.\n \"\"\"\n for station in self.stations.values():\n station.prepare_mseed_download(mseed_storage=self.mseed_storage)\n\n def filter_stations_based_on_minimum_distance(\n self, existing_client_dl_helpers):\n \"\"\"\n Removes stations until all stations have a certain minimum distance to\n each other.\n\n Returns the rejected stations which is mainly useful for testing.\n\n :param existing_client_dl_helpers: Instances of already existing\n client download helpers.\n :type existing_client_dl_helpers: list of\n :class:`~.ClientDownloadHelper`\n \"\"\"\n if not self.restrictions.minimum_interstation_distance_in_m:\n # No rejected stations.\n return []\n\n # Create a sorted copy that will be used in the following. Make it\n # more deterministic by sorting the stations based on the id.\n stations = copy.copy(list(self.stations.values()))\n stations = sorted(stations, key=lambda x: (x.network, x.station))\n\n existing_stations = []\n for dlh in existing_client_dl_helpers:\n existing_stations.extend(list(dlh.stations.values()))\n\n remaining_stations = []\n rejected_stations = []\n\n # There are essentially two possibilities. If no station exists yet,\n # it will choose the largest subset of stations satisfying the\n # minimum inter-station distance constraint.\n if not existing_stations:\n # Build k-d-tree and query for the neighbours of each point within\n # the minimum distance.\n kd_tree = utils.SphericalNearestNeighbour(stations)\n nns = kd_tree.query_pairs(\n self.restrictions.minimum_interstation_distance_in_m)\n\n indexes_to_remove = []\n # Keep removing the station with the most pairs until no pairs are\n # left.\n while nns:\n most_common = collections.Counter(\n itertools.chain.from_iterable(nns)).most_common()[0][0]\n indexes_to_remove.append(most_common)\n nns = list(filterfalse(lambda x: most_common in x, nns))\n\n # Remove these indices this results in a set of stations we wish to\n # keep.\n new_remaining_stations = [_i[1] for _i in enumerate(stations)\n if _i[0] not in indexes_to_remove]\n new_rejected_stations = [_i[1] for _i in enumerate(stations)\n if _i[0] in indexes_to_remove]\n\n # Station objects are not hashable thus we have to go the long\n # route.\n for st in new_remaining_stations:\n if st not in remaining_stations:\n remaining_stations.append(st)\n\n for st in new_rejected_stations:\n if st not in rejected_stations:\n rejected_stations.append(st)\n\n # Otherwise it will add new stations approximating a Poisson disk\n # distribution.\n else:\n while stations:\n # kd-tree with all existing_stations\n existing_kd_tree = utils.SphericalNearestNeighbour(\n existing_stations)\n # Now we have to get the distance to the closest existing\n # station for all new stations.\n distances = np.ma.array(existing_kd_tree.query(stations)[0])\n if np.isinf(distances[0]):\n break\n distances.mask = False\n\n # Step one is to get rid of all stations that are closer\n # than the minimum distance to any existing station.\n remove = np.where(\n distances <\n self.restrictions.minimum_interstation_distance_in_m)[0]\n rejected_stations.extend([stations[_i] for _i in remove])\n\n keep = np.where(\n distances >=\n self.restrictions.minimum_interstation_distance_in_m)[0]\n distances.mask[remove] = True\n\n if len(keep):\n # Station with the largest distance to next closer station.\n largest = np.argmax(distances)\n remaining_stations.append(stations[largest])\n existing_stations.append(stations[largest])\n\n # Add all rejected stations here.\n stations = [stations[_i] for _i in keep if _i != largest]\n else:\n stations = []\n\n # Now actually delete the files and everything of the rejected\n # stations.\n for station in rejected_stations:\n station.remove_files(logger=self.logger,\n reason=\"Minimum distance filtering.\")\n self.stations = {}\n for station in remaining_stations:\n self.stations[(station.network, station.station)] = station\n\n # Return the rejected stations.\n return {(_i.network, _i.station): _i for _i in rejected_stations}\n\n def prepare_stationxml_download(self):\n \"\"\"\n Prepare each Station for the StationXML downloading stage.\n\n This will distribute filenames and identify files that require\n downloading.\n \"\"\"\n for station in self.stations.values():\n station.prepare_stationxml_download(\n stationxml_storage=self.stationxml_storage,\n logger=self.logger)\n\n def download_stationxml(self, threads=3):\n \"\"\"\n Actually download the StationXML files.\n\n :param threads: Limits the maximum number of threads for the client.\n \"\"\"\n\n def star_download_station(args):\n \"\"\"\n Maps arguments to the utils.download_stationxml() function.\n\n :param args: The to-be mapped arguments.\n \"\"\"\n try:\n ret_val = utils.download_stationxml(*args, logger=self.logger)\n except utils.ERRORS as e:\n self.logger.error(str(e))\n return None\n return ret_val\n\n # Build up everything we want to download.\n arguments = []\n for station in self.stations.values():\n if not station.miss_station_information:\n continue\n s, e = station.temporal_bounds\n if self.restrictions.station_starttime:\n s = self.restrictions.station_starttime\n if self.restrictions.station_endtime:\n e = self.restrictions.station_endtime\n bulk = [(station.network, station.station, channel.location,\n channel.channel, s, e) for channel in station.channels]\n arguments.append((self.client, self.client_name, bulk,\n station.stationxml_filename))\n\n if not arguments:\n self.logger.info(\"Client '%s' - No station information to \"\n \"download.\" % self.client_name)\n return\n\n # Download it.\n s_time = timeit.default_timer()\n pool = ThreadPool(min(threads, len(arguments)))\n results = pool.map(star_download_station, arguments)\n pool.close()\n e_time = timeit.default_timer()\n\n results = [_i for _i in results if _i is not None]\n\n # Check it.\n filecount = 0\n download_size = 0\n\n # Update the station structures. Loop over each returned file.\n for s_id, filename in results:\n filecount += 1\n station = self.stations[s_id]\n size = os.path.getsize(filename)\n download_size += size\n\n # Extract information about that file.\n try:\n info = utils.get_stationxml_contents(filename)\n # Sometimes some services choose to not return XML files - guard\n # against it and just delete the file. At subsequent runs the\n # mass downloader will attempt to download it again.\n except XMLSyntaxError:\n self.logger.info(\n \"Client '%s' - File %s is not an XML file - it will be \"\n \"deleted.\" % (self.client_name, filename))\n utils.safe_delete(filename)\n continue\n\n still_missing = {}\n # Make sure all missing information has been downloaded by\n # looping over each channel of the station that originally\n # requested to be downloaded.\n for c_id, times in station.miss_station_information.items():\n # Get the temporal range of information in the file.\n c_info = [_i for _i in info if\n _i.network == station.network and\n _i.station == station.station and\n _i.location == c_id[0] and\n _i.channel == c_id[1]]\n if not c_info:\n continue\n starttime = min([_i.starttime for _i in c_info])\n endtime = max([_i.endtime for _i in c_info])\n if starttime > times[0] or endtime < times[1]:\n # Cope with case that not full day of station info missing\n if starttime < times[1]:\n still_missing[c_id] = (times[0], starttime)\n station.have_station_information[c_id] = (starttime,\n times[1])\n elif endtime > times[0]:\n still_missing[c_id] = (endtime, times[1])\n station.have_station_information[c_id] = (times[0],\n endtime)\n else:\n still_missing[c_id] = times\n continue\n station.have_station_information[c_id] = times\n\n station.miss_station_information = still_missing\n if still_missing:\n station.stationxml_status = STATUS.DOWNLOAD_PARTIALLY_FAILED\n else:\n station.stationxml_status = STATUS.DOWNLOADED\n\n # Now loop over all stations and set the status of the ones that\n # still need downloading to download failed.\n for station in self.stations.values():\n if station.stationxml_status == STATUS.NEEDS_DOWNLOADING:\n station.stationxml_status = STATUS.DOWNLOAD_FAILED\n\n self.logger.info(\"Client '%s' - Downloaded %i station files [%.1f MB] \"\n \"in %.1f seconds [%.2f KB/sec].\" % (\n self.client_name, filecount,\n download_size / 1024.0 ** 2,\n e_time - s_time,\n (download_size / 1024.0) / (e_time - s_time)))\n\n def download_mseed(self, chunk_size_in_mb=25, threads_per_client=3):\n \"\"\"\n Actually download MiniSEED data.\n\n :param chunk_size_in_mb: Attempt to download data in chunks of this\n size.\n :param threads_per_client: Threads to launch per client. 3 seems to\n be a value in agreement with some data centers.\n \"\"\"\n # Estimate the download size to have equally sized chunks.\n channel_sampling_rate = {\n \"F\": 5000, \"G\": 5000, \"D\": 1000, \"C\": 1000, \"E\": 250, \"S\": 80,\n \"H\": 250, \"B\": 80, \"M\": 10, \"L\": 1, \"V\": 0.1, \"U\": 0.01,\n \"R\": 0.001, \"P\": 0.0001, \"T\": 0.00001, \"Q\": 0.000001, \"A\": 5000,\n \"O\": 5000}\n\n # Split into chunks of about equal size in terms of filesize.\n chunks = []\n chunks_curr = []\n curr_chunks_mb = 0\n\n # Don't request more than 50 chunks at once to not choke the servers.\n max_chunk_length = 50\n\n counter = collections.Counter()\n\n # Keep track of attempted downloads.\n for sta in self.stations.values():\n for cha in sta.channels:\n # The band code is used to estimate the sampling rate of the\n # data to be downloaded.\n band_code = cha.channel[0].upper()\n try:\n sr = channel_sampling_rate[band_code]\n except KeyError:\n # Generic sampling rate for exotic band codes.\n sr = 1.0\n\n for interval in cha.intervals:\n counter[interval.status] += 1\n # Only take those time intervals that actually require\n # some downloading.\n if interval.status != STATUS.NEEDS_DOWNLOADING:\n continue\n chunks_curr.append((\n sta.network, sta.station, cha.location, cha.channel,\n interval.start, interval.end, interval.filename))\n # Assume that each sample needs 4 byte, STEIM\n # compression reduces size to about a third.\n # chunk size is in MB\n duration = interval.end - interval.start\n curr_chunks_mb += \\\n sr * duration * 4.0 / 3.0 / 1024.0 / 1024.0\n if curr_chunks_mb >= chunk_size_in_mb or \\\n len(chunks_curr) >= max_chunk_length:\n chunks.append(chunks_curr)\n chunks_curr = []\n curr_chunks_mb = 0\n if chunks_curr:\n chunks.append(chunks_curr)\n\n keys = sorted(counter.keys())\n for key in keys:\n self.logger.info(\n \"Client '%s' - Status for %i time intervals/channels before \"\n \"downloading: %s\" % (self.client_name, counter[key],\n key.upper()))\n\n if not chunks:\n return\n\n def star_download_mseed(args):\n \"\"\"\n Star maps the arguments to the\n utils.download_and_split_mseed_bulk() function.\n\n :param args: The arguments to be passed.\n \"\"\"\n try:\n ret_val = utils.download_and_split_mseed_bulk(\n *args, logger=self.logger)\n except utils.ERRORS as e:\n msg = (\"Client '%s' - \" % args[1]) + str(e)\n if \"no data available\" in msg.lower():\n self.logger.info(msg.split(\"Detailed response\")[0].strip())\n else:\n self.logger.error(msg)\n return []\n return ret_val\n\n pool = ThreadPool(min(threads_per_client, len(chunks)))\n\n d_start = timeit.default_timer()\n pool.map(\n star_download_mseed,\n [(self.client, self.client_name, chunk) for chunk in chunks])\n pool.close()\n d_end = timeit.default_timer()\n\n self.logger.info(\"Client '%s' - Launching basic QC checks...\" %\n self.client_name)\n downloaded_bytes, discarded_bytes = self._check_downloaded_data()\n total_bytes = downloaded_bytes + discarded_bytes\n\n self.logger.info(\"Client '%s' - Downloaded %.1f MB [%.2f KB/sec] of \"\n \"data, %.1f MB of which were discarded afterwards.\" %\n (self.client_name, total_bytes / 1024.0 ** 2,\n total_bytes / 1024.0 / (d_end - d_start),\n discarded_bytes / 1024.0 ** 2))\n\n # Recount everything to be able to emit some nice statistics.\n counter = collections.Counter()\n for sta in self.stations.values():\n for chan in sta.channels:\n for interval in chan.intervals:\n counter[interval.status] += 1\n keys = sorted(counter.keys())\n for key in keys:\n self.logger.info(\n \"Client '%s' - Status for %i time intervals/channels after \"\n \"downloading: %s\" % (\n self.client_name, counter[key], key.upper()))\n\n self._remove_failed_and_ignored_stations()\n\n def _remove_failed_and_ignored_stations(self):\n \"\"\"\n Removes all stations that have no time interval with either exists\n or downloaded status.\n \"\"\"\n to_be_removed_keys = []\n for key, station in self.stations.items():\n if station.has_existing_or_downloaded_time_intervals is True:\n continue\n to_be_removed_keys.append(key)\n for key in to_be_removed_keys:\n del self.stations[key]\n\n def sanitize_downloads(self):\n \"\"\"\n Should be run after the MiniSEED and StationXML downloads finished.\n It will make sure that every MiniSEED file also has a corresponding\n StationXML file.\n \"\"\"\n for station in self.stations.values():\n station.sanitize_downloads(logger=self.logger)\n\n def _check_downloaded_data(self):\n \"\"\"\n Read the downloaded data, set the proper status flags and remove\n data that does not meet the QC criteria. It just checks the\n downloaded data for minimum length and gaps/overlaps.\n\n Returns the downloaded_bytes and the discarded_bytes.\n \"\"\"\n downloaded_bytes = 0\n discarded_bytes = 0\n for sta in self.stations.values():\n for cha in sta.channels:\n for interval in cha.intervals:\n # The status of the interval should not have changed if\n # it did not require downloading in the first place.\n if interval.status != STATUS.NEEDS_DOWNLOADING:\n continue\n\n # If the file does not exist, mark the time interval as\n # download failed.\n if not os.path.exists(interval.filename):\n interval.status = STATUS.DOWNLOAD_FAILED\n continue\n\n size = os.path.getsize(interval.filename)\n if size == 0:\n self.logger.warning(\"Zero byte file '%s'. Will be \"\n \"deleted.\" % interval.filename)\n utils.safe_delete(interval.filename)\n interval.status = STATUS.DOWNLOAD_FAILED\n continue\n\n # Guard against faulty files.\n try:\n st = obspy.read(interval.filename, headonly=True)\n except Exception as e:\n self.logger.warning(\n \"Could not read file '%s' due to: %s\\n\"\n \"Will be discarded.\" % (interval.filename, str(e)))\n utils.safe_delete(interval.filename)\n discarded_bytes += size\n interval.status = STATUS.DOWNLOAD_FAILED\n continue\n\n # Valid files with no data.\n if len(st) == 0:\n self.logger.warning(\n \"Empty file '%s'. Will be deleted.\" %\n interval.filename)\n utils.safe_delete(interval.filename)\n discarded_bytes += size\n interval.status = STATUS.DOWNLOAD_FAILED\n continue\n\n # If user did not want gappy files, remove them.\n if self.restrictions.reject_channels_with_gaps is True and\\\n len(st) > 1:\n self.logger.info(\n \"File '%s' has %i traces and thus contains \"\n \"gaps or overlaps. Will be deleted.\" % (\n interval.filename, len(st)))\n utils.safe_delete(interval.filename)\n discarded_bytes += size\n interval.status = STATUS.DOWNLOAD_REJECTED\n continue\n\n if self.restrictions.minimum_length:\n duration = sum([tr.stats.endtime - tr.stats.starttime\n for tr in st])\n expected_min_duration = \\\n self.restrictions.minimum_length * \\\n (interval.end - interval.start)\n if duration < expected_min_duration:\n self.logger.info(\n \"File '%s' has only %.2f seconds of data. \"\n \"%.2f are required. File will be deleted.\" %\n (interval.filename, duration,\n expected_min_duration))\n utils.safe_delete(interval.filename)\n discarded_bytes += size\n interval.status = STATUS.DOWNLOAD_REJECTED\n continue\n\n downloaded_bytes += size\n interval.status = STATUS.DOWNLOADED\n return downloaded_bytes, discarded_bytes\n\n def _parse_miniseed_filenames(self, filenames, restrictions):\n time_range = restrictions.minimum_length * (restrictions.endtime -\n restrictions.starttime)\n channel_availability = []\n for filename in filenames:\n st = obspy.read(filename, format=\"MSEED\", headonly=True)\n if restrictions.reject_channels_with_gaps and len(st) > 1:\n self.logger.warning(\"Channel %s has gap or overlap. Will be \"\n \"removed.\" % st[0].id)\n try:\n os.remove(filename)\n except OSError:\n pass\n continue\n elif len(st) == 0:\n self.logger.error(\"MiniSEED file with no data detected. \"\n \"Should not happen!\")\n continue\n tr = st[0]\n duration = tr.stats.endtime - tr.stats.starttime\n if restrictions.minimum_length and duration < time_range:\n self.logger.warning(\"Channel %s does not satisfy the minimum \"\n \"length requirement. %.2f seconds instead \"\n \"of the required %.2f seconds.\" % (\n tr.id, duration, time_range))\n try:\n os.remove(filename)\n except OSError:\n pass\n continue\n channel_availability.append(utils.ChannelAvailability(\n tr.stats.network, tr.stats.station, tr.stats.location,\n tr.stats.channel, tr.stats.starttime, tr.stats.endtime,\n filename))\n return channel_availability\n\n def discard_stations(self, existing_client_dl_helpers):\n \"\"\"\n Discard all stations part of any of the already existing client\n download helper instances. The station discarding happens purely\n based on station ids.\n\n :param existing_client_dl_helpers: Instances of already existing\n client download helpers. All stations part of this will not be\n downloaded anymore.\n :type existing_client_dl_helpers: list of\n :class:`~.ClientDownloadHelper`\n \"\"\"\n station_ids = []\n for helper in existing_client_dl_helpers:\n station_ids.extend(helper.stations.keys())\n\n for station_id in station_ids:\n try:\n del self.stations[station_id]\n except KeyError:\n pass\n\n def get_availability(self):\n \"\"\"\n Queries the current client for information on what stations are\n available given the spatial and temporal restrictions.\n \"\"\"\n # Check if stations needs to be filtered after downloading or if the\n # restrictions one can impose with the FDSN webservices queries are\n # enough. This depends on the domain definition.\n try:\n self.domain.is_in_domain(0, 0)\n needs_filtering = True\n except NotImplementedError:\n needs_filtering = False\n\n arguments = {\n \"network\": self.restrictions.network,\n \"station\": self.restrictions.station,\n \"location\": self.restrictions.location,\n \"channel\": self.restrictions.channel,\n \"starttime\": self.restrictions.starttime,\n \"endtime\": self.restrictions.endtime,\n # Request at the channel level.\n \"level\": \"channel\"\n }\n # Add the domain specific query parameters.\n arguments.update(self.domain.get_query_parameters())\n\n # Check the capabilities of the service and see what is the most\n # appropriate way of acquiring availability information. Some services\n # right now require manual overriding of what they claim to be\n # capable of.\n if \"matchtimeseries\" in self.client.services[\"station\"]:\n arguments[\"matchtimeseries\"] = True\n if \"format\" in self.client.services[\"station\"]:\n arguments[\"format\"] = \"text\"\n self.is_availability_reliable = True\n else:\n if \"format\" in self.client.services[\"station\"]:\n arguments[\"format\"] = \"text\"\n self.is_availability_reliable = False\n\n if self.is_availability_reliable:\n self.logger.info(\"Client '%s' - Requesting reliable \"\n \"availability.\" % self.client_name)\n else:\n self.logger.info(\n \"Client '%s' - Requesting unreliable availability.\" %\n self.client_name)\n\n try:\n start = time.time()\n inv = self.client.get_stations(**arguments)\n end = time.time()\n except utils.ERRORS as e:\n if \"no data available\" in str(e).lower():\n self.logger.info(\n \"Client '%s' - No data available for request.\" %\n self.client_name)\n return\n self.logger.error(\n \"Client '{0}' - Failed getting availability: %s\".format(\n self.client_name), str(e))\n return\n # This sometimes fires if a service returns some random stuff which\n # is not a valid station file.\n except Exception as e:\n self.logger.error(\n \"Client '{0}' - Failed getting availability due to \"\n \"unexpected exception: %s\".format(self.client_name), str(e))\n return\n\n self.logger.info(\"Client '%s' - Successfully requested availability \"\n \"(%.2f seconds)\" % (self.client_name, end - start))\n\n # Get the time intervals from the restrictions.\n intervals = [TimeInterval(start=_i[0], end=_i[1])\n for _i in self.restrictions]\n\n for network in inv:\n # Skip network if so desired.\n skip_network = False\n for pattern in self.restrictions.exclude_networks:\n if fnmatch.fnmatch(network.code, pattern):\n skip_network = True\n break\n if skip_network:\n continue\n\n for station in network:\n # Skip station if so desired.\n skip_station = False\n for pattern in self.restrictions.exclude_stations:\n if fnmatch.fnmatch(station.code, pattern):\n skip_station = True\n break\n if skip_station:\n continue\n\n # If an inventory is given, only keep stations part of the\n # inventory.\n if self.restrictions.limit_stations_to_inventory is not None \\\n and (network.code, station.code) not in \\\n self.restrictions.limit_stations_to_inventory:\n continue\n\n # Skip the station if it is not in the desired domain.\n if needs_filtering is True and \\\n not self.domain.is_in_domain(station.latitude,\n station.longitude):\n continue\n\n channels = []\n for channel in station.channels:\n # Remove channels that somehow slipped past the temporal\n # constraints due to weird behaviour from the data center.\n if (channel.start_date > self.restrictions.endtime) or \\\n (channel.end_date < self.restrictions.starttime):\n continue\n new_channel = Channel(\n location=channel.location_code, channel=channel.code,\n intervals=copy.deepcopy(intervals))\n # Multiple channel epochs would result in duplicate\n # channels which we don't want. Bit of a silly logic here\n # to get rid of them.\n if new_channel not in channels:\n channels.append(new_channel)\n\n if self.restrictions.channel is None:\n # Group by locations and apply the channel priority filter\n # to each.\n filtered_channels = []\n\n def get_loc(x):\n return x.location\n\n for location, _channels in itertools.groupby(\n sorted(channels, key=get_loc), get_loc):\n filtered_channels.extend(utils.filter_channel_priority(\n list(_channels), key=\"channel\",\n priorities=self.restrictions.channel_priorities))\n channels = filtered_channels\n\n if self.restrictions.location is None:\n # Filter to remove unwanted locations according to the\n # priority list.\n channels = utils.filter_channel_priority(\n channels, key=\"location\",\n priorities=self.restrictions.location_priorities)\n\n if not channels:\n continue\n\n self.stations[(network.code, station.code)] = Station(\n network=network.code,\n station=station.code,\n latitude=station.latitude,\n longitude=station.longitude,\n channels=channels)\n self.logger.info(\"Client '%s' - Found %i stations (%i channels).\" % (\n self.client_name, len(self.stations),\n sum([len(_i.channels) for _i in self.stations.values()])))\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod(exclude_empty=True)\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nThe InvSim test suite.\n\"\"\"\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\nfrom future.builtins import * # NOQA\nfrom future.utils import native_str\n\nimport ctypes as C\nimport gzip\nimport io\nimport os\nimport unittest\nimport platform\n\nimport numpy as np\n\nfrom obspy import Trace, UTCDateTime, read, read_inventory\nfrom obspy.core.util.base import NamedTemporaryFile\nfrom obspy.core.util.misc import SuppressOutput\nfrom obspy.io.sac import attach_paz\nfrom obspy.signal.headers import clibevresp\nfrom obspy.signal.invsim import (\n cosine_taper, estimate_magnitude, evalresp, simulate_seismometer,\n evalresp_for_frequencies)\n\n\n# Seismometers defined as in Pitsa with one zero less. The corrected\n# signals are in velocity, thus must be integrated to offset and take one\n# zero less than pitsa (remove 1/w in frequency domain)\nPAZ_WOOD_ANDERSON = {'poles': [-6.2832 - 4.7124j,\n -6.2832 + 4.7124j],\n 'zeros': [0.0 + 0.0j] * 1,\n 'sensitivity': 1.0,\n 'gain': 1. / 2.25}\n\nPAZ_WWSSN_SP = {'poles': [-4.0093 - 4.0093j,\n -4.0093 + 4.0093j,\n -4.6077 - 6.9967j,\n -4.6077 + 6.9967j],\n 'zeros': [0.0 + 0.0j] * 2,\n 'sensitivity': 1.0,\n 'gain': 1. / 1.0413}\n\nPAZ_WWSSN_LP = {'poles': [-0.4189 + 0.0j,\n -0.4189 + 0.0j,\n -0.0628 + 0.0j,\n -0.0628 + 0.0j],\n 'zeros': [0.0 + 0.0j] * 2,\n 'sensitivity': 1.0,\n 'gain': 1. / 0.0271}\n\nPAZ_KIRNOS = {'poles': [-0.1257 - 0.2177j,\n -0.1257 + 0.2177j,\n -83.4473 + 0.0j,\n -0.3285 + 0.0j],\n 'zeros': [0.0 + 0.0j] * 2,\n 'sensitivity': 1.0,\n 'gain': 1. / 1.61}\n\nINSTRUMENTS = {'None': None,\n 'kirnos': PAZ_KIRNOS,\n 'wood_anderson': PAZ_WOOD_ANDERSON,\n 'wwssn_lp': PAZ_WWSSN_LP,\n 'wwssn_sp': PAZ_WWSSN_SP}\n\n\nclass InvSimTestCase(unittest.TestCase):\n \"\"\"\n Test cases for InvSim.\n \"\"\"\n def setUp(self):\n # directory where the test files are located\n self.path = os.path.join(os.path.dirname(__file__), 'data')\n\n def test_seis_sim_vs_pitsa1(self):\n \"\"\"\n Test simulate_seismometer seismometer simulation against seismometer\n simulation of Pitsa - LE3D seismometer.\n \"\"\"\n # load test file\n filename = os.path.join(self.path, 'rjob_20051006.gz')\n with gzip.open(filename) as f:\n data = np.loadtxt(f)\n\n # paz of test file\n samp_rate = 200.0\n paz_le3d = {'poles': [-4.21 + 4.66j,\n -4.21 - 4.66j,\n -2.105 + 0.0j],\n 'zeros': [0.0 + 0.0j] * 3,\n 'sensitivity': 1.0,\n 'gain': 0.4}\n\n for id, paz in INSTRUMENTS.items():\n # simulate instrument\n datcorr = simulate_seismometer(\n data, samp_rate, paz_remove=paz_le3d, paz_simulate=paz,\n water_level=600.0, zero_mean=False, nfft_pow2=True)\n # load pitsa file\n filename = os.path.join(self.path, 'rjob_20051006_%s.gz' % id)\n with gzip.open(filename) as f:\n data_pitsa = np.loadtxt(f)\n # calculate normalized rms\n rms = np.sqrt(np.sum((datcorr - data_pitsa) ** 2) /\n np.sum(data_pitsa ** 2))\n self.assertTrue(rms < 1.1e-05)\n\n def test_seis_sim_vs_pitsa_2(self):\n \"\"\"\n Test simulate_seismometer seismometer simulation against seismometer\n simulation of Pitsa - STS-2 seismometer.\n \"\"\"\n # load test file\n file = os.path.join(self.path, 'rotz_20081028.gz')\n with gzip.open(file) as f:\n data = np.loadtxt(f)\n\n # paz of test file\n samp_rate = 200.0\n paz_sts2 = {'poles': [-0.03736 - 0.03617j,\n -0.03736 + 0.03617j],\n 'zeros': [0.0 + 0.0j] * 2,\n 'sensitivity': 1.0,\n 'gain': 1.5}\n\n for id, paz in INSTRUMENTS.items():\n # simulate instrument\n datcorr = simulate_seismometer(\n data, samp_rate, paz_remove=paz_sts2, paz_simulate=paz,\n water_level=600.0, zero_mean=False, nfft_pow2=True)\n # load pitsa file\n filename = os.path.join(self.path, 'rotz_20081028_%s.gz' % id)\n with gzip.open(filename) as f:\n data_pitsa = np.loadtxt(f)\n # calculate normalized rms\n rms = np.sqrt(np.sum((datcorr - data_pitsa) ** 2) /\n np.sum(data_pitsa ** 2))\n self.assertTrue(rms < 1e-04)\n\n def test_estimate_magnitude(self):\n \"\"\"\n Tests against PITSA. Note that PITSA displays microvolt, that is\n the amplitude values must be computed back into counts (for this\n stations .596microvolt/count was used). Pitsa internally calculates\n with the sensitivity 2800 of the WA. Using this we get for the\n following for event 2009-07-19 23:03::\n\n RTSH PITSA 2.263 ObsPy 2.294\n RTBE PITSA 1.325 ObsPy 1.363\n RMOA PITSA 1.629 ObsPy 1.675\n \"\"\"\n # the poles/zeros are the same for all three stations but the overall\n # sensitivity differs, this was probably not taken into account when\n # implementing this test (the specified 'sensitivity' is for RTSH), so\n # below we use the response for station RTSH for the test\n paz = {'poles': [-4.444 + 4.444j, -4.444 - 4.444j, -1.083 + 0j],\n 'zeros': [0 + 0j, 0 + 0j, 0 + 0j],\n 'gain': 1.0,\n 'sensitivity': 671140000.0}\n mag_rtsh = estimate_magnitude(paz, 3.34e6, 0.065, 0.255)\n self.assertAlmostEqual(mag_rtsh, 2.1328727151723488)\n mag_rtbe = estimate_magnitude(paz, 3.61e4, 0.08, 2.197)\n self.assertAlmostEqual(mag_rtbe, 1.1962687721890191)\n mag_rnon = estimate_magnitude(paz, 6.78e4, 0.125, 1.538)\n self.assertAlmostEqual(mag_rnon, 1.4995311686507182)\n\n # now also test using Response object to calculate amplitude\n # (use RTSH response for all three measurements, see above comment)\n # response calculated using all stages is slightly different from the\n # PAZ + overall sensitivity used above, so we get slightly different\n # values here..\n response = read_inventory(os.path.join(self.path, 'BW_RTSH.xml'),\n format='STATIONXML')[0][0][0].response\n mag_rtsh = estimate_magnitude(response, 3.34e6, 0.065, 0.255)\n self.assertAlmostEqual(mag_rtsh, 2.1179529876187635)\n mag_rtbe = estimate_magnitude(response, 3.61e4, 0.08, 2.197)\n self.assertAlmostEqual(mag_rtbe, 1.1832677953138184)\n mag_rnon = estimate_magnitude(response, 6.78e4, 0.125, 1.538)\n self.assertAlmostEqual(mag_rnon, 1.4895395665022975)\n\n # XXX: Test for really big signal is missing, where the water level is\n # actually acting\n # def test_seisSimVsPitsa2(self):\n # from obspy.io.mseed import tests as tests_\n # path = os.path.dirname(__file__)\n # file = os.path.join(path, 'data', 'BW.BGLD..EHE.D.2008.001')\n # g = Trace()\n # g.read(file,format='MSEED')\n # # paz of test file\n # samp_rate = 200.0\n\n def test_sac_instrument_correction(self):\n # SAC recommends to taper the transfer function if a pure\n # deconvolution is done instead of simulating a different\n # instrument. This test checks the difference between the\n # result from removing the instrument response using SAC or\n # ObsPy. Visual inspection shows that the traces are pretty\n # much identical but differences remain (rms ~ 0.042). Haven't\n # found the cause for those, yet. One possible reason is the\n # floating point arithmetic of SAC vs. the double precision\n # arithmetic of Python. However differences still seem to be\n # too big for that.\n pzf = os.path.join(self.path, 'SAC_PZs_KARC_BHZ')\n sacf = os.path.join(self.path, 'KARC.LHZ.SAC.asc.gz')\n testsacf = os.path.join(self.path, 'KARC_corrected.sac.asc.gz')\n plow = 160.\n phigh = 4.\n fl1 = 1.0 / (plow + 0.0625 * plow)\n fl2 = 1.0 / plow\n fl3 = 1.0 / phigh\n fl4 = 1.0 / (phigh - 0.25 * phigh)\n # Uncomment the following to run the sac-commands\n # that created the testing file\n # if 1:\n # import subprocess as sp\n # p = sp.Popen('sac',shell=True,stdin=sp.PIPE)\n # cd1 = p.stdin\n # print(\"r %s\"%sacf, file=cd1)\n # print(\"rmean\", file=cd1)\n # print(\"rtrend\", file=cd1)\n # print(\"taper type cosine width 0.03\", file=cd1)\n # print(\"transfer from polezero subtype %s to none \\\n # freqlimits %f %f %f %f\" % (pzf, fl1, fl2, fl3, fl4), file=cd1)\n # print(\"w over ./data/KARC_corrected.sac\", file=cd1)\n # print(\"quit\", file=cd1)\n # cd1.close()\n # p.wait()\n\n stats = {'network': 'KA', 'delta': 0.99999988079072466,\n 'station': 'KARC', 'location': 'S1',\n 'starttime': UTCDateTime(2001, 2, 13, 0, 0, 0, 993700),\n 'calib': 1.00868e+09, 'channel': 'BHZ'}\n with gzip.open(sacf) as f:\n tr = Trace(np.loadtxt(f), stats)\n\n attach_paz(tr, pzf, tovel=False)\n tr.data = simulate_seismometer(\n tr.data, tr.stats.sampling_rate, paz_remove=tr.stats.paz,\n remove_sensitivity=False, pre_filt=(fl1, fl2, fl3, fl4))\n\n with gzip.open(testsacf) as f:\n data = np.loadtxt(f)\n\n # import matplotlib.pyplot as plt\n # plt.plot(tr.data)\n # plt.plot(data)\n # plt.show()\n rms = np.sqrt(np.sum((tr.data - data) ** 2) /\n np.sum(tr.data ** 2))\n self.assertTrue(rms < 0.0421)\n\n def test_evalresp_vs_obspy(self):\n \"\"\"\n Compare results from removing instrument response using\n evalresp in SAC and ObsPy. Visual inspection shows that the traces are\n pretty much identical but differences remain (rms ~ 0.042). Haven't\n found the cause for those, yet.\n \"\"\"\n evalrespf = os.path.join(self.path, 'CRLZ.HHZ.10.NZ.SAC_resp')\n rawf = os.path.join(self.path, 'CRLZ.HHZ.10.NZ.SAC')\n respf = os.path.join(self.path, 'RESP.NZ.CRLZ.10.HHZ')\n fl1 = 0.00588\n fl2 = 0.00625\n fl3 = 30.\n fl4 = 35.\n\n# #Set the following if-clause to True to run\n# #the sac-commands that created the testing file\n# if False:\n# import subprocess as sp\n# p = sp.Popen('sac', stdin=sp.PIPE)\n# cd1 = p.stdin\n# print(\"r %s\" % rawf, file=cd1)\n# print(\"rmean\", file=cd1)\n# print(\"taper type cosine width 0.05\", file=cd1)\n# print(\"transfer from evalresp fname %s to vel freqlimits\\\n# %f %f %f %f\" % (respf, fl1, fl2, fl3, fl4), file=cd1)\n# print(\"w over %s\" % evalrespf, file=cd1)\n# print(\"quit\", file=cd1)\n# cd1.close()\n# p.wait()\n\n tr = read(rawf)[0]\n trtest = read(evalrespf)[0]\n date = UTCDateTime(2003, 11, 1, 0, 0, 0)\n seedresp = {'filename': respf, 'date': date, 'units': 'VEL',\n 'network': 'NZ', 'station': 'CRLZ', 'location': '10',\n 'channel': 'HHZ'}\n tr.data = simulate_seismometer(\n tr.data, tr.stats.sampling_rate, paz_remove=None,\n pre_filt=(fl1, fl2, fl3, fl4), seedresp=seedresp,\n taper_fraction=0.1, pitsasim=False, sacsim=True)\n tr.data *= 1e9\n rms = np.sqrt(np.sum((tr.data - trtest.data) ** 2) /\n np.sum(trtest.data ** 2))\n self.assertTrue(rms < 0.0094)\n # import matplotlib.pyplot as plt #plt.plot(tr.data-trtest.data,'b')\n # plt.plot(trtest.data,'g')\n # plt.figure()\n # plt.psd(tr.data,Fs=100.,NFFT=32768)\n # plt.psd(trtest.data,Fs=100.,NFFT=32768)\n # plt.figure()\n # plt.psd(tr.data - trtest.data, Fs=100., NFFT=32768)\n # plt.show()\n\n def test_cosine_taper(self):\n # SAC trace was generated with:\n # taper type cosine width 0.05\n for i in [99, 100]:\n sac_taper = os.path.join(self.path,\n 'ones_trace_%d_tapered.sac' % i)\n tr = read(sac_taper)[0]\n tap = cosine_taper(i, p=0.1, halfcosine=False, sactaper=True)\n np.testing.assert_array_almost_equal(tap, tr.data, decimal=6)\n\n # The following lines compare the cosine_taper result with\n # the result of the algorithm used by SAC in its taper routine\n # (taper.c)\n # freqs = np.fft.fftfreq(2**15,0.01)\n # fl1 = 0.00588\n # fl2 = 0.00625\n # fl3 = 30.0\n # fl4 = 35.0\n # npts = freqs.size\n # tap = cosine_taper(freqs.size, freqs=freqs, flimit=(fl1, fl2,\n # fl3, fl4))\n # tap2 = cosine_sac_taper(freqs, flimit=(fl1, fl2, fl3, fl4))\n # import matplotlib.pyplot as plt\n # plt.plot(tap,'b')\n # plt.plot(tap2,'g--')\n # plt.show()\n\n def test_evalresp_using_different_line_separator(self):\n \"\"\"\n The evalresp needs a file with correct line separator, so '\\n' for\n POSIX, '\\r' for Mac OS, or '\\r\\n' for Windows. Here we check that\n evalresp reads all three formats.\n\n This test only checks the parsing capabilities of evalresp,\n the number of fft points used (nfft) can therefore be chosen\n small.\n \"\"\"\n dt = UTCDateTime(2003, 11, 1, 0, 0, 0)\n nfft = 8\n # Linux\n respf = os.path.join(self.path, 'RESP.NZ.CRLZ.10.HHZ')\n evalresp(0.01, nfft, respf, dt)\n # Mac\n respf = os.path.join(self.path, 'RESP.NZ.CRLZ.10.HHZ.mac')\n evalresp(0.01, nfft, respf, dt)\n # Windows\n respf = os.path.join(self.path, 'RESP.NZ.CRLZ.10.HHZ.windows')\n evalresp(0.01, nfft, respf, dt)\n\n def test_evalresp_bug_395(self):\n \"\"\"\n Was a bug due to inconstistent numerical range\n \"\"\"\n resp = os.path.join(self.path, 'RESP.CH._.HHZ.gz')\n with NamedTemporaryFile() as fh:\n tmpfile = fh.name\n with gzip.open(resp) as f:\n fh.write(f.read())\n samprate = 120.0\n nfft = 56328\n args = [1.0 / samprate, nfft, tmpfile,\n UTCDateTime(2012, 9, 4, 5, 12, 15, 863300)]\n kwargs = {'units': 'VEL', 'freq': True}\n _h, f = evalresp(*args, **kwargs)\n self.assertEqual(len(f), nfft // 2 + 1)\n\n def test_evalresp_specific_frequencies(self):\n \"\"\"\n Test getting response for specific frequencies from evalresp\n \"\"\"\n resp = os.path.join(self.path, 'RESP.CH._.HHZ.gz')\n # test some frequencies (results taken from routine\n # test_evalresp_bug_395)\n freqs = [0.0, 0.0021303792075, 0.21303792075, 0.63911376225,\n 2.1303792075, 21.303792075, 59.9978696208, 60.0]\n expected = [0j, -38033660.9731 + 14722854.5862j,\n 623756964.698 + 34705336.5587j,\n 625815840.91 + 11748438.5949j,\n 634173301.327 - 2261888.45356j,\n 689435074.739 - 216615642.231j,\n -105.682658137 - 4360.67242023j,\n -101.693155157 - 4172.61059939j,\n ]\n with NamedTemporaryFile() as fh:\n tmpfile = fh.name\n with gzip.open(resp) as f:\n fh.write(f.read())\n samprate = 120.0\n t = UTCDateTime(2012, 9, 4, 5, 12, 15, 863300)\n h = evalresp_for_frequencies(\n 1.0 / samprate, freqs, tmpfile, t, units='VEL')\n np.testing.assert_allclose(h, expected)\n\n # this test seems to fail sometimes with almost same numbers but slight\n # differences on Appveyor and we could not reproduce it on a local\n # machine.. so skip on windows.. (e.g. http://tests.obspy.org/101648/#1,\n # https://ci.appveyor.com/project/obspy/obspy/build/1.0.6561-master)\n @unittest.skipIf(platform.system() == \"Windows\",\n 'unreproducible test fail encountered on Appveyor '\n 'sometimes.')\n def test_evalresp_file_like_object(self):\n \"\"\"\n Test evalresp with file like object\n \"\"\"\n rawf = os.path.join(self.path, 'CRLZ.HHZ.10.NZ.SAC')\n respf = os.path.join(self.path, 'RESP.NZ.CRLZ.10.HHZ')\n\n tr1 = read(rawf)[0]\n tr2 = read(rawf)[0]\n\n date = UTCDateTime(2003, 11, 1, 0, 0, 0)\n seedresp = {'filename': respf, 'date': date, 'units': 'VEL',\n 'network': 'NZ', 'station': 'CRLZ', 'location': '10',\n 'channel': 'HHZ'}\n tr1.data = simulate_seismometer(\n tr1.data, tr1.stats.sampling_rate, seedresp=seedresp)\n\n with open(respf, 'rb') as fh:\n stringio = io.BytesIO(fh.read())\n seedresp['filename'] = stringio\n tr2.data = simulate_seismometer(tr2.data, tr2.stats.sampling_rate,\n seedresp=seedresp)\n\n self.assertEqual(tr1, tr2)\n\n def test_segfaulting_resp_file(self):\n \"\"\"\n Test case for a file that segfaults when compiled with clang and\n active optimization.\n\n As long as the test does not segfault it is ok.\n \"\"\"\n filename = os.path.join(self.path, \"segfaulting_RESPs\",\n \"RESP.IE.LLRI..EHZ\")\n date = UTCDateTime(2003, 11, 1, 0, 0, 0)\n # raises C-level EVRESP ERROR\n with SuppressOutput():\n self.assertRaises(ValueError, evalresp, t_samp=10.0, nfft=256,\n filename=filename, date=date, station=\"LLRI\",\n channel=\"EHZ\", network=\"IE\", locid=\"*\",\n units=\"VEL\")\n\n def test_evalresp_seed_identifiers_work(self):\n \"\"\"\n Asserts that the network, station, location and channel identifiers can\n be used to select difference responses.\n \"\"\"\n kwargs = {\"filename\": os.path.join(self.path, \"RESP.OB.AAA._.BH_\"),\n \"t_samp\": 0.1, \"nfft\": 1024, \"units\": \"VEL\",\n \"date\": UTCDateTime(2013, 1, 1), \"network\": \"OP\",\n \"station\": \"AAA\", \"locid\": \"\", \"freq\": False, \"debug\": False}\n\n # Get the response for the first channel\n kwargs[\"channel\"] = \"BHE\"\n response_1 = evalresp(**kwargs)\n\n # Get the second one. Should be different.\n kwargs[\"channel\"] = \"BHN\"\n response_2 = evalresp(**kwargs)\n\n # The only thing that changed was the channel code. This should change\n # the response.\n rel_diff = np.abs(response_2 - response_1).ptp() / \\\n max(np.abs(response_1).ptp(), np.abs(response_2).ptp())\n self.assertGreater(rel_diff, 1E-3)\n\n # The RESP file only contains two channels.\n kwargs[\"channel\"] = \"BHZ\"\n # suppress a C-level \"no response found\" warning\n with SuppressOutput():\n self.assertRaises(ValueError, evalresp, **kwargs)\n\n def test_evalresp_spline(self):\n \"\"\"\n evr_spline was based on GPL plotutils, now replaced by LGPL spline\n library. Unittest for this function.\n \"\"\"\n # char *evr_spline(int num_points, double *t, double *y,\n # double tension, double k,\n # double *xvals_arr, int num_xvals,\n # double **p_retvals_arr, int *p_num_retvals)\n clibevresp.evr_spline.argtypes = [\n C.c_int, # num_points\n np.ctypeslib.ndpointer(dtype=np.float64, ndim=1,\n flags=native_str('C_CONTIGUOUS')),\n np.ctypeslib.ndpointer(dtype=np.float64, ndim=1,\n flags=native_str('C_CONTIGUOUS')),\n C.c_double, # tension\n C.c_double, # k\n np.ctypeslib.ndpointer(dtype=np.float64, ndim=1,\n flags=native_str('C_CONTIGUOUS')),\n C.c_int, # num_xvals\n C.POINTER(C.POINTER(C.c_double)),\n C.POINTER(C.c_int)\n ]\n clibevresp.evr_spline.restype = C.c_char_p\n\n x = np.arange(1.2, 2.0, .1)\n n = len(x)\n y = np.sin(x)\n\n xi = x[:-1] + .05\n ni = len(xi)\n\n p_num_retvals = C.c_int(0)\n p_retvals_arr = C.POINTER(C.c_double)()\n res = clibevresp.evr_spline(n, x, y, 0.0, 1.0, xi, ni,\n C.byref(p_retvals_arr),\n C.byref(p_num_retvals))\n self.assertEqual(res, None)\n self.assertEqual(ni, p_num_retvals.value)\n yi = np.array([p_retvals_arr[i] for i in range(ni)])\n\n if False: # visually verify\n import matplotlib.pyplot as plt\n plt.plot(x, y, 'bo-', 'Orig values')\n plt.plot(xi, yi, 'ro-', 'Cubic Spline interpolated values')\n plt.legend()\n plt.show()\n\n yi_ref = [0.94899576, 0.97572004, 0.9927136, 0.99978309, 0.99686554,\n 0.98398301, 0.96128491]\n self.assertTrue(np.allclose(yi, yi_ref, rtol=1e-7, atol=0))\n\n\ndef suite():\n return unittest.makeSuite(InvSimTestCase, 'test')\n\n\nif __name__ == '__main__':\n unittest.main(defaultTest='suite')\n" ]
[ [ "numpy.argmax", "numpy.where", "numpy.isinf" ], [ "matplotlib.pyplot.legend", "numpy.allclose", "numpy.abs", "numpy.arange", "numpy.sin", "matplotlib.pyplot.plot", "numpy.testing.assert_allclose", "matplotlib.pyplot.show", "numpy.sum", "numpy.loadtxt", "numpy.testing.assert_array_almost_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tripzero/deepvoice3_pytorch
[ "90027d27dab2889d856f9db9ffaf39d4f70b3067" ]
[ "deepvoice3_pytorch/modules.py" ]
[ "# coding: utf-8\n\nimport torch\nfrom torch import nn\nimport math\nimport numpy as np\nfrom torch.nn import functional as F\n\n\ndef position_encoding_init(n_position, d_pos_vec, position_rate=1.0,\n sinusoidal=True):\n ''' Init the sinusoid position encoding table '''\n\n # keep dim 0 for padding token position encoding zero vector\n position_enc = np.array([\n [position_rate * pos / np.power(10000, 2 * (i // 2) / d_pos_vec) for i in range(d_pos_vec)]\n if pos != 0 else np.zeros(d_pos_vec) for pos in range(n_position)])\n\n position_enc = torch.from_numpy(position_enc).float()\n if sinusoidal:\n position_enc[1:, 0::2] = torch.sin(position_enc[1:, 0::2]) # dim 2i\n position_enc[1:, 1::2] = torch.cos(position_enc[1:, 1::2]) # dim 2i+1\n\n return position_enc\n\n\ndef sinusoidal_encode(x, w):\n y = w * x\n y[1:, 0::2] = torch.sin(y[1:, 0::2].clone())\n y[1:, 1::2] = torch.cos(y[1:, 1::2].clone())\n return y\n\n\nclass SinusoidalEncoding(nn.Embedding):\n\n def __init__(self, num_embeddings, embedding_dim,\n *args, **kwargs):\n super(SinusoidalEncoding, self).__init__(num_embeddings, embedding_dim,\n padding_idx=0,\n *args, **kwargs)\n self.weight.data = position_encoding_init(num_embeddings, embedding_dim,\n position_rate=1.0,\n sinusoidal=False)\n\n def forward(self, x, w=1.0):\n isscaler = np.isscalar(w)\n assert self.padding_idx is not None\n\n if isscaler or w.size(0) == 1:\n weight = sinusoidal_encode(self.weight, w)\n return F.embedding(\n x, weight, self.padding_idx, self.max_norm,\n self.norm_type, self.scale_grad_by_freq, self.sparse)\n else:\n # TODO: cannot simply apply for batch\n # better to implement efficient function\n pe = []\n for batch_idx, we in enumerate(w):\n weight = sinusoidal_encode(self.weight, we)\n pe.append(F.embedding(\n x[batch_idx], weight, self.padding_idx, self.max_norm,\n self.norm_type, self.scale_grad_by_freq, self.sparse))\n pe = torch.stack(pe)\n return pe\n\n\nclass GradMultiply(torch.autograd.Function):\n @staticmethod\n def forward(ctx, x, scale):\n ctx.scale = scale\n res = x.new(x)\n ctx.mark_shared_storage((x, res))\n return res\n\n @staticmethod\n def backward(ctx, grad):\n return grad * ctx.scale, None\n\n\ndef Linear(in_features, out_features, dropout=0):\n \"\"\"Weight-normalized Linear layer (input: N x T x C)\"\"\"\n m = nn.Linear(in_features, out_features)\n m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features))\n m.bias.data.zero_()\n return nn.utils.weight_norm(m)\n\n\ndef Embedding(num_embeddings, embedding_dim, padding_idx, std=0.01):\n m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)\n m.weight.data.normal_(0, std)\n return m\n\n\ndef Conv1d(in_channels, out_channels, kernel_size, dropout=0, std_mul=4.0, **kwargs):\n from .conv import Conv1d\n m = Conv1d(in_channels, out_channels, kernel_size, **kwargs)\n std = math.sqrt((std_mul * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))\n m.weight.data.normal_(mean=0, std=std)\n m.bias.data.zero_()\n return nn.utils.weight_norm(m)\n\n\ndef ConvTranspose1d(in_channels, out_channels, kernel_size, dropout=0,\n std_mul=1.0, **kwargs):\n m = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, **kwargs)\n std = math.sqrt((std_mul * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))\n m.weight.data.normal_(mean=0, std=std)\n m.bias.data.zero_()\n return nn.utils.weight_norm(m)\n\n\nclass Conv1dGLU(nn.Module):\n \"\"\"(Dilated) Conv1d + Gated linear unit + (optionally) speaker embedding\n \"\"\"\n\n def __init__(self, n_speakers, speaker_embed_dim,\n in_channels, out_channels, kernel_size,\n dropout, padding=None, dilation=1, causal=False, residual=False,\n *args, **kwargs):\n super(Conv1dGLU, self).__init__()\n self.dropout = dropout\n self.residual = residual\n if padding is None:\n # no future time stamps available\n if causal:\n padding = (kernel_size - 1) * dilation\n else:\n padding = (kernel_size - 1) // 2 * dilation\n self.causal = causal\n\n self.conv = Conv1d(in_channels, 2 * out_channels, kernel_size,\n dropout=dropout, padding=padding, dilation=dilation,\n *args, **kwargs)\n if n_speakers > 1:\n self.speaker_proj = Linear(speaker_embed_dim, out_channels)\n else:\n self.speaker_proj = None\n\n def forward(self, x, speaker_embed=None):\n return self._forward(x, speaker_embed, False)\n\n def incremental_forward(self, x, speaker_embed=None):\n return self._forward(x, speaker_embed, True)\n\n def _forward(self, x, speaker_embed, is_incremental):\n residual = x\n x = F.dropout(x, p=self.dropout, training=self.training)\n if is_incremental:\n splitdim = -1\n x = self.conv.incremental_forward(x)\n else:\n splitdim = 1\n x = self.conv(x)\n # remove future time steps\n x = x[:, :, :residual.size(-1)] if self.causal else x\n\n a, b = x.split(x.size(splitdim) // 2, dim=splitdim)\n if self.speaker_proj is not None:\n softsign = F.softsign(self.speaker_proj(speaker_embed))\n # Since conv layer assumes BCT, we need to transpose\n softsign = softsign if is_incremental else softsign.transpose(1, 2)\n a = a + softsign\n x = a * torch.sigmoid(b)\n return (x + residual) * math.sqrt(0.5) if self.residual else x\n\n def clear_buffer(self):\n self.conv.clear_buffer()\n\n\nclass HighwayConv1d(nn.Module):\n \"\"\"Weight normzlized Conv1d + Highway network (support incremental forward)\n \"\"\"\n\n def __init__(self, in_channels, out_channels, kernel_size=1, padding=None,\n dilation=1, causal=False, dropout=0, std_mul=None, glu=False):\n super(HighwayConv1d, self).__init__()\n if std_mul is None:\n std_mul = 4.0 if glu else 1.0\n if padding is None:\n # no future time stamps available\n if causal:\n padding = (kernel_size - 1) * dilation\n else:\n padding = (kernel_size - 1) // 2 * dilation\n self.causal = causal\n self.dropout = dropout\n self.glu = glu\n\n self.conv = Conv1d(in_channels, 2 * out_channels,\n kernel_size=kernel_size, padding=padding,\n dilation=dilation, dropout=dropout,\n std_mul=std_mul)\n\n def forward(self, x):\n return self._forward(x, False)\n\n def incremental_forward(self, x):\n return self._forward(x, True)\n\n def _forward(self, x, is_incremental):\n \"\"\"Forward\n\n Args:\n x: (B, in_channels, T)\n returns:\n (B, out_channels, T)\n \"\"\"\n\n residual = x\n x = F.dropout(x, p=self.dropout, training=self.training)\n if is_incremental:\n splitdim = -1\n x = self.conv.incremental_forward(x)\n else:\n splitdim = 1\n x = self.conv(x)\n # remove future time steps\n x = x[:, :, :residual.size(-1)] if self.causal else x\n\n if self.glu:\n x = F.glu(x, dim=splitdim)\n return (x + residual) * math.sqrt(0.5)\n else:\n a, b = x.split(x.size(splitdim) // 2, dim=splitdim)\n T = torch.sigmoid(b)\n return (T * a + (1 - T) * residual)\n\n def clear_buffer(self):\n self.conv.clear_buffer()\n\n\ndef get_mask_from_lengths(memory, memory_lengths):\n \"\"\"Get mask tensor from list of length\n Args:\n memory: (batch, max_time, dim)\n memory_lengths: array like\n \"\"\"\n mask = memory.data.new(memory.size(0), memory.size(1)).byte().zero_()\n for idx, l in enumerate(memory_lengths):\n mask[idx][:l] = 1\n return ~mask\n" ]
[ [ "torch.nn.functional.embedding", "torch.sigmoid", "torch.nn.functional.glu", "torch.sin", "torch.nn.functional.dropout", "torch.nn.utils.weight_norm", "numpy.power", "torch.from_numpy", "torch.nn.Embedding", "torch.nn.Linear", "numpy.isscalar", "torch.stack", "torch.nn.ConvTranspose1d", "numpy.zeros", "torch.cos" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
boldsort/craftassist
[ "8058d115a250e30deb60d969b7b1a5fefd6e974c" ]
[ "python/base_agent/ttad/back_translation/modeling_gpt2.py" ]
[ "# coding=utf-8\n# Copyright 2018 The OpenAI Team Authors and 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\"\"\"PyTorch OpenAI GPT-2 model.\"\"\"\n\n\nimport logging\nimport os\nimport warnings\nimport torch\nimport torch.nn as nn\nfrom torch.nn import CrossEntropyLoss\nfrom transformers.modeling_gpt2 import PreTrainedModel, GPT2Config\nfrom transformers.modeling_outputs import (\n BaseModelOutputWithPast,\n CausalLMOutputWithPast,\n GPT2DoubleHeadsModelOutput,\n)\nfrom transformers.activations import ACT2FN\nfrom transformers.modeling_utils import (\n Conv1D,\n prune_conv1d_layer,\n SequenceSummary,\n find_pruneable_heads_and_indices,\n)\n\nlogger = logging.getLogger(__name__)\n\n_CONFIG_FOR_DOC = \"GPT2Config\"\n_TOKENIZER_FOR_DOC = \"GPT2Tokenizer\"\n\nGPT2_PRETRAINED_MODEL_ARCHIVE_LIST = [\n \"gpt2\",\n \"gpt2-medium\",\n \"gpt2-large\",\n \"gpt2-xl\",\n \"distilgpt2\",\n # See all GPT-2 models at https://huggingface.co/models?filter=gpt2\n]\n\n\ndef load_tf_weights_in_gpt2(model, config, gpt2_checkpoint_path):\n \"\"\" Load tf checkpoints in a pytorch model\n \"\"\"\n try:\n import re\n import tensorflow as tf\n except ImportError:\n logger.error(\n \"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see \"\n \"https://www.tensorflow.org/install/ for installation instructions.\"\n )\n raise\n tf_path = os.path.abspath(gpt2_checkpoint_path)\n logger.info(\"Converting TensorFlow checkpoint from {}\".format(tf_path))\n # Load weights from TF model\n init_vars = tf.train.list_variables(tf_path)\n names = []\n arrays = []\n for name, shape in init_vars:\n logger.info(\"Loading TF weight {} with shape {}\".format(name, shape))\n array = tf.train.load_variable(tf_path, name)\n names.append(name)\n arrays.append(array.squeeze())\n\n for name, array in zip(names, arrays):\n name = name[6:] # skip \"model/\"\n name = name.split(\"/\")\n pointer = model\n for m_name in name:\n if re.fullmatch(r\"[A-Za-z]+\\d+\", m_name):\n scope_names = re.split(r\"(\\d+)\", m_name)\n else:\n scope_names = [m_name]\n if scope_names[0] == \"w\" or scope_names[0] == \"g\":\n pointer = getattr(pointer, \"weight\")\n elif scope_names[0] == \"b\":\n pointer = getattr(pointer, \"bias\")\n elif scope_names[0] == \"wpe\" or scope_names[0] == \"wte\":\n pointer = getattr(pointer, scope_names[0])\n pointer = getattr(pointer, \"weight\")\n else:\n pointer = getattr(pointer, scope_names[0])\n if len(scope_names) >= 2:\n num = int(scope_names[1])\n pointer = pointer[num]\n try:\n assert (\n pointer.shape == array.shape\n ), f\"Pointer shape {pointer.shape} and array shape {array.shape} mismatched\"\n except AssertionError as e:\n e.args += (pointer.shape, array.shape)\n raise\n logger.info(\"Initialize PyTorch weight {}\".format(name))\n pointer.data = torch.from_numpy(array)\n return model\n\n\nclass Attention(nn.Module):\n def __init__(self, nx, n_ctx, config, scale=False):\n super().__init__()\n\n n_state = nx # in Attention: n_state=768 (nx=n_embd)\n # [switch nx => n_state from Block to Attention to keep identical to TF implem]\n assert n_state % config.n_head == 0\n self.register_buffer(\n \"bias\",\n torch.tril(torch.ones((n_ctx, n_ctx), dtype=torch.uint8)).view(1, 1, n_ctx, n_ctx),\n )\n self.register_buffer(\"masked_bias\", torch.tensor(-1e4))\n self.n_head = config.n_head\n self.split_size = n_state\n self.scale = scale\n\n self.c_attn = Conv1D(n_state * 3, nx)\n # TODO: check config.hidden_size\n self.query = nn.Linear(n_state, nx)\n self.key = nn.Linear(n_state, nx)\n self.value = nn.Linear(n_state, nx)\n\n self.c_proj = Conv1D(n_state, nx)\n self.attn_dropout = nn.Dropout(config.attn_pdrop)\n self.resid_dropout = nn.Dropout(config.resid_pdrop)\n self.pruned_heads = set()\n self.config = config\n\n def prune_heads(self, heads):\n if len(heads) == 0:\n return\n heads, index = find_pruneable_heads_and_indices(\n heads, self.n_head, self.split_size // self.n_head, self.pruned_heads\n )\n index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])\n\n # Prune conv1d layers\n self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)\n self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)\n\n # Update hyper params\n self.split_size = (self.split_size // self.n_head) * (self.n_head - len(heads))\n self.n_head = self.n_head - len(heads)\n self.pruned_heads = self.pruned_heads.union(heads)\n\n def _attn(self, q, k, v, attention_mask=None, head_mask=None, output_attentions=False):\n w = torch.matmul(q, k)\n if self.scale:\n w = w / (float(v.size(-1)) ** 0.5)\n nd, ns = w.size(-2), w.size(-1)\n mask = self.bias[:, :, ns - nd : ns, :ns]\n w = torch.where(mask.bool(), w, self.masked_bias.to(w.dtype))\n\n if attention_mask is not None:\n # Apply the attention mask\n w = w + attention_mask\n\n w = nn.Softmax(dim=-1)(w)\n w = self.attn_dropout(w)\n\n # Mask heads if we want to\n if head_mask is not None:\n w = w * head_mask\n\n outputs = [torch.matmul(w, v)]\n if output_attentions:\n outputs.append(w)\n return outputs\n\n def merge_heads(self, x):\n x = x.permute(0, 2, 1, 3).contiguous()\n new_x_shape = x.size()[:-2] + (x.size(-2) * x.size(-1),)\n return x.view(*new_x_shape) # in Tensorflow implem: fct merge_states\n\n def split_heads(self, x, k=False):\n new_x_shape = x.size()[:-1] + (self.n_head, x.size(-1) // self.n_head)\n x = x.view(*new_x_shape) # in Tensorflow implem: fct split_states\n if k:\n return x.permute(0, 2, 3, 1) # (batch, head, head_features, seq_length)\n else:\n return x.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)\n\n def forward(\n self,\n x,\n layer_past=None,\n attention_mask=None,\n head_mask=None,\n use_cache=False,\n output_attentions=False,\n encoder_hidden_states=None,\n encoder_attention_mask=None,\n ):\n if self.config.is_decoder:\n assert encoder_hidden_states is not None\n key = self.key(encoder_hidden_states)\n value = self.value(encoder_hidden_states)\n query = self.query(x)\n else:\n x = self.c_attn(x)\n query, key, value = x.split(self.split_size, dim=2)\n query = self.split_heads(query)\n key = self.split_heads(key, k=True)\n value = self.split_heads(value)\n\n if layer_past is not None:\n past_key, past_value = (\n layer_past[0].transpose(-2, -1),\n layer_past[1],\n ) # transpose back cf below\n key = torch.cat((past_key, key), dim=-1)\n value = torch.cat((past_value, value), dim=-2)\n\n if use_cache is True:\n present = torch.stack(\n (key.transpose(-2, -1), value)\n ) # transpose to have same shapes for stacking\n else:\n present = (None,)\n if self.config.is_decoder:\n attn_outputs = self._attn(\n query, key, value, encoder_attention_mask, head_mask, output_attentions\n )\n else:\n attn_outputs = self._attn(\n query, key, value, attention_mask, head_mask, output_attentions\n )\n\n at = attn_outputs[0]\n at = self.merge_heads(at)\n at = self.c_proj(at)\n at = self.resid_dropout(at)\n outputs = [at, present] + attn_outputs[1:]\n return outputs # a, present, (attentions)\n\n\nclass MLP(nn.Module):\n def __init__(self, n_state, config): # in MLP: n_state=3072 (4 * n_embd)\n super().__init__()\n nx = config.n_embd\n self.c_fc = Conv1D(n_state, nx)\n self.c_proj = Conv1D(nx, n_state)\n self.act = ACT2FN[config.activation_function]\n self.dropout = nn.Dropout(config.resid_pdrop)\n\n def forward(self, x):\n h = self.act(self.c_fc(x))\n h2 = self.c_proj(h)\n return self.dropout(h2)\n\n\nclass Block(nn.Module):\n def __init__(self, n_ctx, config, scale=False):\n super().__init__()\n nx = config.n_embd\n inner_dim = config.n_inner if config.n_inner is not None else 4 * nx\n self.ln_1 = nn.LayerNorm(nx, eps=config.layer_norm_epsilon)\n self.attn = Attention(nx, n_ctx, config, scale)\n self.ln_2 = nn.LayerNorm(nx, eps=config.layer_norm_epsilon)\n self.mlp = MLP(inner_dim, config)\n self.config = config\n \"\"\"\n TODO: add another self attention layer?\n \"\"\"\n\n def forward(\n self,\n x,\n layer_past=None,\n attention_mask=None,\n head_mask=None,\n use_cache=False,\n output_attentions=False,\n encoder_hidden_states=None,\n encoder_attention_mask=None,\n ):\n output_attn = self.attn(\n self.ln_1(x),\n layer_past=layer_past,\n attention_mask=attention_mask,\n head_mask=head_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n )\n a = output_attn[0] # output_attn: a, present, (attentions)\n x = x + a\n m = self.mlp(self.ln_2(x))\n x = x + m\n\n outputs = [x] + output_attn[1:]\n return outputs # x, present, (attentions)\n\n\nclass GPT2PreTrainedModel(PreTrainedModel):\n \"\"\" An abstract class to handle weights initialization and\n a simple interface for downloading and loading pretrained models.\n \"\"\"\n\n config_class = GPT2Config\n load_tf_weights = load_tf_weights_in_gpt2\n base_model_prefix = \"transformer\"\n\n def __init__(self, *inputs, **kwargs):\n super().__init__(*inputs, **kwargs)\n\n def _init_weights(self, module):\n \"\"\" Initialize the weights.\n \"\"\"\n if isinstance(module, (nn.Linear, nn.Embedding, Conv1D)):\n # Slightly different from the TF version which uses truncated_normal for initialization\n # cf https://github.com/pytorch/pytorch/pull/5617\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n if isinstance(module, (nn.Linear, Conv1D)) and module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n\nclass GPT2Model(GPT2PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.wte = nn.Embedding(config.vocab_size, config.n_embd)\n self.wpe = nn.Embedding(config.n_positions, config.n_embd)\n self.drop = nn.Dropout(config.embd_pdrop)\n self.h = nn.ModuleList(\n [Block(config.n_ctx, config, scale=True) for _ in range(config.n_layer)]\n )\n self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)\n\n self.init_weights()\n\n def get_input_embeddings(self):\n return self.wte\n\n def set_input_embeddings(self, new_embeddings):\n self.wte = new_embeddings\n\n def _prune_heads(self, heads_to_prune):\n \"\"\" Prunes heads of the model.\n heads_to_prune: dict of {layer_num: list of heads to prune in this layer}\n \"\"\"\n for layer, heads in heads_to_prune.items():\n self.h[layer].attn.prune_heads(heads)\n\n def forward(\n self,\n input_ids=None,\n past_key_values=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n use_cache=None,\n encoder_hidden_states=None,\n encoder_attention_mask=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n **kwargs,\n ):\n if \"past\" in kwargs:\n warnings.warn(\n \"The `past` argument is deprecated and will be removed in a future version, use `past_key_values` instead.\",\n FutureWarning,\n )\n past_key_values = kwargs.pop(\"past\")\n assert kwargs == {}, f\"Unexpected keyword arguments: {list(kwargs.keys())}.\"\n\n output_attentions = (\n output_attentions if output_attentions is not None else self.config.output_attentions\n )\n output_hidden_states = (\n output_hidden_states\n if output_hidden_states is not None\n else self.config.output_hidden_states\n )\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\n \"You cannot specify both input_ids and inputs_embeds at the same time\"\n )\n elif input_ids is not None:\n input_shape = input_ids.size()\n input_ids = input_ids.view(-1, input_shape[-1])\n batch_size = input_ids.shape[0]\n elif inputs_embeds is not None:\n input_shape = inputs_embeds.size()[:-1]\n batch_size = inputs_embeds.shape[0]\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n\n if token_type_ids is not None:\n token_type_ids = token_type_ids.view(-1, input_shape[-1])\n if position_ids is not None:\n position_ids = position_ids.view(-1, input_shape[-1])\n\n if past_key_values is None:\n past_length = 0\n past_key_values = [None] * len(self.h)\n else:\n past_length = past_key_values[0][0].size(-2)\n if position_ids is None:\n device = input_ids.device if input_ids is not None else inputs_embeds.device\n position_ids = torch.arange(\n past_length, input_shape[-1] + past_length, dtype=torch.long, device=device\n )\n position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])\n\n # Attention mask.\n if attention_mask is not None:\n assert batch_size > 0, \"batch_size has to be defined and > 0\"\n attention_mask = attention_mask.view(batch_size, -1)\n # We create a 3D attention mask from a 2D tensor mask.\n # Sizes are [batch_size, 1, 1, to_seq_length]\n # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]\n # this attention mask is more simple than the triangular masking of causal attention\n # used in OpenAI GPT, we just need to prepare the broadcast dimension here.\n attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n attention_mask = attention_mask.to(\n dtype=next(self.parameters()).dtype\n ) # fp16 compatibility\n attention_mask = (1.0 - attention_mask) * -10000.0\n\n # Prepare head mask if needed\n # 1.0 in head_mask indicate we keep the head\n # attention_probs has shape bsz x n_heads x N x N\n # head_mask has shape n_layer x batch x n_heads x N x N\n head_mask = self.get_head_mask(head_mask, self.config.n_layer)\n if self.config.is_decoder and encoder_hidden_states is not None:\n encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()\n encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)\n if encoder_attention_mask is None:\n encoder_attention_mask = torch.ones(encoder_hidden_shape)\n\n if inputs_embeds is None:\n inputs_embeds = self.wte(input_ids)\n position_embeds = self.wpe(position_ids)\n if token_type_ids is not None:\n token_type_embeds = self.wte(token_type_ids)\n else:\n token_type_embeds = 0\n hidden_states = inputs_embeds + position_embeds + token_type_embeds\n hidden_states = self.drop(hidden_states)\n\n output_shape = input_shape + (hidden_states.size(-1),)\n\n presents = () if use_cache else None\n all_attentions = () if output_attentions else None\n all_hidden_states = () if output_hidden_states else None\n for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states.view(*output_shape),)\n\n outputs = block(\n hidden_states,\n layer_past=layer_past,\n attention_mask=attention_mask,\n head_mask=head_mask[i],\n use_cache=use_cache,\n output_attentions=output_attentions,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n )\n\n hidden_states, present = outputs[:2]\n if use_cache is True:\n presents = presents + (present,)\n\n if output_attentions:\n all_attentions = all_attentions + (outputs[2],)\n\n hidden_states = self.ln_f(hidden_states)\n hidden_states = hidden_states.view(*output_shape)\n # Add last hidden state\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(\n v\n for v in [hidden_states, presents, all_hidden_states, all_attentions]\n if v is not None\n )\n\n return BaseModelOutputWithPast(\n last_hidden_state=hidden_states,\n past_key_values=presents,\n hidden_states=all_hidden_states,\n attentions=all_attentions,\n )\n\n\nclass GPT2LMHeadModel(GPT2PreTrainedModel):\n authorized_missing_keys = [r\"h\\.\\d+\\.attn\\.masked_bias\", r\"lm_head\\.weight\"]\n\n def __init__(self, config):\n super().__init__(config)\n self.transformer = GPT2Model(config)\n self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)\n\n self.init_weights()\n\n def get_output_embeddings(self):\n return self.lm_head\n\n def prepare_inputs_for_generation(self, input_ids, past, **kwargs):\n # only last token for inputs_ids if past is defined in kwargs\n if past:\n input_ids = input_ids[:, -1].unsqueeze(-1)\n\n return {\"input_ids\": input_ids, \"past_key_values\": past, \"use_cache\": kwargs[\"use_cache\"]}\n\n def forward(\n self,\n input_ids=None,\n past_key_values=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n labels=None,\n use_cache=None,\n encoder_hidden_states=None,\n encoder_attention_mask=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n **kwargs,\n ):\n r\"\"\"\n labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):\n Labels for language modeling.\n Note that the labels **are shifted** inside the model, i.e. you can set ``labels = input_ids``\n Indices are selected in ``[-100, 0, ..., config.vocab_size]``\n All labels set to ``-100`` are ignored (masked), the loss is only\n computed for labels in ``[0, ..., config.vocab_size]``\n \"\"\"\n if \"past\" in kwargs:\n warnings.warn(\n \"The `past` argument is deprecated and will be removed in a future version, use `past_key_values` instead.\",\n FutureWarning,\n )\n past_key_values = kwargs.pop(\"past\")\n assert kwargs == {}, f\"Unexpected keyword arguments: {list(kwargs.keys())}.\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n transformer_outputs = self.transformer(\n input_ids,\n past_key_values=past_key_values,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n use_cache=use_cache,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n hidden_states = transformer_outputs[0]\n\n lm_logits = self.lm_head(hidden_states)\n\n loss = None\n if labels is not None:\n # Shift so that tokens < n predict n\n shift_logits = lm_logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n # Flatten the tokens\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + transformer_outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return CausalLMOutputWithPast(\n loss=loss,\n logits=lm_logits,\n past_key_values=transformer_outputs.past_key_values,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )\n\n\nclass GPT2DoubleHeadsModel(GPT2PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n config.num_labels = 1\n self.transformer = GPT2Model(config)\n self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)\n self.multiple_choice_head = SequenceSummary(config)\n\n self.init_weights()\n\n def get_output_embeddings(self):\n return self.lm_head\n\n def forward(\n self,\n input_ids=None,\n past_key_values=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n mc_token_ids=None,\n labels=None,\n mc_labels=None,\n use_cache=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n **kwargs,\n ):\n r\"\"\"\n mc_token_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, num_choices)`, `optional`, default to index of the last token of the input)\n Index of the classification token in each input sequence.\n Selected in the range ``[0, input_ids.size(-1) - 1[``.\n labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`)\n Labels for language modeling.\n Note that the labels **are shifted** inside the model, i.e. you can set ``labels = input_ids``\n Indices are selected in ``[-1, 0, ..., config.vocab_size]``\n All labels set to ``-100`` are ignored (masked), the loss is only\n computed for labels in ``[0, ..., config.vocab_size]``\n mc_labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size)`, `optional`, defaults to :obj:`None`)\n Labels for computing the multiple choice classification loss.\n Indices should be in ``[0, ..., num_choices]`` where `num_choices` is the size of the second dimension\n of the input tensors. (see `input_ids` above)\n kwargs (:obj:`Dict[str, any]`, optional, defaults to `{}`):\n Used to hide legacy arguments that have been deprecated.\n\n Return:\n\n Examples::\n\n >>> import torch\n >>> from transformers import GPT2Tokenizer, GPT2DoubleHeadsModel\n\n >>> tokenizer = GPT2Tokenizer.from_pretrained('gpt2')\n >>> model = GPT2DoubleHeadsModel.from_pretrained('gpt2, return_dict=True)\n\n >>> # Add a [CLS] to the vocabulary (we should train it also!)\n >>> num_added_tokens = tokenizer.add_special_tokens({'cls_token': '[CLS]'})\n\n >>> embedding_layer = model.resize_token_embeddings(len(tokenizer)) # Update the model embeddings with the new vocabulary size\n\n >>> choices = [\"Hello, my dog is cute [CLS]\", \"Hello, my cat is cute [CLS]\"]\n >>> encoded_choices = [tokenizer.encode(s) for s in choices]\n >>> cls_token_location = [tokens.index(tokenizer.cls_token_id) for tokens in encoded_choices]\n\n >>> input_ids = torch.tensor(encoded_choices).unsqueeze(0) # Batch size: 1, number of choices: 2\n >>> mc_token_ids = torch.tensor([cls_token_location]) # Batch size: 1\n\n >>> outputs = model(input_ids, mc_token_ids=mc_token_ids)\n >>> lm_logits = outputs.lm_logits\n >>> mc_logits = outputs.mc_logits\n\n \"\"\"\n if \"lm_labels\" in kwargs:\n warnings.warn(\n \"The `lm_labels` argument is deprecated and will be removed in a future version, use `labels` instead.\",\n FutureWarning,\n )\n labels = kwargs.pop(\"lm_labels\")\n if \"past\" in kwargs:\n warnings.warn(\n \"The `past` argument is deprecated and will be removed in a future version, use `past_key_values` instead.\",\n FutureWarning,\n )\n past_key_values = kwargs.pop(\"past\")\n assert kwargs == {}, f\"Unexpected keyword arguments: {list(kwargs.keys())}.\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n transformer_outputs = self.transformer(\n input_ids,\n past_key_values=past_key_values,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_states = transformer_outputs[0]\n\n lm_logits = self.lm_head(hidden_states)\n mc_logits = self.multiple_choice_head(hidden_states, mc_token_ids).squeeze(-1)\n\n mc_loss = None\n if mc_labels is not None:\n loss_fct = CrossEntropyLoss()\n mc_loss = loss_fct(mc_logits.view(-1, mc_logits.size(-1)), mc_labels.view(-1))\n lm_loss = None\n if labels is not None:\n shift_logits = lm_logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n loss_fct = CrossEntropyLoss()\n lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\n\n if not return_dict:\n output = (lm_logits, mc_logits) + transformer_outputs[1:]\n if mc_loss is not None:\n output = (mc_loss,) + output\n return ((lm_loss,) + output) if lm_loss is not None else output\n\n return GPT2DoubleHeadsModelOutput(\n lm_loss=lm_loss,\n mc_loss=mc_loss,\n lm_logits=lm_logits,\n mc_logits=mc_logits,\n past_key_values=transformer_outputs.past_key_values,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )\n" ]
[ [ "torch.nn.Softmax", "torch.nn.Dropout", "torch.nn.CrossEntropyLoss", "torch.ones", "torch.cat", "torch.from_numpy", "torch.nn.Embedding", "torch.nn.LayerNorm", "tensorflow.train.load_variable", "torch.nn.Linear", "torch.matmul", "torch.tensor", "torch.arange", "tensorflow.train.list_variables" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
louis2889184/sg2im
[ "6df2095bf58703c7d6d74bf47535a7cf45690bc0" ]
[ "scripts/pl_sequence_train.py" ]
[ "import os\nimport json\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom collections import OrderedDict\n\nfrom sg2im.utils import timeit, bool_flag, LossManager\nfrom sg2im.utils import int_tuple, float_tuple, str_tuple\nfrom sg2im.data.vg import SequenceTransformerVgSceneGraphDataset\n\nimport pytorch_lightning as pl\nfrom transformers import (\n BertTokenizerFast, \n BertTokenizer, \n EncoderDecoderModel, \n EncoderDecoderConfig, \n AutoModel,\n BertForSequenceClassification,\n)\n\nfrom pytorch_lightning.plugins import DDPPlugin\n\n\nVG_DIR = os.path.expanduser('datasets/vg')\nCOCO_DIR = os.path.expanduser('datasets/coco')\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--test', action='store_true', default=False)\nparser.add_argument('--dataset', default='coco', choices=['vg', 'coco'])\nparser.add_argument('--scene_graphs_json', default='scene_graphs/figure_6_sheep.json')\nparser.add_argument('--load_checkpoint', default=\"\")\n\n# Optimization hyperparameters\nparser.add_argument('--batch_size', default=32, type=int)\nparser.add_argument('--num_iterations', default=1000000, type=int)\nparser.add_argument('--learning_rate', default=1e-5, type=float)\nparser.add_argument('--gpus', default=1, type=int)\n\n# Switch the generator to eval mode after this many iterations\nparser.add_argument('--eval_mode_after', default=100000, type=int)\n\n# Dataset options common to both VG and COCO\nparser.add_argument('--image_size', default='64,64', type=int_tuple)\nparser.add_argument('--num_train_samples', default=None, type=int)\nparser.add_argument('--num_val_samples', default=1024, type=int)\nparser.add_argument('--shuffle_val', default=True, type=bool_flag)\nparser.add_argument('--loader_num_workers', default=4, type=int)\nparser.add_argument('--include_relationships', default=True, type=bool_flag)\n\n# VG-specific options\nparser.add_argument('--vg_image_dir', default=os.path.join(VG_DIR, 'images'))\nparser.add_argument('--train_h5', default=os.path.join(VG_DIR, 'train.h5'))\nparser.add_argument('--val_h5', default=os.path.join(VG_DIR, 'val.h5'))\nparser.add_argument('--vocab_json', default=os.path.join(VG_DIR, 'vocab.json'))\nparser.add_argument('--max_objects_per_image', default=10, type=int)\nparser.add_argument('--vg_use_orphaned_objects', default=True, type=bool_flag)\n\n# COCO-specific options\nparser.add_argument('--coco_train_image_dir',\n default=os.path.join(COCO_DIR, 'images/train2017'))\nparser.add_argument('--coco_val_image_dir',\n default=os.path.join(COCO_DIR, 'images/val2017'))\nparser.add_argument('--coco_train_instances_json',\n default=os.path.join(COCO_DIR, 'annotations/instances_train2017.json'))\nparser.add_argument('--coco_train_stuff_json',\n default=os.path.join(COCO_DIR, 'annotations/stuff_train2017.json'))\nparser.add_argument('--coco_val_instances_json',\n default=os.path.join(COCO_DIR, 'annotations/instances_val2017.json'))\nparser.add_argument('--coco_val_stuff_json',\n default=os.path.join(COCO_DIR, 'annotations/stuff_val2017.json'))\nparser.add_argument('--instance_whitelist', default=None, type=str_tuple)\nparser.add_argument('--stuff_whitelist', default=None, type=str_tuple)\nparser.add_argument('--coco_include_other', default=False, type=bool_flag)\nparser.add_argument('--min_object_size', default=0.02, type=float)\nparser.add_argument('--min_objects_per_image', default=3, type=int)\nparser.add_argument('--coco_stuff_only', default=True, type=bool_flag)\nparser.add_argument('--max_lengths_for_image', default=1024, type=int)\n\n# Generator options\nparser.add_argument('--mask_size', default=16, type=int) # Set this to 0 to use no masks\nparser.add_argument('--embedding_dim', default=128, type=int)\nparser.add_argument('--gconv_dim', default=128, type=int)\nparser.add_argument('--gconv_hidden_dim', default=512, type=int)\nparser.add_argument('--gconv_num_layers', default=5, type=int)\nparser.add_argument('--mlp_normalization', default='none', type=str)\nparser.add_argument('--refinement_network_dims', default='1024,512,256,128,64', type=int_tuple)\nparser.add_argument('--normalization', default='batch')\nparser.add_argument('--activation', default='leakyrelu-0.2')\nparser.add_argument('--layout_noise_dim', default=32, type=int)\nparser.add_argument('--use_boxes_pred_after', default=-1, type=int)\n\n# Generator losses\nparser.add_argument('--mask_loss_weight', default=0, type=float)\nparser.add_argument('--l1_pixel_loss_weight', default=1.0, type=float)\nparser.add_argument('--bbox_pred_loss_weight', default=10, type=float)\nparser.add_argument('--predicate_pred_loss_weight', default=0, type=float) # DEPRECATED\n\n# Generic discriminator options\nparser.add_argument('--discriminator_loss_weight', default=0.01, type=float)\nparser.add_argument('--gan_loss_type', default='gan')\nparser.add_argument('--d_clip', default=None, type=float)\nparser.add_argument('--d_normalization', default='batch')\nparser.add_argument('--d_padding', default='valid')\nparser.add_argument('--d_activation', default='leakyrelu-0.2')\n\n# Object discriminator\nparser.add_argument('--d_obj_arch',\n default='C4-64-2,C4-128-2,C4-256-2')\nparser.add_argument('--crop_size', default=32, type=int)\nparser.add_argument('--d_obj_weight', default=1.0, type=float) # multiplied by d_loss_weight \nparser.add_argument('--ac_loss_weight', default=0.1, type=float)\n\n# Image discriminator\nparser.add_argument('--d_img_arch',\n default='C4-64-2,C4-128-2,C4-256-2')\nparser.add_argument('--d_img_weight', default=1.0, type=float) # multiplied by d_loss_weight\n\n# Output options\nparser.add_argument('--print_every', default=10, type=int)\nparser.add_argument('--timing', default=False, type=bool_flag)\nparser.add_argument('--checkpoint_every', default=10000, type=int)\nparser.add_argument('--output_dir', default=os.getcwd())\nparser.add_argument('--checkpoint_name', default='checkpoint')\nparser.add_argument('--checkpoint_start_from', default=None)\nparser.add_argument('--restore_from_checkpoint', default=False, type=bool_flag)\n\n\nclass VGDataModule(pl.LightningDataModule):\n\n def __init__(self, args, tokenizer, num_workers=8):\n super().__init__()\n self.args = args\n self.tokenizer = tokenizer\n self.num_workers = num_workers\n self.batch_size = args.batch_size\n\n def setup(self, stage=None):\n args = self.args\n with open(args.vocab_json, 'r') as f:\n vocab = json.load(f)\n dset_kwargs = {\n 'vocab': vocab,\n 'h5_path': args.train_h5,\n 'image_dir': args.vg_image_dir,\n 'image_size': args.image_size,\n 'max_samples': args.num_train_samples,\n 'max_objects': args.max_objects_per_image,\n 'use_orphaned_objects': args.vg_use_orphaned_objects,\n 'include_relationships': args.include_relationships,\n 'max_lengths_for_image': args.max_lengths_for_image\n }\n train_dset = SequenceTransformerVgSceneGraphDataset(\n **dset_kwargs, tokenizer=self.tokenizer\n )\n # iter_per_epoch = len(train_dset) // args.batch_size\n # print('There are %d iterations per epoch' % iter_per_epoch)\n\n dset_kwargs['h5_path'] = args.val_h5\n del dset_kwargs['max_samples']\n\n val_dset = SequenceTransformerVgSceneGraphDataset(\n **dset_kwargs, tokenizer=self.tokenizer\n )\n self.train_dset = train_dset\n self.val_dset = val_dset\n\n def train_dataloader(self):\n return DataLoader(\n self.train_dset, batch_size=self.batch_size, num_workers=self.num_workers, shuffle=True\n )\n\n def val_dataloader(self):\n return DataLoader(self.val_dset, batch_size=self.batch_size, num_workers=self.num_workers)\n\n def test_dataloader(self):\n return DataLoader(self.val_dset, batch_size=self.batch_size, num_workers=self.num_workers)\n\n\nclass Discriminator(nn.Module):\n def __init__(self, backbone):\n super().__init__()\n self.backbone = BertForSequenceClassification.from_pretrained(backbone)\n \n def forward(self, *args, **kwargs):\n outputs = self.backbone(*args, **kwargs)\n\n return outputs[\"loss\"]\n\n def apply_word_embeddings(self, inputs):\n \"\"\"\n Because Gumbel softmax outputs cannot directly feed to huggingface model,\n we have to compute the `input_embed` manually.\n \"\"\"\n word_embeddings = self.backbone.bert.embeddings.word_embeddings\n\n return torch.matmul(inputs, word_embeddings.weight)\n\n\nclass Generator(nn.Module):\n def __init__(self, backbone):\n super().__init__()\n self.backbone = EncoderDecoderModel.from_encoder_decoder_pretrained(\n backbone, backbone, tie_encoder_decoder=True\n )\n\n def forward(self, *args, **kwargs):\n return self.backbone(*args, **kwargs)\n\n def forward_logits(self, *args, **kwargs):\n return self.backbone(*args, **kwargs)[\"logits\"]\n\n def forward_loss(self, *args, **kwargs):\n return self.backbone(*args, **kwargs)[\"loss\"]\n\n def apply_word_embeddings(self, inputs):\n \"\"\"\n Because Gumbel softmax outputs cannot directly feed to huggingface model,\n we have to compute the `input_embed` manually.\n \"\"\"\n word_embeddings = self.backbone.encoder.embeddings.word_embeddings\n\n return torch.matmul(inputs, word_embeddings.weight)\n\n\nclass GAN(pl.LightningModule):\n\n def __init__(\n self,\n args,\n tokenizer,\n backbone=None,\n ):\n super().__init__()\n\n self.args = args\n\n self.validation_z = torch.randn(8, 100)\n self.tokenizer = tokenizer\n self.discriminator = Discriminator(backbone)\n self.generator = Generator(backbone)\n\n self.graph_special_token = \"[graph]\"\n self.image_special_token = \"[image]\"\n\n self.tau = 1\n\n self.image_token_id_list, self.text_token_id_list = self.retrieve_bad_image_text_tokens_ids()\n\n def retrieve_bad_image_text_tokens_ids(self):\n special_tokens_list = [\"[CLS]\", \"[SEP]\"]\n image_tokens_list = [f\"[itoken{i}]\" for i in range(512)]\n extra_image_tokens_list = [f\"[itoken{i}]\" for i in range(512, 32 * 32)]\n \n vocab = self.tokenizer.get_vocab()\n\n special_tokens_id_list = [vocab[token] for token in special_tokens_list]\n image_token_id_list = [vocab[token] for token in image_tokens_list]\n extra_image_tokens_id_list = [vocab[token] for token in extra_image_tokens_list]\n text_token_id_list = [v for k, v in vocab.items()]\n\n text_token_id_list = \\\n list(set(text_token_id_list) - set(image_token_id_list) - set(extra_image_tokens_id_list))\n\n return image_token_id_list + extra_image_tokens_id_list, text_token_id_list + extra_image_tokens_id_list\n\n def adversarial_loss(self, y_hat, y):\n return F.binary_cross_entropy_with_logits(y_hat, y)\n\n def training_step(self, batch, batch_idx, optimizer_idx):\n # sample noise\n # z = torch.randn(imgs.shape[0], self.hparams.latent_dim)\n # z = z.type_as(imgs)\n\n generator_batch = {\n \"input_ids\": batch[\"sent_input/input_ids\"],\n \"attention_mask\": batch[\"sent_input/attention_mask\"],\n \"decoder_input_ids\": batch[\"code_output/input_ids\"],\n \"decoder_attention_mask\": batch[\"code_output/attention_mask\"],\n \"labels\": batch[\"code_output/input_ids\"].clone()\n }\n\n # exlude the loss for padding tokens\n generator_batch[\"labels\"][generator_batch[\"labels\"] == self.tokenizer.pad_token_id] = -100\n\n # train generator\n if optimizer_idx == 0:\n logits = self.generator.forward_logits(**generator_batch)\n\n predictions = F.gumbel_softmax(logits, tau=self.tau, hard=True, dim=-1)\n\n # log sampled images\n # sample_imgs = self.generated_imgs[:6]\n # grid = torchvision.utils.make_grid(sample_imgs)\n # self.logger.experiment.add_image('generated_images', grid, 0)\n\n # ground truth result (ie: all fake)\n # put on GPU because we created this tensor inside training_loop\n\n predictions_embedding = self.generator.apply_word_embeddings(predictions)\n\n fake_batch = {\n \"inputs_embeds\": predictions_embedding,\n \"attention_mask\": batch[\"code_output/attention_mask\"],\n \"decoder_input_ids\": batch[\"sent_output/input_ids\"],\n \"decoder_attention_mask\": batch[\"sent_output/attention_mask\"],\n \"labels\": batch[\"sent_output/input_ids\"].clone()\n }\n\n fake_batch[\"labels\"][fake_batch[\"labels\"] == self.tokenizer.pad_token_id] = -100\n\n ac_loss = self.generator.forward_loss(**fake_batch)\n\n predictions_embedding = self.discriminator.apply_word_embeddings(predictions)\n\n fake_dis_batch = {\n \"inputs_embeds\": predictions_embedding,\n \"attention_mask\": batch[\"code_output/attention_mask\"],\n \"labels\": torch.ones(predictions_embedding.shape[0]).type_as(predictions_embedding).long()\n }\n\n g_d_loss = self.discriminator(**fake_dis_batch)\n\n g_loss = g_d_loss + ac_loss\n # g_loss = ac_loss\n\n self.log('g_ac_loss', ac_loss, prog_bar=True)\n self.log('g_d_loss', g_d_loss, prog_bar=True)\n\n # return {\"loss\": g_loss}\n # train discriminator (inverse generator)\n # if optimizer_idx == 1:\n # Measure discriminator's ability to classify real from generated samples\n logits = self.generator.forward_logits(**generator_batch)\n\n predictions = F.gumbel_softmax(logits, tau=self.tau, hard=True, dim=-1)\n\n # don't compute the gradients of the generator\n predictions = predictions.detach()\n\n predictions_embedding = self.generator.apply_word_embeddings(predictions)\n\n fake_batch = {\n \"inputs_embeds\": predictions_embedding,\n \"attention_mask\": batch[\"code_output/attention_mask\"],\n \"decoder_input_ids\": batch[\"sent_output/input_ids\"],\n \"decoder_attention_mask\": batch[\"sent_output/attention_mask\"],\n \"labels\": batch[\"sent_output/input_ids\"].clone()\n }\n\n fake_batch[\"labels\"][fake_batch[\"labels\"] == self.tokenizer.pad_token_id] = -100\n\n fake_ac_loss = self.generator.forward_loss(**fake_batch)\n\n # For real data\n real_batch = {\n \"input_ids\": batch[\"code_output/input_ids\"],\n \"attention_mask\": batch[\"code_output/attention_mask\"],\n \"decoder_input_ids\": batch[\"sent_output/input_ids\"],\n \"decoder_attention_mask\": batch[\"sent_output/attention_mask\"],\n \"labels\": batch[\"sent_output/input_ids\"].clone()\n }\n\n real_batch[\"labels\"][real_batch[\"labels\"] == self.tokenizer.pad_token_id] = -100\n\n real_ac_loss = self.generator.forward_loss(**real_batch)\n\n ac_loss = (real_ac_loss + fake_ac_loss) / 2\n\n self.log('ac_loss', ac_loss, prog_bar=True)\n # return {\"loss\": ac_loss}\n return g_loss + ac_loss\n\n # train discriminator\n if optimizer_idx == 1:\n # Measure discriminator's ability to classify real from generated samples\n\n logits = self.generator.forward_logits(**generator_batch)\n\n # don't compute the gradients of the generator\n predictions = F.gumbel_softmax(logits, tau=self.tau, hard=True, dim=-1)\n\n predictions_embedding = self.discriminator.apply_word_embeddings(predictions)\n\n fake_dis_batch = {\n \"inputs_embeds\": predictions_embedding,\n \"attention_mask\": batch[\"code_output/attention_mask\"],\n \"labels\": torch.zeros(predictions.shape[0]).type_as(predictions).long()\n }\n\n fake_loss = self.discriminator(**fake_dis_batch)\n\n # fake = torch.zeros(fake_preds.shape)\n # fake = fake.type_as(fake_preds)\n\n # fake_loss = self.adversarial_loss(fake_preds, fake)\n\n real_dis_batch = {\n \"input_ids\": batch[\"code_output/input_ids\"],\n \"attention_mask\": batch[\"code_output/attention_mask\"],\n \"labels\": torch.ones(predictions.shape[0]).type_as(predictions).long()\n }\n\n real_loss = self.discriminator(**real_dis_batch)\n\n # real = torch.ones(real_preds.shape)\n # real = real.type_as(real_preds)\n\n # real_loss = self.adversarial_loss(real_preds, real)\n\n # discriminator loss is the average of these\n d_loss = (real_loss + fake_loss) / 2\n\n self.log('d_loss', d_loss, prog_bar=True)\n return d_loss\n\n def configure_optimizers(self):\n lr = self.args.learning_rate\n\n opt_g = torch.optim.Adam(self.generator.parameters(), lr=lr, betas=(0.5, 0.999))\n opt_d = torch.optim.Adam(\n self.discriminator.parameters(), \n lr=lr, \n betas=(0.5, 0.999)\n )\n return [opt_g, opt_d], []\n\n # def on_epoch_end(self):\n # z = self.validation_z.type_as(self.generator.model[0].weight)\n\n # # log sampled images\n # sample_imgs = self(z)\n # grid = torchvision.utils.make_grid(sample_imgs)\n # self.logger.experiment.add_image('generated_images', grid, self.current_epoch)\n\n def test_step(self, batch, batch_idx):\n pass\n\n def inference(self, scene_graphs_json):\n scene_graphs = self.read_scene_graphs(scene_graphs_json)\n\n image_tokens_generation = self.generator.backbone.generate(\n scene_graphs[\"input_ids\"], \n max_length=66, \n # num_beams=5, \n # no_repeat_ngram_size=2, \n # early_stopping=True,\n do_sample=True,\n top_p=0.92, \n top_k=0,\n decoder_start_token_id=self.generator.backbone.config.decoder.pad_token_id,\n bad_words_ids=[[ids] for ids in self.text_token_id_list],\n )\n\n print(image_tokens_generation)\n\n output = []\n\n for data in image_tokens_generation:\n output.append(self.tokenizer.decode(data, skip_special_tokens=True))\n print(output[-1])\n\n reconstructed_graph = self.generator.backbone.generate(\n image_tokens_generation, \n max_length=64, \n # num_beams=5, \n # no_repeat_ngram_size=2, \n # early_stopping=True,\n do_sample=True,\n top_p=0.92, \n top_k=0,\n decoder_start_token_id=self.generator.backbone.config.decoder.pad_token_id,\n bad_words_ids=[[ids]for ids in self.image_token_id_list],\n )\n\n for data in reconstructed_graph:\n print(self.tokenizer.decode(data, skip_special_tokens=True))\n\n \n if not os.path.exists(self.args.output_dir):\n os.makedirs(self.args.output_dir)\n itokens_output_file = os.path.join(self.args.output_dir, \"itokens_output.json\")\n\n with open(itokens_output_file, \"w\") as f:\n json.dump(output, f, indent=2)\n\n def read_scene_graphs(self, scene_graphs_json):\n with open(scene_graphs_json, 'r') as f:\n scene_graphs = json.load(f)\n\n if isinstance(scene_graphs, dict):\n # We just got a single scene graph, so promote it to a list\n scene_graphs = [scene_graphs]\n\n objs, triples, obj_to_img = [], [], []\n obj_offset = 0\n sents_list = []\n for i, sg in enumerate(scene_graphs):\n # Insert dummy __image__ object and __in_image__ relationships\n sents = []\n for s, p, o in sg['relationships']:\n sent = f\"{sg['objects'][s]} {p} {sg['objects'][o]}.\"\n sents.append(sent)\n\n sent = \" \".join(sents)\n sent = f\"{self.graph_special_token} {sent} {self.image_special_token}\"\n\n sents_list.append(sent)\n\n print(sent)\n \n sent_tensor = self.tokenizer(\n sents_list, \n return_tensors=\"pt\", \n padding=\"max_length\", \n max_length=64, \n truncation=True,\n add_special_tokens=False\n )\n\n device = next(self.parameters()).device\n sent_tensor = {k: v.to(device) for k, v in sent_tensor.items()}\n\n return sent_tensor\n\n\ndef main(args):\n backbone = \"bert-base-uncased-itokens\"\n tokenizer = BertTokenizerFast.from_pretrained(backbone)\n\n # encoder_decoder_config = EncoderDecoderConfig.from_pretrained(\"bert-base-uncased-itokens\")\n # model = EncoderDecoderModel.from_pretrained(\n # \"bert-base-uncased-itokens\", config=encoder_decoder_config\n # )\n\n # model = EncoderDecoderModel.from_encoder_decoder_pretrained(\n # \"bert-base-uncased-itokens\", \"bert-base-uncased-itokens\", tie_encoder_decoder=True\n # )\n\n # generator = Generator(model)\n\n # discriminator = Discriminator(\n # AutoModel.from_pretrained(\"bert-base-uncased-itokens\")\n # )\n\n if args.test:\n model = GAN.load_from_checkpoint(\n args.load_checkpoint,\n args=args, \n tokenizer=tokenizer, \n backbone=backbone\n )\n model.cuda()\n model.eval()\n\n model.inference(args.scene_graphs_json)\n \n return\n \n # train\n if args.gpus > 1:\n dm = VGDataModule(args, tokenizer, 2)\n else:\n dm = VGDataModule(args, tokenizer)\n\n if args.load_checkpoint != \"\":\n model = GAN.load_from_checkpoint(\n args.load_checkpoint, \n args=args, \n tokenizer=tokenizer, \n backbone=backbone\n )\n else:\n model = GAN(args, tokenizer, backbone)\n\n training_args = {\n \"gpus\": args.gpus,\n \"fast_dev_run\": False,\n \"max_steps\": args.num_iterations,\n \"precision\": 32,\n \"gradient_clip_val\": 1,\n }\n\n if args.gpus > 1:\n additional_args = {\n \"accelerator\": \"ddp\",\n \"plugins\": [DDPPlugin(find_unused_parameters=True)]\n # \"plugins\": [my_ddp]\n }\n\n training_args.update(additional_args)\n\n trainer = pl.Trainer(**training_args)\n trainer.fit(model, dm)\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n main(args)" ]
[ [ "torch.nn.functional.gumbel_softmax", "torch.ones", "torch.zeros", "torch.randn", "torch.nn.functional.binary_cross_entropy_with_logits", "torch.utils.data.DataLoader", "torch.matmul" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mpharrigan/OpenFermion
[ "ae5bbaed60faa019fae9d47d6e578933874e074d", "ae5bbaed60faa019fae9d47d6e578933874e074d" ]
[ "src/openfermion/utils/_grid.py", "src/openfermion/utils/_davidson.py" ]
[ "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport itertools\nimport numpy\nimport scipy\nimport scipy.linalg\n\n\n# Exceptions.\nclass OrbitalSpecificationError(Exception):\n pass\n\n\nclass Grid:\n \"\"\"\n A multi-dimension grid of points with an assigned length scale.\n\n This grid acts as a helper class for parallelpiped super cells. It\n tracks a mapping from indices to grid points and stores the associated\n reciprocal lattice with respect to the original real-space lattice.\n This enables calculations with non-trivial unit cells.\n\n Attributes:\n dimensions (int): Number of spatial dimensions the grid occupys\n length (tuple of ints): d-length tuple specifying number of points\n along each dimension.\n shifts (list of ints): Integer shifts in position to center grid.\n scale (ndarray): Vectors defining the super cell being simulated,\n vectors are stored as columns in the matrix.\n volume (float): Total volume of the supercell parallelpiped.\n num_points (int): Total number of points in the grid.\n reciprocal_scale (ndarray): Vectors defining the reciprocal lattice.\n The vectors are stored as the columns in the matrix.\n \"\"\"\n\n def __init__(self, dimensions, length, scale):\n \"\"\"\n Args:\n dimensions (int): The number of dimensions the grid lives in.\n length (int or tuple): The number of points along each grid axis\n that will be taken in both reciprocal and real space.\n If tuple, it is read for each dimension, otherwise assumed\n uniform.\n scale (float or ndarray): The total length of each grid dimension.\n If a float is passed, the uniform cubic unit cell is assumed.\n For an ndarray, dimensions independent vectors of the correct\n dimension must be passed. We assume column vectors define\n the supercell vectors.\n \"\"\"\n if not isinstance(dimensions, int) or dimensions <= 0:\n raise ValueError(\n 'dimensions must be a positive int but was {} {}'.format(\n type(dimensions), repr(dimensions)))\n if ((not isinstance(length, int) or length < 0) and\n (not isinstance(length, tuple)) and\n (not isinstance(length, list))):\n raise ValueError(\n 'length must be a non-negative int or tuple '\n 'but was {} {}'.format(\n type(length), repr(length)))\n if ((not isinstance(scale, float) or not scale > 0) and\n (not isinstance(scale, numpy.ndarray))):\n raise ValueError(\n 'scale must be a positive float or ndarray but was '\n '{} {}'.format(\n type(scale), repr(scale)))\n\n self.dimensions = dimensions\n\n # If single integer, assume uniform\n if isinstance(length, int):\n self.length = (length, ) * dimensions\n else:\n self.length = length\n\n self.shifts = [self.length[i] // 2 for i in range(dimensions)]\n\n # If single float, construct cubic unit cell\n if isinstance(scale, float):\n self.scale = numpy.diag([scale] * self.dimensions)\n else:\n self.scale = scale\n\n # Compute the volume of the super cell\n self.volume = numpy.abs(scipy.linalg.det(self.scale))\n\n # Compute total number of points\n self.num_points = numpy.prod(self.length)\n\n # Compute the reciprocal lattice basis\n self.reciprocal_scale = 2 * numpy.pi * scipy.linalg.inv(self.scale).T\n\n def volume_scale(self):\n \"\"\"\n Returns:\n float: The volume of a length-scale hypercube within the grid.\n \"\"\"\n return self.volume\n\n def all_points_indices(self):\n \"\"\"\n Returns:\n iterable[tuple[int]]:\n The index-coordinate tuple of each point in the grid.\n \"\"\"\n return itertools.product(*[range(self.length[i])\n for i in range(self.dimensions)])\n\n def position_vector(self, position_indices):\n \"\"\"Given grid point coordinate, return position vector with dimensions.\n\n Args:\n position_indices (int|iterable[int]):\n List or tuple of integers giving grid point coordinate.\n Allowed values are ints in [0, grid_length).\n\n Returns:\n position_vector (numpy.ndarray[float])\n \"\"\"\n # Raise exceptions.\n if isinstance(position_indices, int):\n position_indices = [position_indices]\n if not all(0 <= e < self.length[i]\n for i, e in enumerate(position_indices)):\n raise OrbitalSpecificationError(\n 'Position indices must be integers in [0, grid_length).')\n\n # Compute position vector\n vector = sum([(float(n - self.shifts[i]) /\n self.length[i]) * self.scale[:, i]\n for i, n in enumerate(position_indices)])\n return vector\n\n def momentum_vector(self, momentum_indices, periodic=True):\n \"\"\"Given grid point coordinate, return momentum vector with dimensions.\n\n Args:\n momentum_indices (list): integers giving momentum\n indices. Allowed values are ints in [0, grid_length).\n periodic (bool): Wrap the momentum indices according to periodicity\n\n Returns:\n momentum_vector: A numpy array giving the momentum vector with\n dimensions.\n \"\"\"\n # Raise exceptions.\n if isinstance(momentum_indices, int):\n momentum_indices = [momentum_indices]\n if (not all(0 <= e < self.length[i]\n for i, e in enumerate(momentum_indices))):\n raise OrbitalSpecificationError(\n 'Momentum indices must be integers in [0, grid_length).')\n\n # Compute momentum vector.\n momentum_ints = self.index_to_momentum_ints(momentum_indices)\n vector = self.momentum_ints_to_value(momentum_ints, periodic)\n\n return vector\n\n def index_to_momentum_ints(self, index):\n \"\"\"\n Args:\n index (tuple): d-dimensional tuple specifying index in the grid\n Returns:\n Integer momentum vector\n \"\"\"\n # Set baseline for grid between [-N//2, N//2]\n momentum_int = [index[i] - self.shifts[i]\n for i in range(self.dimensions)]\n\n return numpy.array(momentum_int, dtype=int)\n\n def momentum_ints_to_index(self, momentum_ints):\n \"\"\"\n Args:\n momentum_ints (tuple): d-dimensional tuple momentum integers\n Returns:\n d-dimensional tuples of indices\n \"\"\"\n\n indices = momentum_ints\n\n # Shift to indices\n indices = [n + self.shifts[i] for i, n in enumerate(indices)]\n\n # Wrap dimensions\n indices = [n % self.length[i] for i, n in enumerate(indices)]\n\n return indices\n\n def momentum_ints_to_value(self, momentum_ints, periodic=True):\n \"\"\"\n Args:\n momentum_ints (tuple): d-dimensional tuple momentum integers\n periodic (bool): Alias the momentum\n Returns:\n ndarray containing the momentum vector.\n\n \"\"\"\n # Alias the higher momentum modes\n if periodic:\n momentum_ints = self.index_to_momentum_ints(\n self.momentum_ints_to_index(momentum_ints))\n\n momentum_vector = sum([n * self.reciprocal_scale[:, i]\n for i, n in enumerate(momentum_ints)])\n return momentum_vector\n\n def orbital_id(self, grid_coordinates, spin=None):\n \"\"\"Return the tensor factor of a orbital with given coordinates and spin.\n\n Args:\n grid_coordinates: List or tuple of ints giving coordinates of grid\n element. Acceptable to provide an int(instead of tuple or list)\n for 1D case.\n spin (bool): 0 means spin down and 1 means spin up.\n If None, assume spinless model.\n\n Returns:\n tensor_factor (int):\n tensor factor associated with provided orbital label.\n \"\"\"\n # Initialize.\n if isinstance(grid_coordinates, int):\n grid_coordinates = [grid_coordinates]\n\n # Loop through dimensions of coordinate tuple.\n tensor_factor = 0\n for dimension, grid_coordinate in enumerate(grid_coordinates):\n\n # Make sure coordinate is an integer in the correct bounds.\n if (isinstance(grid_coordinate, int) and\n grid_coordinate < self.length[dimension]):\n tensor_factor += (grid_coordinate *\n int(numpy.product(self.length[:dimension])))\n else:\n # Raise for invalid model.\n raise OrbitalSpecificationError(\n 'Invalid orbital coordinates provided.')\n\n # Account for spin and return.\n if spin is None:\n return tensor_factor\n else:\n tensor_factor *= 2\n tensor_factor += spin\n return tensor_factor\n\n def grid_indices(self, qubit_id, spinless):\n \"\"\"This function is the inverse of orbital_id.\n\n Args:\n qubit_id (int): The tensor factor to map to grid indices.\n spinless (bool): Whether to use the spinless model or not.\n\n Returns:\n grid_indices (numpy.ndarray[int]):\n The location of the qubit on the grid.\n \"\"\"\n if not (numpy.product(self.length) * (2 - spinless) > qubit_id >= 0):\n raise OrbitalSpecificationError('Invalid qubit_id provided.')\n\n # Remove spin degree of freedom if it exists.\n orbital_id = qubit_id\n\n if not spinless:\n orbital_id //= 2\n\n # Get grid indices.\n grid_indices = []\n for dimension in range(self.dimensions):\n remainder = (orbital_id %\n int(numpy.product(self.length[:dimension + 1])))\n grid_index = (remainder //\n int(numpy.product(self.length[:dimension])))\n grid_indices += [grid_index]\n return grid_indices\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return (self.dimensions == other.dimensions and\n (self.scale == other.scale).all() and\n self.length == other.length)\n\n def __ne__(self, other):\n return not self == other\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\"\"\"This module is to find lowest eigenvalues with Davidson algorithm.\"\"\"\n\nimport logging\nimport warnings\n\nimport numpy\nimport numpy.linalg\nimport scipy\nimport scipy.linalg\nimport scipy.sparse\nimport scipy.sparse.linalg\n\nfrom openfermion.utils._sparse_tools import get_linear_qubit_operator_diagonal\nfrom openfermion.utils._linear_qubit_operator import generate_linear_qubit_operator\n\nclass DavidsonError(Exception):\n \"\"\"Exceptions.\"\"\"\n pass\n\n\nclass DavidsonOptions(object):\n \"\"\"Davidson algorithm iteration options.\"\"\"\n\n def __init__(self, max_subspace=100, max_iterations=300, eps=1e-6,\n real_only=False):\n \"\"\"\n Args:\n max_subspace(int): Max number of vectors in the auxiliary subspace.\n max_iterations(int): Max number of iterations.\n eps(float): The max error for eigen vector error's elements during\n iterations: linear_operator * v - v * lambda.\n real_only(bool): Desired eigenvectors are real only or not. When one\n specifies the real_only to be true but it only has complex ones,\n no matter it converges or not, the returned vectors will be\n complex.\n \"\"\"\n if max_subspace <= 2 or max_iterations <= 0 or eps <= 0:\n raise ValueError('Invalid values for max_subspace, max_iterations '\n 'and/ or eps: ({}, {}, {}).'.format(\n max_subspace, max_iterations, eps))\n\n self.max_subspace = max_subspace\n self.max_iterations = max_iterations\n self.eps = eps\n self.real_only = real_only\n\n def set_dimension(self, dimension):\n \"\"\"\n Args:\n dimension(int): Dimension of the matrix, which sets a upper limit on\n the work space.\n \"\"\"\n if dimension <= 0:\n raise ValueError('Invalid dimension: {}).'.format(dimension))\n self.max_subspace = min(self.max_subspace, dimension + 1)\n\n\nclass Davidson(object):\n \"\"\"Davidson algorithm to get the n states with smallest eigenvalues.\"\"\"\n\n def __init__(self, linear_operator, linear_operator_diagonal, options=None):\n \"\"\"\n Args:\n linear_operator(scipy.sparse.linalg.LinearOperator): The linear\n operator which defines a dot function when applying on a vector.\n linear_operator_diagonal(numpy.ndarray): The linear operator's\n diagonal elements.\n options(DavidsonOptions): Iteration options.\n \"\"\"\n if options is None:\n options = DavidsonOptions()\n\n if not isinstance(linear_operator,\n (scipy.sparse.linalg.LinearOperator,\n scipy.sparse.spmatrix)):\n raise ValueError(\n 'linear_operator is not a LinearOperator: {}.'.format(type(\n linear_operator)))\n\n self.linear_operator = linear_operator\n self.linear_operator_diagonal = linear_operator_diagonal\n\n self.options = options\n self.options.set_dimension(len(linear_operator_diagonal))\n\n def get_lowest_n(self, n_lowest=1, initial_guess=None, max_iterations=None):\n \"\"\"\n Returns `n` smallest eigenvalues and corresponding eigenvectors for\n linear_operator.\n\n Args:\n n(int): The number of states corresponding to the smallest eigenvalues\n and associated eigenvectors for the linear_operator.\n initial_guess(numpy.ndarray[complex]): Initial guess of eigenvectors\n associated with the `n` smallest eigenvalues.\n max_iterations(int): Max number of iterations when not converging.\n\n Returns:\n success(bool): Indicates whether it converged, i.e. max elementwise\n error is smaller than eps.\n eigen_values(numpy.ndarray[complex]): The smallest n eigenvalues.\n eigen_vectors(numpy.ndarray[complex]): The smallest n eigenvectors\n corresponding with those eigen values.\n \"\"\"\n # Goes through a few checks and preprocessing before iterative\n # diagonalization.\n\n # 1. Checks for number of states desired, should be in the range of\n # [0, max_subspace).\n if n_lowest <= 0 or n_lowest >= self.options.max_subspace:\n raise ValueError('n_lowest {} is supposed to be in [1, {}).'.format(\n n_lowest, self.options.max_subspace))\n\n # 2. Checks for initial guess vectors' dimension is the same to that of\n # the operator.\n if initial_guess is None:\n initial_guess = generate_random_vectors(\n len(self.linear_operator_diagonal), n_lowest,\n real_only=self.options.real_only)\n if initial_guess.shape[0] != len(self.linear_operator_diagonal):\n raise ValueError('Guess vectors have a different dimension with '\n 'linear opearator diagonal elements: {} != {}.'\n .format(initial_guess.shape[1],\n len(self.linear_operator_diagonal)))\n\n # 3. Makes sure real guess vector if real_only is specified.\n if self.options.real_only:\n if not numpy.allclose(numpy.real(initial_guess), initial_guess):\n warnings.warn('Initial guess is not real only!', RuntimeWarning)\n initial_guess = numpy.real(initial_guess)\n\n # 4. Checks for non-trivial (non-zero) initial guesses.\n if numpy.max(numpy.abs(initial_guess)) < self.options.eps:\n raise ValueError('Guess vectors are all zero! {}'.format(\n initial_guess.shape))\n initial_guess = scipy.linalg.orth(initial_guess)\n\n # 5. Makes sure number of initial guess vector is at least n_lowest.\n if initial_guess.shape[1] < n_lowest:\n initial_guess = append_random_vectors(\n initial_guess, n_lowest - initial_guess.shape[1],\n real_only=self.options.real_only)\n\n success = False\n num_iterations = 0\n guess_v = initial_guess\n guess_mv = None\n max_iterations = max_iterations or self.options.max_iterations\n while (num_iterations < max_iterations and not success):\n (eigen_values, eigen_vectors, mat_eigen_vectors, max_trial_error,\n guess_v, guess_mv) = self._iterate(n_lowest, guess_v, guess_mv)\n logging.info(\"Eigenvalues for iteration %d: %s, error is %f.\",\n num_iterations, eigen_values, max_trial_error)\n\n if max_trial_error < self.options.eps:\n success = True\n break\n\n # Make sure it keeps real components only.\n if self.options.real_only:\n guess_v = numpy.real(guess_v)\n\n # Deals with new directions to make sure they're orthonormal.\n # Also makes sure there're new directions added for the next\n # iteration, if not, add n_lowest random vectors.\n count_mvs = guess_mv.shape[1]\n guess_v = orthonormalize(guess_v, count_mvs, self.options.eps)\n if guess_v.shape[1] <= count_mvs:\n guess_v = append_random_vectors(guess_v, n_lowest,\n real_only=self.options.real_only)\n\n\n # Limits number of vectors to self.options.max_subspace, in this\n # case, keep the following:\n # 1) first n_lowest eigen_vectors;\n # 2) first n_lowest matrix multiplication result for eigen_vectors;\n #\n # 3) new search directions which will be used for improvement for\n # the next iteration.\n if guess_v.shape[1] >= self.options.max_subspace:\n guess_v = numpy.hstack([\n eigen_vectors,\n guess_v[:, count_mvs:],\n ])\n guess_mv = mat_eigen_vectors\n\n if self.options.real_only:\n if (not numpy.allclose(numpy.real(guess_v), guess_v) or\n not numpy.allclose(numpy.real(guess_mv), guess_mv)):\n # Forces recalculation for matrix multiplication with\n # vectors.\n guess_mv = None\n\n num_iterations += 1\n\n if (self.options.real_only and\n not numpy.allclose(numpy.real(eigen_vectors), eigen_vectors)):\n warnings.warn('Unable to get real only eigenvectors, return '\n 'complex vectors instead with success state {}.'\n .format(success), RuntimeWarning)\n return success, eigen_values, eigen_vectors\n\n def _iterate(self, n_lowest, guess_v, guess_mv=None):\n \"\"\"One iteration with guess vectors.\n\n Args:\n n_lowest(int): The first n_lowest number of eigenvalues and\n eigenvectors one is interested in.\n guess_v(numpy.ndarray(complex)): Guess eigenvectors associated with\n the smallest eigenvalues.\n guess_mv(numpy.ndarray(complex)): Matrix applied on guess_v,\n therefore they should have the same dimension.\n\n Returns:\n trial_lambda(numpy.ndarray(float)): The minimal eigenvalues based on\n guess eigenvectors.\n trial_v(numpy.ndarray(complex)): New guess eigenvectors.\n trial_mv(numpy.ndarray(complex)): New guess eigenvectors' matrix\n multiplication result.\n max_trial_error(float): The max elementwise error for all guess\n vectors.\n\n guess_v(numpy.ndarray(complex)): Cached guess eigenvectors to avoid\n recalculation for the next iterations.\n guess_mv(numpy.ndarray(complex)): Cached guess vectors which is the\n matrix product of linear_operator with guess_v.\n \"\"\"\n if guess_mv is None:\n guess_mv = self.linear_operator.dot(guess_v)\n dimension = guess_v.shape[1]\n\n # Note that getting guess_mv is the most expensive step.\n if guess_mv.shape[1] < dimension:\n guess_mv = numpy.hstack([guess_mv, self.linear_operator.dot(\n guess_v[:, guess_mv.shape[1] : dimension])])\n guess_vmv = numpy.dot(guess_v.conj().T, guess_mv)\n\n # Gets new set of eigenvalues and eigenvectors in the vmv space, with a\n # smaller dimension which is the number of vectors in guess_v.\n #\n # Note that we don't get the eigenvectors directly, instead we only get\n # a transformation based on the raw vectors, so that mv don't need to be\n # recalculated.\n trial_lambda, trial_transformation = numpy.linalg.eigh(guess_vmv)\n\n # Sorts eigenvalues in ascending order.\n sorted_index = list(reversed(trial_lambda.argsort()[::-1]))\n trial_lambda = trial_lambda[sorted_index]\n trial_transformation = trial_transformation[:, sorted_index]\n\n if len(trial_lambda) > n_lowest:\n trial_lambda = trial_lambda[:n_lowest]\n trial_transformation = trial_transformation[:, :n_lowest]\n\n # Estimates errors based on diagonalization in the smaller space.\n trial_v = numpy.dot(guess_v, trial_transformation)\n trial_mv = numpy.dot(guess_mv, trial_transformation)\n trial_error = trial_mv - trial_v * trial_lambda\n\n new_directions, max_trial_error = self._get_new_directions(\n trial_error, trial_lambda, trial_v)\n if new_directions:\n guess_v = numpy.hstack([guess_v, numpy.stack(new_directions).T])\n return (trial_lambda, trial_v, trial_mv, max_trial_error,\n guess_v, guess_mv)\n\n def _get_new_directions(self, error_v, trial_lambda, trial_v):\n \"\"\"Gets new directions from error vectors.\n\n Args:\n error_v(numpy.ndarray(complex)): Error vectors from the guess\n eigenvalues and associated eigenvectors.\n trial_lambda(numpy.ndarray(float)): The n_lowest minimal guess\n eigenvalues.\n trial_v(numpy.ndarray(complex)): Guess eigenvectors associated with\n trial_lambda.\n\n Returns:\n new_directions(numpy.ndarray(complex)): New directions for searching\n for real eigenvalues and eigenvectors.\n max_trial_error(float): The max elementwise error for all guess\n vectors.\n \"\"\"\n n_lowest = error_v.shape[1]\n\n max_trial_error = 0\n # Adds new guess vectors for the next iteration for the first n_lowest\n # directions.\n origonal_dimension = error_v.shape[0]\n\n new_directions = []\n for i in range(n_lowest):\n current_error_v = error_v[:, i]\n\n if numpy.max(numpy.abs(current_error_v)) < self.options.eps:\n # Already converged for this eigenvector, no contribution to\n # search for new directions.\n continue\n\n max_trial_error = max(max_trial_error, numpy.linalg.norm(current_error_v))\n diagonal_inverse = numpy.ones(origonal_dimension)\n for j in range(origonal_dimension):\n # Makes sure error vectors are bounded.\n diff_lambda = self.linear_operator_diagonal[j] - trial_lambda[i]\n if numpy.abs(diff_lambda) > self.options.eps:\n diagonal_inverse[j] /= diff_lambda\n else:\n diagonal_inverse[j] /= self.options.eps\n diagonal_inverse_error = diagonal_inverse * current_error_v\n diagonal_inverse_trial = diagonal_inverse * trial_v[:, i]\n new_direction = -current_error_v + (trial_v[:, i] * numpy.dot(\n trial_v[:, i].conj(), diagonal_inverse_error) / numpy.dot(\n trial_v[:, i].conj(), diagonal_inverse_trial))\n\n new_directions.append(new_direction)\n return new_directions, max_trial_error\n\n\nclass QubitDavidson(Davidson):\n \"\"\"Davidson algorithm applied to a QubitOperator.\"\"\"\n\n def __init__(self, qubit_operator, n_qubits=None, options=None):\n \"\"\"\n Args:\n qubit_operator(QubitOperator): A qubit operator which is a linear\n operator as well.\n n_qubits(int): Number of qubits.\n options(DavidsonOptions): Iteration options.\n \"\"\"\n super(QubitDavidson, self).__init__(\n generate_linear_qubit_operator(qubit_operator, n_qubits, options),\n get_linear_qubit_operator_diagonal(qubit_operator, n_qubits),\n options=options)\n\n\nclass SparseDavidson(Davidson):\n \"\"\"Davidson algorithm for a sparse matrix.\"\"\"\n\n def __init__(self, sparse_matrix, options=None):\n \"\"\"\n Args:\n sparse_matrix(scipy.sparse.spmatrix): A sparse matrix in scipy.\n options(DavidsonOptions): Iteration options.\n \"\"\"\n super(SparseDavidson, self).__init__(\n sparse_matrix, sparse_matrix.diagonal(), options=options)\n\n\ndef generate_random_vectors(row, col, real_only=False):\n \"\"\"Generates orthonormal random vectors with col columns.\n\n Args:\n row(int): Number of rows for the vectors.\n col(int): Number of columns for the vectors.\n real_only(bool): Real vectors or complex ones.\n\n Returns:\n random_vectors(numpy.ndarray(complex)): Orthonormal random vectors.\n \"\"\"\n random_vectors = numpy.random.rand(row, col)\n if not real_only:\n random_vectors = random_vectors + numpy.random.rand(row, col) * 1.0j\n random_vectors = scipy.linalg.orth(random_vectors)\n return random_vectors\n\n\ndef append_random_vectors(vectors, col, max_trial=3, real_only=False):\n \"\"\"Appends exactly col orthonormal random vectors for vectors.\n\n Assumes vectors is already orthonormal.\n\n Args:\n vectors(numpy.ndarray(complex)): Orthonormal original vectors to be\n appended.\n col(int): Number of columns to be appended.\n real_only(bool): Real vectors or complex ones.\n\n Returns:\n vectors(numpy.ndarray(complex)): Orthonormal vectors with n columns.\n \"\"\"\n if col <= 0:\n return vectors\n\n vector_columns = vectors.shape[1]\n total_columns = min(vector_columns + col, vectors.shape[0] + 1)\n\n num_trial = 0\n while vector_columns < total_columns:\n num_trial += 1\n\n vectors = numpy.hstack([vectors, generate_random_vectors(\n vectors.shape[0], total_columns - vector_columns, real_only)])\n vectors = orthonormalize(vectors, vector_columns)\n\n # Checks whether there are any new vectors added successfully.\n if vectors.shape[1] == vector_columns:\n if num_trial > max_trial:\n warnings.warn('Unable to generate specified number of random '\n 'vectors {}: returning {} in total.'.format(\n col, vector_columns), RuntimeWarning)\n break\n else:\n num_trial = 1\n vector_columns = vectors.shape[1]\n return vectors\n\ndef orthonormalize(vectors, num_orthonormals=1, eps=1e-6):\n \"\"\"Orthonormalize vectors, so that they're all normalized and orthogoal.\n\n The first vector is the same to that of vectors, while vector_i is\n orthogonal to vector_j, where j < i.\n\n Args:\n vectors(numpy.ndarray(complex)): Input vectors to be\n orthonormalized.\n num_orthonormals(int): First `num_orthonormals` columns are already\n orthonormal, so that one doesn't need to make any changes.\n eps(float): criterion of elements' max absolute value for zero vectors.\n\n Returns:\n ortho_normals(numpy.ndarray(complex)): Output orthonormal vectors.\n \"\"\"\n ortho_normals = vectors\n count_orthonormals = num_orthonormals\n # Skip unchanged ones.\n for i in range(num_orthonormals, vectors.shape[1]):\n vector_i = vectors[:, i]\n # Makes sure vector_i is orthogonal to all processed vectors.\n for j in range(i):\n vector_i -= ortho_normals[:, j] * numpy.dot(\n ortho_normals[:, j].conj(), vector_i)\n\n # Makes sure vector_i is normalized.\n if numpy.max(numpy.abs(vector_i)) < eps:\n continue\n ortho_normals[:, count_orthonormals] = (vector_i /\n numpy.linalg.norm(vector_i))\n count_orthonormals += 1\n return ortho_normals[:, :count_orthonormals]\n" ]
[ [ "numpy.diag", "numpy.product", "scipy.linalg.det", "numpy.prod", "scipy.linalg.inv", "numpy.array" ], [ "numpy.dot", "numpy.hstack", "numpy.abs", "numpy.linalg.norm", "numpy.stack", "numpy.ones", "numpy.real", "numpy.linalg.eigh", "scipy.linalg.orth", "numpy.random.rand" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.12", "0.14", "0.15" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.14", "0.15", "0.12", "0.10" ], "tensorflow": [] } ]
profxj/ginga
[ "a5f447b760ac38dafa52181b3f99156545a6f2e7", "a5f447b760ac38dafa52181b3f99156545a6f2e7", "a5f447b760ac38dafa52181b3f99156545a6f2e7", "a5f447b760ac38dafa52181b3f99156545a6f2e7" ]
[ "ginga/canvas/transform.py", "ginga/qtw/CanvasRenderQt.py", "ginga/tests/test_trcalc.py", "ginga/canvas/types/astro.py" ]
[ "#\n# transform.py -- coordinate transforms for Ginga\n#\n# This is open-source software licensed under a BSD license.\n# Please see the file LICENSE.txt for details.\n#\nimport numpy as np\n\nfrom ginga import trcalc\nfrom ginga.misc import Bunch\n\n__all__ = ['TransformError', 'BaseTransform', 'ComposedTransform',\n 'InvertedTransform', 'PassThruTransform',\n 'WindowNativeTransform', 'CartesianWindowTransform',\n 'CartesianNativeTransform',\n 'RotationTransform', 'ScaleTransform',\n 'DataCartesianTransform', 'OffsetDataTransform',\n 'WCSDataTransform', 'get_catalog'\n ]\n\n\nclass TransformError(Exception):\n pass\n\n\nclass BaseTransform(object):\n\n def __init__(self):\n super(BaseTransform, self).__init__()\n\n def to_(self, x, y):\n raise TransformError(\"subclass should override this method\")\n\n def from_(self, tx, ty):\n raise TransformError(\"subclass should override this method\")\n\n def __add__(self, trans):\n return ComposedTransform(self, trans)\n\n def invert(self):\n return InvertedTransform(self)\n\n\nclass ComposedTransform(BaseTransform):\n \"\"\"\n A transform that composes two other transforms to make a new one.\n \"\"\"\n\n def __init__(self, tform1, tform2):\n super(ComposedTransform, self).__init__()\n self.tform1 = tform1\n self.tform2 = tform2\n\n def to_(self, pts, **kwargs):\n return self.tform2.to_(self.tform1.to_(pts, **kwargs))\n\n def from_(self, pts, **kwargs):\n return self.tform1.from_(self.tform2.from_(pts), **kwargs)\n\n\nclass InvertedTransform(BaseTransform):\n \"\"\"\n A transform that inverts another transform.\n \"\"\"\n\n def __init__(self, tform):\n super(InvertedTransform, self).__init__()\n self.tform = tform\n\n def to_(self, pts, **kwargs):\n return self.tform.from_(pts, **kwargs)\n\n def from_(self, pts, **kwargs):\n return self.tform.to_(pts, **kwargs)\n\n\nclass PassThruTransform(BaseTransform):\n \"\"\"\n A transform that essentially acts as a no-op.\n \"\"\"\n\n def __init__(self, viewer):\n super(PassThruTransform, self).__init__()\n\n def to_(self, pts, **kwargs):\n return pts\n\n def from_(self, pts, **kwargs):\n return pts\n\n\nclass WindowNativeTransform(BaseTransform):\n \"\"\"\n A transform from a typical window standard coordinate space with the\n upper left at (0, 0) to the viewer back end native pixel space.\n \"\"\"\n\n def __init__(self, viewer):\n super(WindowNativeTransform, self).__init__()\n self.viewer = viewer\n\n def to_(self, win_pts):\n if self.viewer.origin_upper:\n return win_pts\n\n win_pts = np.asarray(win_pts)\n has_z = (win_pts.shape[-1] > 2)\n\n # invert Y coord for backends that have the origin in the lower left\n win_wd, win_ht = self.viewer.get_window_size()\n\n # win_x, win_y = cvs_x, win_ht - cvs_y\n mpy_pt = [1.0, -1.0]\n if has_z:\n mpy_pt.append(1.0)\n\n add_pt = [0.0, win_ht]\n if has_z:\n add_pt.append(0.0)\n\n ntv_pts = np.add(np.multiply(win_pts, mpy_pt), add_pt)\n\n return ntv_pts\n\n def from_(self, ntv_pts):\n return self.to_(ntv_pts)\n\n\nclass WindowPercentageTransform(BaseTransform):\n \"\"\"\n A transform from standard window coordinates of a viewer\n to percentage coordinates.\n \"\"\"\n\n def __init__(self, viewer, as_int=True):\n super(WindowPercentageTransform, self).__init__()\n self.viewer = viewer\n self.as_int = as_int\n\n def to_(self, win_pts):\n win_pts = np.asarray(win_pts, dtype=np.float)\n has_z = (win_pts.shape[-1] > 2)\n\n max_pt = list(self.viewer.get_window_size())\n if has_z:\n max_pt.append(0.0)\n\n pct_pts = np.divide(win_pts, max_pt)\n return pct_pts\n\n def from_(self, pct_pts):\n \"\"\"Reverse of :meth:`to_`.\"\"\"\n pct_pts = np.asarray(pct_pts, dtype=np.float)\n has_z = (pct_pts.shape[-1] > 2)\n\n max_pt = list(self.viewer.get_window_size())\n if has_z:\n max_pt.append(0.0)\n\n win_pts = np.multiply(pct_pts, max_pt)\n\n # round to pixel units, if asked\n if self.as_int:\n win_pts = np.rint(win_pts).astype(np.int, copy=False)\n\n return win_pts\n\n\nclass CartesianWindowTransform(BaseTransform):\n \"\"\"\n A transform from cartesian coordinates to standard window coordinates\n of a viewer.\n \"\"\"\n\n def __init__(self, viewer, as_int=True):\n super(CartesianWindowTransform, self).__init__()\n self.viewer = viewer\n self.as_int = as_int\n\n def to_(self, off_pts):\n # add center pixel to convert from X/Y coordinate space to\n # window graphics space\n off_pts = np.asarray(off_pts, dtype=np.float)\n has_z = (off_pts.shape[-1] > 2)\n\n ctr_pt = list(self.viewer.get_center())\n if has_z:\n ctr_pt.append(0.0)\n\n # win_x = off_x + ctr_x\n # win_y = ctr_y - off_y\n mpy_pt = [1.0, -1.0]\n if has_z:\n mpy_pt.append(1.0)\n\n win_pts = np.add(np.multiply(off_pts, mpy_pt), ctr_pt)\n\n # round to pixel units, if asked\n if self.as_int:\n win_pts = np.rint(win_pts).astype(np.int, copy=False)\n\n return win_pts\n\n def from_(self, win_pts):\n \"\"\"Reverse of :meth:`to_`.\"\"\"\n # make relative to center pixel to convert from window\n # graphics space to standard X/Y coordinate space\n win_pts = np.asarray(win_pts, dtype=np.float)\n has_z = (win_pts.shape[-1] > 2)\n\n ctr_pt = list(self.viewer.get_center())\n if has_z:\n ctr_pt.append(0.0)\n\n mpy_pt = [1.0, -1.0]\n if has_z:\n mpy_pt.append(1.0)\n\n # off_x = win_x - ctr_x\n # = win_x + -ctr_x\n # off_y = ctr_y - win_y\n # = -win_y + ctr_y\n ctr_pt[0] = -ctr_pt[0]\n off_pts = np.add(np.multiply(win_pts, mpy_pt), ctr_pt)\n\n return off_pts\n\n\nclass CartesianNativeTransform(BaseTransform):\n \"\"\"\n A transform from cartesian coordinates to the native pixel coordinates\n of a viewer.\n \"\"\"\n\n def __init__(self, viewer, as_int=True):\n super(CartesianNativeTransform, self).__init__()\n self.viewer = viewer\n self.as_int = as_int\n\n def to_(self, off_pts):\n # add center pixel to convert from X/Y coordinate space to\n # back end graphics space\n off_pts = np.asarray(off_pts, dtype=np.float)\n has_z = (off_pts.shape[-1] > 2)\n\n ctr_pt = list(self.viewer.get_center())\n if has_z:\n ctr_pt.append(0.0)\n\n if self.viewer.origin_upper:\n mpy_pt = [1.0, -1.0]\n else:\n mpy_pt = [1.0, 1.0]\n\n if has_z:\n mpy_pt.append(1.0)\n\n win_pts = np.add(np.multiply(off_pts, mpy_pt), ctr_pt)\n\n # round to pixel units, if asked\n if self.as_int:\n win_pts = np.rint(win_pts).astype(np.int, copy=False)\n\n return win_pts\n\n def from_(self, win_pts):\n \"\"\"Reverse of :meth:`to_`.\"\"\"\n # make relative to center pixel to convert from back end\n # graphics space to standard X/Y coordinate space\n win_pts = np.asarray(win_pts, dtype=np.float)\n has_z = (win_pts.shape[-1] > 2)\n\n ctr_pt = list(self.viewer.get_center())\n if has_z:\n ctr_pt.append(0.0)\n\n ctr_pt[0] = -ctr_pt[0]\n if self.viewer.origin_upper:\n mpy_pt = [1.0, -1.0]\n else:\n ctr_pt[1] = -ctr_pt[1]\n mpy_pt = [1.0, 1.0]\n\n if has_z:\n mpy_pt.append(1.0)\n\n off_pts = np.add(np.multiply(win_pts, mpy_pt), ctr_pt)\n\n return off_pts\n\n\nclass RotationTransform(BaseTransform):\n \"\"\"\n A transform in cartesian coordinates based on the flip/swap setting and\n rotation setting of a viewer.\n \"\"\"\n\n def __init__(self, viewer):\n super(RotationTransform, self).__init__()\n self.viewer = viewer\n\n def to_(self, off_pts):\n off_pts = np.asarray(off_pts, dtype=np.float)\n has_z = (off_pts.shape[-1] > 2)\n\n t_ = self.viewer.t_\n\n # flip\n flip_pt = [1.0, 1.0]\n if t_['flip_x']:\n flip_pt[0] = -1.0\n if t_['flip_y']:\n flip_pt[1] = -1.0\n if has_z:\n # no flip_z at the moment\n flip_pt.append(1.0)\n\n off_pts = np.multiply(off_pts, flip_pt)\n\n # swap\n if t_['swap_xy']:\n p = list(off_pts.T)\n off_pts = np.asarray([p[1], p[0]] + list(p[2:])).T\n\n # rotate\n if t_['rot_deg'] != 0:\n thetas = [t_['rot_deg']]\n offset = [0.0, 0.0]\n if has_z:\n offset.append(0.0)\n off_pts = trcalc.rotate_coord(off_pts, thetas, offset)\n\n return off_pts\n\n def from_(self, off_pts):\n \"\"\"Reverse of :meth:`to_`.\"\"\"\n off_pts = np.asarray(off_pts, dtype=np.float)\n has_z = (off_pts.shape[-1] > 2)\n\n t_ = self.viewer.t_\n\n # rotate\n if t_['rot_deg'] != 0:\n thetas = [- t_['rot_deg']]\n offset = [0.0, 0.0]\n if has_z:\n offset.append(0.0)\n off_pts = trcalc.rotate_coord(off_pts, thetas, offset)\n\n # swap\n if t_['swap_xy']:\n p = list(off_pts.T)\n off_pts = np.asarray([p[1], p[0]] + list(p[2:])).T\n\n # flip\n flip_pt = [1.0, 1.0]\n if t_['flip_x']:\n flip_pt[0] = -1.0\n if t_['flip_y']:\n flip_pt[1] = -1.0\n if has_z:\n # no flip_z at the moment\n flip_pt.append(1.0)\n\n off_pts = np.multiply(off_pts, flip_pt)\n\n return off_pts\n\n\nclass ScaleTransform(BaseTransform):\n \"\"\"\n A transform in cartesian coordinates based on the scale of a viewer.\n \"\"\"\n\n def __init__(self, viewer):\n super(ScaleTransform, self).__init__()\n self.viewer = viewer\n\n def to_(self, off_pts):\n \"\"\"Reverse of :meth:`from_`.\"\"\"\n off_pts = np.asarray(off_pts, dtype=np.float)\n has_z = (off_pts.shape[-1] > 2)\n\n # scale according to current settings\n scale_pt = [self.viewer._org_scale_x, self.viewer._org_scale_y]\n if has_z:\n scale_pt.append(self.viewer._org_scale_z)\n\n off_pts = np.multiply(off_pts, scale_pt)\n return off_pts\n\n def from_(self, off_pts):\n off_pts = np.asarray(off_pts, dtype=np.float)\n has_z = (off_pts.shape[-1] > 2)\n\n scale_pt = [1.0 / self.viewer._org_scale_x,\n 1.0 / self.viewer._org_scale_y]\n if has_z:\n scale_pt.append(1.0 / self.viewer._org_scale_z)\n\n # Reverse scaling\n off_pts = np.multiply(off_pts, scale_pt)\n return off_pts\n\n\nclass DataCartesianTransform(BaseTransform):\n \"\"\"\n A transform from data coordinates to cartesian coordinates based on\n a viewer's pan position.\n \"\"\"\n\n def __init__(self, viewer, use_center=True):\n super(DataCartesianTransform, self).__init__()\n self.viewer = viewer\n # If use_center is True, then the coordinates are mapped such that the\n # pixel is centered on the square when the image is zoomed in past\n # 1X. This is the specification of the FITS image standard,\n # that the pixel is centered on the integer row/column.\n self.use_center = use_center\n\n def to_(self, data_pts):\n \"\"\"Reverse of :meth:`from_`.\"\"\"\n data_pts = np.asarray(data_pts, dtype=np.float)\n has_z = (data_pts.shape[-1] > 2)\n\n if self.use_center:\n data_pts = data_pts - self.viewer.data_off\n\n # subtract data indexes at center reference pixel\n ref_pt = [self.viewer._org_x, self.viewer._org_y]\n if has_z:\n ref_pt.append(self.viewer._org_z)\n\n off_pts = np.subtract(data_pts, ref_pt)\n return off_pts\n\n def from_(self, off_pts):\n off_pts = np.asarray(off_pts, dtype=np.float)\n has_z = (off_pts.shape[-1] > 2)\n\n # Add data index at center to offset\n # subtract data indexes at center reference pixel\n ref_pt = [self.viewer._org_x, self.viewer._org_y]\n if has_z:\n ref_pt.append(self.viewer._org_z)\n\n data_pts = np.add(off_pts, ref_pt)\n\n if self.use_center:\n data_pts = data_pts + self.viewer.data_off\n\n return data_pts\n\n\nclass OffsetDataTransform(BaseTransform):\n \"\"\"\n A transform whose coordinate space is offsets from a point in\n data space.\n \"\"\"\n\n def __init__(self, pt):\n super(OffsetDataTransform, self).__init__()\n self.pt = pt\n\n def to_(self, delta_pts):\n delta_x, delta_y = np.asarray(delta_pts, dtype=np.float).T\n ref_x, ref_y = self.pt[:2]\n res_x, res_y = ref_x + delta_x, ref_y + delta_y\n return np.asarray((res_x, res_y)).T\n\n def from_(self, data_pts):\n data_x, data_y = np.asarray(data_pts, dtype=np.float).T\n ref_x, ref_y = self.pt[:2]\n res_x, res_y = data_x - ref_x, data_y - ref_y\n return np.asarray((res_x, res_y)).T\n\n\nclass WCSDataTransform(BaseTransform):\n \"\"\"\n A transform whose coordinate space is based on the WCS of the primary\n image loaded in a viewer.\n \"\"\"\n\n def __init__(self, viewer):\n super(WCSDataTransform, self).__init__()\n self.viewer = viewer\n\n def to_(self, wcs_pts):\n wcs_pts = np.asarray(wcs_pts)\n\n # hack to work around passing singleton pt vs. array of pts\n unpack = False\n if len(wcs_pts.shape) < 2:\n # passed a single coordinate\n wcs_pts = np.asarray([wcs_pts])\n unpack = True\n\n image = self.viewer.get_image()\n if image is None:\n raise TransformError(\"No image, no WCS\")\n wcs = image.wcs\n if wcs is None:\n raise TransformError(\"No valid WCS found in image\")\n\n naxispath = image.naxispath\n\n res = wcs.wcspt_to_datapt(wcs_pts, naxispath=naxispath)\n if unpack:\n return res[0]\n return res\n\n def from_(self, data_pts):\n data_pts = np.asarray(data_pts)\n\n # hack to work around passing singleton pt vs. array of pts\n unpack = False\n if len(data_pts.shape) < 2:\n # passed a single coordinate\n data_pts = np.asarray([data_pts])\n unpack = True\n\n image = self.viewer.get_image()\n if image is None:\n raise TransformError(\"No image, no WCS\")\n wcs = image.wcs\n if wcs is None:\n raise TransformError(\"No valid WCS found in image\")\n\n naxispath = image.naxispath\n\n res = wcs.datapt_to_wcspt(data_pts, naxispath=naxispath)\n if unpack:\n return res[0]\n return res\n\n\ndef get_catalog():\n \"\"\"Returns a catalog of available transforms. These are used to\n build chains for rendering with different back ends.\n \"\"\"\n tforms = {}\n for name, value in list(globals().items()):\n if name.endswith('Transform'):\n tforms[name] = value\n\n return Bunch.Bunch(tforms, caseless=True)\n\n#END\n", "#\n# CanvasRenderQt.py -- for rendering into a ImageViewQt widget\n#\n# This is open-source software licensed under a BSD license.\n# Please see the file LICENSE.txt for details.\n#\nimport numpy as np\n\nfrom ginga.qtw.QtHelp import (QtCore, QPen, QPolygon, QColor,\n QPainterPath, QImage, QPixmap, get_font,\n get_painter)\n\nfrom ginga import colors\nfrom ginga.canvas import render\n# force registration of all canvas types\nimport ginga.canvas.types.all # noqa\n\n\nclass RenderContext(render.RenderContextBase):\n\n def __init__(self, renderer, viewer, surface):\n render.RenderContextBase.__init__(self, renderer, viewer)\n\n self.cr = get_painter(surface)\n\n def __get_color(self, color, alpha):\n clr = QColor()\n if isinstance(color, tuple):\n clr.setRgbF(color[0], color[1], color[2], alpha)\n else:\n r, g, b = colors.lookup_color(color)\n clr.setRgbF(r, g, b, alpha)\n return clr\n\n def set_line_from_shape(self, shape):\n pen = QPen()\n pen.setWidthF(getattr(shape, 'linewidth', 1.0))\n\n if hasattr(shape, 'linestyle'):\n if shape.linestyle == 'dash':\n pen.setDashPattern([3.0, 4.0, 6.0, 4.0])\n pen.setDashOffset(5.0)\n\n alpha = getattr(shape, 'alpha', 1.0)\n color = self.__get_color(shape.color, alpha)\n pen.setColor(color)\n self.cr.setPen(pen)\n\n def set_fill_from_shape(self, shape):\n fill = getattr(shape, 'fill', False)\n if fill:\n if hasattr(shape, 'fillcolor') and shape.fillcolor:\n color = shape.fillcolor\n else:\n color = shape.color\n\n if color is None:\n self.cr.setBrush(QtCore.Qt.NoBrush)\n else:\n alpha = getattr(shape, 'alpha', None)\n fillalpha = getattr(shape, 'fillalpha', alpha)\n color = self.__get_color(color, fillalpha)\n self.cr.setBrush(color)\n else:\n self.cr.setBrush(QtCore.Qt.NoBrush)\n\n def set_font_from_shape(self, shape):\n if hasattr(shape, 'font'):\n if (hasattr(shape, 'fontsize') and shape.fontsize is not None and\n not getattr(shape, 'fontscale', False)):\n fontsize = shape.fontsize\n else:\n fontsize = shape.scale_font(self.viewer)\n fontsize = self.scale_fontsize(fontsize)\n font = get_font(shape.font, fontsize)\n self.cr.setFont(font)\n\n def initialize_from_shape(self, shape, line=True, fill=True, font=True):\n if line:\n self.set_line_from_shape(shape)\n if fill:\n self.set_fill_from_shape(shape)\n if font:\n self.set_font_from_shape(shape)\n\n def set_line(self, color, alpha=1.0, linewidth=1, style='solid'):\n clr = self.__get_color(color, alpha)\n pen = self.cr.pen()\n pen.setColor(clr)\n pen.setWidthF(float(linewidth))\n if style == 'dash':\n pen.setDashPattern([3.0, 4.0, 6.0, 4.0])\n pen.setDashOffset(5.0)\n self.cr.setPen(pen)\n\n def set_fill(self, color, alpha=1.0):\n if color is None:\n self.cr.setBrush(QtCore.Qt.NoBrush)\n else:\n color = self.__get_color(color, alpha)\n self.cr.setBrush(color)\n\n def set_font(self, fontname, fontsize, color='black', alpha=1.0):\n self.set_line(color, alpha=alpha)\n fontsize = self.scale_fontsize(fontsize)\n font = get_font(fontname, fontsize)\n self.cr.setFont(font)\n\n def text_extents(self, text):\n fm = self.cr.fontMetrics()\n width = fm.width(text)\n height = fm.height()\n return width, height\n\n ##### DRAWING OPERATIONS #####\n\n def draw_text(self, cx, cy, text, rot_deg=0.0):\n self.cr.save()\n self.cr.translate(cx, cy)\n self.cr.rotate(-rot_deg)\n\n self.cr.drawText(0, 0, text)\n\n self.cr.restore()\n\n def draw_polygon(self, cpoints):\n qpoints = [QtCore.QPoint(p[0], p[1]) for p in cpoints]\n p = cpoints[0]\n qpoints.append(QtCore.QPoint(p[0], p[1]))\n qpoly = QPolygon(qpoints)\n\n self.cr.drawPolygon(qpoly)\n\n def draw_circle(self, cx, cy, cradius):\n # this is necessary to work around a bug in Qt--radius of 0\n # causes a crash\n cradius = max(cradius, 0.000001)\n pt = QtCore.QPointF(cx, cy)\n self.cr.drawEllipse(pt, float(cradius), float(cradius))\n\n def draw_bezier_curve(self, cp):\n path = QPainterPath()\n path.moveTo(cp[0][0], cp[0][1])\n path.cubicTo(cp[1][0], cp[1][1], cp[2][0], cp[2][1], cp[3][0], cp[3][1])\n self.cr.drawPath(path)\n\n def draw_ellipse_bezier(self, cp):\n # draw 4 bezier curves to make the ellipse\n path = QPainterPath()\n path.moveTo(cp[0][0], cp[0][1])\n path.cubicTo(cp[1][0], cp[1][1], cp[2][0], cp[2][1], cp[3][0], cp[3][1])\n path.cubicTo(cp[4][0], cp[4][1], cp[5][0], cp[5][1], cp[6][0], cp[6][1])\n path.cubicTo(cp[7][0], cp[7][1], cp[8][0], cp[8][1], cp[9][0], cp[9][1])\n path.cubicTo(cp[10][0], cp[10][1], cp[11][0], cp[11][1], cp[12][0], cp[12][1])\n self.cr.drawPath(path)\n\n def draw_line(self, cx1, cy1, cx2, cy2):\n self.cr.pen().setCapStyle(QtCore.Qt.RoundCap)\n self.cr.drawLine(cx1, cy1, cx2, cy2)\n\n def draw_path(self, cp):\n self.cr.pen().setCapStyle(QtCore.Qt.RoundCap)\n pts = [QtCore.QLineF(QtCore.QPointF(cp[i][0], cp[i][1]),\n QtCore.QPointF(cp[i + 1][0], cp[i + 1][1]))\n for i in range(len(cp) - 1)]\n self.cr.drawLines(pts)\n\n\nclass CanvasRenderer(render.RendererBase):\n\n def __init__(self, viewer, surface_type='qimage'):\n render.RendererBase.__init__(self, viewer)\n\n self.kind = 'qt'\n # Qt needs this to be in BGRA\n self.rgb_order = 'BGRA'\n self.qimg_fmt = QImage.Format_RGB32\n self.surface_type = surface_type\n # the offscreen drawing surface\n self.surface = None\n\n def resize(self, dims):\n \"\"\"Resize our drawing area to encompass a space defined by the\n given dimensions.\n \"\"\"\n width, height = dims[:2]\n self.logger.debug(\"renderer reconfigured to %dx%d\" % (\n width, height))\n if self.surface_type == 'qpixmap':\n self.surface = QPixmap(width, height)\n else:\n self.surface = QImage(width, height, self.qimg_fmt)\n\n # fill surface with background color;\n # this reduces unwanted garbage in the resizing window\n painter = get_painter(self.surface)\n size = self.surface.size()\n sf_wd, sf_ht = size.width(), size.height()\n bg = self.viewer.img_bg\n bgclr = self._get_color(*bg)\n painter.fillRect(QtCore.QRect(0, 0, sf_wd, sf_ht), bgclr)\n\n def _get_qimage(self, rgb_data):\n ht, wd, channels = rgb_data.shape\n\n result = QImage(rgb_data.data, wd, ht, self.qimg_fmt)\n # Need to hang on to a reference to the array\n result.ndarray = rgb_data\n return result\n\n def _get_color(self, r, g, b):\n # TODO: combine with the method from the RenderContext?\n n = 255.0\n clr = QColor(int(r * n), int(g * n), int(b * n))\n return clr\n\n def render_image(self, rgbobj, dst_x, dst_y):\n \"\"\"Render the image represented by (rgbobj) at dst_x, dst_y\n in the pixel space.\n *** internal method-- do not use ***\n \"\"\"\n self.logger.debug(\"redraw surface=%s\" % (self.surface))\n if self.surface is None:\n return\n self.logger.debug(\"drawing to surface\")\n\n # Prepare array for rendering\n # TODO: what are options for high bit depth under Qt?\n data = rgbobj.get_array(self.rgb_order, dtype=np.uint8)\n (height, width) = data.shape[:2]\n\n daht, dawd, depth = data.shape\n self.logger.debug(\"data shape is %dx%dx%d\" % (dawd, daht, depth))\n\n # Get qimage for copying pixel data\n qimage = self._get_qimage(data)\n drawable = self.surface\n\n painter = get_painter(drawable)\n #painter.setWorldMatrixEnabled(True)\n\n # fill surface with background color\n size = drawable.size()\n sf_wd, sf_ht = size.width(), size.height()\n bg = self.viewer.img_bg\n bgclr = self._get_color(*bg)\n painter.fillRect(QtCore.QRect(0, 0, sf_wd, sf_ht), bgclr)\n\n # draw image data from buffer to offscreen pixmap\n painter.drawImage(QtCore.QRect(dst_x, dst_y, width, height),\n qimage,\n QtCore.QRect(0, 0, width, height))\n\n def get_surface_as_array(self, order=None):\n if self.surface_type == 'qpixmap':\n qimg = self.surface.toImage()\n else:\n qimg = self.surface\n #qimg = qimg.convertToFormat(QImage.Format_RGBA32)\n\n width, height = qimg.width(), qimg.height()\n\n if hasattr(qimg, 'bits'):\n # PyQt\n ptr = qimg.bits()\n ptr.setsize(qimg.byteCount())\n else:\n # PySide\n ptr = qimg.constBits()\n\n arr = np.array(ptr).reshape(height, width, 4)\n\n # adjust according to viewer's needed order\n return self.reorder(order, arr)\n\n def setup_cr(self, shape):\n cr = RenderContext(self, self.viewer, self.surface)\n cr.initialize_from_shape(shape, font=False)\n return cr\n\n def get_dimensions(self, shape):\n cr = self.setup_cr(shape)\n cr.set_font_from_shape(shape)\n return cr.text_extents(shape.text)\n\n\n#END\n", "\nimport numpy as np\n\nfrom ginga import trcalc\n\n\nclass TestTrcalc:\n\n def _2ddata(self):\n data = np.zeros((10, 10), dtype=np.int)\n for i in range(10):\n for j in range(10):\n data[i, j] = min(i, j)\n return data\n\n def _3ddata(self):\n data = np.zeros((10, 10, 10), dtype=np.int)\n for i in range(10):\n for j in range(10):\n for k in range(10):\n data[i, j, k] = min(i, j, k)\n return data\n\n def test_get_scaled_cutout_wdht_view(self):\n\n data = self._2ddata()\n p1 = (2, 2)\n p2 = (4, 4)\n nd = (8, 10)\n\n res = np.asarray([[2, 2, 2, 2, 2, 2, 2, 2],\n [2, 2, 2, 2, 2, 2, 2, 2],\n [2, 2, 2, 2, 2, 2, 2, 2],\n [2, 2, 2, 2, 2, 2, 2, 2],\n [2, 2, 2, 3, 3, 3, 3, 3],\n [2, 2, 2, 3, 3, 3, 3, 3],\n [2, 2, 2, 3, 3, 3, 3, 3],\n [2, 2, 2, 3, 3, 3, 4, 4],\n [2, 2, 2, 3, 3, 3, 4, 4],\n [2, 2, 2, 3, 3, 3, 4, 4]])\n\n view, scales = trcalc.get_scaled_cutout_wdht_view(data.shape,\n p1[0], p1[1],\n p2[0], p2[1],\n nd[0], nd[1])\n new_data = data[view]\n assert new_data.shape == (10, 8)\n assert np.allclose(new_data, res)\n\n def test_get_scaled_cutout_wdhtdp_view(self):\n\n data = self._3ddata()\n p1 = (0, 0, 0)\n p2 = (9, 9, 9)\n nd = (4, 4, 4)\n\n res = np.asarray([[[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]],\n\n [[0, 0, 0, 0],\n [0, 2, 2, 2],\n [0, 2, 2, 2],\n [0, 2, 2, 2]],\n\n [[0, 0, 0, 0],\n [0, 2, 2, 2],\n [0, 2, 5, 5],\n [0, 2, 5, 5]],\n\n [[0, 0, 0, 0],\n [0, 2, 2, 2],\n [0, 2, 5, 5],\n [0, 2, 5, 7]]])\n\n view, scales = trcalc.get_scaled_cutout_wdhtdp_view(data.shape,\n p1, p2, nd)\n new_data = data[view]\n assert new_data.shape == (4, 4, 4)\n assert np.allclose(new_data, res)\n", "#\n# astro.py -- classes for special astronomy shapes drawn on\n# ginga canvases.\n#\n# This is open-source software licensed under a BSD license.\n# Please see the file LICENSE.txt for details.\n#\n\nimport math\nimport numpy as np\n\nfrom ginga.AstroImage import AstroImage\nfrom ginga.canvas.CanvasObject import (CanvasObjectBase, _bool, _color,\n Point, MovePoint, ScalePoint,\n register_canvas_types, get_canvas_type,\n colors_plus_none, coord_names)\nfrom ginga.misc.ParamSet import Param\nfrom ginga.misc import Bunch\nfrom ginga.util import wcs\nfrom ginga.util.wcs import raDegToString, decDegToString\n\nfrom .mixins import (OnePointMixin, TwoPointMixin, OnePointOneRadiusMixin,\n OnePointTwoRadiusMixin)\nfrom .layer import CompoundObject\n\n__all__ = ['Ruler', 'Compass', 'Crosshair', 'AnnulusMixin', 'Annulus',\n 'Annulus2R', 'WCSAxes']\n\n\nclass RulerP(TwoPointMixin, CanvasObjectBase):\n \"\"\"\n Draws a WCS ruler (like a right triangle) on a DrawingCanvas.\n Parameters are:\n x1, y1: 0-based coordinates of one end of the diagonal in the data space\n x2, y2: 0-based coordinates of the opposite end of the diagonal\n Optional parameters for linesize, color, etc.\n \"\"\"\n\n @classmethod\n def get_params_metadata(cls):\n return [\n Param(name='coord', type=str, default='data',\n valid=coord_names,\n description=\"Set type of coordinates\"),\n Param(name='x1', type=float, default=0.0, argpos=0,\n description=\"First X coordinate of object\"),\n Param(name='y1', type=float, default=0.0, argpos=1,\n description=\"First Y coordinate of object\"),\n Param(name='x2', type=float, default=0.0, argpos=2,\n description=\"Second X coordinate of object\"),\n Param(name='y2', type=float, default=0.0, argpos=3,\n description=\"Second Y coordinate of object\"),\n Param(name='linewidth', type=int, default=1,\n min=1, max=20, widget='spinbutton', incr=1,\n description=\"Width of outline\"),\n Param(name='linestyle', type=str, default='solid',\n valid=['solid', 'dash'],\n description=\"Style of outline (default: solid)\"),\n Param(name='color',\n valid=colors_plus_none, type=_color, default='lightgreen',\n description=\"Color of outline\"),\n Param(name='showplumb', type=_bool,\n default=True, valid=[False, True],\n description=\"Show plumb lines for the ruler\"),\n Param(name='showends', type=_bool,\n default=False, valid=[False, True],\n description=\"Show begin and end values for the ruler\"),\n Param(name='color2',\n valid=colors_plus_none, type=_color, default='yellow',\n description=\"Second color of outline\"),\n Param(name='alpha', type=float, default=1.0,\n min=0.0, max=1.0, widget='spinfloat', incr=0.05,\n description=\"Opacity of outline\"),\n Param(name='units', type=str, default='arcmin',\n valid=['arcmin', 'degrees', 'pixels'],\n description=\"Units for text distance (default: arcmin)\"),\n Param(name='font', type=str, default='Sans Serif',\n description=\"Font family for text\"),\n Param(name='fontsize', type=float, default=None,\n min=8, max=72,\n description=\"Font size of text (default: vary by scale)\"),\n Param(name='showcap', type=_bool,\n default=False, valid=[False, True],\n description=\"Show caps for this object\"),\n ]\n\n @classmethod\n def idraw(cls, canvas, cxt):\n return cls((cxt.start_x, cxt.start_y), (cxt.x, cxt.y), **cxt.drawparams)\n\n def __init__(self, pt1, pt2, color='green', color2='skyblue',\n alpha=1.0, linewidth=1, linestyle='solid',\n showcap=True, showplumb=True, showends=False, units='arcmin',\n font='Sans Serif', fontsize=None, **kwdargs):\n self.kind = 'ruler'\n points = np.asarray([pt1, pt2], dtype=np.float)\n CanvasObjectBase.__init__(self, color=color, color2=color2,\n alpha=alpha, units=units,\n showplumb=showplumb, showends=showends,\n linewidth=linewidth, showcap=showcap,\n linestyle=linestyle, points=points,\n font=font, fontsize=fontsize,\n **kwdargs)\n TwoPointMixin.__init__(self)\n\n def get_points(self):\n points = [(self.x1, self.y1), (self.x2, self.y2)]\n points = self.get_data_points(points=points)\n return points\n\n def select_contains_pt(self, viewer, pt):\n points = self.get_points()\n return self.within_line(viewer, pt, points[0], points[1],\n self.cap_radius)\n\n def get_arcmin(self, sep):\n sgn, deg, mn, sec = wcs.degToDms(sep)\n if deg != 0:\n txt = '%02d:%02d:%06.3f' % (deg, mn, sec)\n else:\n txt = '%02d:%06.3f' % (mn, sec)\n return txt\n\n def get_ruler_distances(self, viewer):\n mode = self.units.lower()\n points = self.get_data_points()\n x1, y1 = points[0]\n x2, y2 = points[1]\n\n text = Bunch.Bunch(dict().fromkeys(['x', 'y', 'h', 'b', 'e'],\n 'BAD WCS'))\n try:\n image = viewer.get_image()\n res = wcs.get_ruler_distances(image, points[0], points[1])\n text.res = res\n\n if mode == 'arcmin':\n text.h = self.get_arcmin(res.dh_deg)\n text.x = self.get_arcmin(res.dx_deg)\n text.y = self.get_arcmin(res.dy_deg)\n text.b = (\"%s, %s\" % (wcs.raDegToString(res.ra_org),\n wcs.decDegToString(res.dec_org)))\n text.e = (\"%s, %s\" % (wcs.raDegToString(res.ra_dst),\n wcs.decDegToString(res.dec_dst)))\n\n elif mode == 'degrees':\n text.h = (\"%.8f\" % res.dh_deg)\n text.x = (\"%.8f\" % res.dx_deg)\n text.y = (\"%.8f\" % res.dy_deg)\n text.b = (\"%.3f, %.3f\" % (res.ra_org, res.dec_org))\n text.e = (\"%.3f, %.3f\" % (res.ra_dst, res.dec_dst))\n\n else:\n text.x = (\"%.3f\" % abs(res.dx_pix))\n text.y = (\"%.3f\" % abs(res.dy_pix))\n text.h = (\"%.3f\" % res.dh_pix)\n text.b = (\"%.3f, %.3f\" % (res.x1, res.y1))\n text.e = (\"%.3f, %.3f\" % (res.x2, res.y2))\n\n except Exception as e:\n print(str(e))\n pass\n\n return text\n\n def draw(self, viewer):\n points = self.get_points()\n x1, y1 = points[0]\n x2, y2 = points[1]\n cx1, cy1 = viewer.get_canvas_xy(x1, y1)\n cx2, cy2 = viewer.get_canvas_xy(x2, y2)\n\n text = self.get_ruler_distances(viewer)\n\n cr = viewer.renderer.setup_cr(self)\n cr.set_font_from_shape(self)\n\n cr.draw_line(cx1, cy1, cx2, cy2)\n self.draw_arrowhead(cr, cx1, cy1, cx2, cy2)\n self.draw_arrowhead(cr, cx2, cy2, cx1, cy1)\n\n # calculate offsets and positions for drawing labels\n # try not to cover anything up\n xtwd, xtht = cr.text_extents(text.x)\n ytwd, ytht = cr.text_extents(text.y)\n htwd, htht = cr.text_extents(text.h)\n\n diag_xoffset = 0\n diag_yoffset = 0\n xplumb_yoffset = 0\n yplumb_xoffset = 0\n\n diag_yoffset = 14\n if abs(cy1 - cy2) < 5:\n show_angle = 0 # noqa\n elif cy1 < cy2:\n xplumb_yoffset = -4\n else:\n xplumb_yoffset = 14\n diag_yoffset = -4\n\n if abs(cx1 - cx2) < 5:\n diag_xoffset = -(4 + htwd)\n show_angle = 0 # noqa\n elif (cx1 < cx2):\n diag_xoffset = -(4 + htwd)\n yplumb_xoffset = 4\n else:\n diag_xoffset = 4\n yplumb_xoffset = -(4 + ytwd)\n\n xh = min(cx1, cx2)\n y = cy1 + xplumb_yoffset\n xh += (max(cx1, cx2) - xh) // 2\n yh = min(cy1, cy2)\n x = cx2 + yplumb_xoffset\n yh += (max(cy1, cy2) - yh) // 2\n\n xd = xh + diag_xoffset\n yd = yh + diag_yoffset\n cr.draw_text(xd, yd, text.h)\n\n if self.showends:\n cr.draw_text(cx1 + 4, cy1 + xtht + 4, text.b)\n cr.draw_text(cx2 + 4, cy2 + xtht + 4, text.e)\n\n if self.showplumb:\n if self.color2:\n alpha = getattr(self, 'alpha', 1.0)\n cr.set_line(self.color2, alpha=alpha, style='dash')\n\n # draw X plumb line\n cr.draw_line(cx1, cy1, cx2, cy1)\n\n # draw Y plumb line\n cr.draw_line(cx2, cy1, cx2, cy2)\n\n # draw X plum line label\n xh -= xtwd // 2\n cr.draw_text(xh, y, text.x)\n\n # draw Y plum line label\n cr.draw_text(x, yh, text.y)\n\n if self.showcap and self.showplumb:\n # only cap is at intersection of plumb lines\n self.draw_caps(cr, self.cap, ((cx2, cy1), ))\n\n\nclass Ruler(RulerP):\n\n @classmethod\n def idraw(cls, canvas, cxt):\n return cls(cxt.start_x, cxt.start_y, cxt.x, cxt.y, **cxt.drawparams)\n\n def __init__(self, x1, y1, x2, y2, color='green', color2='skyblue',\n alpha=1.0, linewidth=1, linestyle='solid',\n showcap=True, showplumb=True, showends=False, units='arcmin',\n font='Sans Serif', fontsize=None, **kwdargs):\n RulerP.__init__(self, (x1, y1), (x2, y2), color=color, color2=color2,\n alpha=alpha, units=units,\n showplumb=showplumb, showends=showends,\n linewidth=linewidth, showcap=showcap,\n linestyle=linestyle, font=font, fontsize=fontsize,\n **kwdargs)\n\n\nclass CompassP(OnePointOneRadiusMixin, CanvasObjectBase):\n \"\"\"\n Draws a WCS compass on a DrawingCanvas.\n Parameters are:\n x, y: 0-based coordinates of the center in the coordinate space\n radius: radius of the compass arms, in coordinate units\n Optional parameters for linesize, color, etc.\n \"\"\"\n\n @classmethod\n def get_params_metadata(cls):\n return [\n Param(name='coord', type=str, default='data',\n valid=coord_names,\n description=\"Set type of coordinates\"),\n Param(name='x', type=float, default=0.0, argpos=0,\n description=\"X coordinate of center of object\"),\n Param(name='y', type=float, default=0.0, argpos=1,\n description=\"Y coordinate of center of object\"),\n Param(name='radius', type=float, default=1.0, argpos=2,\n min=0.0,\n description=\"Radius of object\"),\n Param(name='ctype', type=str, default='wcs',\n valid=['pixel', 'wcs'],\n description=\"Type of compass (wcs (N/E), or pixel (X/Y))\"),\n Param(name='linewidth', type=int, default=1,\n min=1, max=20, widget='spinbutton', incr=1,\n description=\"Width of outline\"),\n Param(name='linestyle', type=str, default='solid',\n valid=['solid', 'dash'],\n description=\"Style of outline (default solid)\"),\n Param(name='color',\n valid=colors_plus_none, type=_color, default='skyblue',\n description=\"Color of outline\"),\n Param(name='alpha', type=float, default=1.0,\n min=0.0, max=1.0, widget='spinfloat', incr=0.05,\n description=\"Opacity of outline\"),\n Param(name='font', type=str, default='Sans Serif',\n description=\"Font family for text\"),\n Param(name='fontsize', type=float, default=None,\n min=8, max=72,\n description=\"Font size of text (default: vary by scale)\"),\n Param(name='showcap', type=_bool,\n default=False, valid=[False, True],\n description=\"Show caps for this object\"),\n ]\n\n @classmethod\n def idraw(cls, canvas, cxt):\n radius = np.sqrt(abs(cxt.start_x - cxt.x) ** 2 +\n abs(cxt.start_y - cxt.y) ** 2)\n return cls((cxt.start_x, cxt.start_y), radius, **cxt.drawparams)\n\n def __init__(self, pt, radius, ctype='wcs', color='skyblue',\n linewidth=1, fontsize=None, font='Sans Serif',\n alpha=1.0, linestyle='solid', showcap=True, **kwdargs):\n self.kind = 'compass'\n points = np.asarray([pt], dtype=np.float)\n CanvasObjectBase.__init__(self, ctype=ctype, color=color, alpha=alpha,\n linewidth=linewidth, showcap=showcap,\n linestyle=linestyle,\n points=points, radius=radius,\n font=font, fontsize=fontsize,\n **kwdargs)\n OnePointOneRadiusMixin.__init__(self)\n\n def get_edit_points(self, viewer):\n points = self.get_data_points(points=(\n (self.x, self.y),\n self.crdmap.offset_pt((self.x, self.y),\n (self.radius, self.radius)), ))\n x, y = points[0]\n x1, y1 = points[1]\n radius = math.sqrt((x1 - x) ** 2 + (y1 - y) ** 2)\n\n return [MovePoint(x, y),\n ScalePoint(x + radius, y + radius),\n ]\n\n def get_llur(self):\n points = self.get_data_points(points=(\n (self.x, self.y),\n self.crdmap.offset_pt((self.x, self.y),\n (self.radius, self.radius)), ))\n x, y = points[0]\n x1, y1 = points[1]\n radius = math.sqrt((x1 - x) ** 2 + (y1 - y) ** 2)\n\n x1, y1, x2, y2 = x - radius, y - radius, x + radius, y + radius\n return self.swapxy(x1, y1, x2, y2)\n\n def select_contains_pt(self, viewer, pt):\n p0 = self.crdmap.to_data((self.x, self.y))\n return self.within_radius(viewer, pt, p0, self.cap_radius)\n\n def draw(self, viewer):\n\n points = self.get_data_points(points=(\n (self.x, self.y),\n self.crdmap.offset_pt((self.x, self.y),\n (self.radius, self.radius)), ))\n x, y = points[0]\n x1, y1 = points[1]\n radius = math.sqrt((x1 - x) ** 2 + (y1 - y) ** 2)\n\n bad_arms = False\n\n if self.ctype == 'wcs':\n image = viewer.get_image()\n if image is None:\n return\n\n try:\n x, y, xn, yn, xe, ye = wcs.calc_compass_radius(image,\n x, y,\n radius)\n except Exception as e:\n bad_arms = True\n\n elif self.ctype == 'pixel':\n xn, yn, xe, ye = x, y + radius, x + radius, y\n\n cr = viewer.renderer.setup_cr(self)\n cr.set_font_from_shape(self)\n\n if bad_arms:\n points = self.get_cpoints(viewer, points=[(x, y)])\n cx, cy = points[0]\n cr.draw_text(cx, cy, 'BAD WCS')\n return\n\n points = np.asarray([(x, y), (xn, yn), (xe, ye)])\n\n (cx1, cy1), (cx2, cy2), (cx3, cy3) = self.get_cpoints(viewer,\n points=points)\n # draw North line and arrowhead\n cr.draw_line(cx1, cy1, cx2, cy2)\n self.draw_arrowhead(cr, cx1, cy1, cx2, cy2)\n\n # draw East line and arrowhead\n cr.draw_line(cx1, cy1, cx3, cy3)\n self.draw_arrowhead(cr, cx1, cy1, cx3, cy3)\n\n # draw \"N\" & \"E\" or \"X\" and \"Y\"\n if self.ctype == 'pixel':\n te, tn = 'X', 'Y'\n else:\n te, tn = 'E', 'N'\n cx, cy = self.get_textpos(cr, tn, cx1, cy1, cx2, cy2)\n cr.draw_text(cx, cy, tn)\n cx, cy = self.get_textpos(cr, te, cx1, cy1, cx3, cy3)\n cr.draw_text(cx, cy, te)\n\n if self.showcap:\n self.draw_caps(cr, self.cap, ((cx1, cy1), ))\n\n def get_textpos(self, cr, text, cx1, cy1, cx2, cy2):\n htwd, htht = cr.text_extents(text)\n diag_xoffset = 0\n diag_yoffset = 0\n xplumb_yoffset = 0\n yplumb_xoffset = 0\n\n diag_yoffset = 14\n if abs(cy1 - cy2) < 5:\n pass\n elif cy1 < cy2:\n xplumb_yoffset = -4\n else:\n xplumb_yoffset = 14\n diag_yoffset = -4\n\n if abs(cx1 - cx2) < 5:\n diag_xoffset = -(4 + htwd)\n elif (cx1 < cx2):\n diag_xoffset = -(4 + htwd)\n yplumb_xoffset = 4\n else:\n diag_xoffset = 4\n yplumb_xoffset = -(4 + 0)\n\n xh = min(cx1, cx2)\n y = cy1 + xplumb_yoffset # noqa\n xh += (max(cx1, cx2) - xh) // 2\n yh = min(cy1, cy2)\n x = cx2 + yplumb_xoffset # noqa\n yh += (max(cy1, cy2) - yh) // 2\n\n xd = xh + diag_xoffset\n yd = yh + diag_yoffset\n return (xd, yd)\n\n\nclass Compass(CompassP):\n\n @classmethod\n def idraw(cls, canvas, cxt):\n radius = np.sqrt(abs(cxt.start_x - cxt.x) ** 2 +\n abs(cxt.start_y - cxt.y) ** 2)\n return cls(cxt.start_x, cxt.start_y, radius, **cxt.drawparams)\n\n def __init__(self, x, y, radius, ctype='wcs', color='skyblue',\n linewidth=1, fontsize=None, font='Sans Serif',\n alpha=1.0, linestyle='solid', showcap=True, **kwdargs):\n CompassP.__init__(self, (x, y), radius, ctype=ctype, color=color,\n alpha=alpha, linewidth=linewidth, showcap=showcap,\n linestyle=linestyle, font=font, fontsize=fontsize,\n **kwdargs)\n\n\nclass CrosshairP(OnePointMixin, CanvasObjectBase):\n \"\"\"\n Draws a crosshair on a DrawingCanvas.\n Parameters are:\n x, y: 0-based coordinates of the center in the data space\n Optional parameters for linesize, color, etc.\n \"\"\"\n\n @classmethod\n def get_params_metadata(cls):\n return [\n Param(name='coord', type=str, default='data',\n valid=coord_names,\n description=\"Set type of coordinates\"),\n Param(name='x', type=float, default=0.0, argpos=0,\n description=\"X coordinate of center of object\"),\n Param(name='y', type=float, default=0.0, argpos=1,\n description=\"Y coordinate of center of object\"),\n Param(name='linewidth', type=int, default=1,\n min=1, max=20, widget='spinbutton', incr=1,\n description=\"Width of outline\"),\n Param(name='linestyle', type=str, default='solid',\n valid=['solid', 'dash'],\n description=\"Style of outline (default solid)\"),\n Param(name='color',\n valid=colors_plus_none, type=_color, default='green',\n description=\"Color of outline\"),\n Param(name='alpha', type=float, default=1.0,\n min=0.0, max=1.0, widget='spinfloat', incr=0.05,\n description=\"Opacity of outline\"),\n Param(name='text', type=str, default=None,\n description=\"Text annotation\"),\n Param(name='textcolor',\n valid=colors_plus_none, type=_color, default='yellow',\n description=\"Color of text annotation\"),\n Param(name='font', type=str, default='Sans Serif',\n description=\"Font family for text\"),\n Param(name='fontsize', type=float, default=None,\n min=8, max=72,\n description=\"Font size of text (default: vary by scale)\"),\n Param(name='fontscale', type=_bool,\n default=True, valid=[False, True],\n description=\"Scale font with scale of viewer\"),\n Param(name='format', type=str, default='xy',\n valid=['xy', 'value', 'coords'],\n description=\"Format for text annotation (default: xy)\"),\n ]\n\n @classmethod\n def idraw(cls, canvas, cxt):\n return cls((cxt.x, cxt.y), **cxt.drawparams)\n\n def __init__(self, pt, color='green',\n linewidth=1, alpha=1.0, linestyle='solid',\n text=None, textcolor='yellow',\n fontsize=10.0, font='Sans Serif', fontscale=True,\n format='xy', **kwdargs):\n self.kind = 'crosshair'\n points = np.asarray([pt], dtype=np.float)\n CanvasObjectBase.__init__(self, color=color, alpha=alpha,\n linewidth=linewidth, linestyle=linestyle,\n text=text, textcolor=textcolor,\n fontsize=fontsize, font=font,\n fontscale=fontscale,\n points=points, format=format, **kwdargs)\n OnePointMixin.__init__(self)\n\n self.fontsize_min = 8.0\n self.fontsize_max = 14.0\n\n def select_contains_pt(self, viewer, pt):\n p0 = self.crdmap.to_data((self.x, self.y))\n return self.within_radius(viewer, pt, p0, self.cap_radius)\n\n def draw(self, viewer):\n wd, ht = viewer.get_window_size()\n cpoints = self.get_cpoints(viewer)\n (cx, cy) = cpoints[0]\n\n hx1, hx2 = 0, wd\n hy1 = hy2 = cy\n vy1, vy2 = 0, ht\n vx1 = vx2 = cx\n\n if self.text is None:\n if self.format == 'xy':\n text = \"X:%f, Y:%f\" % (self.x, self.y)\n\n else:\n image = viewer.get_image()\n if image is None:\n return\n # NOTE: x, y are assumed to be in data coordinates\n info = image.info_xy(self.x, self.y, viewer.get_settings())\n if self.format == 'coords':\n if 'ra_lbl' not in info:\n text = 'No WCS'\n else:\n text = \"%s:%s, %s:%s\" % (info.ra_lbl, info.ra_txt,\n info.dec_lbl, info.dec_txt)\n else:\n if np.isscalar(info.value) or len(info.value) <= 1:\n text = \"V: %f\" % (info.value)\n else:\n values = ', '.join([\"%d\" % info.value[i]\n for i in range(len(info.value))])\n text = \"V: [%s]\" % (str(values))\n else:\n text = self.text\n\n cr = viewer.renderer.setup_cr(self)\n cr.set_font_from_shape(self)\n\n # draw horizontal line\n cr.draw_line(hx1, hy1, hx2, hy2)\n\n # draw vertical line\n cr.draw_line(vx1, vy1, vx2, vy2)\n\n txtwd, txtht = cr.text_extents(text)\n cr.set_line(self.textcolor, alpha=self.alpha)\n cr.draw_text(cx + 10, cy + 4 + txtht, text)\n\n\nclass Crosshair(CrosshairP):\n\n @classmethod\n def idraw(cls, canvas, cxt):\n return cls(cxt.x, cxt.y, **cxt.drawparams)\n\n def __init__(self, x, y, color='green',\n linewidth=1, alpha=1.0, linestyle='solid',\n text=None, textcolor='yellow',\n fontsize=10.0, font='Sans Serif', fontscale=True,\n format='xy', **kwdargs):\n CrosshairP.__init__(self, (x, y), color=color, alpha=alpha,\n linewidth=linewidth, linestyle=linestyle,\n text=text, textcolor=textcolor,\n fontsize=fontsize, font=font,\n fontscale=fontscale,\n format=format, **kwdargs)\n\n\nclass AnnulusMixin(object):\n\n def contains_pt(self, pt):\n \"\"\"Containment test.\"\"\"\n obj1, obj2 = self.objects\n return obj2.contains_pt(pt) and np.logical_not(obj1.contains_pt(pt))\n\n def contains_pts(self, pts):\n \"\"\"Containment test on arrays.\"\"\"\n obj1, obj2 = self.objects\n arg1 = obj2.contains_pts(pts)\n arg2 = np.logical_not(obj1.contains_pts(pts))\n return np.logical_and(arg1, arg2)\n\n def get_llur(self):\n \"\"\"Bounded by outer object.\"\"\"\n obj2 = self.objects[1]\n return obj2.get_llur()\n\n def select_contains_pt(self, viewer, pt):\n obj2 = self.objects[1]\n return obj2.select_contains_pt(viewer, pt)\n\n\nclass AnnulusP(AnnulusMixin, OnePointOneRadiusMixin, CompoundObject):\n \"\"\"\n Special compound object to handle annulus shape that\n consists of two objects with the same centroid.\n\n Examples\n --------\n >>> tag = canvas.add(Annulus(100, 200, 10, width=5, atype='circle'))\n >>> obj = canvas.get_object_by_tag(tag)\n >>> arr_masked = image.cutout_shape(obj)\n\n \"\"\"\n @classmethod\n def get_params_metadata(cls):\n return [\n Param(name='coord', type=str, default='data',\n valid=coord_names,\n description=\"Set type of coordinates\"),\n Param(name='x', type=float, default=0.0, argpos=0,\n description=\"X coordinate of center of object\"),\n Param(name='y', type=float, default=0.0, argpos=1,\n description=\"Y coordinate of center of object\"),\n Param(name='radius', type=float, default=1.0, argpos=2,\n min=0.0,\n description=\"Inner radius of annulus\"),\n Param(name='width', type=float, default=None,\n min=0.0,\n description=\"Width of annulus\"),\n Param(name='atype', type=str, default='circle',\n valid=['circle', 'squarebox'],\n description=\"Type of annulus\"),\n Param(name='linewidth', type=int, default=1,\n min=1, max=20, widget='spinbutton', incr=1,\n description=\"Width of outline\"),\n Param(name='linestyle', type=str, default='solid',\n valid=['solid', 'dash'],\n description=\"Style of outline (default solid)\"),\n Param(name='color',\n valid=colors_plus_none, type=_color, default='yellow',\n description=\"Color of outline\"),\n Param(name='alpha', type=float, default=1.0,\n min=0.0, max=1.0, widget='spinfloat', incr=0.05,\n description=\"Opacity of outline\"),\n ]\n\n @classmethod\n def idraw(cls, canvas, cxt):\n radius = np.sqrt(abs(cxt.start_x - cxt.x)**2 +\n abs(cxt.start_y - cxt.y)**2)\n return cls((cxt.start_x, cxt.start_y), radius,\n **cxt.drawparams)\n\n def __init__(self, pt, radius, width=None,\n atype='circle', color='yellow',\n linewidth=1, linestyle='solid', alpha=1.0,\n **kwdargs):\n if width is None:\n # default width is 15% of radius\n width = 0.15 * radius\n oradius = radius + width\n\n if oradius < radius:\n raise ValueError('Outer boundary < inner boundary')\n\n coord = kwdargs.get('coord', None)\n\n klass = get_canvas_type(atype)\n obj1 = klass(pt[0], pt[1], radius, color=color,\n linewidth=linewidth,\n linestyle=linestyle, alpha=alpha,\n coord=coord)\n obj1.editable = False\n\n obj2 = klass(pt[0], pt[1], oradius, color=color,\n linewidth=linewidth,\n linestyle=linestyle, alpha=alpha,\n coord=coord)\n obj2.editable = False\n\n points = np.asarray([pt], dtype=np.float)\n\n CompoundObject.__init__(self, obj1, obj2,\n points=points, radius=radius,\n width=width, color=color,\n linewidth=linewidth, linestyle=linestyle,\n alpha=alpha, **kwdargs)\n OnePointOneRadiusMixin.__init__(self)\n\n self.editable = True\n self.opaque = True\n self.atype = atype\n self.kind = 'annulus'\n\n def get_edit_points(self, viewer):\n points = ((self.x, self.y),\n self.crdmap.offset_pt((self.x, self.y),\n (self.radius, 0)),\n self.crdmap.offset_pt((self.x, self.y),\n (self.radius + self.width, 0)),\n )\n points = self.get_data_points(points=points)\n return [MovePoint(*points[0]),\n ScalePoint(*points[1]),\n Point(*points[2])]\n\n def setup_edit(self, detail):\n detail.center_pos = self.get_center_pt()\n detail.radius = self.radius\n detail.width = self.width\n\n def set_edit_point(self, i, pt, detail):\n if i == 0:\n # move control point\n self.move_to_pt(pt)\n else:\n if i == 1:\n scalef = self.calc_scale_from_pt(pt, detail)\n # inner obj radius control pt\n self.radius = detail.radius * scalef\n elif i == 2:\n scalef = self.calc_scale_from_pt(pt, detail)\n width = detail.width * scalef\n # outer obj radius control pt--calculate new width\n assert width > 0, ValueError(\"Must have a positive width\")\n self.width = width\n else:\n raise ValueError(\"No point corresponding to index %d\" % (i))\n\n self.sync_state()\n\n def sync_state(self):\n \"\"\"Called to synchronize state (e.g. when parameters have changed).\n \"\"\"\n oradius = self.radius + self.width\n if oradius < self.radius:\n raise ValueError('Outer boundary < inner boundary')\n\n d = dict(points=self.points, radius=self.radius, color=self.color,\n linewidth=self.linewidth, linestyle=self.linestyle,\n alpha=self.alpha)\n\n # update inner object\n self.objects[0].__dict__.update(d)\n\n # update outer object\n d['radius'] = oradius\n self.objects[1].__dict__.update(d)\n\n def move_to_pt(self, dst_pt):\n super(Annulus, self).move_to_pt(dst_pt)\n\n self.set_data_points([dst_pt])\n\n\nclass Annulus(AnnulusP):\n\n @classmethod\n def idraw(cls, canvas, cxt):\n radius = np.sqrt(abs(cxt.start_x - cxt.x)**2 +\n abs(cxt.start_y - cxt.y)**2)\n return cls(cxt.start_x, cxt.start_y, radius,\n **cxt.drawparams)\n\n def __init__(self, x, y, radius, width=None,\n atype='circle', color='yellow',\n linewidth=1, linestyle='solid', alpha=1.0,\n **kwdargs):\n AnnulusP.__init__(self, (x, y), radius, width=width, atype=atype,\n color=color, linewidth=linewidth,\n linestyle=linestyle, alpha=alpha, **kwdargs)\n\n\nclass Annulus2RP(AnnulusMixin, OnePointTwoRadiusMixin, CompoundObject):\n \"\"\"\n Special compound object to handle annulus shape that\n consists of two objects, (one center point, plus two radii).\n\n Examples\n --------\n >>> tag = canvas.add(Annulus2R(100, 200, 10, 20, width=5, atype='box'))\n >>> obj = canvas.get_object_by_tag(tag)\n >>> arr_masked = image.cutout_shape(obj)\n\n \"\"\"\n @classmethod\n def get_params_metadata(cls):\n return [\n Param(name='coord', type=str, default='data',\n valid=coord_names,\n description=\"Set type of coordinates\"),\n Param(name='x', type=float, default=0.0, argpos=0,\n description=\"X coordinate of center of object\"),\n Param(name='y', type=float, default=0.0, argpos=1,\n description=\"Y coordinate of center of object\"),\n Param(name='xradius', type=float, default=1.0, argpos=2,\n min=0.0,\n description=\"Inner X radius of annulus\"),\n Param(name='yradius', type=float, default=1.0, argpos=2,\n min=0.0,\n description=\"Inner Y radius of annulus\"),\n Param(name='xwidth', type=float, default=None,\n min=0.0,\n description=\"Width in X of annulus\"),\n Param(name='ywidth', type=float, default=None,\n min=0.0,\n description=\"Width in Y of annulus\"),\n Param(name='atype', type=str, default='ellipse',\n valid=['ellipse', 'box'],\n description=\"Type of annulus\"),\n Param(name='linewidth', type=int, default=1,\n min=1, max=20, widget='spinbutton', incr=1,\n description=\"Width of outline\"),\n Param(name='linestyle', type=str, default='solid',\n valid=['solid', 'dash'],\n description=\"Style of outline (default solid)\"),\n Param(name='color',\n valid=colors_plus_none, type=_color, default='yellow',\n description=\"Color of outline\"),\n Param(name='alpha', type=float, default=1.0,\n min=0.0, max=1.0, widget='spinfloat', incr=0.05,\n description=\"Opacity of outline\"),\n Param(name='rot_deg', type=float, default=0.0,\n min=-359.999, max=359.999, widget='spinfloat', incr=1.0,\n description=\"Rotation about center of object\"),\n ]\n\n @classmethod\n def idraw(cls, canvas, cxt):\n xradius, yradius = abs(cxt.start_x - cxt.x), abs(cxt.start_y - cxt.y)\n return cls((cxt.start_x, cxt.start_y), (xradius, yradius),\n **cxt.drawparams)\n\n def __init__(self, pt, radii, xwidth=None,\n ywidth=None, atype='ellipse', color='yellow',\n linewidth=1, linestyle='solid', alpha=1.0,\n rot_deg=0.0, **kwdargs):\n xradius, yradius = radii\n if xwidth is None:\n # default X width is 15% of X radius\n xwidth = 0.15 * xradius\n if ywidth is None:\n # default Y width is X width\n ywidth = xwidth\n oxradius = xradius + xwidth\n oyradius = yradius + ywidth\n\n if oxradius < xradius or oyradius < yradius:\n raise ValueError('Outer boundary < inner boundary')\n\n coord = kwdargs.get('coord', None)\n\n klass = get_canvas_type(atype)\n obj1 = klass(pt[0], pt[1], radii[0], radii[1], color=color,\n linewidth=linewidth,\n linestyle=linestyle, alpha=alpha,\n coord=coord, rot_deg=rot_deg)\n obj1.editable = False\n\n obj2 = klass(pt[0], pt[1], oxradius, oyradius, color=color,\n linewidth=linewidth,\n linestyle=linestyle, alpha=alpha,\n coord=coord, rot_deg=rot_deg)\n obj2.editable = False\n\n points = np.asarray([pt], dtype=np.float)\n\n CompoundObject.__init__(self, obj1, obj2,\n points=points, xradius=xradius, yradius=yradius,\n xwidth=xwidth, ywidth=ywidth, color=color,\n linewidth=linewidth, linestyle=linestyle,\n alpha=alpha, rot_deg=rot_deg, **kwdargs)\n OnePointTwoRadiusMixin.__init__(self)\n\n self.editable = True\n self.opaque = True\n self.atype = atype\n self.kind = 'annulus2r'\n\n def get_edit_points(self, viewer):\n move_pt, scale_pt, rotate_pt = self.get_move_scale_rotate_pts(viewer)\n\n points = (self.crdmap.offset_pt((self.x, self.y),\n (self.xradius, 0)),\n self.crdmap.offset_pt((self.x, self.y),\n (0, self.yradius)),\n self.crdmap.offset_pt((self.x, self.y),\n (self.xradius + self.xwidth, 0)),\n self.crdmap.offset_pt((self.x, self.y),\n (0, self.yradius + self.ywidth)),\n )\n points = self.get_data_points(points=points)\n return [move_pt, # location\n Point(*points[0]), # adj inner X radius\n Point(*points[1]), # adj inner Y radius\n Point(*points[2]), # adj X width\n Point(*points[3]), # adj Y width\n scale_pt,\n rotate_pt,\n ]\n\n def setup_edit(self, detail):\n detail.center_pos = self.get_center_pt()\n detail.xradius = self.xradius\n detail.yradius = self.yradius\n detail.xwidth = self.xwidth\n detail.ywidth = self.ywidth\n\n def set_edit_point(self, i, pt, detail):\n if i == 0:\n self.move_to_pt(pt)\n elif i == 1:\n # Adjust inner X radius\n scale_x, scale_y = self.calc_dual_scale_from_pt(pt, detail)\n self.xradius = detail.xradius * scale_x\n #scalef = self.calc_scale_from_pt(pt, detail)\n # inner obj radius control pt\n #self.xradius = detail.xradius * scalef\n elif i == 2:\n # Adjust inner Y radius\n scale_x, scale_y = self.calc_dual_scale_from_pt(pt, detail)\n self.yradius = detail.yradius * scale_y\n #scalef = self.calc_scale_from_pt(pt, detail)\n #self.yradius = detail.yradius * scalef\n elif i == 3:\n # Adjust X width\n scale_x, scale_y = self.calc_dual_scale_from_pt(pt, detail)\n xwidth = detail.xwidth * scale_x\n # outer obj radius control pt--calculate new width\n assert xwidth > 0, ValueError(\"Must have a positive width\")\n self.xwidth = xwidth\n elif i == 4:\n # Adjust Y width\n scale_x, scale_y = self.calc_dual_scale_from_pt(pt, detail)\n ywidth = detail.ywidth * scale_y\n # outer obj radius control pt--calculate new width\n assert ywidth > 0, ValueError(\"Must have a positive width\")\n self.ywidth = ywidth\n elif i == 5:\n # Adjust overall scale\n scalef = self.calc_scale_from_pt(pt, detail)\n self.xradius = detail.xradius * scalef\n self.yradius = detail.yradius * scalef\n elif i == 6:\n # Adjust rotation\n delta_deg = self.calc_rotation_from_pt(pt, detail)\n self.rotate_by_deg([delta_deg])\n else:\n raise ValueError(\"No point corresponding to index %d\" % (i))\n\n self.sync_state()\n\n def sync_state(self):\n \"\"\"Called to synchronize state (e.g. when parameters have changed).\n \"\"\"\n oxradius = self.xradius + self.xwidth\n oyradius = self.yradius + self.ywidth\n if oxradius < self.xradius or oyradius < self.yradius:\n raise ValueError('Outer boundary < inner boundary')\n\n d = dict(points=self.points, xradius=self.xradius,\n yradius=self.yradius, color=self.color,\n linewidth=self.linewidth, linestyle=self.linestyle,\n alpha=self.alpha, rot_deg=self.rot_deg)\n\n # update inner object\n self.objects[0].__dict__.update(d)\n\n # update outer object\n d['xradius'] = oxradius\n d['yradius'] = oyradius\n self.objects[1].__dict__.update(d)\n\n def move_to_pt(self, dst_pt):\n super(Annulus2R, self).move_to_pt(dst_pt)\n\n self.set_data_points([dst_pt])\n\n\nclass Annulus2R(Annulus2RP):\n\n @classmethod\n def idraw(cls, canvas, cxt):\n xradius, yradius = abs(cxt.start_x - cxt.x), abs(cxt.start_y - cxt.y)\n return cls(cxt.start_x, cxt.start_y, xradius, yradius,\n **cxt.drawparams)\n\n def __init__(self, x, y, xradius, yradius, xwidth=None,\n ywidth=None, atype='ellipse', color='yellow',\n linewidth=1, linestyle='solid', alpha=1.0,\n rot_deg=0.0, **kwdargs):\n Annulus2RP.__init__(self, (x, y), (xradius, yradius),\n xwidth=xwidth, ywidth=ywidth, atype=atype,\n color=color, linewidth=linewidth,\n linestyle=linestyle, alpha=alpha,\n rot_deg=rot_deg, **kwdargs)\n\n\nclass WCSAxes(CompoundObject):\n \"\"\"\n Special compound object to draw WCS axes.\n \"\"\"\n @classmethod\n def get_params_metadata(cls):\n return [\n Param(name='linewidth', type=int, default=1,\n min=1, max=20, widget='spinbutton', incr=1,\n description=\"Width of outline\"),\n Param(name='linestyle', type=str, default='dash',\n valid=['solid', 'dash'],\n description=\"Style of outline (default dash)\"),\n Param(name='color',\n valid=colors_plus_none, type=_color, default='yellow',\n description=\"Color of grid and text\"),\n Param(name='alpha', type=float, default=1.0,\n min=0.0, max=1.0, widget='spinfloat', incr=0.05,\n description=\"Opacity of grid and text\"),\n Param(name='font', type=str, default='Sans Serif',\n description=\"Font family for text\"),\n Param(name='fontsize', type=float, default=8.0,\n min=8, max=72,\n description=\"Font size of text (default: 8)\"),\n ]\n\n def __init__(self, color='cyan',\n linewidth=1, linestyle='dash', alpha=1.0,\n font='Sans Serif', fontsize=8,\n **kwdargs):\n\n # these could become supplied optional parameters, if desired\n self.show_label = True\n self.num_ra = 10\n self.num_dec = 10\n self._pix_res = 10\n self.txt_off = 4\n self.ra_angle = None\n self.dec_angle = None\n # for keeping track of changes to image and orientation\n self._cur_rot = None\n self._cur_swap = None\n self._cur_image = None\n\n CompoundObject.__init__(self,\n color=color, alpha=alpha,\n linewidth=linewidth, linestyle=linestyle,\n font=font, fontsize=fontsize, **kwdargs)\n\n self.editable = False\n self.pickable = False\n self.opaque = True\n self.kind = 'wcsaxes'\n\n def _calc_axes(self, viewer, image, rot_deg, swapxy):\n self._cur_image = image\n self._cur_rot = rot_deg\n self._cur_swap = swapxy\n\n if not isinstance(image, AstroImage) or not image.has_valid_wcs():\n self.logger.debug(\n 'WCSAxes can only be displayed for AstroImage with valid WCS')\n return []\n\n min_imsize = min(image.width, image.height)\n if min_imsize <= 0:\n self.logger.debug('Cannot draw WCSAxes on image with 0 dim')\n return []\n\n # Approximate bounding box in RA/DEC space\n xmax = image.width - 1\n ymax = image.height - 1\n try:\n radec = image.wcs.datapt_to_system(\n [[0, 0], [0, ymax], [xmax, 0], [xmax, ymax]],\n naxispath=image.naxispath)\n except Exception as e:\n self.logger.warning('WCSAxes failed: {}'.format(str(e)))\n return []\n ra_min, dec_min = radec.ra.min().deg, radec.dec.min().deg\n ra_max, dec_max = radec.ra.max().deg, radec.dec.max().deg\n ra_size = ra_max - ra_min\n dec_size = dec_max - dec_min\n\n # Calculate positions of RA/DEC lines\n d_ra = ra_size / (self.num_ra + 1)\n d_dec = dec_size / (self.num_dec + 1)\n ra_arr = np.arange(ra_min + d_ra, ra_max - d_ra * 0.5, d_ra)\n dec_arr = np.arange(dec_min + d_dec, dec_max - d_ra * 0.5, d_dec)\n\n # RA/DEC step size for each vector\n d_ra_step = ra_size * self._pix_res / min_imsize\n d_dec_step = dec_size * self._pix_res / min_imsize\n\n # Create Path objects\n objs = []\n\n for cur_ra in ra_arr:\n crds = [[cur_ra, cur_dec] for cur_dec in\n np.arange(dec_min, dec_max + d_dec_step, d_dec_step)]\n lbl = raDegToString(cur_ra)\n objs += self._get_path(viewer, image, crds, lbl, 1)\n for cur_dec in dec_arr:\n crds = [[cur_ra, cur_dec] for cur_ra in\n np.arange(ra_min, ra_max + d_ra_step, d_ra_step)]\n lbl = decDegToString(cur_dec)\n objs += self._get_path(viewer, image, crds, lbl, 0)\n\n return objs\n\n def _get_path(self, viewer, image, crds, lbl, axis):\n from ginga.canvas.types.basic import Path, Text\n\n try:\n pts = image.wcs.wcspt_to_datapt(crds, naxispath=image.naxispath)\n except Exception as e:\n self.logger.warning('WCSAxes failed: {}'.format(str(e)))\n return []\n\n # Don't draw outside image area\n mask = ((pts[:, 0] >= 0) & (pts[:, 0] < image.width) &\n (pts[:, 1] >= 0) & (pts[:, 1] < image.height))\n pts = pts[mask]\n\n if len(pts) == 0:\n self.logger.debug(\n 'All WCSAxes coords ({}) out of bound in {}x{} '\n 'image'.format(crds, image.width, image.height))\n return []\n\n path_obj = Path(\n points=pts, coords='data', linewidth=self.linewidth,\n linestyle=self.linestyle, color=self.color,\n alpha=self.alpha)\n # this is necessary because we are not actually adding to a canvas\n path_obj.crdmap = viewer.get_coordmap('data')\n\n if self.show_label:\n # Calculate label orientation\n x1, y1 = pts[0]\n x2, y2 = pts[-1]\n dx = x2 - x1\n dy = y2 - y1\n m = dy / dx\n c = y1 - m * x1\n\n if abs(m) < 1: # x axis varying\n x = min(x1, x2) + abs(dx) * 0.45\n y = m * x + c + self.txt_off\n else: # y axis varying\n y = min(y1, y2) + abs(dy) * 0.45\n if np.isfinite(m):\n x = (y - c) / m\n else:\n x = min(x1, x2)\n x += self.txt_off\n\n if axis == 0: # DEC\n user_angle = self.dec_angle\n default_rot = 0\n else: # RA\n user_angle = self.ra_angle\n default_rot = 90\n\n if user_angle is None:\n try:\n rot = math.atan(m) * 180 / math.pi\n except ValueError:\n rot = default_rot\n rot = self._cur_rot + rot\n else:\n rot = user_angle\n\n if self._cur_swap:\n # axes are swapped\n rot -= 90\n\n text_obj = Text(x, y, text=lbl, font=self.font,\n fontsize=self.fontsize, color=self.color,\n alpha=self.alpha, rot_deg=rot, coord='data')\n text_obj.crdaxis = axis\n # this is necessary because we are not actually adding to a canvas\n text_obj.crdmap = viewer.get_coordmap('data')\n\n return [path_obj, text_obj]\n\n else:\n return [path_obj]\n\n def sync_state(self):\n for obj in self.objects:\n if obj.kind == 'text':\n if self.show_label:\n obj.alpha = self.alpha\n obj.color = self.color\n obj.font = self.font\n obj.fontsize = self.fontsize\n if obj.crdaxis == 0 and self.dec_angle is not None:\n obj.rot_deg = self.dec_angle\n elif obj.crdaxis == 1 and self.ra_angle is not None:\n obj.rot_deg = self.ra_angle\n else:\n obj.alpha = 0 # hide\n\n else: # path\n obj.alpha = self.alpha\n obj.color = self.color\n obj.linewidth = self.linewidth\n obj.linestyle = self.linestyle\n\n def draw(self, viewer):\n # see if we need to recalculate our grid\n image = viewer.get_image()\n update = False\n if self._cur_image != image:\n # new image loaded\n update = True\n\n cur_swap = viewer.get_transforms()[2]\n if cur_swap != self._cur_swap:\n # axes have been swapped\n update = True\n\n cur_rot = viewer.get_rotation()\n if cur_rot != self._cur_rot and self.show_label:\n # rotation has changed\n # TODO: for a rotation or swap axes change, it would be\n # sufficient to simply calculate the new rotation angles\n # and update all the text objects in self.objects\n update = True\n\n if len(self.objects) == 0:\n # initial time\n update = True\n\n if update:\n # only expensive recalculation of grid if needed\n self.ra_angle = None\n self.dec_angle = None\n self.objects = self._calc_axes(viewer, image, cur_rot, cur_swap)\n\n super(WCSAxes, self).draw(viewer)\n\n\nregister_canvas_types(dict(ruler=Ruler, compass=Compass,\n crosshair=Crosshair, annulus=Annulus,\n annulus2r=Annulus2R, wcsaxes=WCSAxes))\n\n# END\n" ]
[ [ "numpy.multiply", "numpy.asarray", "numpy.rint", "numpy.subtract", "numpy.add", "numpy.divide" ], [ "numpy.array" ], [ "numpy.asarray", "numpy.zeros", "numpy.allclose" ], [ "numpy.isfinite", "numpy.asarray", "numpy.arange", "numpy.isscalar", "numpy.logical_and" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vsriv90/mechanical_engineering
[ "c922cdce1a595e9acb6a87cf415fb3685caf51a3" ]
[ "Beams/Cantilever Beam - End Loaded.py" ]
[ "#!/usr/bin/env python\n# coding: utf-8\n\n# # Cantilever beams - End Loaded\n\n# ![Cantilever%20-%20End%20Loaded.jpeg](attachment:Cantilever%20-%20End%20Loaded.jpeg)\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sn # to draw plots\n# import plotly.express as px\n# import csv\n# import sympy\n\nfrom PIL import Image\n\n# SIMPLY SUPPORTED BEAM - Single Load: PARAMETERS\n\nf = 700 # Value of load\nl = 100 # Total length of beam\n\nUnitF = str('N') # To show units of force\nUnitL = str(\"mm\") # To show units of length\n\n\n# In[16]:\n\n\nx = [0,l] \ny = [0,0] \n\n# plotting the points on X axis\nplt.plot(x, y,label = \"Beam\", color='green', linewidth = 10,marker='o', markerfacecolor='blue', markersize=15) \nplt.legend() # giving a legend to my graph\n\n##################### ENTERING LOADS TO GRAPH #####################\n# fig,ax = plt.subplots(1)\n\nAvX = [0,0] # x-axis values\nAvY = [f/2,-f/2] # corresponding y-axis values\nplt.plot(AvX, AvY, linestyle='--',marker='s',markersize=10, color='grey') # To create the reaction line \nplt.text(1,-f,str(round(f,2))+UnitF) # To show the values on the points\n \nLoadX = [l,l] \nLoadY = [0,f] \n \nplt.plot(LoadX, LoadY, linestyle='--',marker='v',markersize=10) # To create the force line \nplt.text(l,f+1,str(round(f,2))+UnitF) # (Coordiante x, Coordinate y,the value in text+Unit)\n\nSupportX = [0]\nSupportY = [0]\nplt.plot(SupportX, SupportX,marker='s',markersize=25) # To create the force line \nplt.text(-2,20,\"RIGID\") # (Coordiante x, Coordinate y,the text)\n\n#################### End of load entering ###########################\n\n# AXIS LEGENDS \n\nplt.xlabel('Beam length in '+ UnitL)\nplt.title('Loads on beam') # giving a title to graph \n\nplt.ylim(top=1.5*f) # to set maximum y-axis value\nplt.ylim(bottom=-1.5*f) # to set minimum y-axis value\n\nplt.gca().axes.get_yaxis().set_visible(False) # Make y-aixs values visible or invisible\nplt.show() # function to show the plot \n\n# ---------------------------------------------------------------------\n# SHEAR FORCE DIAGRAM\n\nShearX = [0,0,l,l] \nShearY = [0,f,f,0] \nplt.plot(ShearX, ShearY, linestyle='--', marker='o') #plotting the points on X axis\n\n# To show the values on the points\nplt.text(0,0,str(0)+UnitF) # (Coordiante x, Coordinate y,the value in text+Unit) # point 1\nplt.text(0,f,str(round(f,2))+UnitF) # point 2, with integers rounded off\nplt.text(l,f,str(round(f,2))+UnitF) # point 3\nplt.text(l,0,str(0)+UnitF) # point 4\n\n# Plotting the 0 line\nZeroLX = [0,l] \nZeroLY = [0,0] \nplt.plot(ZeroLX, ZeroLY, color='black') # plotting the line 2 points \n\n# OVERALL DETAILS FOR THE GRAPH\nplt.xlabel('Position along the beam')\nplt.title('Shear/Transverse Force Diagram') # giving a title to graph \nplt.gca().axes.get_yaxis().set_visible(False) # Make y-aixs values visible or invisible\nplt.show() # function to show the plot \n\n# ---------------------------------------------------------------------\n# BENDING MOMENT DIAGRAM\n\nMomX = [0,0,l] \nMomY = [0,f*l,0] \nplt.plot(MomX, MomY, linestyle=':', marker='o', label=\"Moment direction = Counter-clockwise\") # plotting the points on X axis\nplt.legend() #legend to show direction of moment\n\nplt.text(0,0,str((0))) # (Coordiante x, Coordinate y,the value in text+Unit) # point 1\nplt.text(0,f*l,str(round((f*l),2))+UnitF+UnitL) # To SHOW the Moment value at the point # point 2\nplt.text(l,-10,str((0))) # point 3\n\nplt.plot(ZeroLX, ZeroLY, color='black')\n\n# OVERALL DETAILS FOR THE GRAPH\nplt.xlabel('Position along the beam')\nplt.title('Bending Moment Diagram') # giving a title to graph \nplt.gca().axes.get_yaxis().set_visible(False) # Make y-aixs values visible or invisible \nplt.show() # function to show the plot \n\n\n# https://www.geeksforgeeks.org/graph-plotting-in-python-set-1/\n\n# In[ ]:\n\n\n\n\n\n# In[49]:\n\n\n# help(plt.plot)\n\n\n# In[ ]:\n\n\n\n\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.gca", "matplotlib.pyplot.title", "matplotlib.pyplot.ylim", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.text", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
aetros/aetros-cli
[ "a2a1f38d6af1660e1e2680c7d413ec2aef45faab" ]
[ "aetros/utils/image.py" ]
[ "# Copyright (c) 2014-2016, NVIDIA CORPORATION. All rights reserved.\n# BSD 3-clause license\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport math\nfrom six.moves import range\n\n# Find the best implementation available\nfrom aetros.utils.pilutil import imresize\n\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from io import StringIO\n\nimport numpy as np\nimport PIL.Image\n\n# Library defaults:\n# PIL.Image:\n# size -- (width, height)\n# np.array:\n# shape -- (height, width, channels)\n# range -- [0-255]\n# dtype -- uint8\n# channels -- RGB\n# caffe.datum:\n# datum.data type -- bytes (uint8)\n# datum.float_data type -- float32\n# when decoding images, channels are BGR\n# DIGITS:\n# image_dims -- (height, width, channels)\n\n# List of supported file extensions\n# Use like \"if filename.endswith(SUPPORTED_EXTENSIONS)\"\nSUPPORTED_EXTENSIONS = ('.png', '.jpg', '.jpeg', '.bmp', '.ppm')\n\n\ndef upscale(image, ratio):\n \"\"\"\n return upscaled image array\n Arguments:\n image -- a (H,W,C) numpy.ndarray\n ratio -- scaling factor (>1)\n \"\"\"\n if not isinstance(image, np.ndarray):\n raise ValueError('Expected ndarray')\n if ratio < 1:\n raise ValueError('Ratio must be greater than 1 (ratio=%f)' % ratio)\n width = int(math.floor(image.shape[1] * ratio))\n height = int(math.floor(image.shape[0] * ratio))\n channels = image.shape[2]\n out = np.ndarray((height, width, channels), dtype=np.uint8)\n for x, y in np.ndindex((width, height)):\n out[y, x] = image[int(math.floor(y / ratio)), int(math.floor(x / ratio))]\n return out\n\n\ndef resize_image(image, height, width,\n channels=None,\n resize_mode=None\n ):\n \"\"\"\n Resizes an image and returns it as a np.array\n Arguments:\n image -- a PIL.Image or numpy.ndarray\n height -- height of new image\n width -- width of new image\n Keyword Arguments:\n channels -- channels of new image (stays unchanged if not specified)\n resize_mode -- can be crop, squash, fill or half_crop\n \"\"\"\n if resize_mode is None:\n resize_mode = 'squash'\n if resize_mode not in ['crop', 'squash', 'fill', 'half_crop']:\n raise ValueError('resize_mode \"%s\" not supported' % resize_mode)\n\n if channels not in [None, 1, 3]:\n raise ValueError('unsupported number of channels: %s' % channels)\n\n if isinstance(image, PIL.Image.Image):\n # Convert image mode (channels)\n if channels is None:\n image_mode = image.mode\n if image_mode == 'L':\n channels = 1\n elif image_mode == 'RGB':\n channels = 3\n else:\n raise ValueError('unknown image mode \"%s\"' % image_mode)\n elif channels == 1:\n # 8-bit pixels, black and white\n image_mode = 'L'\n elif channels == 3:\n # 3x8-bit pixels, true color\n image_mode = 'RGB'\n if image.mode != image_mode:\n image = image.convert(image_mode)\n image = np.array(image)\n elif isinstance(image, np.ndarray):\n if image.dtype != np.uint8:\n image = image.astype(np.uint8)\n if image.ndim == 3 and image.shape[2] == 1:\n image = image.reshape(image.shape[:2])\n if channels is None:\n if image.ndim == 2:\n channels = 1\n elif image.ndim == 3 and image.shape[2] == 3:\n channels = 3\n else:\n raise ValueError('invalid image shape: %s' % (image.shape,))\n elif channels == 1:\n if image.ndim != 2:\n if image.ndim == 3 and image.shape[2] == 3:\n # color to grayscale\n image = np.dot(image, [0.299, 0.587, 0.114]).astype(np.uint8)\n else:\n raise ValueError('invalid image shape: %s' % (image.shape,))\n elif channels == 3:\n if image.ndim == 2:\n # grayscale to color\n image = np.repeat(image, 3).reshape(image.shape + (3,))\n elif image.shape[2] != 3:\n raise ValueError('invalid image shape: %s' % (image.shape,))\n else:\n raise ValueError('resize_image() expected a PIL.Image.Image or a numpy.ndarray')\n\n # No need to resize\n if image.shape[0] == height and image.shape[1] == width:\n return image\n\n # Resize\n interp = 'bilinear'\n\n width_ratio = float(image.shape[1]) / width\n height_ratio = float(image.shape[0]) / height\n if resize_mode == 'squash' or width_ratio == height_ratio:\n return imresize(image, (height, width), interp=interp)\n elif resize_mode == 'crop':\n # resize to smallest of ratios (relatively larger image), keeping aspect ratio\n if width_ratio > height_ratio:\n resize_height = height\n resize_width = int(round(image.shape[1] / height_ratio))\n else:\n resize_width = width\n resize_height = int(round(image.shape[0] / width_ratio))\n image = imresize(image, (resize_height, resize_width), interp=interp)\n\n # chop off ends of dimension that is still too long\n if width_ratio > height_ratio:\n start = int(round((resize_width - width) / 2.0))\n return image[:, start:start + width]\n else:\n start = int(round((resize_height - height) / 2.0))\n return image[start:start + height, :]\n else:\n if resize_mode == 'fill':\n # resize to biggest of ratios (relatively smaller image), keeping aspect ratio\n if width_ratio > height_ratio:\n resize_width = width\n resize_height = int(round(image.shape[0] / width_ratio))\n if (height - resize_height) % 2 == 1:\n resize_height += 1\n else:\n resize_height = height\n resize_width = int(round(image.shape[1] / height_ratio))\n if (width - resize_width) % 2 == 1:\n resize_width += 1\n image = imresize(image, (resize_height, resize_width), interp=interp)\n elif resize_mode == 'half_crop':\n # resize to average ratio keeping aspect ratio\n new_ratio = (width_ratio + height_ratio) / 2.0\n resize_width = int(round(image.shape[1] / new_ratio))\n resize_height = int(round(image.shape[0] / new_ratio))\n if width_ratio > height_ratio and (height - resize_height) % 2 == 1:\n resize_height += 1\n elif width_ratio < height_ratio and (width - resize_width) % 2 == 1:\n resize_width += 1\n image = imresize(image, (resize_height, resize_width), interp=interp)\n # chop off ends of dimension that is still too long\n if width_ratio > height_ratio:\n start = int(round((resize_width - width) / 2.0))\n image = image[:, start:start + width]\n else:\n start = int(round((resize_height - height) / 2.0))\n image = image[start:start + height, :]\n else:\n raise Exception('unrecognized resize_mode \"%s\"' % resize_mode)\n\n # fill ends of dimension that is too short with random noise\n if width_ratio > height_ratio:\n padding = (height - resize_height) / 2\n noise_size = (padding, width)\n if channels > 1:\n noise_size += (channels,)\n noise = np.random.randint(0, 255, noise_size).astype('uint8')\n image = np.concatenate((noise, image, noise), axis=0)\n else:\n padding = (width - resize_width) / 2\n noise_size = (height, padding)\n if channels > 1:\n noise_size += (channels,)\n noise = np.random.randint(0, 255, noise_size).astype('uint8')\n image = np.concatenate((noise, image, noise), axis=1)\n\n return image\n\n\ndef embed_image_html(image):\n \"\"\"\n Returns an image embedded in HTML base64 format\n (Based on Caffe's web_demo)\n Arguments:\n image -- a PIL.Image or np.ndarray\n \"\"\"\n if image is None:\n return None\n elif isinstance(image, PIL.Image.Image):\n pass\n elif isinstance(image, np.ndarray):\n image = PIL.Image.fromarray(image)\n else:\n raise ValueError('image must be a PIL.Image or a np.ndarray')\n\n # Read format from the image\n fmt = image.format\n if not fmt:\n # default to JPEG\n fmt = 'jpeg'\n else:\n fmt = fmt.lower()\n\n string_buf = StringIO()\n image.save(string_buf, format=fmt)\n data = string_buf.getvalue().encode('base64').replace('\\n', '')\n return 'data:image/%s;base64,%s' % (fmt, data)\n\n\ndef add_bboxes_to_image(image, bboxes, color='red', width=1):\n \"\"\"\n Draw rectangles on the image for the bounding boxes\n Returns a PIL.Image\n Arguments:\n image -- input image\n bboxes -- bounding boxes in the [((l, t), (r, b)), ...] format\n Keyword arguments:\n color -- color to draw the rectangles\n width -- line width of the rectangles\n Example:\n image = Image.open(filename)\n add_bboxes_to_image(image, bboxes[filename], width=2, color='#FF7700')\n image.show()\n \"\"\"\n def expanded_bbox(bbox, n):\n \"\"\"\n Grow the bounding box by n pixels\n \"\"\"\n l = min(bbox[0][0], bbox[1][0])\n r = max(bbox[0][0], bbox[1][0])\n t = min(bbox[0][1], bbox[1][1])\n b = max(bbox[0][1], bbox[1][1])\n return ((l - n, t - n), (r + n, b + n))\n\n from PIL import Image, ImageDraw\n draw = ImageDraw.Draw(image)\n for bbox in bboxes:\n for n in range(width):\n draw.rectangle(expanded_bbox(bbox, n), outline=color)\n\n return image\n\n\ndef get_layer_vis_square(data,\n allow_heatmap=True,\n normalize=True,\n min_img_dim=100,\n max_width=1200,\n channel_order='RGB',\n colormap='jet',\n ):\n \"\"\"\n Returns a vis_square for the given layer data\n Arguments:\n data -- a np.ndarray\n Keyword arguments:\n allow_heatmap -- if True, convert single channel images to heatmaps\n normalize -- whether to normalize the data when visualizing\n max_width -- maximum width for the vis_square\n \"\"\"\n if channel_order not in ['RGB', 'BGR']:\n raise ValueError('Unsupported channel_order %s' % channel_order)\n if data.ndim == 1:\n # interpret as 1x1 grayscale images\n # (N, 1, 1)\n data = data[:, np.newaxis, np.newaxis]\n elif data.ndim == 2:\n # interpret as 1x1 grayscale images\n # (N, 1, 1)\n data = data.reshape((data.shape[0] * data.shape[1], 1, 1))\n elif data.ndim == 3:\n if data.shape[0] == 3:\n # interpret as a color image\n # (1, H, W,3)\n if channel_order == 'BGR':\n data = data[[2, 1, 0], ...] # BGR to RGB (see issue #59)\n data = data.transpose(1, 2, 0)\n data = data[np.newaxis, ...]\n else:\n # interpret as grayscale images\n # (N, H, W)\n pass\n elif data.ndim == 4:\n if data.shape[0] == 3:\n # interpret as HxW color images\n # (N, H, W, 3)\n data = data.transpose(1, 2, 3, 0)\n if channel_order == 'BGR':\n data = data[:, :, :, [2, 1, 0]] # BGR to RGB (see issue #59)\n elif data.shape[1] == 3:\n # interpret as HxW color images\n # (N, H, W, 3)\n data = data.transpose(0, 2, 3, 1)\n if channel_order == 'BGR':\n data = data[:, :, :, [2, 1, 0]] # BGR to RGB (see issue #59)\n else:\n # interpret as HxW grayscale images\n # (N, H, W)\n data = data.reshape((data.shape[0] * data.shape[1], data.shape[2], data.shape[3]))\n else:\n raise RuntimeError('unrecognized data shape: %s' % (data.shape,))\n\n return get_layer_vis_square_raw(data,\n allow_heatmap,\n normalize,\n min_img_dim,\n max_width,\n colormap,\n )\n\ndef get_image_tales(images, colormap='jet', min_img_dim=100, max_width=1000):\n\n padsize = 1\n # convert to float since we're going to do some math\n images = images.astype('float32')\n\n images -= images.min()\n if images.max() > 0:\n images /= images.max()\n images *= 255\n\n if images.ndim == 3:\n # they're grayscale - convert to a colormap\n redmap, greenmap, bluemap = get_color_map(colormap)\n\n red = np.interp(images * (len(redmap) - 1) / 255.0, range(len(redmap)), redmap)\n green = np.interp(images * (len(greenmap) - 1) / 255.0, range(len(greenmap)), greenmap)\n blue = np.interp(images * (len(bluemap) - 1) / 255.0, range(len(bluemap)), bluemap)\n\n # Slap the channels back together\n images = np.concatenate(\n (red[..., np.newaxis], green[..., np.newaxis], blue[..., np.newaxis]), axis=3)\n images = np.minimum(images, 255)\n images = np.maximum(images, 0)\n\n # convert back to uint8\n images = images.astype('uint8')\n\n # Compute the output image matrix dimensions\n n = int(np.ceil(np.sqrt(images.shape[0])))\n ny = n\n nx = n\n length = images.shape[0]\n if n * (n - 1) >= length:\n nx = n - 1\n\n # Add padding between the images\n padding = ((0, nx * ny - length), (0, padsize), (0, padsize)) + ((0, 0),) * (images.ndim - 3)\n padded = np.pad(images, padding, mode='constant', constant_values=0)\n\n # Tile the images beside each other\n tiles = padded.reshape(\n (ny, nx) + padded.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, padded.ndim + 1)))\n tiles = tiles.reshape((ny * tiles.shape[1], nx * tiles.shape[3]) + tiles.shape[4:])\n\n return tiles\n\ndef get_layer_vis_square_raw(data,\n allow_heatmap=True,\n normalize=True,\n min_img_dim=100,\n max_width=1200,\n colormap='jet',\n ):\n # chop off data so that it will fit within max_width\n padsize = 0\n width = data.shape[2]\n if width > max_width:\n data = data[:1, :max_width, :max_width]\n else:\n if width > 1:\n padsize = 1\n width += 1\n n = max(max_width // width, 1)\n n *= n\n data = data[:n]\n\n if not allow_heatmap and data.ndim == 3:\n data = data[..., np.newaxis]\n\n vis = vis_square(data,\n padsize=padsize,\n normalize=normalize,\n colormap=colormap\n )\n\n # find minimum dimension and upscale if necessary\n _min = sorted(vis.shape[:2])[0]\n if _min < min_img_dim:\n # upscale image\n ratio = min_img_dim / float(_min)\n vis = upscale(vis, ratio)\n return vis\n\n\ndef vis_square(images,\n padsize=1,\n normalize=False,\n colormap='jet',\n ):\n \"\"\"\n Visualize each image in a grid of size approx sqrt(n) by sqrt(n)\n Returns a np.array image\n (Based on Caffe's filter_visualization notebook)\n Arguments:\n images -- an array of shape (N, H, W) or (N, H, W, C)\n if C is not set, a heatmap is computed for the result\n Keyword arguments:\n padsize -- how many pixels go inbetween the tiles\n normalize -- if true, scales (min, max) across all images out to (0, 1)\n colormap -- a string representing one of the supported colormaps\n \"\"\"\n assert 3 <= images.ndim <= 4, 'images.ndim must be 3 or 4'\n # convert to float since we're going to do some math\n images = images.astype('float32')\n if normalize:\n images -= images.min()\n if images.max() > 0:\n images /= images.max()\n images *= 255\n\n if images.ndim == 3:\n # they're grayscale - convert to a colormap\n redmap, greenmap, bluemap = get_color_map(colormap)\n\n red = np.interp(images * (len(redmap) - 1) / 255.0, range(len(redmap)), redmap)\n green = np.interp(images * (len(greenmap) - 1) / 255.0, range(len(greenmap)), greenmap)\n blue = np.interp(images * (len(bluemap) - 1) / 255.0, range(len(bluemap)), bluemap)\n\n # Slap the channels back together\n images = np.concatenate(\n (red[..., np.newaxis], green[..., np.newaxis], blue[..., np.newaxis]), axis=3)\n images = np.minimum(images, 255)\n images = np.maximum(images, 0)\n\n # convert back to uint8\n images = images.astype('uint8')\n\n # Compute the output image matrix dimensions\n n = int(np.ceil(np.sqrt(images.shape[0])))\n ny = n\n nx = n\n length = images.shape[0]\n if n * (n - 1) >= length:\n nx = n - 1\n\n # Add padding between the images\n padding = ((0, nx * ny - length), (0, padsize), (0, padsize)) + ((0, 0),) * (images.ndim - 3)\n padded = np.pad(images, padding, mode='constant', constant_values=255)\n\n # Tile the images beside each other\n tiles = padded.reshape(\n (ny, nx) + padded.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, padded.ndim + 1)))\n tiles = tiles.reshape((ny * tiles.shape[1], nx * tiles.shape[3]) + tiles.shape[4:])\n\n if tiles.shape[-1] == 1:\n # grayscale to color\n tiles = np.dstack([tiles.squeeze()] * 3)\n\n return tiles\n\n\ndef get_color_map(name):\n \"\"\"\n Return a colormap as (redmap, greenmap, bluemap)\n Arguments:\n name -- the name of the colormap. If unrecognized, will default to 'jet'.\n \"\"\"\n redmap = [0]\n greenmap = [0]\n bluemap = [0]\n if name == 'white':\n # essentially a noop\n redmap = [0, 1]\n greenmap = [0, 1]\n bluemap = [0, 1]\n elif name == 'simple':\n redmap = [0, 1, 1, 1]\n greenmap = [0, 0, 1, 1]\n bluemap = [0, 0, 0, 1]\n elif name == 'hot':\n redmap = [0, 0.03968253968253968, 0.07936507936507936, 0.119047619047619, 0.1587301587301587, 0.1984126984126984, 0.2380952380952381, 0.2777777777777778, 0.3174603174603174, 0.3571428571428571, 0.3968253968253968, 0.4365079365079365, 0.4761904761904762, 0.5158730158730158, 0.5555555555555556, 0.5952380952380952,\n 0.6349206349206349, 0.6746031746031745, 0.7142857142857142, 0.753968253968254, 0.7936507936507936, 0.8333333333333333, 0.873015873015873, 0.9126984126984127, 0.9523809523809523, 0.992063492063492, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n greenmap = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.03174603174603163, 0.0714285714285714, 0.1111111111111112, 0.1507936507936507, 0.1904761904761905, 0.23015873015873, 0.2698412698412698, 0.3095238095238093, 0.3492063492063491, 0.3888888888888888, 0.4285714285714284,\n 0.4682539682539679, 0.5079365079365079, 0.5476190476190477, 0.5873015873015872, 0.6269841269841268, 0.6666666666666665, 0.7063492063492065, 0.746031746031746, 0.7857142857142856, 0.8253968253968254, 0.8650793650793651, 0.9047619047619047, 0.9444444444444442, 0.984126984126984, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n bluemap = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.04761904761904745, 0.1269841269841265,\n 0.2063492063492056, 0.2857142857142856, 0.3650793650793656, 0.4444444444444446, 0.5238095238095237, 0.6031746031746028, 0.6825396825396828, 0.7619047619047619, 0.8412698412698409, 0.92063492063492, 1]\n elif name == 'rainbow':\n redmap = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9365079365079367, 0.8571428571428572, 0.7777777777777777, 0.6984126984126986, 0.6190476190476191, 0.53968253968254, 0.4603174603174605, 0.3809523809523814, 0.3015873015873018, 0.2222222222222223, 0.1428571428571432,\n 0.06349206349206415, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.03174603174603208, 0.08465608465608465, 0.1375661375661377, 0.1904761904761907, 0.2433862433862437, 0.2962962962962963, 0.3492063492063493, 0.4021164021164023, 0.4550264550264553, 0.5079365079365079, 0.5608465608465609, 0.6137566137566139, 0.666666666666667]\n greenmap = [0, 0.03968253968253968, 0.07936507936507936, 0.119047619047619, 0.1587301587301587, 0.1984126984126984, 0.2380952380952381, 0.2777777777777778, 0.3174603174603174, 0.3571428571428571, 0.3968253968253968, 0.4365079365079365, 0.4761904761904762, 0.5158730158730158, 0.5555555555555556, 0.5952380952380952, 0.6349206349206349, 0.6746031746031745, 0.7142857142857142, 0.753968253968254, 0.7936507936507936,\n 0.8333333333333333, 0.873015873015873, 0.9126984126984127, 0.9523809523809523, 0.992063492063492, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9841269841269842, 0.9047619047619047, 0.8253968253968256, 0.7460317460317465, 0.666666666666667, 0.587301587301587, 0.5079365079365079, 0.4285714285714288, 0.3492063492063493, 0.2698412698412698, 0.1904761904761907, 0.1111111111111116, 0.03174603174603208, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n bluemap = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01587301587301582, 0.09523809523809534, 0.1746031746031744, 0.2539682539682535,\n 0.333333333333333, 0.412698412698413, 0.4920634920634921, 0.5714285714285712, 0.6507936507936507, 0.7301587301587302, 0.8095238095238093, 0.8888888888888884, 0.9682539682539679, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n elif name == 'winter':\n greenmap = [0, 1]\n bluemap = [1, 0.5]\n else:\n if name != 'jet':\n print('Warning: colormap \"%s\" not supported. Using jet instead.' % name)\n redmap = [0, 0, 0, 0, 0.5, 1, 1, 1, 0.5]\n greenmap = [0, 0, 0.5, 1, 1, 1, 0.5, 0, 0]\n bluemap = [0.5, 1, 1, 1, 0.5, 0, 0, 0, 0]\n return 255.0 * np.array(redmap), 255.0 * np.array(greenmap), 255.0 * np.array(bluemap)\n" ]
[ [ "numpy.dot", "numpy.minimum", "numpy.pad", "numpy.maximum", "numpy.sqrt", "numpy.ndarray", "numpy.concatenate", "numpy.ndindex", "numpy.repeat", "numpy.array", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lkeab/detectron2
[ "d4d2948aed6c0c73558da10f8647661f61470e37", "3a686d889ac83f722ad861be9f8754c4680561b7", "d4d2948aed6c0c73558da10f8647661f61470e37" ]
[ "configs/Misc/torchvision_imagenet_R_50.py", "detectron2/engine/hooks.py", "detectron2/export/c10.py" ]
[ "\"\"\"\nAn example config file to train a ImageNet classifier with detectron2.\nModel and dataloader both come from torchvision.\nThis shows how to use detectron2 as a general engine for any new models and tasks.\nTo run, use the following command:\n\npython tools/lazyconfig_train_net.py --config-file configs/Misc/torchvision_imagenet_R_50.py \\\n --num-gpus 8 dataloader.train.dataset.root=/path/to/imagenet/\n\"\"\"\n\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom omegaconf import OmegaConf\nimport torchvision\nfrom torchvision.transforms import transforms as T\nfrom torchvision.models.resnet import ResNet, Bottleneck\nfrom fvcore.common.param_scheduler import MultiStepParamScheduler\n\nfrom detectron2.solver import WarmupParamScheduler\nfrom detectron2.solver.build import get_default_optimizer_params\nfrom detectron2.config import LazyCall as L\nfrom detectron2.model_zoo import get_config\nfrom detectron2.data.samplers import TrainingSampler, InferenceSampler\nfrom detectron2.evaluation import DatasetEvaluator\nfrom detectron2.utils import comm\n\n\ndef build_data_loader(dataset, batch_size, num_workers, training=True):\n return torch.utils.data.DataLoader(\n dataset,\n sampler=(TrainingSampler if training else InferenceSampler)(len(dataset)),\n batch_size=batch_size,\n num_workers=num_workers,\n pin_memory=True,\n )\n\n\nclass ClassificationNet(nn.Module):\n def __init__(self, model: nn.Module):\n super().__init__()\n self.model = model\n\n @property\n def device(self):\n return list(self.model.parameters())[0].device\n\n def forward(self, inputs):\n image, label = inputs\n pred = self.model(image.to(self.device))\n if self.training:\n label = label.to(self.device)\n return F.cross_entropy(pred, label)\n else:\n return pred\n\n\nclass ClassificationAcc(DatasetEvaluator):\n def reset(self):\n self.corr = self.total = 0\n\n def process(self, inputs, outputs):\n image, label = inputs\n self.corr += (outputs.argmax(dim=1).cpu() == label.cpu()).sum().item()\n self.total += len(label)\n\n def evaluate(self):\n all_corr_total = comm.all_gather([self.corr, self.total])\n corr = sum(x[0] for x in all_corr_total)\n total = sum(x[1] for x in all_corr_total)\n return {\"accuracy\": corr / total}\n\n\ndataloader = OmegaConf.create()\ndataloader.train = L(build_data_loader)(\n dataset=L(torchvision.datasets.ImageNet)(\n root=\"/path/to/imagenet\",\n split=\"train\",\n transform=L(T.Compose)(\n transforms=[\n L(T.RandomResizedCrop)(size=224),\n L(T.RandomHorizontalFlip)(),\n T.ToTensor(),\n L(T.Normalize)(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),\n ]\n ),\n ),\n batch_size=256 // 8,\n num_workers=4,\n training=True,\n)\n\ndataloader.test = L(build_data_loader)(\n dataset=L(torchvision.datasets.ImageNet)(\n root=\"${...train.dataset.root}\",\n split=\"val\",\n transform=L(T.Compose)(\n transforms=[\n L(T.Resize)(size=256),\n L(T.CenterCrop)(size=224),\n T.ToTensor(),\n L(T.Normalize)(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),\n ]\n ),\n ),\n batch_size=256 // 8,\n num_workers=4,\n training=False,\n)\n\ndataloader.evaluator = L(ClassificationAcc)()\n\nmodel = L(ClassificationNet)(\n model=(ResNet)(block=Bottleneck, layers=[3, 4, 6, 3], zero_init_residual=True)\n)\n\n\noptimizer = L(torch.optim.SGD)(\n params=L(get_default_optimizer_params)(),\n lr=0.1,\n momentum=0.9,\n weight_decay=1e-4,\n)\n\nlr_multiplier = L(WarmupParamScheduler)(\n scheduler=L(MultiStepParamScheduler)(\n values=[1.0, 0.1, 0.01, 0.001], milestones=[30, 60, 90, 100]\n ),\n warmup_length=1 / 100,\n warmup_factor=0.1,\n)\n\n\ntrain = get_config(\"common/train.py\").train\ntrain.init_checkpoint = None\ntrain.max_iter = 100 * 1281167 // 256\n", "# -*- coding: utf-8 -*-\n# Copyright (c) Facebook, Inc. and its affiliates.\n\nimport datetime\nimport itertools\nimport logging\nimport os\nimport tempfile\nimport time\nfrom collections import Counter\nimport torch\nfrom fvcore.common.checkpoint import PeriodicCheckpointer as _PeriodicCheckpointer\nfrom fvcore.common.param_scheduler import ParamScheduler\nfrom fvcore.common.timer import Timer\nfrom fvcore.nn.precise_bn import get_bn_modules, update_bn_stats\n\nimport detectron2.utils.comm as comm\nfrom detectron2.evaluation.testing import flatten_results_dict\nfrom detectron2.solver import LRMultiplier\nfrom detectron2.utils.events import EventStorage, EventWriter\nfrom detectron2.utils.file_io import PathManager\n\nfrom .train_loop import HookBase\n\n__all__ = [\n \"CallbackHook\",\n \"IterationTimer\",\n \"PeriodicWriter\",\n \"PeriodicCheckpointer\",\n \"LRScheduler\",\n \"AutogradProfiler\",\n \"EvalHook\",\n \"PreciseBN\",\n]\n\n\n\"\"\"\nImplement some common hooks.\n\"\"\"\n\n\nclass CallbackHook(HookBase):\n \"\"\"\n Create a hook using callback functions provided by the user.\n \"\"\"\n\n def __init__(self, *, before_train=None, after_train=None, before_step=None, after_step=None):\n \"\"\"\n Each argument is a function that takes one argument: the trainer.\n \"\"\"\n self._before_train = before_train\n self._before_step = before_step\n self._after_step = after_step\n self._after_train = after_train\n\n def before_train(self):\n if self._before_train:\n self._before_train(self.trainer)\n\n def after_train(self):\n if self._after_train:\n self._after_train(self.trainer)\n # The functions may be closures that hold reference to the trainer\n # Therefore, delete them to avoid circular reference.\n del self._before_train, self._after_train\n del self._before_step, self._after_step\n\n def before_step(self):\n if self._before_step:\n self._before_step(self.trainer)\n\n def after_step(self):\n if self._after_step:\n self._after_step(self.trainer)\n\n\nclass IterationTimer(HookBase):\n \"\"\"\n Track the time spent for each iteration (each run_step call in the trainer).\n Print a summary in the end of training.\n\n This hook uses the time between the call to its :meth:`before_step`\n and :meth:`after_step` methods.\n Under the convention that :meth:`before_step` of all hooks should only\n take negligible amount of time, the :class:`IterationTimer` hook should be\n placed at the beginning of the list of hooks to obtain accurate timing.\n \"\"\"\n\n def __init__(self, warmup_iter=3):\n \"\"\"\n Args:\n warmup_iter (int): the number of iterations at the beginning to exclude\n from timing.\n \"\"\"\n self._warmup_iter = warmup_iter\n self._step_timer = Timer()\n self._start_time = time.perf_counter()\n self._total_timer = Timer()\n\n def before_train(self):\n self._start_time = time.perf_counter()\n self._total_timer.reset()\n self._total_timer.pause()\n\n def after_train(self):\n logger = logging.getLogger(__name__)\n total_time = time.perf_counter() - self._start_time\n total_time_minus_hooks = self._total_timer.seconds()\n hook_time = total_time - total_time_minus_hooks\n\n num_iter = self.trainer.iter + 1 - self.trainer.start_iter - self._warmup_iter\n\n if num_iter > 0 and total_time_minus_hooks > 0:\n # Speed is meaningful only after warmup\n # NOTE this format is parsed by grep in some scripts\n logger.info(\n \"Overall training speed: {} iterations in {} ({:.4f} s / it)\".format(\n num_iter,\n str(datetime.timedelta(seconds=int(total_time_minus_hooks))),\n total_time_minus_hooks / num_iter,\n )\n )\n\n logger.info(\n \"Total training time: {} ({} on hooks)\".format(\n str(datetime.timedelta(seconds=int(total_time))),\n str(datetime.timedelta(seconds=int(hook_time))),\n )\n )\n\n def before_step(self):\n self._step_timer.reset()\n self._total_timer.resume()\n\n def after_step(self):\n # +1 because we're in after_step, the current step is done\n # but not yet counted\n iter_done = self.trainer.iter - self.trainer.start_iter + 1\n if iter_done >= self._warmup_iter:\n sec = self._step_timer.seconds()\n self.trainer.storage.put_scalars(time=sec)\n else:\n self._start_time = time.perf_counter()\n self._total_timer.reset()\n\n self._total_timer.pause()\n\n\nclass PeriodicWriter(HookBase):\n \"\"\"\n Write events to EventStorage (by calling ``writer.write()``) periodically.\n\n It is executed every ``period`` iterations and after the last iteration.\n Note that ``period`` does not affect how data is smoothed by each writer.\n \"\"\"\n\n def __init__(self, writers, period=20):\n \"\"\"\n Args:\n writers (list[EventWriter]): a list of EventWriter objects\n period (int):\n \"\"\"\n self._writers = writers\n for w in writers:\n assert isinstance(w, EventWriter), w\n self._period = period\n\n def after_step(self):\n if (self.trainer.iter + 1) % self._period == 0 or (\n self.trainer.iter == self.trainer.max_iter - 1\n ):\n for writer in self._writers:\n writer.write()\n\n def after_train(self):\n for writer in self._writers:\n # If any new data is found (e.g. produced by other after_train),\n # write them before closing\n writer.write()\n writer.close()\n\n\nclass PeriodicCheckpointer(_PeriodicCheckpointer, HookBase):\n \"\"\"\n Same as :class:`detectron2.checkpoint.PeriodicCheckpointer`, but as a hook.\n\n Note that when used as a hook,\n it is unable to save additional data other than what's defined\n by the given `checkpointer`.\n\n It is executed every ``period`` iterations and after the last iteration.\n \"\"\"\n\n def before_train(self):\n self.max_iter = self.trainer.max_iter\n\n def after_step(self):\n # No way to use **kwargs\n self.step(self.trainer.iter)\n\n\nclass LRScheduler(HookBase):\n \"\"\"\n A hook which executes a torch builtin LR scheduler and summarizes the LR.\n It is executed after every iteration.\n \"\"\"\n\n def __init__(self, optimizer=None, scheduler=None):\n \"\"\"\n Args:\n optimizer (torch.optim.Optimizer):\n scheduler (torch.optim.LRScheduler or fvcore.common.param_scheduler.ParamScheduler):\n if a :class:`ParamScheduler` object, it defines the multiplier over the base LR\n in the optimizer.\n\n If any argument is not given, will try to obtain it from the trainer.\n \"\"\"\n self._optimizer = optimizer\n self._scheduler = scheduler\n\n def before_train(self):\n self._optimizer = self._optimizer or self.trainer.optimizer\n if isinstance(self.scheduler, ParamScheduler):\n self._scheduler = LRMultiplier(\n self._optimizer,\n self.scheduler,\n self.trainer.max_iter,\n last_iter=self.trainer.iter - 1,\n )\n\n # NOTE: some heuristics on what LR to summarize\n # summarize the param group with most parameters\n largest_group = max(len(g[\"params\"]) for g in self._optimizer.param_groups)\n\n if largest_group == 1:\n # If all groups have one parameter,\n # then find the most common initial LR, and use it for summary\n lr_count = Counter([g[\"lr\"] for g in self._optimizer.param_groups])\n lr = lr_count.most_common()[0][0]\n for i, g in enumerate(self._optimizer.param_groups):\n if g[\"lr\"] == lr:\n self._best_param_group_id = i\n break\n else:\n for i, g in enumerate(self._optimizer.param_groups):\n if len(g[\"params\"]) == largest_group:\n self._best_param_group_id = i\n break\n\n def after_step(self):\n lr = self._optimizer.param_groups[self._best_param_group_id][\"lr\"]\n self.trainer.storage.put_scalar(\"lr\", lr, smoothing_hint=False)\n self.scheduler.step()\n\n @property\n def scheduler(self):\n return self._scheduler or self.trainer.scheduler\n\n def state_dict(self):\n if isinstance(self.scheduler, torch.optim.lr_scheduler._LRScheduler):\n return self.scheduler.state_dict()\n return {}\n\n def load_state_dict(self, state_dict):\n if isinstance(self.scheduler, torch.optim.lr_scheduler._LRScheduler):\n logger = logging.getLogger(__name__)\n logger.info(\"Loading scheduler from state_dict ...\")\n self.scheduler.load_state_dict(state_dict)\n\n\nclass AutogradProfiler(HookBase):\n \"\"\"\n A hook which runs `torch.autograd.profiler.profile`.\n\n Examples:\n ::\n hooks.AutogradProfiler(\n lambda trainer: trainer.iter > 10 and trainer.iter < 20, self.cfg.OUTPUT_DIR\n )\n\n The above example will run the profiler for iteration 10~20 and dump\n results to ``OUTPUT_DIR``. We did not profile the first few iterations\n because they are typically slower than the rest.\n The result files can be loaded in the ``chrome://tracing`` page in chrome browser.\n\n Note:\n When used together with NCCL on older version of GPUs,\n autograd profiler may cause deadlock because it unnecessarily allocates\n memory on every device it sees. The memory management calls, if\n interleaved with NCCL calls, lead to deadlock on GPUs that do not\n support ``cudaLaunchCooperativeKernelMultiDevice``.\n \"\"\"\n\n def __init__(self, enable_predicate, output_dir, *, use_cuda=True):\n \"\"\"\n Args:\n enable_predicate (callable[trainer -> bool]): a function which takes a trainer,\n and returns whether to enable the profiler.\n It will be called once every step, and can be used to select which steps to profile.\n output_dir (str): the output directory to dump tracing files.\n use_cuda (bool): same as in `torch.autograd.profiler.profile`.\n \"\"\"\n self._enable_predicate = enable_predicate\n self._use_cuda = use_cuda\n self._output_dir = output_dir\n\n def before_step(self):\n if self._enable_predicate(self.trainer):\n self._profiler = torch.autograd.profiler.profile(use_cuda=self._use_cuda)\n self._profiler.__enter__()\n else:\n self._profiler = None\n\n def after_step(self):\n if self._profiler is None:\n return\n self._profiler.__exit__(None, None, None)\n PathManager.mkdirs(self._output_dir)\n out_file = os.path.join(\n self._output_dir, \"profiler-trace-iter{}.json\".format(self.trainer.iter)\n )\n if \"://\" not in out_file:\n self._profiler.export_chrome_trace(out_file)\n else:\n # Support non-posix filesystems\n with tempfile.TemporaryDirectory(prefix=\"detectron2_profiler\") as d:\n tmp_file = os.path.join(d, \"tmp.json\")\n self._profiler.export_chrome_trace(tmp_file)\n with open(tmp_file) as f:\n content = f.read()\n with PathManager.open(out_file, \"w\") as f:\n f.write(content)\n\n\nclass EvalHook(HookBase):\n \"\"\"\n Run an evaluation function periodically, and at the end of training.\n\n It is executed every ``eval_period`` iterations and after the last iteration.\n \"\"\"\n\n def __init__(self, eval_period, eval_function):\n \"\"\"\n Args:\n eval_period (int): the period to run `eval_function`. Set to 0 to\n not evaluate periodically (but still after the last iteration).\n eval_function (callable): a function which takes no arguments, and\n returns a nested dict of evaluation metrics.\n\n Note:\n This hook must be enabled in all or none workers.\n If you would like only certain workers to perform evaluation,\n give other workers a no-op function (`eval_function=lambda: None`).\n \"\"\"\n self._period = eval_period\n self._func = eval_function\n\n def _do_eval(self):\n results = self._func()\n\n if results:\n assert isinstance(\n results, dict\n ), \"Eval function must return a dict. Got {} instead.\".format(results)\n\n flattened_results = flatten_results_dict(results)\n for k, v in flattened_results.items():\n try:\n v = float(v)\n except Exception as e:\n raise ValueError(\n \"[EvalHook] eval_function should return a nested dict of float. \"\n \"Got '{}: {}' instead.\".format(k, v)\n ) from e\n self.trainer.storage.put_scalars(**flattened_results, smoothing_hint=False)\n\n # Evaluation may take different time among workers.\n # A barrier make them start the next iteration together.\n comm.synchronize()\n\n def after_step(self):\n next_iter = self.trainer.iter + 1\n if self._period > 0 and next_iter % self._period == 0:\n # do the last eval in after_train\n if next_iter != self.trainer.max_iter:\n self._do_eval()\n\n def after_train(self):\n # This condition is to prevent the eval from running after a failed training\n if self.trainer.iter + 1 >= self.trainer.max_iter:\n self._do_eval()\n # func is likely a closure that holds reference to the trainer\n # therefore we clean it to avoid circular reference in the end\n del self._func\n\n\nclass PreciseBN(HookBase):\n \"\"\"\n The standard implementation of BatchNorm uses EMA in inference, which is\n sometimes suboptimal.\n This class computes the true average of statistics rather than the moving average,\n and put true averages to every BN layer in the given model.\n\n It is executed every ``period`` iterations and after the last iteration.\n \"\"\"\n\n def __init__(self, period, model, data_loader, num_iter):\n \"\"\"\n Args:\n period (int): the period this hook is run, or 0 to not run during training.\n The hook will always run in the end of training.\n model (nn.Module): a module whose all BN layers in training mode will be\n updated by precise BN.\n Note that user is responsible for ensuring the BN layers to be\n updated are in training mode when this hook is triggered.\n data_loader (iterable): it will produce data to be run by `model(data)`.\n num_iter (int): number of iterations used to compute the precise\n statistics.\n \"\"\"\n self._logger = logging.getLogger(__name__)\n if len(get_bn_modules(model)) == 0:\n self._logger.info(\n \"PreciseBN is disabled because model does not contain BN layers in training mode.\"\n )\n self._disabled = True\n return\n\n self._model = model\n self._data_loader = data_loader\n self._num_iter = num_iter\n self._period = period\n self._disabled = False\n\n self._data_iter = None\n\n def after_step(self):\n next_iter = self.trainer.iter + 1\n is_final = next_iter == self.trainer.max_iter\n if is_final or (self._period > 0 and next_iter % self._period == 0):\n self.update_stats()\n\n def update_stats(self):\n \"\"\"\n Update the model with precise statistics. Users can manually call this method.\n \"\"\"\n if self._disabled:\n return\n\n if self._data_iter is None:\n self._data_iter = iter(self._data_loader)\n\n def data_loader():\n for num_iter in itertools.count(1):\n if num_iter % 100 == 0:\n self._logger.info(\n \"Running precise-BN ... {}/{} iterations.\".format(num_iter, self._num_iter)\n )\n # This way we can reuse the same iterator\n yield next(self._data_iter)\n\n with EventStorage(): # capture events in a new storage to discard them\n self._logger.info(\n \"Running precise-BN for {} iterations... \".format(self._num_iter)\n + \"Note that this could produce different statistics every time.\"\n )\n update_bn_stats(self._model, data_loader(), self._num_iter)\n", "# Copyright (c) Facebook, Inc. and its affiliates.\n\nimport math\nimport torch\nimport torch.nn.functional as F\n\nfrom detectron2.layers import cat\nfrom detectron2.layers.roi_align_rotated import ROIAlignRotated\nfrom detectron2.modeling import poolers\nfrom detectron2.modeling.proposal_generator import rpn\nfrom detectron2.modeling.roi_heads.mask_head import mask_rcnn_inference\nfrom detectron2.structures import Boxes, ImageList, Instances, Keypoints\n\nfrom .shared import alias, to_device\n\n\n\"\"\"\nThis file contains caffe2-compatible implementation of several detectron2 components.\n\"\"\"\n\n\nclass Caffe2Boxes(Boxes):\n \"\"\"\n Representing a list of detectron2.structures.Boxes from minibatch, each box\n is represented by a 5d vector (batch index + 4 coordinates), or a 6d vector\n (batch index + 5 coordinates) for RotatedBoxes.\n \"\"\"\n\n def __init__(self, tensor):\n assert isinstance(tensor, torch.Tensor)\n assert tensor.dim() == 2 and tensor.size(-1) in [4, 5, 6], tensor.size()\n # TODO: make tensor immutable when dim is Nx5 for Boxes,\n # and Nx6 for RotatedBoxes?\n self.tensor = tensor\n\n\n# TODO clean up this class, maybe just extend Instances\nclass InstancesList(object):\n \"\"\"\n Tensor representation of a list of Instances object for a batch of images.\n\n When dealing with a batch of images with Caffe2 ops, a list of bboxes\n (instances) are usually represented by single Tensor with size\n (sigma(Ni), 5) or (sigma(Ni), 4) plus a batch split Tensor. This class is\n for providing common functions to convert between these two representations.\n \"\"\"\n\n def __init__(self, im_info, indices, extra_fields=None):\n # [N, 3] -> (H, W, Scale)\n self.im_info = im_info\n # [N,] -> indice of batch to which the instance belongs\n self.indices = indices\n # [N, ...]\n self.batch_extra_fields = extra_fields or {}\n\n self.image_size = self.im_info\n\n def get_fields(self):\n \"\"\"like `get_fields` in the Instances object,\n but return each field in tensor representations\"\"\"\n ret = {}\n for k, v in self.batch_extra_fields.items():\n # if isinstance(v, torch.Tensor):\n # tensor_rep = v\n # elif isinstance(v, (Boxes, Keypoints)):\n # tensor_rep = v.tensor\n # else:\n # raise ValueError(\"Can't find tensor representation for: {}\".format())\n ret[k] = v\n return ret\n\n def has(self, name):\n return name in self.batch_extra_fields\n\n def set(self, name, value):\n data_len = len(value)\n if len(self.batch_extra_fields):\n assert (\n len(self) == data_len\n ), \"Adding a field of length {} to a Instances of length {}\".format(data_len, len(self))\n self.batch_extra_fields[name] = value\n\n def __setattr__(self, name, val):\n if name in [\"im_info\", \"indices\", \"batch_extra_fields\", \"image_size\"]:\n super().__setattr__(name, val)\n else:\n self.set(name, val)\n\n def __getattr__(self, name):\n if name not in self.batch_extra_fields:\n raise AttributeError(\"Cannot find field '{}' in the given Instances!\".format(name))\n return self.batch_extra_fields[name]\n\n def __len__(self):\n return len(self.indices)\n\n def flatten(self):\n ret = []\n for _, v in self.batch_extra_fields.items():\n if isinstance(v, (Boxes, Keypoints)):\n ret.append(v.tensor)\n else:\n ret.append(v)\n return ret\n\n @staticmethod\n def to_d2_instances_list(instances_list):\n \"\"\"\n Convert InstancesList to List[Instances]. The input `instances_list` can\n also be a List[Instances], in this case this method is a non-op.\n \"\"\"\n if not isinstance(instances_list, InstancesList):\n assert all(isinstance(x, Instances) for x in instances_list)\n return instances_list\n\n ret = []\n for i, info in enumerate(instances_list.im_info):\n instances = Instances(torch.Size([int(info[0].item()), int(info[1].item())]))\n\n ids = instances_list.indices == i\n for k, v in instances_list.batch_extra_fields.items():\n if isinstance(v, torch.Tensor):\n instances.set(k, v[ids])\n continue\n elif isinstance(v, Boxes):\n instances.set(k, v[ids, -4:])\n continue\n\n target_type, tensor_source = v\n assert isinstance(tensor_source, torch.Tensor)\n assert tensor_source.shape[0] == instances_list.indices.shape[0]\n tensor_source = tensor_source[ids]\n\n if issubclass(target_type, Boxes):\n instances.set(k, Boxes(tensor_source[:, -4:]))\n elif issubclass(target_type, Keypoints):\n instances.set(k, Keypoints(tensor_source))\n elif issubclass(target_type, torch.Tensor):\n instances.set(k, tensor_source)\n else:\n raise ValueError(\"Can't handle targe type: {}\".format(target_type))\n\n ret.append(instances)\n return ret\n\n\nclass Caffe2Compatible(object):\n \"\"\"\n A model can inherit this class to indicate that it can be traced and deployed with caffe2.\n \"\"\"\n\n def _get_tensor_mode(self):\n return self._tensor_mode\n\n def _set_tensor_mode(self, v):\n self._tensor_mode = v\n\n tensor_mode = property(_get_tensor_mode, _set_tensor_mode)\n \"\"\"\n If true, the model expects C2-style tensor only inputs/outputs format.\n \"\"\"\n\n\nclass Caffe2RPN(Caffe2Compatible, rpn.RPN):\n def _generate_proposals(\n self, images, objectness_logits_pred, anchor_deltas_pred, gt_instances=None\n ):\n assert isinstance(images, ImageList)\n if self.tensor_mode:\n im_info = images.image_sizes\n else:\n im_info = torch.tensor([[im_sz[0], im_sz[1], 1.0] for im_sz in images.image_sizes]).to(\n images.tensor.device\n )\n assert isinstance(im_info, torch.Tensor)\n\n rpn_rois_list = []\n rpn_roi_probs_list = []\n for scores, bbox_deltas, cell_anchors_tensor, feat_stride in zip(\n objectness_logits_pred,\n anchor_deltas_pred,\n iter(self.anchor_generator.cell_anchors),\n self.anchor_generator.strides,\n ):\n scores = scores.detach()\n bbox_deltas = bbox_deltas.detach()\n\n rpn_rois, rpn_roi_probs = torch.ops._caffe2.GenerateProposals(\n scores,\n bbox_deltas,\n im_info,\n cell_anchors_tensor,\n spatial_scale=1.0 / feat_stride,\n pre_nms_topN=self.pre_nms_topk[self.training],\n post_nms_topN=self.post_nms_topk[self.training],\n nms_thresh=self.nms_thresh,\n min_size=self.min_box_size,\n # correct_transform_coords=True, # deprecated argument\n angle_bound_on=True, # Default\n angle_bound_lo=-180,\n angle_bound_hi=180,\n clip_angle_thresh=1.0, # Default\n legacy_plus_one=False,\n )\n rpn_rois_list.append(rpn_rois)\n rpn_roi_probs_list.append(rpn_roi_probs)\n\n # For FPN in D2, in RPN all proposals from different levels are concated\n # together, ranked and picked by top post_nms_topk. Then in ROIPooler\n # it calculates level_assignments and calls the RoIAlign from\n # the corresponding level.\n\n if len(objectness_logits_pred) == 1:\n rpn_rois = rpn_rois_list[0]\n rpn_roi_probs = rpn_roi_probs_list[0]\n else:\n assert len(rpn_rois_list) == len(rpn_roi_probs_list)\n rpn_post_nms_topN = self.post_nms_topk[self.training]\n\n device = rpn_rois_list[0].device\n input_list = [to_device(x, \"cpu\") for x in (rpn_rois_list + rpn_roi_probs_list)]\n\n # TODO remove this after confirming rpn_max_level/rpn_min_level\n # is not needed in CollectRpnProposals.\n feature_strides = list(self.anchor_generator.strides)\n rpn_min_level = int(math.log2(feature_strides[0]))\n rpn_max_level = int(math.log2(feature_strides[-1]))\n assert (rpn_max_level - rpn_min_level + 1) == len(\n rpn_rois_list\n ), \"CollectRpnProposals requires continuous levels\"\n\n rpn_rois = torch.ops._caffe2.CollectRpnProposals(\n input_list,\n # NOTE: in current implementation, rpn_max_level and rpn_min_level\n # are not needed, only the subtraction of two matters and it\n # can be infer from the number of inputs. Keep them now for\n # consistency.\n rpn_max_level=2 + len(rpn_rois_list) - 1,\n rpn_min_level=2,\n rpn_post_nms_topN=rpn_post_nms_topN,\n )\n rpn_rois = to_device(rpn_rois, device)\n rpn_roi_probs = []\n\n proposals = self.c2_postprocess(im_info, rpn_rois, rpn_roi_probs, self.tensor_mode)\n return proposals, {}\n\n def forward(self, images, features, gt_instances=None):\n assert not self.training\n features = [features[f] for f in self.in_features]\n objectness_logits_pred, anchor_deltas_pred = self.rpn_head(features)\n return self._generate_proposals(\n images,\n objectness_logits_pred,\n anchor_deltas_pred,\n gt_instances,\n )\n\n @staticmethod\n def c2_postprocess(im_info, rpn_rois, rpn_roi_probs, tensor_mode):\n proposals = InstancesList(\n im_info=im_info,\n indices=rpn_rois[:, 0],\n extra_fields={\n \"proposal_boxes\": Caffe2Boxes(rpn_rois),\n \"objectness_logits\": (torch.Tensor, rpn_roi_probs),\n },\n )\n if not tensor_mode:\n proposals = InstancesList.to_d2_instances_list(proposals)\n else:\n proposals = [proposals]\n return proposals\n\n\nclass Caffe2ROIPooler(Caffe2Compatible, poolers.ROIPooler):\n @staticmethod\n def c2_preprocess(box_lists):\n assert all(isinstance(x, Boxes) for x in box_lists)\n if all(isinstance(x, Caffe2Boxes) for x in box_lists):\n # input is pure-tensor based\n assert len(box_lists) == 1\n pooler_fmt_boxes = box_lists[0].tensor\n else:\n pooler_fmt_boxes = poolers.convert_boxes_to_pooler_format(box_lists)\n return pooler_fmt_boxes\n\n def forward(self, x, box_lists):\n assert not self.training\n\n pooler_fmt_boxes = self.c2_preprocess(box_lists)\n num_level_assignments = len(self.level_poolers)\n\n if num_level_assignments == 1:\n if isinstance(self.level_poolers[0], ROIAlignRotated):\n c2_roi_align = torch.ops._caffe2.RoIAlignRotated\n aligned = True\n else:\n c2_roi_align = torch.ops._caffe2.RoIAlign\n aligned = self.level_poolers[0].aligned\n\n out = c2_roi_align(\n x[0],\n pooler_fmt_boxes,\n order=\"NCHW\",\n spatial_scale=float(self.level_poolers[0].spatial_scale),\n pooled_h=int(self.output_size[0]),\n pooled_w=int(self.output_size[1]),\n sampling_ratio=int(self.level_poolers[0].sampling_ratio),\n aligned=aligned,\n )\n return out\n\n device = pooler_fmt_boxes.device\n assert (\n self.max_level - self.min_level + 1 == 4\n ), \"Currently DistributeFpnProposals only support 4 levels\"\n fpn_outputs = torch.ops._caffe2.DistributeFpnProposals(\n to_device(pooler_fmt_boxes, \"cpu\"),\n roi_canonical_scale=self.canonical_box_size,\n roi_canonical_level=self.canonical_level,\n roi_max_level=self.max_level,\n roi_min_level=self.min_level,\n legacy_plus_one=False,\n )\n fpn_outputs = [to_device(x, device) for x in fpn_outputs]\n\n rois_fpn_list = fpn_outputs[:-1]\n rois_idx_restore_int32 = fpn_outputs[-1]\n\n roi_feat_fpn_list = []\n for roi_fpn, x_level, pooler in zip(rois_fpn_list, x, self.level_poolers):\n if isinstance(pooler, ROIAlignRotated):\n c2_roi_align = torch.ops._caffe2.RoIAlignRotated\n aligned = True\n else:\n c2_roi_align = torch.ops._caffe2.RoIAlign\n aligned = bool(pooler.aligned)\n\n roi_feat_fpn = c2_roi_align(\n x_level,\n roi_fpn,\n order=\"NCHW\",\n spatial_scale=float(pooler.spatial_scale),\n pooled_h=int(self.output_size[0]),\n pooled_w=int(self.output_size[1]),\n sampling_ratio=int(pooler.sampling_ratio),\n aligned=aligned,\n )\n roi_feat_fpn_list.append(roi_feat_fpn)\n\n roi_feat_shuffled = cat(roi_feat_fpn_list, dim=0)\n assert roi_feat_shuffled.numel() > 0 and rois_idx_restore_int32.numel() > 0, (\n \"Caffe2 export requires tracing with a model checkpoint + input that can produce valid\"\n \" detections. But no detections were obtained with the given checkpoint and input!\"\n )\n roi_feat = torch.ops._caffe2.BatchPermutation(roi_feat_shuffled, rois_idx_restore_int32)\n return roi_feat\n\n\nclass Caffe2FastRCNNOutputsInference:\n def __init__(self, tensor_mode):\n self.tensor_mode = tensor_mode # whether the output is caffe2 tensor mode\n\n def __call__(self, box_predictor, predictions, proposals):\n \"\"\"equivalent to FastRCNNOutputLayers.inference\"\"\"\n num_classes = box_predictor.num_classes\n score_thresh = box_predictor.test_score_thresh\n nms_thresh = box_predictor.test_nms_thresh\n topk_per_image = box_predictor.test_topk_per_image\n is_rotated = len(box_predictor.box2box_transform.weights) == 5\n\n if is_rotated:\n box_dim = 5\n assert box_predictor.box2box_transform.weights[4] == 1, (\n \"The weights for Rotated BBoxTransform in C2 have only 4 dimensions,\"\n + \" thus enforcing the angle weight to be 1 for now\"\n )\n box2box_transform_weights = box_predictor.box2box_transform.weights[:4]\n else:\n box_dim = 4\n box2box_transform_weights = box_predictor.box2box_transform.weights\n\n class_logits, box_regression = predictions\n if num_classes + 1 == class_logits.shape[1]:\n class_prob = F.softmax(class_logits, -1)\n else:\n assert num_classes == class_logits.shape[1]\n class_prob = F.sigmoid(class_logits)\n # BoxWithNMSLimit will infer num_classes from the shape of the class_prob\n # So append a zero column as placeholder for the background class\n class_prob = torch.cat((class_prob, torch.zeros(class_prob.shape[0], 1)), dim=1)\n\n assert box_regression.shape[1] % box_dim == 0\n cls_agnostic_bbox_reg = box_regression.shape[1] // box_dim == 1\n\n input_tensor_mode = proposals[0].proposal_boxes.tensor.shape[1] == box_dim + 1\n\n rois = type(proposals[0].proposal_boxes).cat([p.proposal_boxes for p in proposals])\n device, dtype = rois.tensor.device, rois.tensor.dtype\n if input_tensor_mode:\n im_info = proposals[0].image_size\n rois = rois.tensor\n else:\n im_info = torch.tensor(\n [[sz[0], sz[1], 1.0] for sz in [x.image_size for x in proposals]]\n )\n batch_ids = cat(\n [\n torch.full((b, 1), i, dtype=dtype, device=device)\n for i, b in enumerate(len(p) for p in proposals)\n ],\n dim=0,\n )\n rois = torch.cat([batch_ids, rois.tensor], dim=1)\n\n roi_pred_bbox, roi_batch_splits = torch.ops._caffe2.BBoxTransform(\n to_device(rois, \"cpu\"),\n to_device(box_regression, \"cpu\"),\n to_device(im_info, \"cpu\"),\n weights=box2box_transform_weights,\n apply_scale=True,\n rotated=is_rotated,\n angle_bound_on=True,\n angle_bound_lo=-180,\n angle_bound_hi=180,\n clip_angle_thresh=1.0,\n legacy_plus_one=False,\n )\n roi_pred_bbox = to_device(roi_pred_bbox, device)\n roi_batch_splits = to_device(roi_batch_splits, device)\n\n nms_outputs = torch.ops._caffe2.BoxWithNMSLimit(\n to_device(class_prob, \"cpu\"),\n to_device(roi_pred_bbox, \"cpu\"),\n to_device(roi_batch_splits, \"cpu\"),\n score_thresh=float(score_thresh),\n nms=float(nms_thresh),\n detections_per_im=int(topk_per_image),\n soft_nms_enabled=False,\n soft_nms_method=\"linear\",\n soft_nms_sigma=0.5,\n soft_nms_min_score_thres=0.001,\n rotated=is_rotated,\n cls_agnostic_bbox_reg=cls_agnostic_bbox_reg,\n input_boxes_include_bg_cls=False,\n output_classes_include_bg_cls=False,\n legacy_plus_one=False,\n )\n roi_score_nms = to_device(nms_outputs[0], device)\n roi_bbox_nms = to_device(nms_outputs[1], device)\n roi_class_nms = to_device(nms_outputs[2], device)\n roi_batch_splits_nms = to_device(nms_outputs[3], device)\n roi_keeps_nms = to_device(nms_outputs[4], device)\n roi_keeps_size_nms = to_device(nms_outputs[5], device)\n if not self.tensor_mode:\n roi_class_nms = roi_class_nms.to(torch.int64)\n\n roi_batch_ids = cat(\n [\n torch.full((b, 1), i, dtype=dtype, device=device)\n for i, b in enumerate(int(x.item()) for x in roi_batch_splits_nms)\n ],\n dim=0,\n )\n\n roi_class_nms = alias(roi_class_nms, \"class_nms\")\n roi_score_nms = alias(roi_score_nms, \"score_nms\")\n roi_bbox_nms = alias(roi_bbox_nms, \"bbox_nms\")\n roi_batch_splits_nms = alias(roi_batch_splits_nms, \"batch_splits_nms\")\n roi_keeps_nms = alias(roi_keeps_nms, \"keeps_nms\")\n roi_keeps_size_nms = alias(roi_keeps_size_nms, \"keeps_size_nms\")\n\n results = InstancesList(\n im_info=im_info,\n indices=roi_batch_ids[:, 0],\n extra_fields={\n \"pred_boxes\": Caffe2Boxes(roi_bbox_nms),\n \"scores\": roi_score_nms,\n \"pred_classes\": roi_class_nms,\n },\n )\n\n if not self.tensor_mode:\n results = InstancesList.to_d2_instances_list(results)\n batch_splits = roi_batch_splits_nms.int().tolist()\n kept_indices = list(roi_keeps_nms.to(torch.int64).split(batch_splits))\n else:\n results = [results]\n kept_indices = [roi_keeps_nms]\n\n return results, kept_indices\n\n\nclass Caffe2MaskRCNNInference:\n def __call__(self, pred_mask_logits, pred_instances):\n \"\"\"equivalent to mask_head.mask_rcnn_inference\"\"\"\n if all(isinstance(x, InstancesList) for x in pred_instances):\n assert len(pred_instances) == 1\n mask_probs_pred = pred_mask_logits.sigmoid()\n mask_probs_pred = alias(mask_probs_pred, \"mask_fcn_probs\")\n pred_instances[0].pred_masks = mask_probs_pred\n else:\n mask_rcnn_inference(pred_mask_logits, pred_instances)\n\n\nclass Caffe2KeypointRCNNInference:\n def __init__(self, use_heatmap_max_keypoint):\n self.use_heatmap_max_keypoint = use_heatmap_max_keypoint\n\n def __call__(self, pred_keypoint_logits, pred_instances):\n # just return the keypoint heatmap for now,\n # there will be option to call HeatmapMaxKeypointOp\n output = alias(pred_keypoint_logits, \"kps_score\")\n if all(isinstance(x, InstancesList) for x in pred_instances):\n assert len(pred_instances) == 1\n if self.use_heatmap_max_keypoint:\n device = output.device\n output = torch.ops._caffe2.HeatmapMaxKeypoint(\n to_device(output, \"cpu\"),\n pred_instances[0].pred_boxes.tensor,\n should_output_softmax=True, # worth make it configerable?\n )\n output = to_device(output, device)\n output = alias(output, \"keypoints_out\")\n pred_instances[0].pred_keypoints = output\n return pred_keypoint_logits\n" ]
[ [ "torch.nn.functional.cross_entropy" ], [ "torch.autograd.profiler.profile" ], [ "torch.ops._caffe2.BatchPermutation", "torch.nn.functional.softmax", "torch.full", "torch.cat", "torch.zeros", "torch.ops._caffe2.GenerateProposals", "torch.tensor", "torch.nn.functional.sigmoid" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
miraclestatus/mllearning
[ "f5db6642e8c05488b133ee627e5f63c92e45ff6e", "f5db6642e8c05488b133ee627e5f63c92e45ff6e" ]
[ "ml/myscript/Logisticegression.py", "ml/myscript/KNeighborsClassifier.py" ]
[ "import numpy as np\nfrom .metrics import accuracy_score\nclass Logisticegression():\n def __init__(self):\n # 系数\n self.coef_ = None\n # 截距\n self.intercept_ = None\n # 向量\n self._theta = None\n def _sigmoid(self, t):\n return 1./(1. + np.exp(-t))\n\n def fit(self, X_train, y_train, eta=0.01, n_iters=1e4):\n \"\"\"根据训练数据集X_train, y_train, 使用梯度下降法训练Linear Regression模型\"\"\"\n assert X_train.shape[0] == y_train.shape[0], \\\n \"the size of X_train must be equal to the size of y_train\"\n\n def J(theta, X_b, y):\n y_hat = self._sigmoid(X_b.dot(theta))\n try:\n return - np.sum(y*np.log(y_hat) + (1-y)*np.log(1-y_hat)) / len(y)\n except:\n return float('inf')\n\n def dJ(theta, X_b, y):\n return X_b.T.dot(self._sigmoid(X_b.dot(theta))-y) /len(y)\n\n def gradient_descent(X_b, y, initial_theta, eta, n_iters=1e4, epsilon=1e-8):\n\n theta = initial_theta\n cur_iter = 0\n\n while cur_iter < n_iters:\n gradient = dJ(theta, X_b, y)\n last_theta = theta\n theta = theta - eta * gradient\n if (abs(J(theta, X_b, y) - J(last_theta, X_b, y)) < epsilon):\n break\n\n cur_iter += 1\n\n return theta\n\n X_b = np.hstack([np.ones((len(X_train), 1)), X_train])\n initial_theta = np.zeros(X_b.shape[1])\n self._theta = gradient_descent(X_b, y_train, initial_theta, eta, n_iters)\n\n self.intercept_ = self._theta[0]\n self.coef_ = self._theta[1:]\n\n return self\n def predict_proba(self,X_predict):\n X_b = np.hstack([np.ones((len(X_predict), 1)), X_predict])\n return self._sigmoid(X_b.dot(self._theta))\n def predict(self, X_predict):\n proba = self.predict_proba(X_predict)\n return np.array(proba >= 0.5, dtype='int')\n def score(self, X_test, y_test):\n y_predict = self.predict(X_test)\n return accuracy_score(y_test, y_predict)\n def __repr__(self):\n return \"Logisticegression()\"", "from collections import Counter\nfrom math import sqrt\nfrom .metrics import accuracy_score\nimport numpy as np\nclass KNeighborsClassifier():\n def __init__(self,k):\n assert k >= 1, 'k must be valid'\n self.k = k\n self._X_train = None\n self._y_train = None\n\n def fit(self,X_train, y_train):\n \"\"\"根据训练数据集X_train和y_train训练kNN分类器\"\"\"\n assert X_train.shape[0] == y_train.shape[0], \\\n \"the size of X_train must equal to the size of y_train\"\n assert self.k <= X_train.shape[0], \\\n \"the size of X_train must be at least k.\"\n self._X_train = X_train\n self._y_train = y_train\n return self\n def predict(self,X_predict):\n \"\"\"给定待预测数据集X_predict,返回标示X_predict的结果向量\"\"\"\n assert self._X_train is not None and self._y_train is not None, \\\n \"mush fit before predict\"\n assert self._X_train.shape[1] == X_predict.shape[1], \"the feature number of x must be equal to X_train\"\n\n y_predict = [self._predict(x) for x in X_predict]\n return np.array(y_predict)\n\n\n def _predict(self, x):\n \"\"\"单个的\"\"\"\n distances = [sqrt(np.sum((x_train - x)**2)) for x_train in self._X_train]\n nearset = np.argsort(distances)\n topK_y = [self._y_train[i] for i in nearset[:self.k]]\n return Counter(topK_y).most_common(1)[0][0]\n\n def score(self, X_test, y_test):\n \"\"\"根据测试数据, 确定当前模型的准确度\"\"\"\n y_predict = self.predict(X_test)\n return accuracy_score(y_test, y_predict)\n\n" ]
[ [ "numpy.exp", "numpy.log", "numpy.array", "numpy.zeros" ], [ "numpy.argsort", "numpy.array", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
civodlu/trw
[ "b9a1cf045f61d6df9c65c014ef63b4048972dcdc", "b9a1cf045f61d6df9c65c014ef63b4048972dcdc", "b9a1cf045f61d6df9c65c014ef63b4048972dcdc", "b9a1cf045f61d6df9c65c014ef63b4048972dcdc", "b9a1cf045f61d6df9c65c014ef63b4048972dcdc" ]
[ "tests/test_transforms_resize_modulo_pad_crop.py", "tutorials/classification_cifar10_resnet.py", "tests/test_collate.py", "src/trw/callbacks/callback_tensorboard_record_model.py", "src/trw/callbacks/callback_reporting_classification_errors.py" ]
[ "import unittest\nimport trw\nimport torch\nimport numpy as np\n\n\nclass TestTransformsResizeModuloPadCrop(unittest.TestCase):\n def test_crop_mode_torch(self):\n batch = {\n 'images': torch.rand([2, 3, 64, 64], dtype=torch.float32)\n }\n\n tfm = trw.transforms.TransformResizeModuloCropPad(60)\n transformed = tfm(batch)\n assert transformed['images'].shape == (2, 3, 60, 60)\n\n def test_crop_mode_torch_multiples(self):\n # test with multiple of `multiples_of` shape\n batch = {\n 'images': torch.rand([2, 3, 64, 64], dtype=torch.float32)\n }\n\n tfm = trw.transforms.TransformResizeModuloCropPad(10)\n transformed = tfm(batch)\n assert transformed['images'].shape == (2, 3, 60, 60)\n\n def test_crop_mode_torch_different_shape(self):\n batch = {\n 'images': torch.rand([2, 3, 64, 64], dtype=torch.float32),\n 'images2': torch.rand([2, 1, 64, 64], dtype=torch.float32)\n }\n batch['images'][0, 0, 32, 32] = 42.0\n batch['images2'][0, 0, 32, 32] = 42.0\n\n tfm = trw.transforms.TransformResizeModuloCropPad(60)\n transformed = tfm(batch)\n\n # make sure we can handle different shapes of the same dimension\n assert transformed['images'].shape == (2, 3, 60, 60)\n assert transformed['images2'].shape == (2, 1, 60, 60)\n\n # make sure the crop/pad are the same for the different images\n indices = np.where(batch['images'].numpy() == 42)\n assert (batch['images2'][indices] == 42.0).all()\n\n def test_pad_mode_torch(self):\n batch = {\n 'images': torch.rand([2, 3, 65, 65], dtype=torch.float32)\n }\n\n tfm = trw.transforms.TransformResizeModuloCropPad(32, mode='pad')\n transformed = tfm(batch)\n assert transformed['images'].shape == (2, 3, 96, 96)\n", "import copy\nimport os\n# we already use worker threads, limit each process to 1 thread!\nfrom functools import partial\nfrom numbers import Number\nfrom typing import Optional, Sequence\n\nfrom trw.basic_typing import Stride, KernelSize\nfrom trw.layers import LayerConfig, BlockConv, BlockConvNormActivation, default_layer_config\n\nimport trw\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom trw.layers.layer_config import PoolType\n\ntorch.set_num_threads(1)\n\nimport logging\n\nlogging.basicConfig(filename='log.log', filemode='w', level=logging.DEBUG)\n\n\n\n\n\n\n\n\nclass PreActBlock(nn.Module):\n '''Pre-activation version of the BasicBlock.'''\n expansion = 1\n\n def __init__(self, in_planes, planes, stride=1):\n super(PreActBlock, self).__init__()\n self.bn1 = nn.BatchNorm2d(in_planes)\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)\n\n if stride != 1 or in_planes != self.expansion*planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False)\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(x))\n shortcut = self.shortcut(out) if hasattr(self, 'shortcut') else x\n out = self.conv1(out)\n out = self.conv2(F.relu(self.bn2(out)))\n out += shortcut\n return out\n\n\nclass PreActBottleneck(nn.Module):\n '''Pre-activation version of the original Bottleneck module.'''\n expansion = 4\n\n def __init__(self, in_planes, planes, stride=1):\n super(PreActBottleneck, self).__init__()\n self.bn1 = nn.BatchNorm2d(in_planes)\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, self.expansion*planes, kernel_size=1, bias=False)\n\n if stride != 1 or in_planes != self.expansion*planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False)\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(x))\n shortcut = self.shortcut(out) if hasattr(self, 'shortcut') else x\n out = self.conv1(out)\n out = self.conv2(F.relu(self.bn2(out)))\n out = self.conv3(F.relu(self.bn3(out)))\n out += shortcut\n return out\n\n\nclass PreActResNet(nn.Module):\n def __init__(self, block, num_blocks, num_classes=10):\n super(PreActResNet, self).__init__()\n self.in_planes = 64\n\n self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)\n self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)\n self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)\n self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)\n self.linear = nn.Linear(512*block.expansion, num_classes)\n\n def _make_layer(self, block, planes, num_blocks, stride):\n strides = [stride] + [1]*(num_blocks-1)\n layers = []\n for stride in strides:\n layers.append(block(self.in_planes, planes, stride))\n self.in_planes = planes * block.expansion\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = self.conv1(x)\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n out = F.avg_pool2d(out, 4)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\n\ndef PreActResNet18():\n return PreActResNet(PreActBlock, [2,2,2,2])\n\ndef PreActResNet18v2():\n return PreActResNetV2(\n dimensionality=2,\n input_channels=3,\n output_channels=10,\n block=BlockResPreAct,\n num_blocks=[2, 2, 2, 2])\n\ndef PreActResNet34():\n return PreActResNet(PreActBlock, [3,4,6,3])\n\ndef PreActResNet50():\n return PreActResNet(PreActBottleneck, [3,4,6,3])\n\ndef PreActResNet101():\n return PreActResNet(PreActBottleneck, [3,4,23,3])\n\ndef PreActResNet152():\n return PreActResNet(PreActBottleneck, [3,8,36,3])\n\n\nclass Net(nn.Module):\n def __init__(self):\n super().__init__()\n self.net = trw.layers.PreActResNet18()\n\n def forward(self, batch):\n x = batch['images']\n x = self.net(x)\n return {\n 'softmax': trw.train.OutputClassification(x, batch['targets'], classes_name='targets')\n }\n\n\ndef create_model():\n model = Net()\n return model\n\n\nif __name__ == '__main__':\n # configure and run the training/evaluation\n num_epochs = 200\n options = trw.train.Options(num_epochs=num_epochs)\n trainer = trw.train.TrainerV2(\n callbacks_post_training=None,\n callbacks_pre_training=None,\n )\n\n mean = np.asarray([0.4914, 0.4822, 0.4465], dtype=np.float32)\n std = np.asarray([0.2023, 0.1994, 0.2010], dtype=np.float32)\n\n transform_train = [\n trw.transforms.TransformRandomCropPad(padding=[0, 4, 4], mode='constant'),\n trw.transforms.TransformRandomFlip(axis=3),\n trw.transforms.TransformRandomCutout(cutout_size=(3, 16, 16), probability=0.2),\n trw.transforms.TransformNormalizeIntensity(mean=mean, std=std)\n ]\n\n transform_valid = [\n trw.transforms.TransformNormalizeIntensity(mean=mean, std=std)\n ]\n\n datasets = trw.datasets.create_cifar10_dataset(\n transform_train=transform_train,\n transform_valid=transform_valid,\n nb_workers=4,\n batch_size=128,\n data_processing_batch_size=64,\n )\n\n scheduler_fn = lambda optimizer: torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=num_epochs)\n optimizer_fn_1 = lambda datasets, model: trw.train.create_sgd_optimizers_fn(\n datasets,\n model,\n learning_rate=0.1,\n momentum=0.9,\n weight_decay=5e-4,\n nesterov=False,\n scheduler_fn=scheduler_fn\n )\n\n results = trainer.fit(\n options,\n datasets=datasets,\n log_path='cifar10_resnet',\n model=create_model(),\n optimizers_fn=optimizer_fn_1\n )\n\n\n", "from unittest import TestCase\nimport trw\nimport numpy as np\nimport torch\nimport collections\nimport trw.train.collate\n\nimport trw.utils\n\n\nclass TestCollate(TestCase):\n def test_collate_dicts(self):\n batch = {\n 'list': [1, 2, 3],\n 'value': 42.0,\n 'np': np.ones(shape=[3, 2]),\n 'torch': torch.ones([3, 2]),\n 'strs': ['1', '2', '3'],\n }\n\n collated = trw.train.collate.default_collate_fn(batch, device=None)\n self.assertTrue(isinstance(collated, collections.OrderedDict))\n self.assertTrue(isinstance(collated['list'], torch.Tensor))\n self.assertTrue(len(collated['list']) == 3)\n self.assertTrue(isinstance(collated['np'], torch.Tensor))\n self.assertTrue(collated['np'].shape == (3, 2))\n self.assertTrue(isinstance(collated['torch'], torch.Tensor))\n self.assertTrue(collated['torch'].shape == (3, 2))\n self.assertTrue(isinstance(collated['value'], float))\n self.assertTrue(isinstance(collated['strs'], list))\n\n def test_collate_list_of_dicts(self):\n batch_1 = {\n 'np': np.ones(shape=[1, 3, 2]),\n 'list': [1],\n 'value': 42.0,\n 'torch': torch.ones([1, 3, 2]),\n 'strs': ['1'],\n }\n\n batch_2 = {\n 'np': np.ones(shape=[1, 3, 2]),\n 'list': [2],\n 'value': 42.0,\n 'torch': torch.ones([1, 3, 2]),\n 'strs': ['2'],\n }\n\n collated = trw.train.collate.default_collate_fn([batch_1, batch_2], device=None)\n\n self.assertTrue(isinstance(collated, collections.OrderedDict))\n self.assertTrue(trw.utils.len_batch(collated) == 2)\n self.assertTrue(isinstance(collated['list'], torch.Tensor))\n self.assertTrue(len(collated['list']) == 2)\n self.assertTrue(isinstance(collated['np'], torch.Tensor))\n self.assertTrue(collated['np'].shape == (2, 3, 2))\n self.assertTrue(isinstance(collated['torch'], torch.Tensor))\n self.assertTrue(collated['torch'].shape == (2, 3, 2))\n self.assertTrue(isinstance(collated['value'], torch.Tensor))\n self.assertTrue(len(collated['torch']) == 2)\n self.assertTrue(isinstance(collated['strs'], list))\n self.assertTrue(len(collated['strs']) == 2)\n self.assertTrue(isinstance(collated['value'], torch.Tensor))\n self.assertTrue(len(collated['value']) == 2)\n", "from ..train.utilities import postprocess_batch\nfrom .callback_tensorboard import CallbackTensorboardBased\nfrom ..train import utilities\nimport os\nimport logging\nimport torch\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass CallbackTensorboardRecordModel(CallbackTensorboardBased):\n \"\"\"\n This callback will export the model to tensorboard\n\n @TODO ONNX is probably adding hooks and are not removed. To be investigated.\n \"\"\"\n def __init__(self, dataset_name=None, split_name=None, onnx_folder='onnx'):\n self.dataset_name = dataset_name\n self.split_name = split_name\n self.onnx_folder = onnx_folder\n\n def __call__(self, options, history, model, losses, outputs, datasets, datasets_infos, callbacks_per_batch, **kwargs):\n root = options.workflow_options.current_logging_directory\n logger.info('root={}'.format(root))\n logger_tb = CallbackTensorboardBased.create_logger(root)\n if logger_tb is None:\n return\n\n if self.dataset_name is None:\n if self.dataset_name is None:\n self.dataset_name = next(iter(datasets))\n\n if self.split_name is None:\n self.split_name = next(iter(datasets[self.dataset_name]))\n\n device = options.workflow_options.device\n\n # ONNX export MUST be in eval mode!\n model.eval()\n\n batch = next(iter(datasets[self.dataset_name][self.split_name]))\n batch = utilities.transfer_batch_to_device(batch, device=device)\n postprocess_batch(self.dataset_name, self.split_name, batch, callbacks_per_batch)\n\n class NoDictModel(torch.nn.Module):\n # cahce the model input as onnx doesn't handle dict like input\n # or output\n def __init__(self, model, batch):\n super().__init__()\n self.model = model\n self.batch = batch\n\n def __call__(self, *input, **kwargs):\n with torch.no_grad():\n r = self.model(self.batch)\n outputs = [o.output for name, o in r.items()]\n return outputs\n\n # at the moment, few issues with the onnx export with the support\n # of return dictionary is spotty. There are 2 ways options:\n # 1) export to onnx format and use `logger_tb.add_onnx_graph` to export the graph -> this requires the `onnx` additional dependency. This only works for the\n # latest PyTorch. Additionally, onnx should be installed via conda\n # 2) export directly using `logger_tb.add_graph(NoDictModel(model, batch), input_to_model=torch.Tensor())`, but in the dev build, this fails\n # option 2 is preferable but doesn't work right now\n\n try:\n # option 1)\n root_onnx = os.path.join(root, self.onnx_folder)\n utilities.create_or_recreate_folder(root_onnx)\n onnx_filepath = os.path.join(root_onnx, 'model.onnx')\n logger.info('exporting ONNX model to `{}`'.format(onnx_filepath))\n with utilities.CleanAddedHooks(model): # make sure no extra hooks are kept\n with open(onnx_filepath, 'wb') as f:\n torch.onnx.export(NoDictModel(model, batch), torch.Tensor(), f) # fake input. The input is already binded in the wrapper!\n logger_tb.add_onnx_graph(onnx_filepath)\n # else there is an assert here. Not sure what is happening\n\n # option 2)\n #logger_tb.add_graph(NoDictModel(model, batch), input_to_model=torch.Tensor())\n logger.info('successfully exported!')\n except Exception as e:\n logger.error('ONNX export failed! Exception=', str(e))\n", "import collections\nimport logging\nimport numpy as np\n\nfrom .callback_reporting_export_samples import CallbackReportingExportSamples\nfrom ..utils import to_value, len_batch\nfrom .callback import Callback\nfrom ..train import outputs_trw\n\nlogger = logging.getLogger(__name__)\n\n\ndef select_classification_errors(batch, loss_terms):\n nb_samples = len_batch(batch)\n indices_errors = collections.defaultdict(list)\n for name, loss_term in loss_terms.items():\n ref = loss_term.get('output_ref')\n if ref is None or not isinstance(ref, outputs_trw.OutputClassification):\n continue\n\n truth_values = to_value(loss_term['output_truth'])\n found_values = to_value(loss_term['output'])\n samples_with_errors = np.where(found_values != truth_values)[0]\n for i in samples_with_errors:\n indices_errors[i].append(name)\n\n samples = []\n samples_error = [''] * nb_samples\n for index, values in indices_errors.items():\n samples.append(index)\n samples_error[index] = '|'.join(values)\n\n # add additional data in the batch so that we can easily display the errors\n batch['samples_error'] = samples_error\n return samples\n\n\nclass CallbackReportingClassificationErrors(Callback):\n def __init__(\n self,\n max_samples=10,\n table_name='errors',\n loss_terms_inclusion=None,\n feature_exclusions=None,\n dataset_exclusions=None,\n split_exclusions=None,\n clear_previously_exported_samples=True,\n format='{dataset_name}_{split_name}_s{id}_e{epoch}',\n reporting_config_keep_last_n_rows=None,\n reporting_config_subsampling_factor=1.0):\n \"\"\"\n Export samples with classification errors\n\n Args:\n max_samples: the maximum number of samples to be exported (per dataset and per split)\n table_name: the root of the export directory\n loss_terms_inclusion: specifies what output name from each loss term will be exported. if None, defaults to ['output']\n feature_exclusions: specifies what feature should be excluded from the export\n dataset_exclusions: specifies what dataset should be excluded from the export\n split_exclusions: specifies what split should be excluded from the export\n format: the format of the files exported. Sometimes need evolution by epoch, other time we may want\n samples by epoch so make this configurable\n reporting_config_keep_last_n_rows: Only visualize the last ``reporting_config_keep_last_n_rows``\n samples. Prior samples are discarded. This parameter will be added to the reporting configuration.\n reporting_config_subsampling_factor: Specifies how the data is sub-sampled. Must be in range [0..1]\n or ``None``. This parameter will be added to the reporting configuration.\n clear_previously_exported_samples: if ``True``, the table will be emptied before each sample export\n \"\"\"\n\n # this callback is a simple re-parameterization of the export samples\n self.impl = CallbackReportingExportSamples(\n max_samples=max_samples,\n table_name=table_name,\n loss_terms_inclusion=loss_terms_inclusion,\n feature_exclusions=feature_exclusions,\n dataset_exclusions=dataset_exclusions,\n split_exclusions=split_exclusions,\n format=format,\n reporting_config_keep_last_n_rows=reporting_config_keep_last_n_rows,\n reporting_config_subsampling_factor=reporting_config_subsampling_factor,\n select_sample_to_export=select_classification_errors,\n clear_previously_exported_samples=clear_previously_exported_samples,\n )\n\n def __call__(\n self,\n options,\n history,\n model,\n losses,\n outputs,\n datasets,\n datasets_infos,\n callbacks_per_batch,\n **kwargs):\n\n self.impl(\n options,\n history,\n model,\n losses,\n outputs,\n datasets,\n datasets_infos,\n callbacks_per_batch,\n **kwargs)\n" ]
[ [ "torch.rand" ], [ "torch.nn.Sequential", "torch.optim.lr_scheduler.CosineAnnealingLR", "numpy.asarray", "torch.nn.functional.avg_pool2d", "torch.nn.Conv2d", "torch.nn.Linear", "torch.set_num_threads", "torch.nn.BatchNorm2d" ], [ "torch.ones", "numpy.ones" ], [ "torch.no_grad", "torch.Tensor" ], [ "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
djhoese/verde
[ "ad14acf94717ee5c6672559f40576f65989753a5", "ad14acf94717ee5c6672559f40576f65989753a5", "ad14acf94717ee5c6672559f40576f65989753a5", "24416cfc8388c6c7f3c0867dcd2ad3fdca37bb1b" ]
[ "verde/tests/test_scipy.py", "verde/datasets/sample_data.py", "verde/tests/test_coordinates.py", "verde/scipygridder.py" ]
[ "\"\"\"\nTest the scipy based interpolator.\n\"\"\"\nimport warnings\n\nimport pytest\nimport pandas as pd\nimport numpy as np\nimport numpy.testing as npt\n\nfrom ..scipygridder import ScipyGridder\nfrom ..coordinates import grid_coordinates\nfrom ..datasets.synthetic import CheckerBoard\n\n\ndef test_scipy_gridder_same_points():\n \"See if the gridder recovers known points.\"\n region = (1000, 5000, -8000, -7000)\n synth = CheckerBoard(region=region)\n data = synth.scatter(size=1000, random_state=0)\n coords = (data.easting, data.northing)\n # The interpolation should be perfect on top of the data points\n for method in [\"nearest\", \"linear\", \"cubic\"]:\n grd = ScipyGridder(method=method)\n grd.fit(coords, data.scalars)\n predicted = grd.predict(coords)\n npt.assert_allclose(predicted, data.scalars)\n npt.assert_allclose(grd.score(coords, data.scalars), 1)\n\n\ndef test_scipy_gridder():\n \"See if the gridder recovers known points.\"\n synth = CheckerBoard(region=(1000, 5000, -8000, -6000))\n data = synth.scatter(size=20000, random_state=0)\n coords = (data.easting, data.northing)\n pt_coords = (3000, -7000)\n true_data = synth.predict(pt_coords)\n # nearest will never be too close to the truth\n grd = ScipyGridder(\"cubic\").fit(coords, data.scalars)\n npt.assert_almost_equal(grd.predict(pt_coords), true_data, decimal=2)\n grd = ScipyGridder(\"linear\").fit(coords, data.scalars)\n npt.assert_almost_equal(grd.predict(pt_coords), true_data, decimal=1)\n\n\ndef test_scipy_gridder_region():\n \"See if the region is gotten from the data is correct.\"\n region = (1000, 5000, -8000, -6000)\n synth = CheckerBoard(region=region)\n # Test using xarray objects\n grid = synth.grid()\n coords = grid_coordinates(region, grid.scalars.shape)\n grd = ScipyGridder().fit(coords, grid.scalars)\n npt.assert_allclose(grd.region_, region)\n # Test using pandas objects\n data = pd.DataFrame(\n {\n \"easting\": coords[0].ravel(),\n \"northing\": coords[1].ravel(),\n \"scalars\": grid.scalars.values.ravel(),\n }\n )\n grd = ScipyGridder().fit((data.easting, data.northing), data.scalars)\n npt.assert_allclose(grd.region_, region)\n\n\ndef test_scipy_gridder_extra_args():\n \"Passing in extra arguments to scipy\"\n data = CheckerBoard().scatter(random_state=100)\n coords = (data.easting, data.northing)\n grd = ScipyGridder(method=\"linear\", extra_args=dict(rescale=True))\n grd.fit(coords, data.scalars)\n predicted = grd.predict(coords)\n npt.assert_allclose(predicted, data.scalars)\n\n\ndef test_scipy_gridder_fails():\n \"fit should fail for invalid method name\"\n data = CheckerBoard().scatter(random_state=0)\n grd = ScipyGridder(method=\"some invalid method name\")\n with pytest.raises(ValueError):\n grd.fit((data.easting, data.northing), data.scalars)\n\n\ndef test_scipy_gridder_warns():\n \"Check that a warning is issued when using weights.\"\n data = CheckerBoard().scatter(random_state=100)\n weights = np.ones_like(data.scalars)\n grd = ScipyGridder()\n msg = \"ScipyGridder does not support weights and they will be ignored.\"\n with warnings.catch_warnings(record=True) as warn:\n grd.fit((data.easting, data.northing), data.scalars, weights=weights)\n assert len(warn) == 1\n assert issubclass(warn[-1].category, UserWarning)\n assert str(warn[-1].message) == msg\n", "\"\"\"\nFunctions to load sample data\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nfrom .download import fetch_data\n\n\ndef _setup_map(ax, xticks, yticks, crs, region, land=None, ocean=None):\n \"\"\"\n Setup a Cartopy map with land and ocean features and proper tick labels.\n \"\"\"\n import cartopy.feature as cfeature\n from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter\n\n if land is not None:\n ax.add_feature(cfeature.LAND, facecolor=land)\n if ocean is not None:\n ax.add_feature(cfeature.OCEAN, facecolor=ocean)\n ax.set_extent(region, crs=crs)\n # Set the proper ticks for a Cartopy map\n ax.set_xticks(xticks, crs=crs)\n ax.set_yticks(yticks, crs=crs)\n ax.xaxis.set_major_formatter(LongitudeFormatter())\n ax.yaxis.set_major_formatter(LatitudeFormatter())\n\n\ndef fetch_baja_bathymetry(force_download=False):\n \"\"\"\n Fetch sample bathymetry data from Baja California.\n\n This is the ``@tut_ship.xyz`` sample data from the `GMT\n <http://gmt.soest.hawaii.edu/>`__ tutorial.\n\n If the file isn't already in your data directory (``$HOME/.verde/data`` by\n default), it will be downloaded.\n\n Parameters\n ----------\n force_download : bool\n If True, will download the file even if it already exists.\n\n Returns\n -------\n data : pandas.DataFrame\n The bathymetry data. Columns are longitude, latitude, and bathymetry\n (in meters) for each data point.\n\n See also\n --------\n setup_baja_bathymetry_map: Utility function to help setup a Cartopy map.\n\n \"\"\"\n data_file = fetch_data(\n \"baja-california-bathymetry.csv.xz\", force_download=force_download\n )\n data = pd.read_csv(data_file, compression=\"xz\")\n return data\n\n\ndef setup_baja_bathymetry_map(\n ax, region=(245.0, 254.705, 20.0, 29.99), land=\"gray\", ocean=None\n):\n \"\"\"\n Setup a Cartopy map for the Baja California bathymetry dataset.\n\n Parameters\n ----------\n ax : matplotlib Axes\n The axes where the map is being plotted.\n region : list = [W, E, S, N]\n The boundaries of the map region in the coordinate system of the data.\n land : str or None\n The name of the color of the land feature or None to omit it.\n ocean : str or None\n The name of the color of the ocean feature or None to omit it.\n\n See also\n --------\n fetch_baja_bathymetry: Sample bathymetry data from Baja California.\n\n \"\"\"\n import cartopy.crs as ccrs\n\n _setup_map(\n ax,\n xticks=np.arange(-114, -105, 2),\n yticks=np.arange(21, 30, 2),\n land=land,\n ocean=ocean,\n region=region,\n crs=ccrs.PlateCarree(),\n )\n\n\ndef fetch_rio_magnetic(force_download=False):\n \"\"\"\n Fetch sample total-field magnetic anomaly data from Rio de Janeiro, Brazil.\n\n These data were cropped from the northwestern part of an airborne survey of\n Rio de Janeiro, Brazil, conducted in 1978. The data are made available by\n the Geological Survey of Brazil (CPRM) through their `GEOSGB portal\n <http://geosgb.cprm.gov.br/>`__.\n\n The anomaly is calculated with respect to the IGRF field parameters listed\n on the table below. See the original data for more processing information.\n\n +----------+-----------+----------------+-------------+-------------+\n | IGRF for year 1978.3 at 500 m height |\n +----------+-----------+----------------+-------------+-------------+\n | Latitude | Longitude | Intensity (nT) | Declination | Inclination |\n +==========+===========+================+=============+=============+\n | -22º15' | -42º15' | 23834 | -19º19' | -27º33' |\n +----------+-----------+----------------+-------------+-------------+\n\n If the file isn't already in your data directory (``$HOME/.verde/data`` by\n default), it will be downloaded.\n\n Parameters\n ----------\n force_download : bool\n If True, will download the file even if it already exists.\n\n Returns\n -------\n data : pandas.DataFrame\n The magnetic anomaly data. Columns are longitude, latitude, total-field\n magnetic anomaly (nanoTesla), and observation height above the\n ellipsoid (in meters) for each data point.\n\n See also\n --------\n setup_rio_magnetic_map: Utility function to help setup a Cartopy map.\n\n \"\"\"\n data_file = fetch_data(\n \"rio-de-janeiro-magnetic.csv.xz\", force_download=force_download\n )\n data = pd.read_csv(data_file, compression=\"xz\")\n return data\n\n\ndef setup_rio_magnetic_map(ax, region=(-42.6, -42, -22.5, -22)):\n \"\"\"\n Setup a Cartopy map for the Rio de Janeiro magnetic anomaly dataset.\n\n Parameters\n ----------\n ax : matplotlib Axes\n The axes where the map is being plotted.\n region : list = [W, E, S, N]\n The boundaries of the map region in the coordinate system of the data.\n land : str or None\n The name of the color of the land feature or None to omit it.\n ocean : str or None\n The name of the color of the ocean feature or None to omit it.\n\n See also\n --------\n fetch_rio_magnetic: Sample magnetic anomaly data from Rio de Janeiro, Brazil.\n\n \"\"\"\n import cartopy.crs as ccrs\n\n _setup_map(\n ax,\n xticks=np.arange(-42.5, -42, 0.1),\n yticks=np.arange(-22.5, -21.99, 0.1),\n land=None,\n ocean=None,\n region=region,\n crs=ccrs.PlateCarree(),\n )\n\n\ndef fetch_california_gps(force_download=False):\n \"\"\"\n Fetch sample GPS velocity data from California (the U.S. West coast).\n\n Velocities and their standard deviations are in meters/year. Height is\n geometric height above WGS84 in meters. Velocities are referenced to the\n North American tectonic plate (NAM08). The average velocities were released\n on 2017-12-27.\n\n This material is based on EarthScope Plate Boundary Observatory data\n services provided by UNAVCO through the GAGE Facility with support from the\n National Science Foundation (NSF) and National Aeronautics and Space\n Administration (NASA) under NSF Cooperative Agreement No. EAR-1261833.\n\n If the file isn't already in your data directory (``$HOME/.verde/data`` by\n default), it will be downloaded.\n\n Parameters\n ----------\n force_download : bool\n If True, will download the file even if it already exists.\n\n Returns\n -------\n data : pandas.DataFrame\n The GPS velocity data. Columns are longitude, latitude, height\n (geometric, in meters), East velocity (meter/year), North velocity\n (meter/year), upward velocity (meter/year), standard deviation of East\n velocity (meter/year), standard deviation of North velocity\n (meter/year), standard deviation of upward velocity (meter/year).\n\n See also\n --------\n setup_california_gps_map: Utility function to help setup a Cartopy map.\n\n \"\"\"\n data_file = fetch_data(\"california-gps.csv.xz\", force_download=force_download)\n data = pd.read_csv(data_file, compression=\"xz\")\n return data\n\n\ndef setup_california_gps_map(\n ax, region=(235.2, 245.3, 31.9, 42.3), land=\"gray\", ocean=\"skyblue\"\n):\n \"\"\"\n Setup a Cartopy map for the California GPS velocity dataset.\n\n Parameters\n ----------\n ax : matplotlib Axes\n The axes where the map is being plotted.\n region : list = [W, E, S, N]\n The boundaries of the map region in the coordinate system of the data.\n land : str or None\n The name of the color of the land feature or None to omit it.\n ocean : str or None\n The name of the color of the ocean feature or None to omit it.\n\n See also\n --------\n fetch_california_gps: Sample GPS velocity data from California.\n\n \"\"\"\n import cartopy.crs as ccrs\n\n _setup_map(\n ax,\n xticks=np.arange(-124, -115, 4),\n yticks=np.arange(33, 42, 2),\n land=land,\n ocean=ocean,\n region=region,\n crs=ccrs.PlateCarree(),\n )\n", "\"\"\"\nTest the coordinate generation functions\n\"\"\"\nimport pytest\nimport numpy.testing as npt\n\nfrom ..coordinates import (\n check_region,\n spacing_to_shape,\n profile_coordinates,\n grid_coordinates,\n)\n\n\ndef test_spacing_to_shape():\n \"Check that correct spacing and region are returned\"\n region = (-10, 0, 0, 5)\n\n shape, new_region = spacing_to_shape(region, spacing=2.5, adjust=\"spacing\")\n npt.assert_allclose(shape, (3, 5))\n npt.assert_allclose(new_region, region)\n\n shape, new_region = spacing_to_shape(region, spacing=(2.5, 2), adjust=\"spacing\")\n npt.assert_allclose(shape, (3, 6))\n npt.assert_allclose(new_region, region)\n\n shape, new_region = spacing_to_shape(region, spacing=2.6, adjust=\"spacing\")\n npt.assert_allclose(shape, (3, 5))\n npt.assert_allclose(new_region, region)\n\n shape, new_region = spacing_to_shape(region, spacing=2.4, adjust=\"spacing\")\n npt.assert_allclose(shape, (3, 5))\n npt.assert_allclose(new_region, region)\n\n shape, new_region = spacing_to_shape(region, spacing=(2.4, 1.9), adjust=\"spacing\")\n npt.assert_allclose(shape, (3, 6))\n npt.assert_allclose(new_region, region)\n\n shape, new_region = spacing_to_shape(region, spacing=2.6, adjust=\"region\")\n npt.assert_allclose(shape, (3, 5))\n npt.assert_allclose(new_region, (-10, 0.4, 0, 5.2))\n\n shape, new_region = spacing_to_shape(region, spacing=(2.6, 2.4), adjust=\"region\")\n npt.assert_allclose(shape, (3, 5))\n npt.assert_allclose(new_region, (-10, -0.4, 0, 5.2))\n\n\ndef test_spacing_to_shape_fails():\n \"Should fail if more than 2 spacings are given\"\n with pytest.raises(ValueError):\n spacing_to_shape((0, 1, 0, 1), (1, 2, 3), adjust=\"region\")\n\n\ndef test_grid_coordinates_fails():\n \"Check failures for invalid arguments\"\n region = (0, 1, 0, 10)\n shape = (10, 20)\n spacing = 0.5\n # Make sure it doesn't fail for these parameters\n grid_coordinates(region, shape)\n grid_coordinates(region, spacing=spacing)\n\n with pytest.raises(ValueError):\n grid_coordinates(region, shape=shape, spacing=spacing)\n with pytest.raises(ValueError):\n grid_coordinates(region, shape=None, spacing=None)\n with pytest.raises(ValueError):\n grid_coordinates(region, spacing=spacing, adjust=\"invalid adjust\")\n\n\ndef test_check_region():\n \"Make sure an exception is raised for bad regions\"\n with pytest.raises(ValueError):\n check_region([])\n with pytest.raises(ValueError):\n check_region([1, 2, 3, 4, 5])\n with pytest.raises(ValueError):\n check_region([1, 2, 3])\n with pytest.raises(ValueError):\n check_region([1, 2, 3, 1])\n with pytest.raises(ValueError):\n check_region([2, 1, 3, 4])\n with pytest.raises(ValueError):\n check_region([-1, -2, -4, -3])\n with pytest.raises(ValueError):\n check_region([-2, -1, -2, -3])\n\n\ndef test_profile_coordiantes_fails():\n \"Should raise an exception for invalid input\"\n with pytest.raises(ValueError):\n profile_coordinates((0, 1), (1, 2), size=0)\n with pytest.raises(ValueError):\n profile_coordinates((0, 1), (1, 2), size=-10)\n with pytest.raises(ValueError):\n profile_coordinates((0, 1), (1, 2), size=10, coordinate_system=\"meh\")\n with pytest.raises(NotImplementedError):\n profile_coordinates((0, 1), (1, 2), size=10, coordinate_system=\"geographic\")\n", "\"\"\"\nA gridder that uses scipy.interpolate as the backend.\n\"\"\"\nfrom warnings import warn\n\nimport numpy as np\nfrom sklearn.utils.validation import check_is_fitted\nfrom scipy.interpolate import (\n LinearNDInterpolator,\n NearestNDInterpolator,\n CloughTocher2DInterpolator,\n)\n\nfrom .base import BaseGridder, check_fit_input\nfrom .coordinates import get_region\n\n\nclass ScipyGridder(BaseGridder):\n \"\"\"\n A scipy.interpolate based gridder for scalar Cartesian data.\n\n Provides a verde gridder interface to the scipy interpolators\n :class:`scipy.interpolate.LinearNDInterpolator`,\n :class:`scipy.interpolate.NearestNDInterpolator`, and\n :class:`scipy.interpolate.CloughTocher2DInterpolator` (cubic).\n\n Parameters\n ----------\n method : str\n The interpolation method. Either ``'linear'``, ``'nearest'``, or\n ``'cubic'``.\n extra_args : None or dict\n Extra keyword arguments to pass to the scipy interpolator class. See\n the documentation for each interpolator for a list of possible\n arguments.\n\n Attributes\n ----------\n interpolator_ : scipy interpolator class\n An instance of the corresponding scipy interpolator class.\n region_ : tuple\n The boundaries (``[W, E, S, N]``) of the data used to fit the\n interpolator. Used as the default region for the\n :meth:`~verde.ScipyGridder.grid` and\n :meth:`~verde.ScipyGridder.scatter` methods.\n\n \"\"\"\n\n def __init__(self, method=\"cubic\", extra_args=None):\n self.method = method\n self.extra_args = extra_args\n\n def fit(self, coordinates, data, weights=None):\n \"\"\"\n Fit the interpolator to the given data.\n\n Any keyword arguments passed as the ``extra_args`` attribute will be\n used when instantiating the scipy interpolator.\n\n The data region is captured and used as default for the\n :meth:`~verde.ScipyGridder.grid` and\n :meth:`~verde.ScipyGridder.scatter` methods.\n\n Parameters\n ----------\n coordinates : tuple of arrays\n Arrays with the coordinates of each data point. Should be in the\n following order: (easting, northing, vertical, ...). Only easting\n and northing will be used, all subsequent coordinates will be\n ignored.\n data : array\n The data values that will be interpolated.\n weights : None or array\n If not None, then the weights assigned to each data point.\n Typically, this should be 1 over the data uncertainty squared.\n Ignored for this interpolator. Only present for compatibility with\n other gridder.\n\n Returns\n -------\n self : verde.ScipyGridder\n Returns this gridder instance for chaining operations.\n\n \"\"\"\n classes = dict(\n linear=LinearNDInterpolator,\n nearest=NearestNDInterpolator,\n cubic=CloughTocher2DInterpolator,\n )\n if self.method not in classes:\n raise ValueError(\n \"Invalid interpolation method '{}'. Must be one of {}.\".format(\n self.method, str(classes.keys())\n )\n )\n if self.extra_args is None:\n kwargs = {}\n else:\n kwargs = self.extra_args\n if weights is not None:\n warn(\n \"{} does not support weights and they will be ignored.\".format(\n self.__class__.__name__\n )\n )\n coordinates, data, weights = check_fit_input(coordinates, data, weights)\n easting, northing = coordinates[:2]\n self.region_ = get_region((easting, northing))\n points = np.column_stack((np.ravel(easting), np.ravel(northing)))\n self.interpolator_ = classes[self.method](points, np.ravel(data), **kwargs)\n return self\n\n def predict(self, coordinates):\n \"\"\"\n Interpolate data on the given set of points.\n\n Requires a fitted gridder (see :meth:`~verde.ScipyGridder.fit`).\n\n Parameters\n ----------\n coordinates : tuple of arrays\n Arrays with the coordinates of each data point. Should be in the\n following order: (easting, northing, vertical, ...). Only easting\n and northing will be used, all subsequent coordinates will be\n ignored.\n\n Returns\n -------\n data : array\n The data values interpolated on the given points.\n\n \"\"\"\n check_is_fitted(self, [\"interpolator_\"])\n easting, northing = coordinates[:2]\n return self.interpolator_((easting, northing))\n" ]
[ [ "numpy.ones_like", "numpy.testing.assert_allclose" ], [ "numpy.arange", "pandas.read_csv" ], [ "numpy.testing.assert_allclose" ], [ "numpy.ravel", "sklearn.utils.validation.check_is_fitted" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
liushulinle/CRACSpell
[ "e0b495ed8424be7fdbd7fc3ef8c2919ab195b0e4" ]
[ "src/run_evaluation.py" ]
[ "import sys, os\nimport numpy as np\nimport tensorflow as tf\nfrom bert_tagging import DataProcessor, BertTagging\nimport modeling\nimport optimization\nimport time\nfrom tagging_eval import score_f\ntf.logging.set_verbosity(tf.logging.ERROR)\n\nDEBUG = False\ndef evaluate(FLAGS, label_list=None):\n gpuid = FLAGS.gpuid\n max_sen_len = FLAGS.max_sen_len\n test_file = FLAGS.test_path\n out_dir = FLAGS.output_dir\n model_dir = FLAGS.model_dir\n batch_size = FLAGS.batch_size\n bert_config_path = './conf/bert_config.json'\n vocob_file = './conf/vocab.txt'\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = gpuid \n\n # data processor\n data_processor = DataProcessor(test_file, max_sen_len, vocob_file, out_dir, label_list=None, is_training=False)\n test_num = data_processor.num_examples\n test_data = data_processor.build_data_generator(batch_size)\n iterator = test_data.make_one_shot_iterator()\n input_ids, input_mask, segment_ids, lmask, label_ids, masked_sample = iterator.get_next()\n\n #load model\n model = BertTagging(bert_config_path, num_class=len(data_processor.get_label_list()), max_sen_len=max_sen_len)\n\n (pred_loss, pred_result, gold_result, gold_mask, r_loss) = model.create_model(input_ids, input_mask, segment_ids, lmask, label_ids, batch_size=batch_size, masked_sample=masked_sample, is_training=False)\n tf_config = tf.ConfigProto(log_device_placement=False)\n tf_config.gpu_options.allow_growth = True\n sess = tf.Session(config=tf_config)\n ckpt = tf.train.get_checkpoint_state(model_dir)\n saver = tf.train.Saver()\n saver.restore(sess, ckpt.model_checkpoint_path)\n\n\n label_list = data_processor.label_list\n ans = []\n all_inputs, all_golds, all_preds = [], [], []\n all_py_inputs, all_py_golds, all_py_preds = [], [], []\n all_fusion_preds = []\n all_inputs_sent, all_golds_sent, all_preds_sent = [], [], []\n for step in range(test_num // batch_size): \n inputs, loss_value, preds, golds, gmask = sess.run([input_ids, pred_loss, pred_result, gold_result, gold_mask])\n\n\n for k in range(batch_size):\n gsent, psent, isent = [], [], []\n for j in range(max_sen_len):\n if gmask[k][j] == 0: continue\n all_golds.append(golds[k][j])\n all_preds.append(preds[k][j])\n all_inputs.append(inputs[k][j])\n gsent.append(label_list[golds[k][j]])\n psent.append(label_list[preds[k][j]])\n isent.append(label_list[inputs[k][j]])\n all_golds_sent.append(gsent)\n all_preds_sent.append(psent)\n all_inputs_sent.append(isent) \n if DEBUG and step > 5: break\n fout = open('%s/pred_sent.txt' % out_dir, 'w', encoding='utf-8')\n fout.writelines('## input/gold/pred TAB ... ...\\n') \n for k in range(len(all_inputs_sent)):\n for j in range(len(all_inputs_sent[k])):\n ic = all_inputs_sent[k][j]\n pc = all_preds_sent[k][j]\n gc = all_golds_sent[k][j]\n fout.writelines('%s/%s/%s\\t' % (ic, gc, pc))\n fout.writelines('\\n')\n fout.close()\n \n all_golds = [label_list[k] for k in all_golds]\n all_preds = [label_list[k] for k in all_preds]\n all_inputs = [label_list[k] for k in all_inputs]\n \n print ('ALL LEN:%d' % len(all_preds))\n print('zi result:') \n p, r, f = score_f((all_inputs, all_golds, all_preds), only_check=False, out_dir=out_dir)\n return f\n\nif __name__ == '__main__':\n\n flags = tf.flags\n ## Required parameters\n flags.DEFINE_string(\"gpuid\", '0', \"The gpu NO. \")\n\n ## Optional\n flags.DEFINE_string(\"test_path\", '', \"train path \")\n flags.DEFINE_string(\"output_dir\", '', \"out dir \")\n flags.DEFINE_string(\"model_dir\", '', \"out dir \")\n flags.DEFINE_integer(\"batch_size\", '1', \"out dir \")\n flags.DEFINE_integer(\"max_sen_len\", 64, 'max_sen_len')\n\n\n flags.mark_flag_as_required('gpuid')\n flags.mark_flag_as_required('test_path')\n flags.mark_flag_as_required('output_dir')\n flags.mark_flag_as_required('max_sen_len')\n\n FLAGS = flags.FLAGS\n print ('Confings:')\n print ('\\tgpuid=', FLAGS.gpuid)\n print ('\\ttest_path=', FLAGS.test_path)\n print ('\\toutput_dir=', FLAGS.output_dir)\n evaluate(FLAGS, FLAGS.test_path)\n\n" ]
[ [ "tensorflow.train.get_checkpoint_state", "tensorflow.ConfigProto", "tensorflow.logging.set_verbosity", "tensorflow.Session", "tensorflow.train.Saver" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]